code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
'use strict';
/*@ngInject*/
function repoItemClassifierFilter() {
return function(node) {
if (node.type) {
return 'uib-repository__item--movable';
} else {
return 'uib-repository__group';
}
};
}
module.exports = repoItemClassifierFilter;
| raqystyle/ui-builder | frontend/scripts/builder/modules/repository/filters/repoItemClassifier.filter.js | JavaScript | gpl-2.0 | 268 |
(function($) {
function ACFTableField() {
var t = this;
t.version = '1.3.4';
t.param = {};
// DIFFERENT IN ACF VERSION 4 and 5 {
t.param.classes = {
btn_small: 'acf-icon small',
// "acf-icon-plus" becomes "-plus" since ACF Pro Version 5.3.2
btn_add_row: 'acf-icon-plus -plus',
btn_add_col: 'acf-icon-plus -plus',
btn_remove_row: 'acf-icon-minus -minus',
btn_remove_col: 'acf-icon-minus -minus',
};
t.param.htmlbuttons = {
add_row: '<a href="#" class="acf-table-add-row ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_add_row + '"></a>',
remove_row: '<a href="#" class="acf-table-remove-row ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_remove_row + '"></a>',
add_col: '<a href="#" class="acf-table-add-col ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_add_col + '"></a>',
remove_col: '<a href="#" class="acf-table-remove-col ' + t.param.classes.btn_small + ' ' + t.param.classes.btn_remove_row + '"></a>',
};
// }
t.param.htmltable = {
body_row: '<div class="acf-table-body-row">' +
'<div class="acf-table-body-left">' +
t.param.htmlbuttons.add_row +
'<div class="acf-table-body-cont"><!--ph--></div>' +
'</div>' +
'<div class="acf-table-body-right">' +
t.param.htmlbuttons.remove_row +
'</div>' +
'</div>',
top_cell: '<div class="acf-table-top-cell" data-colparam="">' +
t.param.htmlbuttons.add_col +
'<div class="acf-table-top-cont"><!--ph--></div>' +
'</div>',
header_cell: '<div class="acf-table-header-cell">' +
'<div class="acf-table-header-cont"><!--ph--></div>' +
'</div>',
body_cell: '<div class="acf-table-body-cell">' +
'<div class="acf-table-body-cont"><!--ph--></div>' +
'</div>',
bottom_cell: '<div class="acf-table-bottom-cell">' +
t.param.htmlbuttons.remove_col +
'</div>',
table: '<div class="acf-table-wrap">' +
'<div class="acf-table-table">' + // acf-table-hide-header acf-table-hide-left acf-table-hide-top
'<div class="acf-table-top-row">' +
'<div class="acf-table-top-left">' +
t.param.htmlbuttons.add_col +
'</div>' +
'<div class="acf-table-top-right"></div>' +
'</div>' +
'<div class="acf-table-header-row acf-table-header-hide-off">' +
'<div class="acf-table-header-left">' +
t.param.htmlbuttons.add_row +
'</div>' +
'<div class="acf-table-header-right"></div>' +
'</div>' +
'<div class="acf-table-bottom-row">' +
'<div class="acf-table-bottom-left"></div>' +
'<div class="acf-table-bottom-right"></div>' +
'</div>' +
'</div>' +
'</div>',
};
t.param.htmleditor = '<div class="acf-table-cell-editor">' +
'<textarea name="acf-table-cell-editor-textarea" class="acf-table-cell-editor-textarea"></textarea>' +
'</div>';
t.obj = {
body: $( 'body' ),
};
t.var = {
ajax: false,
};
t.state = {
'current_cell_obj': false,
'cell_editor_cell': false,
'cell_editor_last_keycode': false
};
t.init = function() {
t.init_workflow();
};
t.init_workflow = function() {
t.each_table();
t.table_add_col_event();
t.table_remove_col();
t.table_add_row_event();
t.table_remove_row();
t.cell_editor();
t.cell_editor_tab_navigation();
t.prevent_cell_links();
t.sortable_row();
t.sortable_col();
t.ui_event_use_header();
t.ui_event_caption();
t.ui_event_new_flex_field();
t.ui_event_change_location_rule();
t.ui_event_ajax();
};
t.ui_event_ajax = function() {
$( document ).ajaxComplete( function( event ) {
t.each_table();
});
}
t.ui_event_change_location_rule = function() {
t.obj.body.on( 'change', '[name="post_category[]"], [name="post_format"], [name="page_template"], [name="parent_id"], [name="role"], [name^="tax_input"]', function() {
var interval = setInterval( function() {
var table_fields = $( '.field_type-table' );
if ( table_fields.length > 0 ) {
t.each_table();
clearInterval( interval );
}
}, 100 );
} );
};
t.each_table = function( ) {
$( '.acf-field-table .acf-table-root' ).not( '.acf-table-rendered' ).each( function() {
var p = {};
p.obj_root = $( this ),
table = p.obj_root.find( '.acf-table-wrap' );
if ( table.length > 0 ) {
return;
}
p.obj_root.addClass( 'acf-table-rendered' );
t.data_get( p );
t.data_default( p );
t.field_options_get( p );
t.table_render( p );
t.misc_render( p );
if ( typeof p.data.b[ 1 ] === 'undefined' && typeof p.data.b[ 0 ][ 1 ] === 'undefined' && p.data.b[ 0 ][ 0 ].c === '' ) {
p.obj_root.find( '.acf-table-remove-col' ).hide(),
p.obj_root.find( '.acf-table-remove-row' ).hide();
}
} );
};
t.field_options_get = function( p ) {
try {
p.field_options = $.parseJSON( decodeURIComponent( p.obj_root.find( '[data-field-options]' ).data( 'field-options' ) ) );
}
catch (e) {
p.field_options = {
use_header: 2
};
console.log( 'The tablefield options value is not a valid JSON string:', decodeURIComponent( p.obj_root.find( '[data-field-options]' ).data( 'field-options' ) ) );
console.log( 'The parsing error:', e );
}
};
t.ui_event_use_header = function() {
// HEADER: SELECT FIELD ACTIONS {
t.obj.body.on( 'change', '.acf-table-fc-opt-use-header', function() {
var that = $( this ),
p = {};
p.obj_root = that.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
t.data_get( p );
t.data_default( p );
if ( that.val() === '1' ) {
p.obj_table.removeClass( 'acf-table-hide-header' );
p.data.p.o.uh = 1;
t.update_table_data_field( p );
}
else {
p.obj_table.addClass( 'acf-table-hide-header' );
p.data.p.o.uh = 0;
t.update_table_data_field( p );
}
} );
// }
};
t.ui_event_caption = function() {
// CAPTION: INPUT FIELD ACTIONS {
t.obj.body.on( 'change', '.acf-table-fc-opt-caption', function() {
var that = $( this ),
p = {};
p.obj_root = that.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
t.data_get( p );
t.data_default( p );
p.data.p.ca = that.val();
t.update_table_data_field( p );
} );
// }
};
t.ui_event_new_flex_field = function() {
t.obj.body.on( 'click', '.acf-fc-popup', function() {
// SORTABLE {
$( '.acf-table-table' )
.sortable('destroy')
.unbind();
window.setTimeout( function() {
t.sortable_row();
}, 300 );
// }
} );
};
t.data_get = function( p ) {
// DATA FROM FIELD {
var val = p.obj_root.find( 'input.table' ).val();
p.data = false;
// CHECK FIELD CONTEXT {
if ( p.obj_root.closest( '.acf-fields' ).hasClass( 'acf-block-fields' ) ) {
p.field_context = 'block';
}
else {
p.field_context = 'box';
}
// }
if ( val !== '' ) {
try {
if ( p.field_context === 'box' ) {
p.data = $.parseJSON( decodeURIComponent( val.replace(/\+/g, '%20') ) );
}
if ( p.field_context === 'block' ) {
p.data = $.parseJSON( decodeURIComponent( decodeURIComponent( val.replace(/\+/g, '%20') ) ) );
}
}
catch (e) {
if ( p.field_context === 'box' ) {
console.log( 'The tablefield value is not a valid JSON string:', decodeURIComponent( val.replace(/\+/g, '%20') ) );
console.log( 'The parsing error:', e );
}
if ( p.field_context === 'block' ) {
console.log( 'The tablefield value is not a valid JSON string:', decodeURIComponent( decodeURIComponent( val.replace(/\+/g, '%20') ) ) );
console.log( 'The tablefield value is not a valid JSON string:', decodeURIComponent( decodeURIComponent( decodeURIComponent( val.replace(/\+/g, '%20') ) ) ) );
console.log( 'The parsing error:', e );
}
}
}
return p.data;
// }
};
t.data_default = function( p ) {
// DEFINE DEFAULT DATA {
p.data_defaults = {
acftf: {
v: t.version,
},
p: {
o: {
uh: 0, // use header
},
ca: '', // caption content
},
// from data-colparam
c: [
{
c: '',
},
],
// header
h: [
{
c: '',
},
],
// body
b: [
[
{
c: '',
},
],
],
};
// }
// MERGE DEFAULT DATA {
if ( p.data ) {
if ( typeof p.data.b === 'array' ) {
$.extend( true, p.data, p.data_defaults );
}
}
else {
p.data = p.data_defaults;
}
// }
};
t.table_render = function( p ) {
// TABLE HTML MAIN {
p.obj_root.find( '.acf-table-wrap' ).remove();
p.obj_root.append( t.param.htmltable.table );
// }
// TABLE GET OBJECTS {
p.obj_table = p.obj_root.find( '.acf-table-table' );
p.obj_top_row = p.obj_root.find( '.acf-table-top-row' ),
p.obj_top_insert = p.obj_top_row.find( '.acf-table-top-right' ),
p.obj_header_row = p.obj_root.find( '.acf-table-header-row' ),
p.obj_header_insert = p.obj_header_row.find( '.acf-table-header-right' ),
p.obj_bottom_row = p.obj_root.find( '.acf-table-bottom-row' ),
p.obj_bottom_insert = p.obj_bottom_row.find( '.acf-table-bottom-right' );
// }
// TOP CELLS {
if ( p.data.c ) {
for ( i in p.data.c ) {
p.obj_top_insert.before( t.param.htmltable.top_cell );
}
}
t.table_top_labels( p );
// }
// HEADER CELLS {
if ( p.data.h ) {
for ( i in p.data.h ) {
p.obj_header_insert.before( t.param.htmltable.header_cell.replace( '<!--ph-->', p.data.h[ i ].c.replace( /xxx"/g, '"' ) ) );
}
}
// }
// BODY ROWS {
if ( p.data.b ) {
for ( i in p.data.b ) {
p.obj_bottom_row.before( t.param.htmltable.body_row.replace( '<!--ph-->', parseInt(i) + 1 ) );
}
}
// }
// BODY ROWS CELLS {
var body_rows = p.obj_root.find( '.acf-table-body-row'),
row_i = 0;
if ( body_rows ) {
body_rows.each( function() {
var body_row = $( this ),
row_insert = body_row.find( '.acf-table-body-right' );
for( i in p.data.b[ row_i ] ) {
row_insert.before( t.param.htmltable.body_cell.replace( '<!--ph-->', p.data.b[ row_i ][ i ].c.replace( /xxx"/g, '"' ) ) );
}
row_i = row_i + 1
} );
}
// }
// TABLE BOTTOM {
if ( p.data.c ) {
for ( i in p.data.c ) {
p.obj_bottom_insert.before( t.param.htmltable.bottom_cell );
}
}
// }
};
t.misc_render = function( p ) {
t.init_option_use_header( p );
t.init_option_caption( p );
};
t.init_option_use_header = function( p ) {
// VARS {
var v = {};
v.obj_use_header = p.obj_root.find( '.acf-table-fc-opt-use-header' );
// }
// HEADER {
// HEADER: FIELD OPTIONS, THAT AFFECTS DATA {
// HEADER IS NOT ALLOWED
if ( p.field_options.use_header === 2 ) {
p.obj_table.addClass( 'acf-table-hide-header' );
p.data.p.o.uh = 0;
t.update_table_data_field( p );
}
// HEADER IS REQUIRED
if ( p.field_options.use_header === 1 ) {
p.data.p.o.uh = 1;
t.update_table_data_field( p );
}
// }
// HEADER: SET CHECKBOX STATUS {
if ( p.data.p.o.uh === 1 ) {
v.obj_use_header.val( '1' );
}
if ( p.data.p.o.uh === 0 ) {
v.obj_use_header.val( '0' );
}
// }
// HEADER: SET HEADER VISIBILITY {
if ( p.data.p.o.uh === 1 ) {
p.obj_table.removeClass( 'acf-table-hide-header' );
}
if ( p.data.p.o.uh === 0 ) {
p.obj_table.addClass( 'acf-table-hide-header' );
}
// }
// }
};
t.init_option_caption = function( p ) {
if (
typeof p.field_options.use_caption !== 'number' ||
p.field_options.use_caption === 2
) {
return;
}
// VARS {
var v = {};
v.obj_caption = p.obj_root.find( '.acf-table-fc-opt-caption' );
// }
// SET CAPTION VALUE {
v.obj_caption.val( p.data.p.ca );
// }
};
t.table_add_col_event = function() {
t.obj.body.on( 'click', '.acf-table-add-col', function( e ) {
e.preventDefault();
var that = $( this ),
p = {};
p.obj_col = that.parent();
t.table_add_col( p );
} );
};
t.table_add_col = function( p ) {
// requires
// p.obj_col
var that_index = p.obj_col.index();
p.obj_root = p.obj_col.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
$( p.obj_table.find( '.acf-table-top-row' ).children()[ that_index ] ).after( t.param.htmltable.top_cell.replace( '<!--ph-->', '' ) );
$( p.obj_table.find( '.acf-table-header-row' ).children()[ that_index ] ).after( t.param.htmltable.header_cell.replace( '<!--ph-->', '' ) );
p.obj_table.find( '.acf-table-body-row' ).each( function() {
$( $( this ).children()[ that_index ] ).after( t.param.htmltable.body_cell.replace( '<!--ph-->', '' ) );
} );
$( p.obj_table.find( '.acf-table-bottom-row' ).children()[ that_index ] ).after( t.param.htmltable.bottom_cell.replace( '<!--ph-->', '' ) );
t.table_top_labels( p );
p.obj_table.find( '.acf-table-remove-col' ).show();
p.obj_table.find( '.acf-table-remove-row' ).show();
t.table_build_json( p );
};
t.table_remove_col = function() {
t.obj.body.on( 'click', '.acf-table-remove-col', function( e ) {
e.preventDefault();
var p = {},
that = $( this ),
that_index = that.parent().index(),
obj_rows = undefined,
cols_count = false;
p.obj_root = that.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
p.obj_top = p.obj_root.find( '.acf-table-top-row' );
obj_rows = p.obj_table.find( '.acf-table-body-row' );
cols_count = p.obj_top.find( '.acf-table-top-cell' ).length;
$( p.obj_table.find( '.acf-table-top-row' ).children()[ that_index ] ).remove();
$( p.obj_table.find( '.acf-table-header-row' ).children()[ that_index ] ).remove();
if ( cols_count == 1 ) {
obj_rows.remove();
t.table_add_col( {
obj_col: p.obj_table.find( '.acf-table-top-left' )
} );
t.table_add_row( {
obj_row: p.obj_table.find( '.acf-table-header-row' )
} );
p.obj_table.find( '.acf-table-remove-col' ).hide();
p.obj_table.find( '.acf-table-remove-row' ).hide();
}
else {
obj_rows.each( function() {
$( $( this ).children()[ that_index ] ).remove();
} );
}
$( p.obj_table.find( '.acf-table-bottom-row' ).children()[ that_index ] ).remove();
t.table_top_labels( p );
t.table_build_json( p );
} );
};
t.table_add_row_event = function() {
t.obj.body.on( 'click', '.acf-table-add-row', function( e ) {
e.preventDefault();
var that = $( this ),
p = {};
p.obj_row = that.parent().parent();
t.table_add_row( p );
});
};
t.table_add_row = function( p ) {
// requires
// p.obj_row
var that_index = 0,
col_amount = 0,
body_cells_html = '';
p.obj_root = p.obj_row.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
p.obj_table_rows = p.obj_table.children();
col_amount = p.obj_table.find( '.acf-table-top-cell' ).size();
that_index = p.obj_row.index();
for ( i = 0; i < col_amount; i++ ) {
body_cells_html = body_cells_html + t.param.htmltable.body_cell.replace( '<!--ph-->', '' );
}
$( p.obj_table_rows[ that_index ] )
.after( t.param.htmltable.body_row )
.next()
.find('.acf-table-body-left')
.after( body_cells_html );
t.table_left_labels( p );
p.obj_table.find( '.acf-table-remove-col' ).show();
p.obj_table.find( '.acf-table-remove-row' ).show();
t.table_build_json( p );
};
t.table_remove_row = function() {
t.obj.body.on( 'click', '.acf-table-remove-row', function( e ) {
e.preventDefault();
var p = {},
that = $( this ),
rows_count = false;
p.obj_root = that.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
p.obj_rows = p.obj_root.find( '.acf-table-body-row' );
rows_count = p.obj_rows.length;
that.parent().parent().remove();
if ( rows_count == 1 ) {
t.table_add_row( {
obj_row: p.obj_table.find( '.acf-table-header-row' )
} );
p.obj_table.find( '.acf-table-remove-row' ).hide();
}
t.table_left_labels( p );
t.table_build_json( p );
} );
};
t.table_top_labels = function( p ) {
var letter_i_1 = 'A'.charCodeAt( 0 ),
letter_i_2 = 'A'.charCodeAt( 0 ),
use_2 = false;
p.obj_table.find( '.acf-table-top-cont' ).each( function() {
var string = '';
if ( !use_2 ) {
string = String.fromCharCode( letter_i_1 );
if ( letter_i_1 === 'Z'.charCodeAt( 0 ) ) {
letter_i_1 = 'A'.charCodeAt( 0 );
use_2 = true;
}
else {
letter_i_1 = letter_i_1 + 1;
}
}
else {
string = String.fromCharCode( letter_i_1 ) + String.fromCharCode( letter_i_2 );
if ( letter_i_2 === 'Z'.charCodeAt( 0 ) ) {
letter_i_1 = letter_i_1 + 1;
letter_i_2 = 'A'.charCodeAt( 0 );
}
else {
letter_i_2 = letter_i_2 + 1;
}
}
$( this ).text( string );
} );
};
t.table_left_labels = function( p ) {
var i = 0;
p.obj_table.find( '.acf-table-body-left' ).each( function() {
i = i + 1;
$( this ).find( '.acf-table-body-cont' ).text( i );
} );
};
t.table_build_json = function( p ) {
var i = 0,
i2 = 0;
p.data = t.data_get( p );
t.data_default( p );
p.data.c = [];
p.data.h = [];
p.data.b = [];
// TOP {
i = 0;
p.obj_table.find( '.acf-table-top-cont' ).each( function() {
p.data.c[ i ] = {};
p.data.c[ i ].p = $( this ).parent().data( 'colparam' );
i = i + 1;
} );
// }
// HEADER {
i = 0;
p.obj_table.find( '.acf-table-header-cont' ).each( function() {
p.data.h[ i ] = {};
p.data.h[ i ].c = $( this ).html();
i = i + 1;
} );
// }
// BODY {
i = 0;
i2 = 0;
p.obj_table.find( '.acf-table-body-row' ).each( function() {
p.data.b[ i ] = [];
$( this ).find( '.acf-table-body-cell .acf-table-body-cont' ).each( function() {
p.data.b[ i ][ i2 ] = {};
p.data.b[ i ][ i2 ].c = $( this ).html();
i2 = i2 + 1;
} );
i2 = 0;
i = i + 1;
} );
// }
// UPDATE INPUT WITH NEW DATA {
t.update_table_data_field( p );
// }
};
t.update_table_data_field = function( p ) {
// UPDATE INPUT WITH NEW DATA {
p.data = t.update_table_data_version( p.data );
// makes json string from data object
var data = JSON.stringify( p.data );
// adds backslash to all \" in JSON string because encodeURIComponent() strippes backslashes
data.replace( /\\"/g, '\\"' );
// encodes the JSON string to URI component, the format, the JSON string is saved to the database
data = encodeURIComponent( data )
p.obj_root.find( 'input.table' ).val( data );
t.field_changed( p );
// }
};
t.update_table_data_version = function( data ) {
if ( typeof data.acftf === 'undefined' ) {
data.acftf = {};
}
data.acftf.v = t.version;
return data;
}
t.cell_editor = function() {
t.obj.body.on( 'click', '.acf-table-body-cell, .acf-table-header-cell', function( e ) {
e.stopImmediatePropagation();
t.cell_editor_save();
var that = $( this );
t.cell_editor_add_editor({
'that': that
});
} );
t.obj.body.on( 'click', '.acf-table-cell-editor-textarea', function( e ) {
e.stopImmediatePropagation();
} );
t.obj.body.on( 'click', function( e ) {
t.cell_editor_save();
} );
};
t.cell_editor_add_editor = function( p ) {
var defaults = {
'that': false
};
p = $.extend( true, defaults, p );
if ( p['that'] ) {
var that_val = p['that'].find( '.acf-table-body-cont, .acf-table-header-cont' ).html();
t.state.current_cell_obj = p['that'];
t.state.cell_editor_is_open = true;
p['that'].prepend( t.param.htmleditor ).find( '.acf-table-cell-editor-textarea' ).html( that_val ).focus();
}
};
t.get_next_table_cell = function( p ) {
var defaults = {
'key': false
};
p = $.extend( true, defaults, p );
// next cell of current row
var next_cell = t.state.current_cell_obj
.next( '.acf-table-body-cell, .acf-table-header-cell' );
// else if get next row
if ( next_cell.length === 0 ) {
next_cell = t.state.current_cell_obj
.parent()
.next( '.acf-table-body-row' )
.find( '.acf-table-body-cell')
.first();
}
// if next row, get first cell of that row
if ( next_cell.length !== 0 ) {
t.state.current_cell_obj = next_cell;
}
else {
t.state.current_cell_obj = false;
}
};
t.get_prev_table_cell = function( p ) {
var defaults = {
'key': false
};
p = $.extend( true, defaults, p );
// prev cell of current row
var table_obj = t.state.current_cell_obj.closest( '.acf-table-table' ),
no_header = table_obj.hasClass( 'acf-table-hide-header' );
prev_cell = t.state.current_cell_obj
.prev( '.acf-table-body-cell, .acf-table-header-cell' );
// else if get prev row
if ( prev_cell.length === 0 ) {
var row_selectors = [ '.acf-table-body-row' ];
// prevents going to header cell if table header is hidden
if ( no_header === false ) {
row_selectors.push( '.acf-table-header-row' );
}
prev_cell = t.state.current_cell_obj
.parent()
.prev( row_selectors.join( ',' ) )
.find( '.acf-table-body-cell, .acf-table-header-cell' )
.last();
}
// if next row, get first cell of that row
if ( prev_cell.length !== 0 ) {
t.state.current_cell_obj = prev_cell;
}
else {
t.state.current_cell_obj = false;
}
};
t.cell_editor_save = function() {
var cell_editor = t.obj.body.find( '.acf-table-cell-editor' ),
cell_editor_textarea = cell_editor.find( '.acf-table-cell-editor-textarea' ),
p = {},
cell_editor_val = '';
if ( typeof cell_editor_textarea.val() !== 'undefined' ) {
p.obj_root = cell_editor.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
var cell_editor_val = cell_editor_textarea.val();
// prevent XSS injection
cell_editor_val = cell_editor_val.replace( /\<(script)/ig, '<$1' );
cell_editor_val = cell_editor_val.replace( /\<\/(script)/ig, '</$1' );
cell_editor.next().html( cell_editor_val );
t.table_build_json( p );
cell_editor.remove();
t.state.cell_editor_is_open = false;
p.obj_root.find( '.acf-table-remove-col' ).show(),
p.obj_root.find( '.acf-table-remove-row' ).show();
}
};
t.cell_editor_tab_navigation = function() {
t.obj.body.on( 'keydown', '.acf-table-cell-editor', function( e ) {
var keyCode = e.keyCode || e.which;
if ( keyCode == 9 ) {
e.preventDefault();
t.cell_editor_save();
if ( t.state.cell_editor_last_keycode === 16 ) {
t.get_prev_table_cell();
}
else {
t.get_next_table_cell();
}
t.cell_editor_add_editor({
'that': t.state.current_cell_obj
});
}
t.state.cell_editor_last_keycode = keyCode;
});
};
t.prevent_cell_links = function() {
t.obj.body.on( 'click', '.acf-table-body-cont a, .acf-table-header-cont a', function( e ) {
e.preventDefault();
} );
};
t.sortable_fix_width = function(e, ui) {
ui.children().each( function() {
var that = $( this );
that.width( that.width() );
} );
return ui;
};
t.sortable_row = function() {
var param = {
axis: 'y',
items: '> .acf-table-body-row',
containment: 'parent',
handle: '.acf-table-body-left',
helper: t.sortable_fix_width,
update: function( event, ui ) {
var p = {};
p.obj_root = ui.item.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
t.table_left_labels( p );
t.table_build_json( p );
},
};
$( '.acf-table-table' ).sortable( param );
};
t.sortable_col = function() {
var p = {};
p.start_index = 0;
p.end_index = 0;
var param = {
axis: 'x',
items: '> .acf-table-top-cell',
containment: 'parent',
helper: t.sortable_fix_width,
start: function(event, ui) {
p.start_index = ui.item.index();
},
update: function( event, ui ) {
p.end_index = ui.item.index();
p.obj_root = ui.item.parents( '.acf-table-root' );
p.obj_table = p.obj_root.find( '.acf-table-table' );
t.table_top_labels( p );
t.sort_cols( p );
t.table_build_json( p );
},
};
$( '.acf-table-top-row' ).sortable( param );
t.obj.body.on( 'click', '.acf-fc-popup', function() {
$( '.acf-table-top-row' )
.sortable('destroy')
.unbind();
window.setTimeout( function() {
$( '.acf-table-top-row' ).sortable( param );
}, 300 );
} );
};
t.field_changed = function( p ) {
if ( p.field_context === 'block' ) {
p.obj_root.change();
}
};
t.sort_cols = function( p ) {
p.obj_table.find('.acf-table-header-row').each( function() {
p.header_row = $(this),
p.header_row_children = p.header_row.children();
if ( p.end_index < p.start_index ) {
$( p.header_row_children[ p.end_index ] ).before( $( p.header_row_children[ p.start_index ] ) );
}
if ( p.end_index > p.start_index ) {
$( p.header_row_children[ p.end_index ] ).after( $( p.header_row_children[ p.start_index ] ) );
}
} );
p.obj_table.find('.acf-table-body-row').each( function() {
p.body_row = $(this),
p.body_row_children = p.body_row.children();
if ( p.end_index < p.start_index ) {
$( p.body_row_children[ p.end_index ] ).before( $( p.body_row_children[ p.start_index ] ) );
}
if ( p.end_index > p.start_index ) {
$( p.body_row_children[ p.end_index ] ).after( $( p.body_row_children[ p.start_index ] ) );
}
} );
};
t.helper = {
getLength: function( o ) {
var len = o.length ? --o.length : -1;
for (var k in o) {
len++;
}
return len;
},
};
};
var acf_table_field = new ACFTableField();
acf_table_field.init();
})( jQuery );
| johannheyne/acf-table | advanced-custom-fields-table-field/tags/1.3.4/js/input-v5.js | JavaScript | gpl-2.0 | 26,869 |
/**
* App Control
*
* Central controller attached to the top level <html>
* element
*/
"use strict";
( function ( angular, app ) {
// get user profile data
app.controller( "AppCtrl", [ '$rootScope', '$scope', '$state', 'UserService',
function ( $rootScope, $scope, $state, UserService ) {
//
// bodyClass definitions
//
// in a larger project this would be abstracted to allow for multiple
// classes to easily be added or removed
//
// current state
$rootScope.$on( '$stateChangeStart',
function ( event, toState, toParams, fromState, fromParams ) {
var currentState = toState.name.replace( '.', '-' );
$scope.bodyClass = 'state-' + currentState;
}
);
/**
* Format Avatar
*/
$scope.currentUserAvatar = function ( src, size ) {
return UserService.getCurrentUserAvatar( size );
};
}
] );
} )( angular, SimplySocial ); | Kevinlearynet/angular-trial-app | scripts/controllers/app-controller.js | JavaScript | gpl-2.0 | 901 |
'use strict';
/**
* @ngdoc function
* @name quickNewsApp.controller:CbcCtrl
* @description
* # CbcCtrl
* Controller of the quickNewsApp
*/
angular.module('quickNewsApp')
.controller('CbcCtrl', function ($scope, $http) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.postLimit = 10;
$scope.showMorePosts = function() {
$scope.postLimit += 5;
};
$scope.isSet = function(checkTab) {
return this.tab === checkTab;
};
$scope.setTab = function(activeTab) {
this.tab = activeTab;
$scope.postLimit = 10;
$scope.getFeed(activeTab);
};
$scope.getActiveTab = function() {
return this.tab;
};
$scope.getFeed = function(category) {
/*jshint unused: false */
$scope.loading = true;
var url = '//quicknews.amanuppal.ca:5000/cbc?url=' + category;
$http.get(url)
.success(function(data, status, headers, config) {
$scope.entries = data.items;
console.log($scope.entries);
$scope.numEntries = Object.keys($scope.entries).length;
$scope.loading = false;
})
.error(function(data, status, headers, config) {
console.log('Error loading feed: ' + url + ', status: ' + status);
});
};
});
| amtux/quick-news | app/scripts/controllers/cbc.js | JavaScript | gpl-2.0 | 1,204 |
/*! jQuery UI - v1.8.20 - 2012-04-30
* https://github.com/jquery/jquery-ui
* Includes: jquery.effects.transfer.js
* Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */(function(a,b){a.effects.transfer=function(b){return this.queue(function(){var c=a(this),d=a(b.options.to),e=d.offset(),f={top:e.top,left:e.left,height:d.innerHeight(),width:d.innerWidth()},g=c.offset(),h=a('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(b.options.className).css({top:g.top,left:g.left,height:c.innerHeight(),width:c.innerWidth(),position:"absolute"}).animate(f,b.duration,b.options.easing,function(){h.remove(),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}})(jQuery); | gustavoguichard/simsimultaneas | wp-includes/js/jquery/jquery.effects.transfer.min-ck.js | JavaScript | gpl-2.0 | 697 |
module.exports = {
dist: {
options: {
plugin_slug: 'simple-user-adding',
svn_user: 'wearerequired',
build_dir: 'release/svn/',
assets_dir: 'assets/'
}
}
};
| wearerequired/simple-user-adding | grunt/wp_deploy.js | JavaScript | gpl-2.0 | 180 |
/**
* The routes worker process
*
* This worker process gets the app routes by running the application dynamically
* on the server, then stores the publicly exposed routes in an intermediate format
* (just the url paths) in Redis.
* From there, the paths are used by the live app for serving /sitemap.xml and /robots.txt requests.
* The paths are also used by downstream worker processes (snapshots) to produce the site's html snapshots
* for _escaped_fragment_ requests.
*
* Run this worker anytime the app menu has changed and needs to be refreshed.
*
* PATH and NODE_ENV have to set in the environment before running this.
* PATH has to include phantomjs bin
*/
var phantom = require("node-phantom");
var urlm = require("url");
var redis = require("../../../helpers/redis");
var configLib = require("../../../config");
var config = configLib.create();
// Write the appRoutes to Redis
function writeAppRoutes(appRoutes) {
// remove pattern routes, and prepend /
appRoutes = appRoutes.filter(function(appRoute) {
return !/[*\(\:]/.test(appRoute);
}).map(function(appRoute) {
return "/"+appRoute;
});
if (appRoutes.length > 0) {
var redisClient = redis.client();
redisClient.set(config.keys.routes, appRoutes, function(err) {
if (err) {
console.error("failed to store the routes for "+config.keys.routes);
} else {
console.log("successfully stored "+appRoutes.length+" routes in "+config.keys.routes);
}
redisClient.quit();
});
} else {
console.error("no routes found for "+config.app.hostname);
}
}
// Start up phantom, wait for the page, get the appRoutes
function routes(urlPath, timeout) {
var url = urlm.format({
protocol: "http",
hostname: config.app.hostname,
port: config.app.port || 80,
pathname: urlPath
});
phantom.create(function(err, ph) {
return ph.createPage(function(err, page) {
return page.open(url, function(err, status) {
if (status !== "success") {
console.error("Unable to load page " + url);
ph.exit();
} else {
setTimeout(function() {
return page.evaluate(function() {
return window.wpspa.appRoutes;
}, function(err, result) {
if (err) {
console.error("failed to get appRoutes");
} else {
writeAppRoutes(Object.keys(result));
}
ph.exit();
});
}, timeout);
}
});
});
});
}
module.exports = {
routes: routes
}; | localnerve/wpspa | server/workers/routes/lib/index.js | JavaScript | gpl-2.0 | 2,589 |
jQuery('#bootstrapslider').carousel({
interval: bootstrapslider_script_vars.interval,
pause: bootstrapslider_script_vars.pause,
wrap: bootstrapslider_script_vars.wrap
});
| bassjobsen/twitter-bootstrap-slider | js/bootstrapslider.js | JavaScript | gpl-2.0 | 177 |
/**
* Setup (required for Joomla! 3)
*/
if(typeof(akeeba) == 'undefined') {
var akeeba = {};
}
if(typeof(akeeba.jQuery) == 'undefined') {
akeeba.jQuery = jQuery.noConflict();
}
akeeba.jQuery(document).ready(function($){
function atsAssignmentClick()
{
var parent = akeeba.jQuery(this).parent('td');
var id = akeeba.jQuery(this).parents('td').find('input.ticket_id').val();
var hide = ['.loading img', '.loading .icon-warning-sign'];
var show = ['.loading .icon-ok'];
var assign_to = 0;
if(akeeba.jQuery(this).hasClass('assignme'))
{
assign_to = akeeba.jQuery('#user').val();
}
else if(akeeba.jQuery(this).parent('.assignto'))
{
assign_to = akeeba.jQuery(this).parent().find('input.assignto').val();
}
if(this.hasClass('unassign')){
hide.push('.unassign');
show.push('.assignme');
}
else{
hide.push('.assignme');
show.push('.unassign');
}
var structure = {
_rootElement: this,
type: "POST",
dataType: 'json',
url : ATS_ROOT_URL + 'index.php?option=com_ats&view=ticket&format=json&' + akeeba.jQuery('#token').attr('name') + '=1',
data: {
'task' : 'assign',
'id' : id,
'assigned_to' : assign_to
},
beforeSend: function() {
var wait = akeeba.jQuery(this._rootElement).parents('td').find('.loading');
wait.css('display','inline').find('i').css('display', 'none');
wait.find('img').css('display', 'inline-block');
},
success: function(responseJSON)
{
var assigned = akeeba.jQuery(this._rootElement).parents('td').find('.assigned_to');
var unassign = akeeba.jQuery(this._rootElement).hasClass('unassign');
if(responseJSON.result == true){
assigned.html(responseJSON.assigned);
unassign ? assigned.removeClass('badge-info') : assigned.addClass('badge-info');
for (var i = 0; i < hide.length; i++)
{
var elementDefinition = hide[i];
akeeba.jQuery(this._rootElement).parents('td').find(elementDefinition).css('display', 'none');
}
for (var i = 0; i < show.length; i++)
{
var elementDefinition = show[i];
akeeba.jQuery(this._rootElement).parents('td').find(elementDefinition).css('display', 'inline-block');
}
}
else
{
var wait = akeeba.jQuery(this._rootElement).parents('td').find('.loading');
wait.find('.icon-ok,img').css('display', 'none');
wait.find('.icon-warning-sign').show('fast');
}
}
};
akeeba.jQuery.ajax( structure );
}
akeeba.jQuery('.unassign a').click(atsAssignmentClick);
akeeba.jQuery('.assignme a').click(atsAssignmentClick);
akeeba.jQuery('.assignto li a').click(atsAssignmentClick);
akeeba.jQuery('.select-status li a').click(function(){
var image = akeeba.jQuery(this).parent().find('img');
var self = this;
akeeba.jQuery.ajax(ATS_ROOT_URL + 'index.php?option=com_ats&view=tickets&task=ajax_set_status&format=json&'+jQuery('#token').attr('name')+'=1',{
type : 'POST',
dataType : 'json',
data : {
'id' : akeeba.jQuery(this).parents('tr').find('.ats_ticket_id').val(),
'status' : akeeba.jQuery(this).data('status')
},
beforeSend : function(){
image.show();
},
success : function(responseJSON){
image.hide();
if(responseJSON.err){
alert(responseJSON.err);
}
else{
var label = akeeba.jQuery(self).parents('td').find('span[class*="label-"]');
label.attr('class', 'ats-status label pull-right ' + responseJSON.ats_class).html(responseJSON.msg);
}
}
})
})
}); | SirPiter/folk | www/media/com_ats/js/tickets.js | JavaScript | gpl-2.0 | 3,563 |
/**
* Created by LPAC006013 on 23/11/14.
*/
/*
* wiring Super fish to menu
*/
var sfvar = jQuery('div.menu');
var phoneSize = 600;
jQuery(document).ready(function($) {
//if screen size is bigger than phone's screen (Tablet,Desktop)
if($(document).width() >= phoneSize) {
// enable superfish
sfvar.superfish({
delay: 500,
speed: 'slow'
});
jQuery("#menu-main-menu").addClass('clear');
var containerheight = jQuery("#menu-main-menu").height();
jQuery("#menu-main-menu").children().css("height",containerheight);
}
$(window).resize(function() {
if($(document).width() >= phoneSize && !sfvar.hasClass('sf-js-enabled')) {
sfvar.superfish({
delay: 500,
speed: 'slow'
});
}
// phoneSize, disable superfish
else if($(document).width() < phoneSize) {
sfvar.superfish('destroy');
}
});
});
| dejanmarkovic/topcat-final | js/global.js | JavaScript | gpl-2.0 | 994 |
var ajaxManager = (function() {
$jq = jQuery.noConflict();
var requests = [];
return {
addReq: function(opt) {
requests.push(opt);
},
removeReq: function(opt) {
if($jq.inArray(opt, requests) > -1) {
requests.splice($jq.inArray(opt, requests), 1);
}
},
run: function() {
var self = this, orgSuc;
if(requests.length) {
oriSuc = requests[0].complete;
requests[0].complete = function() {
if(typeof oriSuc === 'function') {
oriSuc();
}
requests.shift();
self.run.apply(self, []);
};
$jq.ajax(requests[0]);
} else {
self.tid = setTimeout(function() {
self.run.apply(self, []);
}, 1000);
}
},
stop: function() {
requests = [];
clearTimeout(this.tid);
}
};
}());
ajaxManager.run();
(function($){
$(document).ready(function(){
$('.purAddToCart, .purAddToCartImage').click(function() {
$(this).attr('disabled', 'disabled');
})
$('.Cart66AjaxWarning').hide();
// Added to remove error on double-click when add to cart is clicked
$('.purAddToCart, .purAddToCartImage').click(function() {
$(this).attr('disabled', 'disabled');
})
$('.ajax-button').click(function() {
$(this).attr('disabled', true);
var id = $(this).attr('id').replace('addToCart_', '');
$('#task_' + id).val('ajax');
var product = C66.products[id];
if(C66.trackInventory) {
inventoryCheck(id, C66.ajaxurl, product.ajax, product.name, product.returnUrl, product.addingText);
}
else {
if(product.ajax === 'no') {
$('#task_' + id).val('addToCart');
$('#cartButtonForm_' + id).submit();
return false;
}
else if(product.ajax === 'yes' || product.ajax === 'true') {
buttonTransform(id, C66.ajaxurl, product.name, product.returnUrl, product.addingText);
}
}
return false;
});
$('.modalClose').click(function() {
$('.Cart66Unavailable, .Cart66Warning, .Cart66Error, .alert-message').fadeOut(800);
});
$('#Cart66CancelPayPalSubscription').click(function() {
return confirm('Are you sure you want to cancel your subscription?\n');
});
var original_methods = $('#shipping_method_id').html();
var selected_country = $('#shipping_country_code').val();
$('.methods-country').each(function() {
if(!$(this).hasClass(selected_country) && !$(this).hasClass('all-countries') && !$(this).hasClass('select')) {
$(this).remove();
}
});
$('#shipping_country_code').change(function() {
var selected_country = $(this).val();
$('#shipping_method_id').html(original_methods);
$('.methods-country').each(function() {
if(!$(this).hasClass(selected_country) && !$(this).hasClass('all-countries') && !$(this).hasClass('select')) {
$(this).remove();
}
});
$("#shipping_method_id option:eq(1)").attr('selected','selected').change();
});
$('#shipping_method_id').change(function() {
$('#Cart66CartForm').submit();
});
$('#live_rates').change(function() {
$('#Cart66CartForm').submit();
});
$('.showEntriesLink').click(function() {
var panel = $(this).attr('rel');
$('#' + panel).toggle();
return false;
});
$('#change_shipping_zip_link').click(function() {
$('#set_shipping_zip_row').toggle();
return false;
});
})
})(jQuery);
function getCartButtonFormData(formId) {
$jq = jQuery.noConflict();
var theForm = $jq('#' + formId);
var str = '';
$jq('input:not([type=checkbox], :radio), input[type=checkbox]:checked, input:radio:checked, select, textarea', theForm).each(
function() {
var name = $jq(this).attr('name');
var val = $jq(this).val();
str += name + '=' + encodeURIComponent(val) + '&';
}
);
return str.substring(0, str.length-1);
}
function inventoryCheck(formId, ajaxurl, useAjax, productName, productUrl, addingText) {
$jq = jQuery.noConflict();
var mydata = getCartButtonFormData('cartButtonForm_' + formId);
ajaxManager.addReq({
type: "POST",
url: ajaxurl + '=1',
data: mydata,
dataType: 'json',
success: function(response) {
if(response[0]) {
$jq('#task_' + formId).val('addToCart');
if(useAjax == 'no') {
$jq('#cartButtonForm_' + formId).submit();
}
else {
buttonTransform(formId, ajaxurl, productName, productUrl, addingText);
}
}
else {
$jq('.modalClose').show();
$jq('#stock_message_box_' + formId).fadeIn(300);
$jq('#stock_message_' + formId).html(response[1]);
$jq('#addToCart_' + formId).removeAttr('disabled');
}
},
error: function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
}
});
}
function addToCartAjax(formId, ajaxurl, productName, productUrl, buttonText) {
$jq = jQuery.noConflict();
var options1 = $jq('#cartButtonForm_' + formId + ' .cart66Options.options_1').val();
var options2 = $jq('#cartButtonForm_' + formId + ' .cart66Options.options_2').val();
var itemQuantity = $jq('#Cart66UserQuantityInput_' + formId).val();
var itemUserPrice = $jq('#Cart66UserPriceInput_' + formId).val();
var cleanProductId = formId.split('_');
cleanProductId = cleanProductId[0];
var data = {
cart66ItemId: cleanProductId,
itemName: productName,
options_1: options1,
options_2: options2,
item_quantity: itemQuantity,
item_user_price: itemUserPrice,
product_url: productUrl
};
ajaxManager.addReq({
type: "POST",
url: ajaxurl + '=2',
data: data,
dataType: 'json',
success: function(response) {
$jq('#addToCart_' + formId).removeAttr('disabled');
$jq('#addToCart_' + formId).removeClass('ajaxPurAddToCart');
$jq('#addToCart_' + formId).val(buttonText);
$jq.hookExecute('addToCartAjaxHook', response);
ajaxUpdateCartWidgets(ajaxurl);
if($jq('.customAjaxAddToCartMessage').length > 0) {
$jq('.customAjaxAddToCartMessage').show().html(response.msg);
$jq.hookExecute('customAjaxAddToCartMessage', response);
}
else {
if((response.msgId) == 0){
$jq('.success_' + formId).fadeIn(300);
$jq('.success_message_' + formId).html(response.msg);
if(typeof response.msgHeader !== 'undefined') {
$jq('.success' + formId + ' .message-header').html(response.msgHeader);
}
$jq('.success_' + formId).delay(2000).fadeOut(300);
}
if((response.msgId) == -1){
$jq('.warning_' + formId).fadeIn(300);
$jq('.warning_message_' + formId).html(response.msg);
if(typeof response.msgHeader !== 'undefined') {
$jq('.warning' + formId + ' .message-header').html(response.msgHeader);
}
}
if((response.msgId) == -2){
$jq('.error_' + formId).fadeIn(300);
$jq('.error_message_' + formId).html(response.msg);
if(typeof response.msgHeader !== 'undefined') {
$jq('.error_' + formId + ' .message-header').html(response.msgHeader);
}
}
}
}
})
}
function buttonTransform(formId, ajaxurl, productName, productUrl, addingText) {
$jq = jQuery.noConflict();
var buttonText = $jq('#addToCart_' + formId).val();
$jq('#addToCart_' + formId).attr('disabled', 'disabled');
$jq('#addToCart_' + formId).addClass('ajaxPurAddToCart');
$jq('#addToCart_' + formId).val(addingText);
addToCartAjax(formId, ajaxurl, productName, productUrl, buttonText);
}
function ajaxUpdateCartWidgets(ajaxurl) {
$jq = jQuery.noConflict();
var widgetId = $jq('.Cart66CartWidget').attr('id');
var data = {
action: "ajax_cart_elements"
};
ajaxManager.addReq({
type: "POST",
url: ajaxurl + '=3',
data: data,
dataType: 'json',
success: function(response) {
$jq.hookExecute('cartElementsAjaxHook', response);
$jq('#Cart66AdvancedSidebarAjax, #Cart66WidgetCartContents').show();
$jq('.Cart66WidgetViewCartCheckoutEmpty, #Cart66WidgetCartEmpty').hide();
$jq('#Cart66WidgetCartLink').each(function(){
widgetContent = "<span id=\"Cart66WidgetCartCount\">" + response.summary.count + "</span>";
widgetContent += "<span id=\"Cart66WidgetCartCountText\">" + response.summary.items + "</span>";
widgetContent += "<span id=\"Cart66WidgetCartCountDash\"> – </span>"
widgetContent += "<span id=\"Cart66WidgetCartPrice\">" + response.summary.amount + "</span>";
$jq(this).html(widgetContent).fadeIn('slow');
});
$jq('.Cart66RequireShipping').each(function(){
if(response.shipping == 1) {
$jq(this).show();
}
})
$jq('#Cart66WidgetCartEmptyAdvanced').each(function(){
widgetContent = C66.youHave + ' ' + response.summary.count + " " + response.summary.items + " (" + response.summary.amount + ") " + C66.inYourShoppingCart;
$jq(this).html(widgetContent).fadeIn('slow');
});
$jq("#Cart66AdvancedWidgetCartTable .product_items").remove();
$jq.each(response.products.reverse(), function(index, array){
widgetContent = "<tr class=\"product_items\"><td>";
widgetContent += "<span class=\"Cart66ProductTitle\">" + array.productName + "</span>";
widgetContent += "<span class=\"Cart66QuanPrice\">";
widgetContent += "<span class=\"Cart66ProductQuantity\">" + array.productQuantity + "</span>";
widgetContent += "<span class=\"Cart66MetaSep\"> x </span>";
widgetContent += "<span class=\"Cart66ProductPrice\">" + array.productPrice + "</span>";
widgetContent += "</span>";
widgetContent += "</td><td class=\"Cart66ProductSubtotalColumn\">";
widgetContent += "<span class=\"Cart66ProductSubtotal\">" + array.productSubtotal + "</span>";
widgetContent += "</td></tr>";
$jq("#Cart66AdvancedWidgetCartTable tbody").prepend(widgetContent).fadeIn("slow");
});
$jq('.Cart66Subtotal').each(function(){
$jq(this).html(response.subtotal)
});
$jq('.Cart66Shipping').each(function(){
$jq(this).html(response.shippingAmount)
});
}
})
}
jQuery.extend({
hookExecute: function (function_name, response){
if (typeof window[function_name] == "function"){
window[function_name](response);
return true;
}
else{
return false;
}
}
}); | rbredow/allyzabbacart | js/cart66-library.js | JavaScript | gpl-2.0 | 10,666 |
var express = require('express');
var path = require('path');
var tilestrata = require('tilestrata');
var disk = require('tilestrata-disk');
var mapnik = require('tilestrata-mapnik');
var dependency = require('tilestrata-dependency');
var strata = tilestrata();
var app = express();
// define layers
strata.layer('hillshade')
.route('shade.png')
.use(disk.cache({dir: './tiles/shade/'}))
.use(mapnik({
pathname: './styles/hillshade.xml',
tileSize: 256,
scale: 1
}));
strata.layer('dem')
.route('dem.png')
.use(disk.cache({dir: './tiles/dem/'}))
.use(mapnik({
pathname: './styles/dem.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim1')
.route('sim1.png')
.use(disk.cache({dir: './tiles/sim1/'}))
.use(mapnik({
pathname: './styles/sim1.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim2')
.route('sim2.png')
.use(disk.cache({dir: './tiles/sim2/'}))
.use(mapnik({
pathname: './styles/sim2.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim3')
.route('sim3.png')
.use(disk.cache({dir: './tiles/sim3/'}))
.use(mapnik({
pathname: './styles/sim3.xml',
tileSize: 256,
scale: 1
}));
strata.layer('slope')
.route('slope.png')
.use(disk.cache({dir: './tiles/slope/'}))
.use(mapnik({
pathname: './styles/slope.xml',
tileSize: 256,
scale: 1
}));
var staticPath = path.resolve(__dirname, './public/');
app.use(express.static(staticPath));
app.use(tilestrata.middleware({
server: strata,
prefix: ''
}));
app.listen(8080, function() {
console.log('Express server running on port 8080.');
});
| nronnei/srtm-server | app.js | JavaScript | gpl-2.0 | 1,877 |
/* ========================================================================
* Bootstrap: alert.js v3.0.3
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2013 Twitter, 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.
* ======================================================================== */
+function($) {
"use strict";
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function(element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.DEFAULTS = {
animation: true
, placement: 'top'
, selector: false
, template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
, trigger: 'hover focus'
, title: ''
, delay: 0
, html: false
, container: false
}
Tooltip.prototype.init = function(type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--; ) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, {trigger: 'manual', selector: ''})) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function() {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function(options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay
, hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function() {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function(key, value) {
if (defaults[key] != value)
options[key] = value
})
return options
}
Tooltip.prototype.enter = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show)
return self.show()
self.timeout = setTimeout(function() {
if (self.hoverState == 'in')
self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide)
return self.hide()
self.timeout = setTimeout(function() {
if (self.hoverState == 'out')
self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function() {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
if (e.isDefaultPrevented())
return
var $tip = this.tip()
this.setContent()
if (this.options.animation)
$tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace)
placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({top: 0, left: 0, display: 'block'})
.addClass(placement)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var $parent = this.$element.parent()
var orgPlacement = placement
var docScroll = document.documentElement.scrollTop || document.body.scrollTop
var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth()
var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
this.$element.trigger('shown.bs.' + this.type)
}
}
Tooltip.prototype.applyPlacement = function(offset, placement) {
var replace
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop))
marginTop = 0
if (isNaN(marginLeft))
marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
$tip
.offset(offset)
.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
replace = true
offset.top = offset.top + height - actualHeight
}
if (/bottom|top/.test(placement)) {
var delta = 0
if (offset.left < 0) {
delta = offset.left * -2
offset.left = 0
$tip.offset(offset)
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
}
this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
} else {
this.replaceArrow(actualHeight - height, actualHeight, 'top')
}
if (replace)
$tip.offset(offset)
}
Tooltip.prototype.replaceArrow = function(delta, dimension, position) {
this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
}
Tooltip.prototype.setContent = function() {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function() {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in')
$tip.detach()
}
this.$element.trigger(e)
if (e.isDefaultPrevented())
return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one($.support.transition.end, complete)
.emulateTransitionEnd(150) :
complete()
this.$element.trigger('hidden.bs.' + this.type)
return this
}
Tooltip.prototype.fixTitle = function() {
var $e = this.$element
if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function() {
return this.getTitle()
}
Tooltip.prototype.getPosition = function() {
var el = this.$element[0]
return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
width: el.offsetWidth
, height: el.offsetHeight
}, this.$element.offset())
}
Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} :
placement == 'top' ? {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} :
placement == 'left' ? {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} :
/* placement == 'right' */ {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
}
Tooltip.prototype.getTitle = function() {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.tip = function() {
return this.$tip = this.$tip || $(this.options.template)
}
Tooltip.prototype.arrow = function() {
return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')
}
Tooltip.prototype.validate = function() {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
Tooltip.prototype.enable = function() {
this.enabled = true
}
Tooltip.prototype.disable = function() {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function() {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function(e) {
var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function() {
this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
}
// TOOLTIP PLUGIN DEFINITION
// =========================
var old = $.fn.tooltip
$.fn.tooltip = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data)
$this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function() {
$.fn.tooltip = old
return this
}
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function(el) {
$(el).on('click', dismiss, this.close)
}
Alert.prototype.close = function(e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e)
e.preventDefault()
if (!$parent.length) {
$parent = $this.hasClass('alert') ? $this : $this.parent()
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented())
return
$parent.removeClass('in')
function removeElement() {
$parent.trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one($.support.transition.end, removeElement)
.emulateTransitionEnd(150) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
var old = $.fn.alert
$.fn.alert = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data)
$this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string')
data[option].call($this)
})
}
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function() {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.0.3
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2013 Twitter, 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.
* ======================================================================== */
+function($) {
"use strict";
// TAB CLASS DEFINITION
// ====================
var Tab = function(element) {
this.element = $(element)
}
Tab.prototype.show = function() {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ($this.parent('li').hasClass('active'))
return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented())
return
var $target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function() {
$this.trigger({
type: 'shown.bs.tab'
, relatedTarget: previous
})
})
}
Tab.prototype.activate = function(element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active
.one($.support.transition.end, next)
.emulateTransitionEnd(150) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
var old = $.fn.tab
$.fn.tab = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data)
$this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function() {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function(e) {
e.preventDefault()
$(this).tab('show')
})
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.0.3
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2013 Twitter, 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.
* ======================================================================== */
+function($) {
"use strict";
// AFFIX CLASS DEFINITION
// ======================
var Affix = function(element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$window = $(window)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin = null
this.checkPosition()
}
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0
}
Affix.prototype.checkPositionWithEventLoop = function() {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function() {
if (!this.$element.is(':visible'))
return
var scrollHeight = $(document).height()
var scrollTop = this.$window.scrollTop()
var position = this.$element.offset()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
if (typeof offset != 'object')
offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function')
offsetTop = offset.top()
if (typeof offsetBottom == 'function')
offsetBottom = offset.bottom()
var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false
if (this.affixed === affix)
return
if (this.unpin)
this.$element.css('top', '')
this.affixed = affix
this.unpin = affix == 'bottom' ? position.top - scrollTop : null
this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : ''))
if (affix == 'bottom') {
this.$element.offset({top: document.body.offsetHeight - offsetBottom - this.$element.height()})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
var old = $.fn.affix
$.fn.affix = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data)
$this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function() {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function() {
$('[data-spy="affix"]').each(function() {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom)
data.offset.bottom = data.offsetBottom
if (data.offsetTop)
data.offset.top = data.offsetTop
$spy.affix(data)
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.0.3
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2013 Twitter, 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.
* ======================================================================== */
+function($) {
"use strict";
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.transitioning = null
if (this.options.parent)
this.$parent = $(this.options.parent)
if (this.options.toggle)
this.toggle()
}
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function() {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function() {
if (this.transitioning || this.$element.hasClass('in'))
return
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented())
return
var actives = this.$parent && this.$parent.find('> .panel > .in')
if (actives && actives.length) {
var hasData = actives.data('bs.collapse')
if (hasData && hasData.transitioning)
return
actives.collapse('hide')
hasData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')
[dimension](0)
this.transitioning = 1
var complete = function() {
this.$element
.removeClass('collapsing')
.addClass('in')
[dimension]('auto')
this.transitioning = 0
this.$element.trigger('shown.bs.collapse')
}
if (!$.support.transition)
return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function() {
if (this.transitioning || !this.$element.hasClass('in'))
return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented())
return
var dimension = this.dimension()
this.$element
[dimension](this.$element[dimension]())
[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse')
.removeClass('in')
this.transitioning = 1
var complete = function() {
this.transitioning = 0
this.$element
.trigger('hidden.bs.collapse')
.removeClass('collapsing')
.addClass('collapse')
}
if (!$.support.transition)
return complete.call(this)
this.$element
[dimension](0)
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
}
Collapse.prototype.toggle = function() {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
var old = $.fn.collapse
$.fn.collapse = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data)
$this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function() {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function(e) {
var $this = $(this), href
var target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
var $target = $(target)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
var parent = $this.attr('data-parent')
var $parent = parent && $(parent)
if (!data || !data.transitioning) {
if ($parent)
$parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed')
$this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
}
$target.collapse(option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.0.3
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2013 Twitter, 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.
* ======================================================================== */
+function($) {
"use strict";
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var href
var process = $.proxy(this.process, this)
this.$element = $(element).is('body') ? $(window) : $(element)
this.$body = $('body')
this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.offsets = $([])
this.targets = $([])
this.activeTarget = null
this.refresh()
this.process()
}
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.refresh = function() {
var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
this.offsets = $([])
this.targets = $([])
var self = this
var $targets = this.$body
.find(this.selector)
.map(function() {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#\w/.test(href) && $(href)
return ($href
&& $href.length
&& [[$href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href]]) || null
})
.sort(function(a, b) {
return a[0] - b[0]
})
.each(function() {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function() {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
var maxScroll = scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0]) && this.activate(i)
}
for (i = offsets.length; i--; ) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function(target) {
this.activeTarget = target
$(this.selector)
.parents('.active')
.removeClass('active')
var selector = this.selector
+ '[data-target="' + target + '"],'
+ this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
var old = $.fn.scrollspy
$.fn.scrollspy = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data)
$this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function() {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load', function() {
$('[data-spy="scroll"]').each(function() {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.0.3
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2013 Twitter, 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.
* ======================================================================== */
+function($) {
"use strict";
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd'
, 'MozTransition': 'transitionend'
, 'OTransition': 'oTransitionEnd otransitionend'
, 'transition': 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return {end: transEndEventNames[name]}
}
}
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function(duration) {
var called = false, $el = this
$(this).one($.support.transition.end, function() {
called = true
})
var callback = function() {
if (!called)
$($el).trigger($.support.transition.end)
}
setTimeout(callback, duration)
return this
}
$(function() {
$.support.transition = transitionEnd()
})
}(jQuery);
| nick144/Tournaments | js/bootstrap.js | JavaScript | gpl-2.0 | 36,381 |
var express = require('express'),
Weapon = require('../models/Weapon'),
router = express.Router();
// HOMEPAGE
router.get('/', function(req, res) {
res.render('index', {
title:'Weapons Guide | Fire Emblem | Awakening',
credit: 'Matt.Dodson.Digital',
msg: 'Hello Word!'
});
});
// WEAPON
router.get('/weapon', function(req, res) {
var schema = {};
Weapon.schema.eachPath(function (pathname, schemaType) {
schema[pathname] = schemaType.instance;
});
res.render('weapon', {
title:'Weapons Guide | Fire Emblem | Awakening',
credit: 'Matt.Dodson.Digital',
msg: 'This is a form.',
schema: schema
});
});
module.exports = router;
| dodsonm/fire-emblem-awakening | routes/index.js | JavaScript | gpl-2.0 | 717 |
Package.describe({
summary: "Next bike list package"
});
Package.on_use(function (api) {
api.use(['nb','underscore', 'templating', 'nb-autocomplete', 'nb-markers', 'nb-infowindow', 'nb-directions', 'nb-geocoder', 'nb-markerlabel', 'nb-citypicker'], ['client']);
api.add_files(['list.html', 'list.js'], ['client']);
});
| wolasss/nextbike-poland | packages/nb-list/package.js | JavaScript | gpl-2.0 | 326 |
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Mecab = require('mecab-async');
var mecab = new Mecab();
var MarkovChain = function () {
function MarkovChain(text) {
_classCallCheck(this, MarkovChain);
this.text = text;
this.result = null;
this.dictionary = {};
this.output = 'output';
}
_createClass(MarkovChain, [{
key: 'start',
value: function start(sentence, callback) {
this.parse(sentence, callback);
}
}, {
key: 'parse',
value: function parse(sentence, callback) {
var _this = this;
mecab.parse(this.text, function (err, result) {
_this.dictionary = _this.makeDic(result);
_this.makeSentence(_this.dictionary, sentence);
callback(_this.output);
});
}
}, {
key: 'makeDic',
value: function makeDic(items) {
var tmp = ['@'];
var dic = {};
for (var i in items) {
var t = items[i];
var word = t[0];
word = word.replace(/\s*/, '');
if (word == '' || word == 'EOS') continue;
tmp.push(word);
if (tmp.length < 3) continue;
if (tmp.length > 3) tmp.splice(0, 1);
this.setWord3(dic, tmp);
if (word == '。') {
tmp = ['@'];
continue;
}
}
return dic;
}
}, {
key: 'setWord3',
value: function setWord3(p, s3) {
var w1 = s3[0];
var w2 = s3[1];
var w3 = s3[2];
if (p[w1] == undefined) p[w1] = {};
if (p[w1][w2] == undefined) p[w1][w2] = {};
if (p[w1][w2][w3] == undefined) p[w1][w2][w3] = 0;
p[w1][w2][w3]++;
}
}, {
key: 'makeSentence',
value: function makeSentence(dic, sentence) {
for (var i = 0; i < sentence; i++) {
var ret = [];
var top = dic['@'];
if (!top) continue;
var w1 = this.choiceWord(top);
var w2 = this.choiceWord(top[w1]);
ret.push(w1);
ret.push(w2);
for (;;) {
var w3 = this.choiceWord(dic[w1][w2]);
ret.push(w3);
if (w3 == '。') break;
w1 = w2, w2 = w3;
}
this.output = ret.join('');
return this.output;
}
}
}, {
key: 'objKeys',
value: function objKeys(obj) {
var r = [];
for (var i in obj) {
r.push(i);
}
return r;
}
}, {
key: 'choiceWord',
value: function choiceWord(obj) {
var ks = this.objKeys(obj);
var i = this.rnd(ks.length);
return ks[i];
}
}, {
key: 'rnd',
value: function rnd(num) {
return Math.floor(Math.random() * num);
}
}]);
return MarkovChain;
}();
module.exports = MarkovChain; | uraway/markov-chain-mecab | lib/index.js | JavaScript | gpl-2.0 | 3,365 |
/**************************************************
* Funkcje związane z geolokalizacją GPS
**************************************************/
WMB.Comment = {
/**
* Funkcja dodająca nowy komentarz do zgłoszenia
*
* @method onAddSubmit
*/
onAddSubmit: function(marker_id) {
if (WMB.User.isLoggedIn()) {
if ($('#add-comment-form')[0].checkValidity()) {
var post_data = new FormData();
post_data.append('user_id', parseInt(getCookie('user_id')));
post_data.append('marker_id', parseInt(marker_id));
post_data.append('comment', $('#comment').val());
$.ajax({
url: REST_API_URL + 'comment',
beforeSend: function(request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'POST',
cache: false,
processData: false,
contentType: false,
data: post_data,
success: function(s) {
$('#add-comment-modal').modal('hide');
bootbox.alert('Pomyślnie dodaną komentarz.', function() {
location.reload();
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#add-comment-modal').modal('hide');
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message);
}
});
}
} else {
bootbox.alert('Aby móc dodawać komentarze musisz być zalogowany.');
}
},
onEditClick: function(id) {
// Pobranie danych o komentarzu
$.ajax({
url: REST_API_URL + 'comment/id/' + id,
type: 'GET',
success: function(data) {
// Wstawienie danych do formularza
$('#comment_id').val(id);
$('#comment').val(data.comment);
$('#edit-comment-modal').modal('show');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message, function() {
window.location.href = WEBSITE_URL;
});
}
});
},
onEditSubmit: function() {
if ($('#edit-comment-form')[0].checkValidity()) {
var comment_data = new FormData(),
comment_id = parseInt($('#comment_id').val()),
comment = $('#comment').val();
comment_data.append('comment', comment);
$.ajax({
url: REST_API_URL + 'comment/id/' + comment_id + '/edit',
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'POST',
cache: false,
processData: false,
contentType: false,
data: comment_data,
success: function(s) {
$('#edit-comment-modal').modal('hide');
bootbox.alert('Pomyślnie zedytowano komentarz.', function() {
window.location.href = WEBSITE_URL + 'comments';
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message);
}
});
}
},
onDeleteClick: function(id) {
$.ajax({
url: REST_API_URL + 'comment/id/' + id,
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'DELETE',
cache: false,
processData: false,
contentType: false,
success: function(data) {
$('#edit-comment-modal').modal('hide');
bootbox.alert('Pomyślnie usunięto komentarz.', function() {
location.reload();
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message, function() {
window.location.href = WEBSITE_URL;
});
}
});
},
/**
* Funkcja służąca do zmiany statusu komentarza
*
* @method changeStatus
* @param {Integer} id Identyfikator komentarza
* @param {Integer} status_id Identyfikator statusu
*/
changeStatus: function(id, status_id) {
if (WMB.User.isLoggedIn()) {
$.ajax({
url: REST_API_URL + 'comment/id/' + id + '/status/' + status_id,
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'PUT',
cache: false,
processData: false,
contentType: false,
success: function(data) {
if (status_id == 0) {
bootbox.alert('Pomyślnie zgłoszono nadużycie w komentarzu.', function() {
location.reload();
});
} else {
bootbox.alert('Pomyślnie zmieniono status komentarza na ' + comment_statuses[status_id] + '.', function() {
location.reload();
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message, function() {
window.location.href = WEBSITE_URL;
});
}
});
} else {
bootbox.alert('Aby zgłosić nadużycie musisz być zalogowany/a.');
}
},
/**
* Funkcja pobierająca wszystkie komentarze dla danego zgłoszenia
*
* @method getAll
* @param {Integer} marker_id Identyfikator zgłoszenia
*/
getAll: function(marker_id) {
$.ajax({
url: REST_API_URL + 'comment/marker/' + marker_id,
type: 'GET',
cache: false,
dataType: 'json',
success: function(data) {
$.each(data.comments, function(i) {
if (data.comments[i].status_id != 0 && data.comments[i].user_id == parseInt(getCookie('user_id'))) {
$('#marker-comment-list').append(
'<tr>' +
'<td>' + data.comments[i].login + '</td>' +
'<td>' + data.comments[i].date + '</td>' +
'<td>' + data.comments[i].comment + '</td>' +
'<td>brak</td>' +
'</tr>');
} else if (data.comments[i].status_id != 0) {
$('#marker-comment-list').append(
'<tr>' +
'<td>' + data.comments[i].login + '</td>' +
'<td>' + data.comments[i].date + '</td>' +
'<td>' + data.comments[i].comment + '</td>' +
'<td><a href="#" onclick="WMB.Comment.changeStatus(' + data.comments[i].comment_id + ', 0)">Zgłoś nadużycie</a></td>' +
'</tr>');
}
});
}
});
}
} | airwaves-pl/WroclawskaMapaBarier | web/lib/js/wmb.comment.js | JavaScript | gpl-2.0 | 5,969 |
;(function() {
/** Used to access the Firebug Lite panel (set by `run`). */
var fbPanel;
/** Used as a safe reference for `undefined` in pre ES5 environments. */
var undefined;
/** Used as a reference to the global object. */
var root = typeof global == 'object' && global || this;
/** Method and object shortcuts. */
var phantom = root.phantom,
amd = root.define && define.amd,
argv = root.process && process.argv,
document = !phantom && root.document,
noop = function() {},
params = root.arguments,
system = root.system;
/** Add `console.log()` support for Narwhal, Rhino, and RingoJS. */
var console = root.console || (root.console = { 'log': root.print });
/** The file path of the Lo-Dash file to test. */
var filePath = (function() {
var min = 0,
result = [];
if (phantom) {
result = params = phantom.args;
} else if (system) {
min = 1;
result = params = system.args;
} else if (argv) {
min = 2;
result = params = argv;
} else if (params) {
result = params;
}
var last = result[result.length - 1];
result = (result.length > min && !/perf(?:\.js)?$/.test(last)) ? last : '../lodash.js';
if (!amd) {
try {
result = require('fs').realpathSync(result);
} catch(e) {}
try {
result = require.resolve(result);
} catch(e) {}
}
return result;
}());
/** Used to match path separators. */
var rePathSeparator = /[\/\\]/;
/** Used to detect primitive types. */
var rePrimitive = /^(?:boolean|number|string|undefined)$/;
/** Used to match RegExp special characters. */
var reSpecialChars = /[.*+?^=!:${}()|[\]\/\\]/g;
/** The `ui` object. */
var ui = root.ui || (root.ui = {
'buildPath': basename(filePath, '.js'),
'otherPath': 'underscore'
});
/** The Lo-Dash build basename. */
var buildName = root.buildName = basename(ui.buildPath, '.js');
/** The other library basename. */
var otherName = root.otherName = (function() {
var result = basename(ui.otherPath, '.js');
return result + (result == buildName ? ' (2)' : '');
}());
/** Used to score performance. */
var score = { 'a': [], 'b': [] };
/** Used to queue benchmark suites. */
var suites = [];
/** Used to resolve a value's internal [[Class]]. */
var toString = Object.prototype.toString;
/** Detect if in a browser environment. */
var isBrowser = isHostType(root, 'document') && isHostType(root, 'navigator');
/** Detect if in a Java environment. */
var isJava = !isBrowser && /Java/.test(toString.call(root.java));
/** Use a single "load" function. */
var load = (typeof require == 'function' && !amd)
? require
: (isJava && root.load) || noop;
/** Load Lo-Dash. */
var lodash = root.lodash || (root.lodash = (
lodash = load(filePath) || root._,
lodash = lodash._ || lodash,
(lodash.runInContext ? lodash.runInContext(root) : lodash),
lodash.noConflict()
));
/** Load Benchmark.js. */
var Benchmark = root.Benchmark || (root.Benchmark = (
Benchmark = load('../vendor/benchmark.js/benchmark.js') || root.Benchmark,
Benchmark = Benchmark.Benchmark || Benchmark,
Benchmark.runInContext(lodash.extend({}, root, { '_': lodash }))
));
/** Load Underscore. */
var _ = root._ || (root._ = (
_ = load('../vendor/underscore/underscore.js') || root._,
_._ || _
));
/*--------------------------------------------------------------------------*/
/**
* Gets the basename of the given `filePath`. If the file `extension` is passed,
* it will be removed from the basename.
*
* @private
* @param {string} path The file path to inspect.
* @param {string} extension The extension to remove.
* @returns {string} Returns the basename.
*/
function basename(filePath, extension) {
var result = (filePath || '').split(rePathSeparator).pop();
return (arguments.length < 2)
? result
: result.replace(RegExp(extension.replace(reSpecialChars, '\\$&') + '$'), '');
}
/**
* Computes the geometric mean (log-average) of an array of values.
* See http://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_arithmetic_mean_of_logarithms.
*
* @private
* @param {Array} array The array of values.
* @returns {number} The geometric mean.
*/
function getGeometricMean(array) {
return Math.pow(Math.E, lodash.reduce(array, function(sum, x) {
return sum + Math.log(x);
}, 0) / array.length) || 0;
}
/**
* Gets the Hz, i.e. operations per second, of `bench` adjusted for the
* margin of error.
*
* @private
* @param {Object} bench The benchmark object.
* @returns {number} Returns the adjusted Hz.
*/
function getHz(bench) {
var result = 1 / (bench.stats.mean + bench.stats.moe);
return isFinite(result) ? result : 0;
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of "object", "function", or "unknown".
*
* @private
* @param {*} object The owner of the property.
* @param {string} property The property to check.
* @returns {boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
if (object == null) {
return false;
}
var type = typeof object[property];
return !rePrimitive.test(type) && (type != 'object' || !!object[property]);
}
/**
* Logs text to the console.
*
* @private
* @param {string} text The text to log.
*/
function log(text) {
console.log(text + '');
if (fbPanel) {
// Scroll the Firebug Lite panel down.
fbPanel.scrollTop = fbPanel.scrollHeight;
}
}
/**
* Runs all benchmark suites.
*
* @private (@public in the browser)
*/
function run() {
fbPanel = (fbPanel = root.document && document.getElementById('FirebugUI')) &&
(fbPanel = (fbPanel = fbPanel.contentWindow || fbPanel.contentDocument).document || fbPanel) &&
fbPanel.getElementById('fbPanel1');
log('\nSit back and relax, this may take a while.');
suites[0].run({ 'async': !isJava });
}
/*--------------------------------------------------------------------------*/
lodash.extend(Benchmark.Suite.options, {
'onStart': function() {
log('\n' + this.name + ':');
},
'onCycle': function(event) {
log(event.target);
},
'onComplete': function() {
for (var index = 0, length = this.length; index < length; index++) {
var bench = this[index];
if (bench.error) {
var errored = true;
}
}
if (errored) {
log('There was a problem, skipping...');
}
else {
var formatNumber = Benchmark.formatNumber,
fastest = this.filter('fastest'),
fastestHz = getHz(fastest[0]),
slowest = this.filter('slowest'),
slowestHz = getHz(slowest[0]),
aHz = getHz(this[0]),
bHz = getHz(this[1]);
if (fastest.length > 1) {
log('It\'s too close to call.');
aHz = bHz = slowestHz;
}
else {
var percent = ((fastestHz / slowestHz) - 1) * 100;
log(
fastest[0].name + ' is ' +
formatNumber(percent < 1 ? percent.toFixed(2) : Math.round(percent)) +
'% faster.'
);
}
// Add score adjusted for margin of error.
score.a.push(aHz);
score.b.push(bHz);
}
// Remove current suite from queue.
suites.shift();
if (suites.length) {
// Run next suite.
suites[0].run({ 'async': !isJava });
}
else {
var aMeanHz = getGeometricMean(score.a),
bMeanHz = getGeometricMean(score.b),
fastestMeanHz = Math.max(aMeanHz, bMeanHz),
slowestMeanHz = Math.min(aMeanHz, bMeanHz),
xFaster = fastestMeanHz / slowestMeanHz,
percentFaster = formatNumber(Math.round((xFaster - 1) * 100)),
message = 'is ' + percentFaster + '% ' + (xFaster == 1 ? '' : '(' + formatNumber(xFaster.toFixed(2)) + 'x) ') + 'faster than';
// Report results.
if (aMeanHz >= bMeanHz) {
log('\n' + buildName + ' ' + message + ' ' + otherName + '.');
} else {
log('\n' + otherName + ' ' + message + ' ' + buildName + '.');
}
}
}
});
/*--------------------------------------------------------------------------*/
lodash.extend(Benchmark.options, {
'async': true,
'setup': '\
var _ = global._,\
lodash = global.lodash,\
belt = this.name == buildName ? lodash : _;\
\
var date = new Date,\
limit = 20,\
regexp = /x/,\
object = {},\
objects = Array(limit),\
numbers = Array(limit),\
fourNumbers = [5, 25, 10, 30],\
nestedNumbers = [1, [2], [3, [[4]]]],\
nestedObjects = [{}, [{}], [{}, [[{}]]]],\
twoNumbers = [12, 23];\
\
for (var index = 0; index < limit; index++) {\
numbers[index] = index;\
object["key" + index] = index;\
objects[index] = { "num": index };\
}\
var strNumbers = numbers + "";\
\
if (typeof bind != "undefined") {\
var thisArg = { "name": "fred" };\
\
var func = function(greeting, punctuation) {\
return (greeting || "hi") + " " + this.name + (punctuation || ".");\
};\
\
var _boundNormal = _.bind(func, thisArg),\
_boundMultiple = _boundNormal,\
_boundPartial = _.bind(func, thisArg, "hi");\
\
var lodashBoundNormal = lodash.bind(func, thisArg),\
lodashBoundMultiple = lodashBoundNormal,\
lodashBoundPartial = lodash.bind(func, thisArg, "hi");\
\
for (index = 0; index < 10; index++) {\
_boundMultiple = _.bind(_boundMultiple, { "name": "fred" + index });\
lodashBoundMultiple = lodash.bind(lodashBoundMultiple, { "name": "fred" + index });\
}\
}\
if (typeof bindAll != "undefined") {\
var bindAllCount = -1,\
bindAllObjects = Array(this.count);\
\
var funcNames = belt.reject(belt.functions(belt).slice(0, 40), function(funcName) {\
return /^_/.test(funcName);\
});\
\
// Potentially expensive.\n\
for (index = 0; index < this.count; index++) {\
bindAllObjects[index] = belt.reduce(funcNames, function(object, funcName) {\
object[funcName] = belt[funcName];\
return object;\
}, {});\
}\
}\
if (typeof chaining != "undefined") {\
var even = function(v) { return v % 2 == 0; },\
square = function(v) { return v * v; };\
\
var largeArray = belt.range(10000),\
_chaining = _.chain ? _(largeArray).chain() : _(largeArray),\
lodashChaining = lodash(largeArray);\
}\
if (typeof compact != "undefined") {\
var uncompacted = numbers.slice();\
uncompacted[2] = false;\
uncompacted[6] = null;\
uncompacted[18] = "";\
}\
if (typeof compose != "undefined") {\
var compAddOne = function(n) { return n + 1; },\
compAddTwo = function(n) { return n + 2; },\
compAddThree = function(n) { return n + 3; };\
\
var _composed = _.compose(compAddThree, compAddTwo, compAddOne),\
lodashComposed = lodash.compose(compAddThree, compAddTwo, compAddOne);\
}\
if (typeof countBy != "undefined" || typeof omit != "undefined") {\
var wordToNumber = {\
"one": 1,\
"two": 2,\
"three": 3,\
"four": 4,\
"five": 5,\
"six": 6,\
"seven": 7,\
"eight": 8,\
"nine": 9,\
"ten": 10,\
"eleven": 11,\
"twelve": 12,\
"thirteen": 13,\
"fourteen": 14,\
"fifteen": 15,\
"sixteen": 16,\
"seventeen": 17,\
"eighteen": 18,\
"nineteen": 19,\
"twenty": 20,\
"twenty-one": 21,\
"twenty-two": 22,\
"twenty-three": 23,\
"twenty-four": 24,\
"twenty-five": 25,\
"twenty-six": 26,\
"twenty-seven": 27,\
"twenty-eight": 28,\
"twenty-nine": 29,\
"thirty": 30,\
"thirty-one": 31,\
"thirty-two": 32,\
"thirty-three": 33,\
"thirty-four": 34,\
"thirty-five": 35,\
"thirty-six": 36,\
"thirty-seven": 37,\
"thirty-eight": 38,\
"thirty-nine": 39,\
"forty": 40\
};\
\
var words = belt.keys(wordToNumber).slice(0, limit);\
}\
if (typeof flatten != "undefined") {\
var _flattenDeep = _.flatten([[1]])[0] !== 1,\
lodashFlattenDeep = lodash.flatten([[1]]) !== 1;\
}\
if (typeof isEqual != "undefined") {\
var objectOfPrimitives = {\
"boolean": true,\
"number": 1,\
"string": "a"\
};\
\
var objectOfObjects = {\
"boolean": new Boolean(true),\
"number": new Number(1),\
"string": new String("a")\
};\
\
var objectOfObjects2 = {\
"boolean": new Boolean(true),\
"number": new Number(1),\
"string": new String("A")\
};\
\
var object2 = {},\
object3 = {},\
objects2 = Array(limit),\
objects3 = Array(limit),\
numbers2 = Array(limit),\
numbers3 = Array(limit),\
nestedNumbers2 = [1, [2], [3, [[4]]]],\
nestedNumbers3 = [1, [2], [3, [[6]]]];\
\
for (index = 0; index < limit; index++) {\
object2["key" + index] = index;\
object3["key" + index] = index;\
objects2[index] = { "num": index };\
objects3[index] = { "num": index };\
numbers2[index] = index;\
numbers3[index] = index;\
}\
object3["key" + (limit - 1)] = -1;\
objects3[limit - 1].num = -1;\
numbers3[limit - 1] = -1;\
}\
if (typeof matches != "undefined") {\
var source = { "num": 9 };\
\
var _findWhere = _.findWhere || _.find,\
_match = (_.matches || _.createCallback || _.noop)(source);\
\
var lodashFindWhere = lodash.findWhere || lodash.find,\
lodashMatch = (lodash.matches || lodash.createCallback || lodash.noop)(source);\
}\
if (typeof multiArrays != "undefined") {\
var twentyValues = belt.shuffle(belt.range(20)),\
fortyValues = belt.shuffle(belt.range(40)),\
hundredSortedValues = belt.range(100),\
hundredValues = belt.shuffle(hundredSortedValues),\
hundredValues2 = belt.shuffle(hundredValues),\
hundredTwentyValues = belt.shuffle(belt.range(120)),\
hundredTwentyValues2 = belt.shuffle(hundredTwentyValues),\
twoHundredValues = belt.shuffle(belt.range(200)),\
twoHundredValues2 = belt.shuffle(twoHundredValues);\
}\
if (typeof partial != "undefined") {\
var func = function(greeting, punctuation) {\
return greeting + " fred" + (punctuation || ".");\
};\
\
var _partial = _.partial(func, "hi"),\
lodashPartial = lodash.partial(func, "hi");\
}\
if (typeof template != "undefined") {\
var tplData = {\
"header1": "Header1",\
"header2": "Header2",\
"header3": "Header3",\
"header4": "Header4",\
"header5": "Header5",\
"header6": "Header6",\
"list": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]\
};\
\
var tpl =\
"<div>" +\
"<h1 class=\'header1\'><%= header1 %></h1>" +\
"<h2 class=\'header2\'><%= header2 %></h2>" +\
"<h3 class=\'header3\'><%= header3 %></h3>" +\
"<h4 class=\'header4\'><%= header4 %></h4>" +\
"<h5 class=\'header5\'><%= header5 %></h5>" +\
"<h6 class=\'header6\'><%= header6 %></h6>" +\
"<ul class=\'list\'>" +\
"<% for (var index = 0, length = list.length; index < length; index++) { %>" +\
"<li class=\'item\'><%= list[index] %></li>" +\
"<% } %>" +\
"</ul>" +\
"</div>";\
\
var tplVerbose =\
"<div>" +\
"<h1 class=\'header1\'><%= data.header1 %></h1>" +\
"<h2 class=\'header2\'><%= data.header2 %></h2>" +\
"<h3 class=\'header3\'><%= data.header3 %></h3>" +\
"<h4 class=\'header4\'><%= data.header4 %></h4>" +\
"<h5 class=\'header5\'><%= data.header5 %></h5>" +\
"<h6 class=\'header6\'><%= data.header6 %></h6>" +\
"<ul class=\'list\'>" +\
"<% for (var index = 0, length = data.list.length; index < length; index++) { %>" +\
"<li class=\'item\'><%= data.list[index] %></li>" +\
"<% } %>" +\
"</ul>" +\
"</div>";\
\
var settingsObject = { "variable": "data" };\
\
var _tpl = _.template(tpl),\
_tplVerbose = _.template(tplVerbose, null, settingsObject);\
\
var lodashTpl = lodash.template(tpl),\
lodashTplVerbose = lodash.template(tplVerbose, null, settingsObject);\
}\
if (typeof wrap != "undefined") {\
var add = function(a, b) {\
return a + b;\
};\
\
var average = function(func, a, b) {\
return (func(a, b) / 2).toFixed(2);\
};\
\
var _wrapped = _.wrap(add, average);\
lodashWrapped = lodash.wrap(add, average);\
}\
if (typeof zip != "undefined") {\
var unzipped = [["a", "b", "c"], [1, 2, 3], [true, false, true]];\
}'
});
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_(...).map(...).filter(...).take(...).value()`')
.add(buildName, {
'fn': 'lodashChaining.map(square).filter(even).take(100).value()',
'teardown': 'function chaining(){}'
})
.add(otherName, {
'fn': '_chaining.map(square).filter(even).take(100).value()',
'teardown': 'function chaining(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.bind` (slow path)')
.add(buildName, {
'fn': 'lodash.bind(function() { return this.name; }, { "name": "fred" })',
'teardown': 'function bind(){}'
})
.add(otherName, {
'fn': '_.bind(function() { return this.name; }, { "name": "fred" })',
'teardown': 'function bind(){}'
})
);
suites.push(
Benchmark.Suite('bound call with arguments')
.add(buildName, {
'fn': 'lodashBoundNormal("hi", "!")',
'teardown': 'function bind(){}'
})
.add(otherName, {
'fn': '_boundNormal("hi", "!")',
'teardown': 'function bind(){}'
})
);
suites.push(
Benchmark.Suite('bound and partially applied call with arguments')
.add(buildName, {
'fn': 'lodashBoundPartial("!")',
'teardown': 'function bind(){}'
})
.add(otherName, {
'fn': '_boundPartial("!")',
'teardown': 'function bind(){}'
})
);
suites.push(
Benchmark.Suite('bound multiple times')
.add(buildName, {
'fn': 'lodashBoundMultiple()',
'teardown': 'function bind(){}'
})
.add(otherName, {
'fn': '_boundMultiple()',
'teardown': 'function bind(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.bindAll` iterating arguments')
.add(buildName, {
'fn': 'lodash.bindAll.apply(lodash, [bindAllObjects[++bindAllCount]].concat(funcNames))',
'teardown': 'function bindAll(){}'
})
.add(otherName, {
'fn': '_.bindAll.apply(_, [bindAllObjects[++bindAllCount]].concat(funcNames))',
'teardown': 'function bindAll(){}'
})
);
suites.push(
Benchmark.Suite('`_.bindAll` iterating the `object`')
.add(buildName, {
'fn': 'lodash.bindAll(bindAllObjects[++bindAllCount])',
'teardown': 'function bindAll(){}'
})
.add(otherName, {
'fn': '_.bindAll(bindAllObjects[++bindAllCount])',
'teardown': 'function bindAll(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.clone` with an array')
.add(buildName, '\
lodash.clone(numbers)'
)
.add(otherName, '\
_.clone(numbers)'
)
);
suites.push(
Benchmark.Suite('`_.clone` with an object')
.add(buildName, '\
lodash.clone(object)'
)
.add(otherName, '\
_.clone(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.compact`')
.add(buildName, {
'fn': 'lodash.compact(uncompacted)',
'teardown': 'function compact(){}'
})
.add(otherName, {
'fn': '_.compact(uncompacted)',
'teardown': 'function compact(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.compose`')
.add(buildName, {
'fn': 'lodash.compose(compAddThree, compAddTwo, compAddOne)',
'teardown': 'function compose(){}'
})
.add(otherName, {
'fn': '_.compose(compAddThree, compAddTwo, compAddOne)',
'teardown': 'function compose(){}'
})
);
suites.push(
Benchmark.Suite('composed call')
.add(buildName, {
'fn': 'lodashComposed(0)',
'teardown': 'function compose(){}'
})
.add(otherName, {
'fn': '_composed(0)',
'teardown': 'function compose(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.countBy` with `callback` iterating an array')
.add(buildName, '\
lodash.countBy(numbers, function(num) { return num >> 1; })'
)
.add(otherName, '\
_.countBy(numbers, function(num) { return num >> 1; })'
)
);
suites.push(
Benchmark.Suite('`_.countBy` with `property` name iterating an array')
.add(buildName, {
'fn': 'lodash.countBy(words, "length")',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.countBy(words, "length")',
'teardown': 'function countBy(){}'
})
);
suites.push(
Benchmark.Suite('`_.countBy` with `callback` iterating an object')
.add(buildName, {
'fn': 'lodash.countBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.countBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.defaults`')
.add(buildName, '\
lodash.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)'
)
.add(otherName, '\
_.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.difference`')
.add(buildName, '\
lodash.difference(numbers, twoNumbers, fourNumbers)'
)
.add(otherName, '\
_.difference(numbers, twoNumbers, fourNumbers)'
)
);
suites.push(
Benchmark.Suite('`_.difference` iterating 200 elements')
.add(buildName, {
'fn': 'lodash.difference(twoHundredValues, twoHundredValues2)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.difference(twoHundredValues, twoHundredValues2)',
'teardown': 'function multiArrays(){}'
})
);
suites.push(
Benchmark.Suite('`_.difference` iterating 20 and 40 elements')
.add(buildName, {
'fn': 'lodash.difference(twentyValues, fortyValues)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.difference(twentyValues, fortyValues)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.each` iterating an array')
.add(buildName, '\
var result = [];\
lodash.each(numbers, function(num) {\
result.push(num * 2);\
})'
)
.add(otherName, '\
var result = [];\
_.each(numbers, function(num) {\
result.push(num * 2);\
})'
)
);
suites.push(
Benchmark.Suite('`_.each` iterating an array with `thisArg` (slow path)')
.add(buildName, '\
var result = [];\
lodash.each(numbers, function(num, index) {\
result.push(num + this["key" + index]);\
}, object)'
)
.add(otherName, '\
var result = [];\
_.each(numbers, function(num, index) {\
result.push(num + this["key" + index]);\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.each` iterating an object')
.add(buildName, '\
var result = [];\
lodash.each(object, function(num) {\
result.push(num * 2);\
})'
)
.add(otherName, '\
var result = [];\
_.each(object, function(num) {\
result.push(num * 2);\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.every` iterating an array')
.add(buildName, '\
lodash.every(numbers, function(num) {\
return num < limit;\
})'
)
.add(otherName, '\
_.every(numbers, function(num) {\
return num < limit;\
})'
)
);
suites.push(
Benchmark.Suite('`_.every` iterating an object')
.add(buildName, '\
lodash.every(object, function(num) {\
return num < limit;\
})'
)
.add(otherName, '\
_.every(object, function(num) {\
return num < limit;\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.extend`')
.add(buildName, '\
lodash.extend({}, object)'
)
.add(otherName, '\
_.extend({}, object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.filter` iterating an array')
.add(buildName, '\
lodash.filter(numbers, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.filter(numbers, function(num) {\
return num % 2;\
})'
)
);
suites.push(
Benchmark.Suite('`_.filter` iterating an array with `thisArg` (slow path)')
.add(buildName, '\
lodash.filter(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
.add(otherName, '\
_.filter(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.filter` iterating an object')
.add(buildName, '\
lodash.filter(object, function(num) {\
return num % 2\
})'
)
.add(otherName, '\
_.filter(object, function(num) {\
return num % 2\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.find` iterating an array')
.add(buildName, '\
lodash.find(numbers, function(num) {\
return num === (limit - 1);\
})'
)
.add(otherName, '\
_.find(numbers, function(num) {\
return num === (limit - 1);\
})'
)
);
suites.push(
Benchmark.Suite('`_.find` iterating an object')
.add(buildName, '\
lodash.find(object, function(value, key) {\
return /\D9$/.test(key);\
})'
)
.add(otherName, '\
_.find(object, function(value, key) {\
return /\D9$/.test(key);\
})'
)
);
// Avoid Underscore induced `OutOfMemoryError` in Rhino, Narwhal, and Ringo.
if (!isJava) {
suites.push(
Benchmark.Suite('`_.find` with `properties`')
.add(buildName, {
'fn': 'lodashFindWhere(objects, source)',
'teardown': 'function matches(){}'
})
.add(otherName, {
'fn': '_findWhere(objects, source)',
'teardown': 'function matches(){}'
})
);
}
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.flatten`')
.add(buildName, {
'fn': 'lodash.flatten(nestedNumbers, !lodashFlattenDeep)',
'teardown': 'function flatten(){}'
})
.add(otherName, {
'fn': '_.flatten(nestedNumbers, !_flattenDeep)',
'teardown': 'function flatten(){}'
})
);
suites.push(
Benchmark.Suite('`_.flatten` nested arrays of numbers with `isDeep`')
.add(buildName, {
'fn': 'lodash.flatten(nestedNumbers, lodashFlattenDeep)',
'teardown': 'function flatten(){}'
})
.add(otherName, {
'fn': '_.flatten(nestedNumbers, _flattenDeep)',
'teardown': 'function flatten(){}'
})
);
suites.push(
Benchmark.Suite('`_.flatten` nest arrays of objects with `isDeep`')
.add(buildName, {
'fn': 'lodash.flatten(nestedObjects, lodashFlattenDeep)',
'teardown': 'function flatten(){}'
})
.add(otherName, {
'fn': '_.flatten(nestedObjects, _flattenDeep)',
'teardown': 'function flatten(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.functions`')
.add(buildName, '\
lodash.functions(lodash)'
)
.add(otherName, '\
_.functions(lodash)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.groupBy` with `callback` iterating an array')
.add(buildName, '\
lodash.groupBy(numbers, function(num) { return num >> 1; })'
)
.add(otherName, '\
_.groupBy(numbers, function(num) { return num >> 1; })'
)
);
suites.push(
Benchmark.Suite('`_.groupBy` with `property` name iterating an array')
.add(buildName, {
'fn': 'lodash.groupBy(words, "length")',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.groupBy(words, "length")',
'teardown': 'function countBy(){}'
})
);
suites.push(
Benchmark.Suite('`_.groupBy` with `callback` iterating an object')
.add(buildName, {
'fn': 'lodash.groupBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.groupBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.include` iterating an array')
.add(buildName, '\
lodash.include(numbers, limit - 1)'
)
.add(otherName, '\
_.include(numbers, limit - 1)'
)
);
suites.push(
Benchmark.Suite('`_.include` iterating an object')
.add(buildName, '\
lodash.include(object, limit - 1)'
)
.add(otherName, '\
_.include(object, limit - 1)'
)
);
if (lodash.include('ab', 'ab') && _.include('ab', 'ab')) {
suites.push(
Benchmark.Suite('`_.include` iterating a string')
.add(buildName, '\
lodash.include(strNumbers, "," + (limit - 1))'
)
.add(otherName, '\
_.include(strNumbers, "," + (limit - 1))'
)
);
}
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.indexBy` with `callback` iterating an array')
.add(buildName, '\
lodash.indexBy(numbers, function(num) { return num >> 1; })'
)
.add(otherName, '\
_.indexBy(numbers, function(num) { return num >> 1; })'
)
);
suites.push(
Benchmark.Suite('`_.indexBy` with `property` name iterating an array')
.add(buildName, {
'fn': 'lodash.indexBy(words, "length")',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.indexBy(words, "length")',
'teardown': 'function countBy(){}'
})
);
suites.push(
Benchmark.Suite('`_.indexBy` with `callback` iterating an object')
.add(buildName, {
'fn': 'lodash.indexBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.indexBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.indexOf`')
.add(buildName, {
'fn': 'lodash.indexOf(hundredSortedValues, 99)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.indexOf(hundredSortedValues, 99)',
'teardown': 'function multiArrays(){}'
})
);
suites.push(
Benchmark.Suite('`_.indexOf` performing a binary search')
.add(buildName, {
'fn': 'lodash.indexOf(hundredSortedValues, 99, true)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.indexOf(hundredSortedValues, 99, true)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.intersection`')
.add(buildName, '\
lodash.intersection(numbers, twoNumbers, fourNumbers)'
)
.add(otherName, '\
_.intersection(numbers, twoNumbers, fourNumbers)'
)
);
suites.push(
Benchmark.Suite('`_.intersection` iterating 120 elements')
.add(buildName, {
'fn': 'lodash.intersection(hundredTwentyValues, hundredTwentyValues2)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.intersection(hundredTwentyValues, hundredTwentyValues2)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.invert`')
.add(buildName, '\
lodash.invert(object)'
)
.add(otherName, '\
_.invert(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.invoke` iterating an array')
.add(buildName, '\
lodash.invoke(numbers, "toFixed")'
)
.add(otherName, '\
_.invoke(numbers, "toFixed")'
)
);
suites.push(
Benchmark.Suite('`_.invoke` with arguments iterating an array')
.add(buildName, '\
lodash.invoke(numbers, "toFixed", 1)'
)
.add(otherName, '\
_.invoke(numbers, "toFixed", 1)'
)
);
suites.push(
Benchmark.Suite('`_.invoke` with a function for `methodName` iterating an array')
.add(buildName, '\
lodash.invoke(numbers, Number.prototype.toFixed, 1)'
)
.add(otherName, '\
_.invoke(numbers, Number.prototype.toFixed, 1)'
)
);
suites.push(
Benchmark.Suite('`_.invoke` iterating an object')
.add(buildName, '\
lodash.invoke(object, "toFixed", 1)'
)
.add(otherName, '\
_.invoke(object, "toFixed", 1)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.isEqual` comparing primitives')
.add(buildName, {
'fn': '\
lodash.isEqual(1, "1");\
lodash.isEqual(1, 1)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(1, "1");\
_.isEqual(1, 1);',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing primitives and their object counterparts (edge case)')
.add(buildName, {
'fn': '\
lodash.isEqual(objectOfPrimitives, objectOfObjects);\
lodash.isEqual(objectOfPrimitives, objectOfObjects2)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(objectOfPrimitives, objectOfObjects);\
_.isEqual(objectOfPrimitives, objectOfObjects2)',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing arrays')
.add(buildName, {
'fn': '\
lodash.isEqual(numbers, numbers2);\
lodash.isEqual(numbers2, numbers3)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(numbers, numbers2);\
_.isEqual(numbers2, numbers3)',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing nested arrays')
.add(buildName, {
'fn': '\
lodash.isEqual(nestedNumbers, nestedNumbers2);\
lodash.isEqual(nestedNumbers2, nestedNumbers3)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(nestedNumbers, nestedNumbers2);\
_.isEqual(nestedNumbers2, nestedNumbers3)',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing arrays of objects')
.add(buildName, {
'fn': '\
lodash.isEqual(objects, objects2);\
lodash.isEqual(objects2, objects3)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(objects, objects2);\
_.isEqual(objects2, objects3)',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing objects')
.add(buildName, {
'fn': '\
lodash.isEqual(object, object2);\
lodash.isEqual(object2, object3)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(object, object2);\
_.isEqual(object2, object3)',
'teardown': 'function isEqual(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.isArguments`, `_.isDate`, `_.isFunction`, `_.isNumber`, `_.isObject`, `_.isRegExp`')
.add(buildName, '\
lodash.isArguments(arguments);\
lodash.isArguments(object);\
lodash.isDate(date);\
lodash.isDate(object);\
lodash.isFunction(lodash);\
lodash.isFunction(object);\
lodash.isNumber(1);\
lodash.isNumber(object);\
lodash.isObject(object);\
lodash.isObject(1);\
lodash.isRegExp(regexp);\
lodash.isRegExp(object)'
)
.add(otherName, '\
_.isArguments(arguments);\
_.isArguments(object);\
_.isDate(date);\
_.isDate(object);\
_.isFunction(_);\
_.isFunction(object);\
_.isNumber(1);\
_.isNumber(object);\
_.isObject(object);\
_.isObject(1);\
_.isRegExp(regexp);\
_.isRegExp(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.keys` (uses native `Object.keys` if available)')
.add(buildName, '\
lodash.keys(object)'
)
.add(otherName, '\
_.keys(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.lastIndexOf`')
.add(buildName, {
'fn': 'lodash.lastIndexOf(hundredSortedValues, 0)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.lastIndexOf(hundredSortedValues, 0)',
'teardown': 'function multiArrays(){}'
})
);
suites.push(
Benchmark.Suite('`_.lastIndexOf` performing a binary search')
.add(buildName, {
'fn': 'lodash.lastIndexOf(hundredSortedValues, 0, true)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.lastIndexOf(hundredSortedValues, 0, true)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.map` iterating an array')
.add(buildName, '\
lodash.map(objects, function(value) {\
return value.num;\
})'
)
.add(otherName, '\
_.map(objects, function(value) {\
return value.num;\
})'
)
);
suites.push(
Benchmark.Suite('`_.map` with `thisArg` iterating an array (slow path)')
.add(buildName, '\
lodash.map(objects, function(value, index) {\
return this["key" + index] + value.num;\
}, object)'
)
.add(otherName, '\
_.map(objects, function(value, index) {\
return this["key" + index] + value.num;\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.map` iterating an object')
.add(buildName, '\
lodash.map(object, function(value) {\
return value;\
})'
)
.add(otherName, '\
_.map(object, function(value) {\
return value;\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.matches` predicate')
.add(buildName, {
'fn': 'lodash.filter(objects, lodashMatch)',
'teardown': 'function matches(){}'
})
.add(otherName, {
'fn': '_.filter(objects, _match)',
'teardown': 'function matches(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.max`')
.add(buildName, '\
lodash.max(numbers)'
)
.add(otherName, '\
_.max(numbers)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.min`')
.add(buildName, '\
lodash.min(numbers)'
)
.add(otherName, '\
_.min(numbers)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.omit` iterating 20 properties, omitting 2 keys')
.add(buildName, '\
lodash.omit(object, "key6", "key13")'
)
.add(otherName, '\
_.omit(object, "key6", "key13")'
)
);
suites.push(
Benchmark.Suite('`_.omit` iterating 40 properties, omitting 20 keys')
.add(buildName, {
'fn': 'lodash.omit(wordToNumber, words)',
'teardown': 'function omit(){}'
})
.add(otherName, {
'fn': '_.omit(wordToNumber, words)',
'teardown': 'function omit(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.pairs`')
.add(buildName, '\
lodash.pairs(object)'
)
.add(otherName, '\
_.pairs(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.partial` (slow path)')
.add(buildName, {
'fn': 'lodash.partial(function(greeting) { return greeting + " " + this.name; }, "hi")',
'teardown': 'function partial(){}'
})
.add(otherName, {
'fn': '_.partial(function(greeting) { return greeting + " " + this.name; }, "hi")',
'teardown': 'function partial(){}'
})
);
suites.push(
Benchmark.Suite('partially applied call with arguments')
.add(buildName, {
'fn': 'lodashPartial("!")',
'teardown': 'function partial(){}'
})
.add(otherName, {
'fn': '_partial("!")',
'teardown': 'function partial(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.partition` iterating an array')
.add(buildName, '\
lodash.partition(numbers, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.partition(numbers, function(num) {\
return num % 2;\
})'
)
);
suites.push(
Benchmark.Suite('`_.partition` iterating an array with `thisArg` (slow path)')
.add(buildName, '\
lodash.partition(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
.add(otherName, '\
_.partition(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.partition` iterating an object')
.add(buildName, '\
lodash.partition(object, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.partition(object, function(num) {\
return num % 2;\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.pick`')
.add(buildName, '\
lodash.pick(object, "key6", "key13")'
)
.add(otherName, '\
_.pick(object, "key6", "key13")'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.pluck`')
.add(buildName, '\
lodash.pluck(objects, "num")'
)
.add(otherName, '\
_.pluck(objects, "num")'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.reduce` iterating an array')
.add(buildName, '\
lodash.reduce(numbers, function(result, value, index) {\
result[index] = value;\
return result;\
}, {})'
)
.add(otherName, '\
_.reduce(numbers, function(result, value, index) {\
result[index] = value;\
return result;\
}, {})'
)
);
suites.push(
Benchmark.Suite('`_.reduce` iterating an object')
.add(buildName, '\
lodash.reduce(object, function(result, value, key) {\
result.push(key, value);\
return result;\
}, [])'
)
.add(otherName, '\
_.reduce(object, function(result, value, key) {\
result.push(key, value);\
return result;\
}, [])'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.reduceRight` iterating an array')
.add(buildName, '\
lodash.reduceRight(numbers, function(result, value, index) {\
result[index] = value;\
return result;\
}, {})'
)
.add(otherName, '\
_.reduceRight(numbers, function(result, value, index) {\
result[index] = value;\
return result;\
}, {})'
)
);
suites.push(
Benchmark.Suite('`_.reduceRight` iterating an object')
.add(buildName, '\
lodash.reduceRight(object, function(result, value, key) {\
result.push(key, value);\
return result;\
}, [])'
)
.add(otherName, '\
_.reduceRight(object, function(result, value, key) {\
result.push(key, value);\
return result;\
}, [])'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.reject` iterating an array')
.add(buildName, '\
lodash.reject(numbers, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.reject(numbers, function(num) {\
return num % 2;\
})'
)
);
suites.push(
Benchmark.Suite('`_.reject` iterating an array with `thisArg` (slow path)')
.add(buildName, '\
lodash.reject(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
.add(otherName, '\
_.reject(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.reject` iterating an object')
.add(buildName, '\
lodash.reject(object, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.reject(object, function(num) {\
return num % 2;\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.sample` with an `n`')
.add(buildName, '\
lodash.sample(numbers, limit / 2)'
)
.add(otherName, '\
_.sample(numbers, limit / 2)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.shuffle`')
.add(buildName, '\
lodash.shuffle(numbers)'
)
.add(otherName, '\
_.shuffle(numbers)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.size` with an object')
.add(buildName, '\
lodash.size(object)'
)
.add(otherName, '\
_.size(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.some` iterating an array')
.add(buildName, '\
lodash.some(numbers, function(num) {\
return num == (limit - 1);\
})'
)
.add(otherName, '\
_.some(numbers, function(num) {\
return num == (limit - 1);\
})'
)
);
suites.push(
Benchmark.Suite('`_.some` with `thisArg` iterating an array (slow path)')
.add(buildName, '\
lodash.some(objects, function(value, index) {\
return this["key" + index] == (limit - 1);\
}, object)'
)
.add(otherName, '\
_.some(objects, function(value, index) {\
return this["key" + index] == (limit - 1);\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.some` iterating an object')
.add(buildName, '\
lodash.some(object, function(num) {\
return num == (limit - 1);\
})'
)
.add(otherName, '\
_.some(object, function(num) {\
return num == (limit - 1);\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.sortBy` with `callback`')
.add(buildName, '\
lodash.sortBy(numbers, function(num) { return Math.sin(num); })'
)
.add(otherName, '\
_.sortBy(numbers, function(num) { return Math.sin(num); })'
)
);
suites.push(
Benchmark.Suite('`_.sortBy` with `callback` and `thisArg` (slow path)')
.add(buildName, '\
lodash.sortBy(numbers, function(num) { return this.sin(num); }, Math)'
)
.add(otherName, '\
_.sortBy(numbers, function(num) { return this.sin(num); }, Math)'
)
);
suites.push(
Benchmark.Suite('`_.sortBy` with `property` name')
.add(buildName, {
'fn': 'lodash.sortBy(words, "length")',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.sortBy(words, "length")',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.sortedIndex` with `callback`')
.add(buildName, {
'fn': '\
lodash.sortedIndex(words, "twenty-five", function(value) {\
return wordToNumber[value];\
})',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '\
_.sortedIndex(words, "twenty-five", function(value) {\
return wordToNumber[value];\
})',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.template` (slow path)')
.add(buildName, {
'fn': 'lodash.template(tpl)(tplData)',
'teardown': 'function template(){}'
})
.add(otherName, {
'fn': '_.template(tpl)(tplData)',
'teardown': 'function template(){}'
})
);
suites.push(
Benchmark.Suite('compiled template')
.add(buildName, {
'fn': 'lodashTpl(tplData)',
'teardown': 'function template(){}'
})
.add(otherName, {
'fn': '_tpl(tplData)',
'teardown': 'function template(){}'
})
);
suites.push(
Benchmark.Suite('compiled template without a with-statement')
.add(buildName, {
'fn': 'lodashTplVerbose(tplData)',
'teardown': 'function template(){}'
})
.add(otherName, {
'fn': '_tplVerbose(tplData)',
'teardown': 'function template(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.times`')
.add(buildName, '\
var result = [];\
lodash.times(limit, function(n) { result.push(n); })'
)
.add(otherName, '\
var result = [];\
_.times(limit, function(n) { result.push(n); })'
)
);
suites.push(
Benchmark.Suite('`_.times` with `thisArg` (slow path)')
.add(buildName, '\
var result = [];\
lodash.times(limit, function(n) { result.push(this.sin(n)); }, Math)'
)
.add(otherName, '\
var result = [];\
_.times(limit, function(n) { result.push(this.sin(n)); }, Math)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.toArray` with an array (edge case)')
.add(buildName, '\
lodash.toArray(numbers)'
)
.add(otherName, '\
_.toArray(numbers)'
)
);
suites.push(
Benchmark.Suite('`_.toArray` with an object')
.add(buildName, '\
lodash.toArray(object)'
)
.add(otherName, '\
_.toArray(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.unescape` string without html entities')
.add(buildName, '\
lodash.unescape("`&`, `<`, `>`, `\\"`, and `\'`")'
)
.add(otherName, '\
_.unescape("`&`, `<`, `>`, `\\"`, and `\'`")'
)
);
suites.push(
Benchmark.Suite('`_.unescape` string with html entities')
.add(buildName, '\
lodash.unescape("`&`, `<`, `>`, `"`, and `'`")'
)
.add(otherName, '\
_.unescape("`&`, `<`, `>`, `"`, and `'`")'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.union`')
.add(buildName, '\
lodash.union(numbers, twoNumbers, fourNumbers)'
)
.add(otherName, '\
_.union(numbers, twoNumbers, fourNumbers)'
)
);
suites.push(
Benchmark.Suite('`_.union` iterating an array of 200 elements')
.add(buildName, {
'fn': 'lodash.union(hundredValues, hundredValues2)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.union(hundredValues, hundredValues2)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.uniq`')
.add(buildName, '\
lodash.uniq(numbers.concat(twoNumbers, fourNumbers))'
)
.add(otherName, '\
_.uniq(numbers.concat(twoNumbers, fourNumbers))'
)
);
suites.push(
Benchmark.Suite('`_.uniq` with `callback`')
.add(buildName, '\
lodash.uniq(numbers.concat(twoNumbers, fourNumbers), function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.uniq(numbers.concat(twoNumbers, fourNumbers), function(num) {\
return num % 2;\
})'
)
);
suites.push(
Benchmark.Suite('`_.uniq` iterating an array of 200 elements')
.add(buildName, {
'fn': 'lodash.uniq(twoHundredValues)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.uniq(twoHundredValues)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.values`')
.add(buildName, '\
lodash.values(object)'
)
.add(otherName, '\
_.values(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.where`')
.add(buildName, {
'fn': 'lodash.where(objects, source)',
'teardown': 'function matches(){}'
})
.add(otherName, {
'fn': '_.where(objects, source)',
'teardown': 'function matches(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.without`')
.add(buildName, '\
lodash.without(numbers, 9, 12, 14, 15)'
)
.add(otherName, '\
_.without(numbers, 9, 12, 14, 15)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.wrap` result called')
.add(buildName, {
'fn': 'lodashWrapped(2, 5)',
'teardown': 'function wrap(){}'
})
.add(otherName, {
'fn': '_wrapped(2, 5)',
'teardown': 'function wrap(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.zip`')
.add(buildName, {
'fn': 'lodash.zip.apply(lodash, unzipped)',
'teardown': 'function zip(){}'
})
.add(otherName, {
'fn': '_.zip.apply(_, unzipped)',
'teardown': 'function zip(){}'
})
);
/*--------------------------------------------------------------------------*/
if (Benchmark.platform + '') {
log(Benchmark.platform);
}
// Expose `run` to be called later when executing in a browser.
if (document) {
root.run = run;
} else {
run();
}
}.call(this));
| Great-Bee/NVWA-Client | js/bower_components/lodash/perf/perf.js | JavaScript | gpl-2.0 | 60,255 |
/*
Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
of Simon Willison (see comments by Simon below).
Small fixes by J.Dobrowolski for Front Accounting May 2008
Description:
Uses css selectors to apply javascript behaviours to enable
unobtrusive javascript in html documents.
Usage:
var myrules = {
'b.someclass' : function(element){
element.onclick = function(){
alert(this.innerHTML);
}
},
'#someid u' : function(element){
element.onmouseover = function(){
this.innerHTML = "BLAH!";
}
}
};
Behaviour.register(myrules);
// Call Behaviour.apply() to re-apply the rules (if you
// update the dom, etc).
License:
This file is entirely BSD licensed.
More information:
http://ripcord.co.nz/behaviour/
*/
var Behaviour = {
list : new Array,
register : function(sheet){
Behaviour.list.push(sheet);
},
start : function(){
Behaviour.addLoadEvent(function(){
Behaviour.apply();
});
},
apply : function(){
for (h=0;sheet=Behaviour.list[h];h++){
for (selector in sheet){
var sels = selector.split(',');
for (var n = 0; n < sels.length; n++) {
list = document.getElementsBySelector(sels[n]);
if (!list){
continue;
}
for (i=0;element=list[i];i++){
sheet[selector](element);
}
}
}
}
},
addLoadEvent : function(func){
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
}
Behaviour.start();
/*
The following code is Copyright (C) Simon Willison 2004.
document.getElementsBySelector(selector)
- returns an array of element objects from the current document
matching the CSS selector. Selectors can contain element names,
class names and ids and can be nested. For example:
elements = document.getElementsBySelect('div#main p a.external')
Will return an array of all 'a' elements with 'external' in their
class attribute that are contained inside 'p' elements that are
contained inside the 'div' element which has id="main"
New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
See http://www.w3.org/TR/css3-selectors/#attribute-selectors
Version 0.4 - Simon Willison, March 25th 2003
-- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
-- Opera 7 fails
*/
function getAllChildren(e) {
// Returns all children of element. Workaround required for IE5/Windows. Ugh.
return e.all ? e.all : e.getElementsByTagName('*');
}
document.getElementsBySelector = function(selector) {
// Attempt to fail gracefully in lesser browsers
if (!document.getElementsByTagName) {
return new Array();
}
// Split selector in to tokens
var tokens = selector.split(' ');
var currentContext = new Array(document);
for (var i = 0; i < tokens.length; i++) {
token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
if (token.indexOf('#') > -1) {
// Token is an ID selector
var bits = token.split('#');
var tagName = bits[0];
var id = bits[1];
var element = document.getElementById(id);
if (tagName && element.nodeName.toLowerCase() != tagName) {
// tag with that ID not found, return false
return new Array();
}
// Set currentContext to contain just this element
currentContext = new Array(element);
continue; // Skip to next token
}
if (token.indexOf('.') > -1) {
// Token contains a class selector
var bits = token.split('.');
var tagName = bits[0];
var className = bits[1];
if (!tagName) {
tagName = '*';
}
// Get elements matching tag, filter them for class selector
var found = new Array;
var foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements;
if (tagName == '*') {
elements = getAllChildren(currentContext[h]);
} else {
elements = currentContext[h].getElementsByTagName(tagName);
}
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = new Array;
var currentContextIndex = 0;
for (var k = 0; k < found.length; k++) {
if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
currentContext[currentContextIndex++] = found[k];
}
}
continue; // Skip to next token
}
// Code to deal with attribute selectors
/* Original reg expression /^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
was replaced by new RegExp() cuz compressor fault */
if (token.match(new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$'))) {
var tagName = RegExp.$1;
var attrName = RegExp.$2;
var attrOperator = RegExp.$3;
var attrValue = RegExp.$4;
if (!tagName) {
tagName = '*';
}
// Grab all of the tagName elements within current context
var found = new Array;
var foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements;
if (tagName == '*') {
elements = getAllChildren(currentContext[h]);
} else {
elements = currentContext[h].getElementsByTagName(tagName);
}
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = new Array;
var currentContextIndex = 0;
var checkFunction; // This function will be used to filter the elements
switch (attrOperator) {
case '=': // Equality
checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
break;
case '~': // Match one of space seperated words
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.match(new RegExp('\\b'+attrValue+'\\b'))); };
break;
case '|': // Match start with value followed by optional hyphen
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.match(new RegExp('^'+attrValue+'-?'))); };
break;
case '^': // Match starts with value
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.indexOf(attrValue) == 0); };
break;
case '$': // Match ends with value - fails with "Warning" in Opera 7
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
break;
case '*': // Match contains value
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.indexOf(attrValue) > -1); };
break;
default :
// Just test for existence of attribute
checkFunction = function(e) { return e.getAttribute(attrName); };
}
currentContext = new Array;
var currentContextIndex = 0;
for (var k = 0; k < found.length; k++) {
if (checkFunction(found[k])) {
currentContext[currentContextIndex++] = found[k];
}
}
// alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
continue; // Skip to next token
}
if (!currentContext[0]){
return;
}
// If we get here, token is JUST an element (not a class or ID selector)
tagName = token;
var found = new Array;
var foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements = currentContext[h].getElementsByTagName(tagName);
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = found;
}
return currentContext;
}
/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
\---/ \---/\-------------/ \-------/
| | | |
| | | The value
| | ~,|,^,$,* or =
| Attribute
Tag
*/
| w2pc/front_accounting | js/behaviour.js | JavaScript | gpl-2.0 | 8,278 |
define(function(require) {
var Model = require("web/common/model");
var SpsrModel = Model.extend({
idAttribute: "recordId",
defaults: {
name: "SDI1",
kzck: 0,
ydsd: 0,
srjkxh: 0,
ld: 123,
dbd: 124,
bhd: 125,
sppy: 126,
czpy: 127
},
urls: {
"create": "spsr.psp",
"update": "spsr.psp",
"delete": "spsr.psp",
"read": "spsr.psp"
}
});
return SpsrModel;
}); | huang147300/EDSFrontEnd | js/index/pz/spsr/spsr_model.js | JavaScript | gpl-2.0 | 413 |
var express = require('express'),
formidable = require('formidable'),
imgur = require('imgur'),
fs = require('fs'),
url = require('url'),
bodyParser = require('body-parser'),
router = express.Router(),
uuid = require('node-uuid'),
db = require('../lib/database'),
tools = require('../lib/functions');
var connection = db.connectdb();
router.post('/upload', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Transfer-Encoding': 'chunked'
});
var id = tools.makeid();
var owner = uuid.v1();
var form = new formidable.IncomingForm(),
files = [],
fields = [];
form.uploadDir = 'tmp/';
form.on('field', function(field, value) {
fields.push(value);
});
form.on('file', function(field, file) {
files.push(file);
});
form.on('end', function() {
res.end('http://' + req.headers.host + '/' + id);
if (fields[0]) {
owner = fields[0];
}
files.forEach(function(file) {
imgur.uploadFile(file.path)
.then(function(json) {
fs.unlink(file.path);
connection.query("INSERT INTO `imgsnap`.`images` (`id`, `direct`, `timestamp`, `delete`, `owner`) VALUES ('" + connection.escape(id).replace(/'/g, '') + "', '" + connection.escape(json.data.link).replace(/'/g, '') + "', '" + connection.escape(json.data.datetime) + "', '" + connection.escape(json.data.deletehash).replace(/'/g, '') + "', '" + connection.escape(owner).replace(/'/g, '') + "')");
})
.catch(function(err) {
fs.unlink(file.path);
console.log(err);
});
});
});
form.parse(req);
});
router.get('/image/:id', function(req, res) {
var id = req.params.id;
connection.query('SELECT * FROM images WHERE id = ' + connection.escape(id), function(err, row, fields) {
if (!row[0]) {
res.json({
status: false
});
} else {
res.json({
status: true,
direct: row[0].direct,
timestamp: row[0].timestamp
});
}
});
});
router.get('/check', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Transfer-Encoding': 'chunked'
});
res.end('Server Online');
});
module.exports = router; | luigiplr/imgSnap-backend | routes/api.js | JavaScript | gpl-2.0 | 2,487 |
var UniteNivoPro = new function() {
var t = this;
var containerID = "slider_container";
var container, arrow_left, arrow_right, bullets_container;
var caption_back, caption_text;
var bulletsRelativeY = "";
/**
* show slider view error, hide all the elements
*/
t.showSliderViewError = function(errorMessage) {
jQuery("#config-document").hide();
UniteAdmin.showErrorMessage(errorMessage);
}
/**
* main init of the object
*/
var init = function() {
container = jQuery("#" + containerID);
arrow_left = jQuery("#arrow_left");
arrow_right = jQuery("#arrow_right");
bullets_container = jQuery("#bullets_wrapper");
caption_back = jQuery("#caption_back");
caption_text = jQuery("#caption_text");
UniteAdmin.hideSystemMessageDelay();
}
/**
* init visual form width
*/
t.initSliderView = function() {
init(); //init the object - must call
//update menu event
jQuery("#visual").click(function() {
setTimeout("UniteNivoPro.initAfterDelay()", 300);
});
//update visual from fields
updateFromFields();
initSliderEvents();
initVisualTabs();
//update arrows fields ) if not set
setTimeout("UniteNivoPro.initAfterDelay()", 1000);
}
/* ===================== Item View Section =================== */
/**
* init item view
*/
t.initItemView = function() {
//operate on slide image change
var obj = document.getElementById("jform_params_image");
obj.addEvent('change', function() {
var urlImage = g_urlRoot + this.value;
//trace(urlImage);
jQuery("#image_preview_wrapper").show().css("background-image", "url(\"" + urlImage + "\")");
});
}
/* ===================== Item View End =================== */
/**
* on visual tab display event. update some fields
*/
t.onVisualDisplay = function() {
updateArrowPosFields();
bulletsAlignCenter();
}
/**
* init elements after delay
*/
t.initAfterDelay = function() {
updateArrowPosFields();
initBullets();
}
/**
* align the bullets to center
*/
var bulletsAlignCenter = function() {
var align = jQuery("#jform_visual_bullets_align").val();
if (align != "center")
return(true);
var data = getElementsData();
var bulletsX = Math.round((data.sliderWidth - data.bulletsWidth) / 2);
bullets_container.css("left", bulletsX + "px");
updateBulletFields("center");
}
/**
* set bullets position by relative.
*/
var bulletsSetRelativeYPos = function() {
var data = getElementsData();
if (data.bulletsWidth == 0)
return(true);
if (bulletsRelativeY == "")
return(true);
var bulletsPosY = data.sliderHeight + bulletsRelativeY;
bullets_container.css("top", bulletsPosY + "px");
updateBulletFields("relative");
}
/**
* do some actions on bullets align change
*/
var onBulletsAlignChange = function(align) {
switch (align) {
case "center":
bullets_container.draggable("option", "axis", "y");
bulletsAlignCenter();
UniteAdmin.hideFormField("jform_visual_bullets_xleft");
UniteAdmin.hideFormField("jform_visual_bullets_xright");
break;
case "left":
bullets_container.draggable("option", "axis", "");
UniteAdmin.showFormField("jform_visual_bullets_xleft");
UniteAdmin.hideFormField("jform_visual_bullets_xright");
jQuery("#jform_visual_bullets_xleft-lbl").css('display', 'inline');
break;
case "right":
bullets_container.draggable("option", "axis", "");
UniteAdmin.hideFormField("jform_visual_bullets_xleft");
UniteAdmin.showFormField("jform_visual_bullets_xright");
jQuery("#jform_visual_bullets_xright-lbl").css('display', 'inline');
break;
}
}
/**
* on bullets drag event, update fields.
*/
var onBulletsDrag = function() {
updateBulletFields("drag");
}
/**
* update relative y
*/
var updateBulletsRelativeY = function() {
var data = getElementsData();
bulletsRelativeY = data.bulletsY - data.sliderHeight;
}
/**
* init the bullets position
*/
var initBullets = function() {
var selectorBulletsAlign = "#jform_visual_bullets_align";
var selectorBulletReverse = "#jform_visual_reverse_bullets";
var align = jQuery(selectorBulletsAlign).val();
//set bullets draggable
var drag_options = {drag: onBulletsDrag};
if (align == "center") {
bulletsAlignCenter();
//set draggable only y axis
drag_options.axis = "y";
}
jQuery(selectorBulletReverse).change(function() {
reverse_bullets();
})
//set select event
jQuery(selectorBulletsAlign).change(function() {
onBulletsAlignChange(this.value);
});
//set draggable event
bullets_container.draggable(drag_options);
//show the bullets (if hidden)
bullets_container.removeClass("invisible");
updateBulletsRelativeY();
}
/**
* show some tab, set it selecetd class, and hide the others.
*/
var showVisualTab = function(linkID) {
var link = jQuery("#" + linkID);
if (!link.length)
return(false);
var tabID = link.data("tab");
//set togler selected
jQuery("#tabs_visual li a").removeClass("selected");
link.addClass("selected");
//show panel
jQuery(".visual_panel").removeClass("hidden").hide();
jQuery(tabID).show();
}
/**
* init visual tabs functionality
*/
var initVisualTabs = function() {
var hash = location.hash;
if (hash) {
var linkID = hash.replace("#tab-", "");
showVisualTab(linkID);
}
//set event
jQuery("#tabs_visual li a").click(function() {
showVisualTab(this.id);
});
}
/**
* on slider resize event. update all elements and fields accordingly
*/
var onSliderResize = function(event, ui) {
//update fields widht / height
if (event) { //only if came from event
jQuery("#jform_visual_width").val(container.width());
jQuery("#jform_visual_height").val(container.height());
}
checkArrowsConnection("arrow_left");
bulletsSetRelativeYPos();
bulletsAlignCenter();
}
/**
* init slider view onchange events
*/
var initSliderEvents = function() {
//set fields onchange events
var fields = "#visual_wrapper input";
jQuery(fields).blur(updateFromFields).click(updateFromFields);
jQuery(fields).keypress(function(event) {
if (event.keyCode == 13)
updateFromFields(this);
});
jQuery("#visual_wrapper select").change(updateFromFields);
//set resizible event:
container.resizable({resize: onSliderResize});
//set on color picker move event:
UniteAdmin.onColorPickerMove(function() {
updateFromFields();
});
//set arrows draggable
jQuery("#arrow_left,#arrow_right").draggable({
drag: onArrowsDrag
});
jQuery("#arrows_gocenter").click(arrowsToCenter);
}
/**
* get all element sizes and positions.
*/
var getElementsData = function() {
var data = {};
//slider data
data.sliderWidth = Number(jQuery("#jform_visual_width").val());
data.sliderHeight = Number(jQuery("#jform_visual_height").val());
//arrows data
var arrowLeftPos = arrow_left.position();
var arrowRightPos = arrow_right.position();
data.arrowLeftX = Math.round(arrowLeftPos.left);
data.arrowLeftY = Math.round(arrowLeftPos.top);
data.arrowRightX = Math.round(arrowRightPos.left);
data.arrowRightY = Math.round(arrowRightPos.top);
data.arrowLeftWidth = arrow_left.width();
data.arrowLeftHeight = arrow_left.height();
data.arrowRightWidth = arrow_right.width();
data.arrowRightHeight = arrow_right.height();
//bullets data:
var bulletsPos = bullets_container.position();
data.bulletsWidth = bullets_container.width();
data.bulletsHeight = bullets_container.height();
data.bulletsX = Math.round(bulletsPos.left);
data.bulletsY = Math.round(bulletsPos.top);
return(data);
}
/**
* get the arrows to center of the banner (y axes)
*/
var arrowsToCenter = function() {
var data = getElementsData();
var arrowsNewY = Math.round(data.sliderHeight - data.arrowLeftHeight) / 2;
arrow_right.css("top", arrowsNewY + "px");
arrow_left.css("top", arrowsNewY + "px");
//update position fields on the panel
updateArrowPosFields();
}
/**
* check arrows connection, and
*/
var checkArrowsConnection = function(arrowID) {
var freeDrag = jQuery("#jform_visual_arrows_free_drag").is(":checked");
if (freeDrag == true) {
updateArrowPosFields();
return(false);
}
var data = getElementsData();
if (arrowID == "arrow_left") { //left arrow is main.
var arrowRightNewX = data.sliderWidth - data.arrowLeftX - data.arrowRightWidth;
//set right arrow position
arrow_right.css({"top": data.arrowLeftY + "px",
"left": arrowRightNewX + "px"});
} else if (arrowID == "arrow_right") { //right arrow is main
var arrowLeftNewX = data.sliderWidth - data.arrowRightX - data.arrowRightWidth;
//set left arrow position
arrow_left.css({"top": data.arrowRightY + "px",
"left": arrowLeftNewX + "px"});
}
updateArrowPosFields();
}
/**
* on arrows drag event. update form fields, and operate arrow connections.
*/
var onArrowsDrag = function() {
var arrowID = this.id;
checkArrowsConnection(arrowID);
}
/**
*
* update bullets position from the bullets
*/
var updateBulletFields = function(fromWhere) {
//trace("update fields "+fromWhere);return(false);
if (bullets_container.is(":visible") == false)
return(true);
var data = getElementsData();
//update fields:
var bulletsRightX = data.sliderWidth - data.bulletsX - data.bulletsWidth;
jQuery("#jform_visual_bullets_y").val(data.bulletsY);
jQuery("#jform_visual_bullets_xleft").val(data.bulletsX);
jQuery("#jform_visual_bullets_xright").val(bulletsRightX);
//update relative option
updateBulletsRelativeY();
}
/**
* update arrows positions from the arrows
*/
var updateArrowPosFields = function() {
//don't update if the container not visible
if (container.is(':visible') == false)
return(true);
if (arrow_left.is(':visible') == false)
return(true);
var data = getElementsData();
//set values
jQuery("#jform_visual_arrow_left_x").val(data.arrowLeftX);
jQuery("#jform_visual_arrow_left_y").val(data.arrowLeftY);
jQuery("#jform_visual_arrow_right_x").val(data.arrowRightX);
jQuery("#jform_visual_arrow_right_y").val(data.arrowRightY);
}
/**
* hide arrows and disable panel elements
*/
var hideArrows = function() {
if (arrow_left.is(':visible') == false)
return(true);
arrow_left.hide();
arrow_right.hide();
//hide arrow fields
jQuery("#section_arrows").hide();
}
/**
* show arrows and enable panel elements
*/
var showArrows = function() {
if (arrow_left.is(':visible') == true)
return(true);
arrow_left.show();
arrow_right.show();
//show arrow fields
jQuery("#section_arrows").show();
}
/**
* update the container from fields.
*/
var updateFromFields = function(element) {
if (element == undefined || element.id == undefined)
element = this;
var elemID = null;
if (element.id != undefined)
elemID = element.id;
//---- update width / height
var width = jQuery("#jform_visual_width").val();
var height = jQuery("#jform_visual_height").val();
container.width(width).height(height);
//width / heigth event
switch (elemID) {
case "jform_visual_width":
case "jform_visual_height":
onSliderResize();
break;
}
//update border
updateFromFields_border();
//update shadow
updateFromFields_shadow();
//update arrows
updateFromFields_arrows(elemID);
//update bullets
updateFromFields_bullets(elemID);
//set the bullets according the resize
bulletsSetRelativeYPos();
//update captions
updateFromFields_caption(elemID);
//update caption text
updateFromFields_captionText();
}
/**
* update caption text
*/
var updateFromFields_captionText = function() {
var css = {};
if (caption_back.is(":visible") == false)
return(true);
//set color
var textColor = jQuery("#jform_visual_text_color").val();
css["color"] = textColor;
//set text align
var textAlign = jQuery("#jform_visual_text_align").val();
css["text-align"] = textAlign;
//set padding
var textPadding = jQuery("#jform_visual_text_padding").val();
css["padding"] = textPadding + "px";
var fontSize = jQuery("#jform_visual_font_size").val();
css["font-size"] = fontSize + "px";
//set the css
caption_text.css(css);
}
/**
* show the caption
*/
var showCaption = function() {
if (caption_back.is(":visible") == true)
return(false);
caption_back.show();
}
/**
* hide the caption
*/
var hideCaption = function() {
if (caption_back.is(":visible") == false)
return(false);
caption_back.hide();
}
/**
* update captions fields
*/
var updateFromFields_caption = function(elemID) {
var css = {};
if (elemID == "jform_visual_has_caption") {
var hasCaption = jQuery("#jform_visual_has_caption").is(":checked");
if (hasCaption == true)
showCaption();
else
hideCaption();
}
if (caption_back.is(":visible") == false)
return(true);
//set back color
var backColor = jQuery("#jform_visual_caption_back_color").val();
css["background-color"] = backColor;
//set alpha
var alpha = jQuery("#jform_visual_caption_back_alpha").val();
var alpha = Number(alpha) / 100;
caption_back.fadeTo(0, alpha);
//set position:
var position = jQuery("#jform_visual_caption_position").val();
if (position == "top") {
css["bottom"] = ""; //set to top
css["top"] = "0px";
} else {
css["bottom"] = "0px"; //set to bottom
css["top"] = "";
}
//set the css
caption_back.css(css);
}
/**
* hide the bullets
*/
var hideBullets = function() {
if (bullets_container.is(":visible") == false)
return(true);
//hide fields
jQuery("#section_bullets").hide();
//hide bullets
bullets_container.hide();
}
/**
* show the bullets
*/
var showBullets = function() {
if (bullets_container.is(":visible") == true)
return(true);
//show fields
jQuery("#section_bullets").show();
//show bullets
bullets_container.removeClass("invisible").show();
}
/**
* update bullets fields
*/
var reverse_bullets = function() {
var reverseChecked = jQuery("#jform_visual_reverse_bullets").is(":checked");
var normal = 'normal';
var active = 'active';
if (reverseChecked) {
normal = 'active';
active = 'normal';
}
jQuery("#bullets_wrapper img").each(function(index, value) {
if (index == 1) {
jQuery(this).attr('src', jQuery(this).attr('src').replace(normal, active));
} else {
jQuery(this).attr('src', jQuery(this).attr('src').replace(active, normal));
}
});
}
/**
* update bullets fields
*/
var updateFromFields_bullets = function(elemID) {
//trace("update bullets");return(false);
switch (elemID) {
case "jform_visual_has_bullets":
var showBulletsCheck = jQuery("#jform_visual_has_bullets").is(":checked");
if (showBulletsCheck)
showBullets();
else
hideBullets();
break;
}
//skip invisible container
if (bullets_container.is(':visible') == false)
return(true);
var bulletsY = jQuery("#jform_visual_bullets_y").val();
switch (elemID) {
default:
case "jform_visual_bullets_xleft":
var bulletsX = jQuery("#jform_visual_bullets_xleft").val();
break;
case "jform_visual_bullets_xright":
var data = getElementsData();
var bulletsRightX = jQuery("#jform_visual_bullets_xright").val();
var bulletsX = data.sliderWidth - data.bulletsWidth - bulletsRightX;
break;
case "jform_visual_bullets_spacing": //set spacing
var spacing = jQuery("#jform_visual_bullets_spacing").val();
bullets_container.find("ul li:not(:first-child)").css("margin-left", spacing + "px");
bulletsAlignCenter();
break;
}
bullets_container.css({"top": bulletsY + "px", "left": bulletsX + "px"});
updateBulletFields("fields");
}
/**
* update border
*/
var updateFromFields_border = function() {
var has_border = jQuery("#jform_visual_has_border").is(':checked');
if (has_border == true) {
var border_color = jQuery("#jform_visual_border_color").val();
var border_size = jQuery("#jform_visual_border_size").val();
container.css({"border-style": "solid",
"border-width": border_size + "px",
"border-color": border_color
});
} else
container.css({"border-style": "none"});
}
/**
* update shadow from fields
*/
var updateFromFields_shadow = function() {
//----update shadow:
var has_shadow = jQuery("#jform_visual_has_shadow").is(':checked');
if (has_shadow == true) {
var shadow_color = jQuery("#jform_visual_shadow_color").val();
var shadowProps = "0px 1px 5px 0px " + shadow_color;
container.css({"box-shadow": shadowProps,
"-moz-box-shadow": shadowProps,
"-webkit-box-shadow": shadowProps});
} else
container.css({"box-shadow": "none", "-moz-box-shadow": "none", "-webkit-box-shadow": "none"});
}
/**
* set arrows in the place of the fields
*/
var updateFromFields_arrows = function(elemID) {
var showArrows_check = jQuery("#jform_visual_has_arrows").is(":checked");
//check arrows hide / show
if (elemID == "jform_visual_has_arrows") {
if (showArrows_check == false)
hideArrows();
else
showArrows();
}
//position arrows
if (arrow_left.is(':visible') == false)
return(true);
var arrowLeftX = jQuery("#jform_visual_arrow_left_x").val();
var arrowLeftY = jQuery("#jform_visual_arrow_left_y").val();
var arrowRightX = jQuery("#jform_visual_arrow_right_x").val();
var arrowRightY = jQuery("#jform_visual_arrow_right_y").val();
arrow_left.css({"top": arrowLeftY + "px", "left": arrowLeftX + "px"});
arrow_right.css({"top": arrowRightY + "px", "left": arrowRightX + "px"});
//operate errors connection:
switch (elemID) {
case "jform_visual_has_arrows":
case "jform_visual_arrow_left_y":
case "jform_visual_arrow_left_x":
checkArrowsConnection("arrow_left");
break;
case "jform_visual_arrow_right_y":
case "jform_visual_arrow_right_x":
checkArrowsConnection("arrow_right");
break;
}
}
/**
* on arrows select event - update arrow pictures and change arrows set
*/
t.onArrowsSelect = function(data) {
jQuery("#arrow_left").attr("src", data.url_left);
jQuery("#arrow_right").attr("src", data.url_right);
jQuery("#jform_visual_arrows_set").val(data.arrowName);
//align arrows
setTimeout("UniteNivoPro.operationDelay('checkArrowsConnection')", 500);
}
/**
* on bullets select - take bullets html by ajax, and change the bullets.
*/
t.onBulletsSelect = function(setName) {
var data = {setName: setName};
UniteAdmin.ajaxRequest("get_bullets_html", data, function(response) {
jQuery("#bullets_wrapper").html(response.bullets_html);
jQuery("#jform_visual_bullets_set").val(setName);
//align center after delay
setTimeout("UniteNivoPro.operationDelay('bulletsAlignCenter')", 500);
bulletsAlignCenter();
reverse_bullets();
});
}
/**
* align center after delay function
*/
t.operationDelay = function(operation) {
switch (operation) {
case "bulletsAlignCenter":
bulletsAlignCenter();
break;
case "checkArrowsConnection":
checkArrowsConnection("arrow_left");
break;
}
}
}
| VS-Studio3/build | administrator/components/com_nivosliderpro/assets/nivopro.js | JavaScript | gpl-2.0 | 22,978 |
/*
Copyright: © 2011 Thomas Stein, CodeLounge.de
<mailto:[email protected]> <http://www.codelounge.de/>
Released under the terms of the GNU General Public License.
You should have received a copy of the GNU General Public License,
along with this software. In the main directory, see: licence.txt
If not, see: <http://www.gnu.org/licenses/>.
*/
/*
* MBP - Mobile boilerplate helper functions
*/
(function(document){
window.MBP = window.MBP || {};
// Fix for iPhone viewport scale bug
// http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/
MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]');
MBP.ua = navigator.userAgent;
MBP.scaleFix = function () {
if (MBP.viewportmeta && /iPhone|iPad/.test(MBP.ua) && !/Opera Mini/.test(MBP.ua)) {
MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
document.addEventListener("gesturestart", MBP.gestureStart, false);
}
};
MBP.gestureStart = function () {
MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6";
};
// Hide URL Bar for iOS
// http://remysharp.com/2010/08/05/doing-it-right-skipping-the-iphone-url-bar/
MBP.hideUrlBar = function () {
/iPhone/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () {
window.scrollTo(0, 1);
}, 1000),
/iPad/.test(MBP.ua) && !pageYOffset && !location.hash && setTimeout(function () {
window.scrollTo(0, 1);
}, 1000);
};
});
jQuery( function() {
$("a.facebox").fancybox();
//$("a.fancybox").prettyPhoto({
// social_tools: false
//});
jQuery('.entenlogo').click(function() {
$('.entenlogo').hide();
});
var current_url = $(location).attr('href');
//console.log($(location).attr('href'));
jQuery('body').bind( 'taphold', function( e ) {
//$('#next_post_link').attr('refresh');
//$('#previous_post_link').attr('refresh');
$('#page').page('refresh');
var next_url = $('#next_post_link').attr('href');
var previous_url = $('#previous_post_link').attr('href');
console.log(next_url + ' --- ' + previous_url);
e.stopImmediatePropagation();
return false;
} );
jQuery('body').bind( 'swipeleft', function( e ) {
var next_url = $('.ui-page-active #next_post_link').attr('href');
var previous_url = $('.ui-page-active #previous_post_link').attr('href');
console.log("Swiped Left: " + next_url + ' --- ' + previous_url);
if (undefined != previous_url) {
//$.mobile.changePage( previous_url,"slide", true);
$.mobile.changePage( previous_url, {
transition: "slide",
reverse: false,
changeHash: true
});
e.stopImmediatePropagation();
return false;
}
} );
jQuery('body').bind( 'swiperight', function( e ) {
var next_url = $('.ui-page-active #next_post_link').attr('href');
var previous_url = $('.ui-page-active #previous_post_link').attr('href');
console.log("Swiped Right: " + next_url + ' --- ' + previous_url);
if (undefined != next_url) {
//$.mobile.changePage( next_url, "slide", true);
$.mobile.changePage( next_url, {
transition: "slide",
reverse: true,
changeHash: true
});
e.stopImmediatePropagation();
return false;
}
} );
} );
| codelounge/codelounge-exposure-theme | js/exposure.js | JavaScript | gpl-2.0 | 3,408 |
/**
* card_view = new BaristaCardView({el: $("target_selector",
url:"",
title:"",
subtitle:"",
fg_color: "#1b9e77",
image:"",
span_class: "col-lg-12"});
*
* A Backbone View that displays a card of information wrapped in link
* The view is meant to be a top level entry point to other pages
* basic use:
card_view = new BaristaCardView();
* optional arguments:
* @param {string} url the link to navigate to if the card is clicked, defaults to ""
* @param {string} title the title of the card. defaults to "title"
* @param {string} subtitle the subtitle of the card. defaults to "subtitle"
* @param {string} image the link to an image to show as the cards main content. defaults to ""
* @param {string} fg_color the hex color code to use as the foreground color of the view, defaults to
* #1b9e77
* @param {string} span_class a bootstrap span class to size the width of the view, defaults to
* "col-lg-12"
*/
Barista.Views.BaristaCardView = Backbone.View.extend({
/**
* give the view a name to be used throughout the View's functions when it needs to know what its class
* name is
* @type {String}
*/
name: "BaristaCardView",
/**
* supply a base model for the view
* Overide this if you need to use it for dynamic content
* @type {Backbone}
*/
model: new Backbone.Model(),
/**
* overide the view's default initialize method in order to catch options and render a custom template
*/
initialize: function(){
// set up color options. default if not specified
this.fg_color = (this.options.fg_color !== undefined) ? this.options.fg_color : "#1b9e77";
// set up the span size
this.span_class = (this.options.span_class !== undefined) ? this.options.span_class : "col-lg-12";
// set up the url
this.url = (this.options.url !== undefined) ? this.options.url : "";
// set up the title
this.title = (this.options.title !== undefined) ? this.options.title : "Title";
// set up the subtitle
this.subtitle = (this.options.subtitle !== undefined) ? this.options.subtitle : "subtitle";
// set up the image
this.image = (this.options.image !== undefined) ? this.options.image : "";
// bind render to model changes
this.listenTo(this.model,'change', this.update);
// compile the default template for the view
this.compile_template();
},
/**
* use Handlebars to compile the template for the view
*/
compile_template: function(){
var self = this;
this.div_string = 'barista_view' + new Date().getTime();;
this.$el.append(BaristaTemplates.CMapCard({div_string: this.div_string,
span_class: this.span_class,
url: this.url,
title: this.title,
subtitle: this.subtitle,
image: this.image,
fg_color: this.fg_color}));
}
});
| cmap/barista | source/views/BaristaCardView.js | JavaScript | gpl-2.0 | 2,907 |
'use strict';
app.controller('orderController', ['$scope', '$rootScope', 'toastrService', 'orderService',
function ($scope, $rootScope, toastrService, orderService) {
$scope.paging = 1;
$scope.disabledMore = false;
$scope.data = [];
$scope.getOrders = function () {
orderService.get($scope.paging).then(function (data) {
if (data.length > 0) {
$scope.data.push.apply($scope.data, data);
} else {
$scope.disabledMore = true;
}
});
}
$scope.more = function () {
$scope.paging++;
$scope.getOrders();
};
$scope.refresh = function () {
$scope.paging = 1;
$scope.data = [];
$scope.getOrders();
};
$scope.getOrders();
$scope.openOrder = function (item, $index) {
$scope.order = item;
$scope.order.$index = $index;
$('#modal-order').modal({
backdrop: true
});
};
}
]); | ozalvarez/elcubo9 | elcubo9.admin/app/controllers/orderController.js | JavaScript | gpl-2.0 | 1,103 |
/*
* Flocking Debugging Unit Generators
* http://github.com/colinbdclark/flocking
*
* Copyright 2011-2014, Colin Clark
* Dual licensed under the MIT and GPL Version 2 licenses.
*/
/*global require*/
/*jshint white: false, newcap: true, regexp: true, browser: true,
forin: false, nomen: true, bitwise: false, maxerr: 100,
indent: 4, plusplus: false, curly: true, eqeqeq: true,
freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true,
unused: true, strict: true, asi: false, boss: false, evil: false, expr: false,
funcscope: false*/
var fluid = fluid || require("infusion"),
flock = fluid.registerNamespace("flock");
(function () {
"use strict";
// TODO: Unit tests.
flock.ugen.print = function (input, output, options) {
var that = flock.ugen(input, output, options);
that.gen = function (numSamps) {
var inputs = that.inputs,
out = that.output,
m = that.model,
label = m.label,
chan = inputs.channel,
// Basic multichannel support. This should be inproved
// by factoring the multichannel input code out of flock.ugen.out.
source = chan ? inputs.source.output[chan.output[0]] : inputs.source.output,
trig = inputs.trigger.output[0],
freq = inputs.freq.output[0],
i,
j,
val;
if (trig > 0.0 && m.prevTrig <= 0.0) {
fluid.log(fluid.logLevel.IMPORTANT, label + source);
}
if (m.freq !== freq) {
m.sampInterval = Math.round(m.sampleRate / freq);
m.freq = freq;
m.counter = m.sampInterval;
}
for (i = 0, j = 0 ; i < numSamps; i++, j += m.strides.source) {
if (m.counter >= m.sampInterval) {
fluid.log(fluid.logLevel.IMPORTANT, label + source[j]);
m.counter = 0;
}
m.counter++;
out[i] = val = source[i];
}
m.value = m.unscaledValue = val;
};
that.init = function () {
var o = that.options;
that.model.label = o.label ? o.label + ": " : "";
that.onInputChanged();
};
that.init();
return that;
};
flock.ugenDefaults("flock.ugen.print", {
rate: "audio",
inputs: {
source: null,
trigger: 0.0,
freq: 1.0
},
ugenOptions: {
model: {
unscaledValue: 0.0,
value: 0.0,
counter: 0
},
strideInputs: ["source"]
}
});
}());
| mcanthony/Flocking | src/ugens/debugging.js | JavaScript | gpl-2.0 | 2,806 |
import { createSelector } from '@automattic/state-utils';
import { filter, orderBy } from 'lodash';
import 'calypso/state/comments/init';
function filterCommentsByStatus( comments, status ) {
return 'all' === status
? filter(
comments,
( comment ) => 'approved' === comment.status || 'unapproved' === comment.status
)
: filter( comments, ( comment ) => status === comment.status );
}
/**
* Returns list of loaded comments for a given site, filtered by status
*
* @param {object} state Redux state
* @param {number} siteId Site for whose comments to find
* @param {string} [status] Status to filter comments
* @param {string} [order=asc] Order in which to sort filtered comments
* @returns {Array<object>} Available comments for site, filtered by status
*/
export const getSiteComments = createSelector(
( state, siteId, status, order = 'asc' ) => {
const comments = state.comments.items ?? {};
const parsedComments = Object.keys( comments )
.filter( ( key ) => parseInt( key.split( '-', 1 ), 10 ) === siteId )
.reduce( ( list, key ) => [ ...list, ...comments[ key ] ], [] );
return status
? orderBy( filterCommentsByStatus( parsedComments, status ), 'date', order )
: orderBy( parsedComments, 'date', order );
},
( state ) => [ state.comments.items ]
);
| Automattic/wp-calypso | client/state/comments/selectors/get-site-comments.js | JavaScript | gpl-2.0 | 1,304 |
(function(customer_id) {
tinymce.create('tinymce.plugins.ItStream_AttachToPost', {
customer_id: customer_id,
init : function(editor, plugin_url) {
editor.addButton('player_scheduling', {
title : 'Embed ItStream Player',
cmd : 'itm_scheduling',
image : plugin_url + '/scheduling.gif'
});
// Register a new TinyMCE command
editor.addCommand('itm_scheduling', this.render_attach_to_post_interface, {
editor: editor,
plugin: editor.plugins.ItStream_AttachToPost
});
},
createControl : function(n, cm) {
return null;
},
getInfo : function() {
return {
longname : 'ItStream Scheduling Button',
author : 'It-Marketing',
authorurl : 'http://www.itmarketingsrl.it/',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example',
version : "0.1"
};
},
wm_close_event: function() {
// Restore scrolling for the main content window when the attach to post interface is closed
jQuery('html,body').css('overflow', 'auto');
tinyMCE.activeEditor.selection.select(tinyMCE.activeEditor.dom.select('p')[0]);
tinyMCE.activeEditor.selection.collapse(0);
},
render_attach_to_post_interface: function() {
var attach_to_post_url = itstream_ajax.attach_to_post;
if (typeof(customer_id) != 'undefined') {
attach_to_post_url += "?id=" + itstream_ajax.customer_id;
}
var win = window;
while (win.parent != null && win.parent != win) {
win = win.parent;
}
win = jQuery(win);
var winWidth = win.width();
var winHeight = win.height();
var popupWidth = 680;
var popupHeight = 560;
var minWidth = 320;
var minHeight = 200;
var maxWidth = winWidth - (winWidth * 0.05);
var maxHeight = winHeight - (winHeight * 0.05);
if (maxWidth < minWidth) { maxWidth = winWidth - 10; }
if (maxHeight < minHeight) { maxHeight = winHeight - 10; }
if (popupWidth > maxWidth) { popupWidth = maxWidth; }
if (popupHeight > maxHeight) { popupHeight = maxHeight; }
// Open a window
this.editor.windowManager.open({
url: attach_to_post_url,
id: 'its_attach_to_post_dialog',
width: popupWidth,
height: popupHeight,
title: 'ItStream - Embed Player',
inline: 1
/*buttons: [{
text: 'Close',
onclick: 'close'
}]*/
});
// Ensure that the window cannot be scrolled - XXX actually allow scrolling in the main window and disable it for the inner-windows/frames/elements as to create a single scrollbar
jQuery('html,body').css('overflow', 'hidden');
jQuery('#its_attach_to_post_dialog_ifr').css('overflow-y', 'auto');
jQuery('#its_attach_to_post_dialog_ifr').css('overflow-x', 'hidden');
}
});
// Register plugin
tinymce.PluginManager.add( 'itstream', tinymce.plugins.ItStream_AttachToPost );
})(itstream_ajax.customer_id); | wp-plugins/itstream | admin/assets/js/editor.js | JavaScript | gpl-2.0 | 3,621 |
jQuery(function($) {
///////////////////////////////////////////////////////////////////
///// META BOXES JS
///////////////////////////////////////////////////////////////////
jQuery('.repeatable-add').live('click', function() {
var field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true);
var fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last');
field.find('input.regular-text, textarea, select').val('');
field.find('input, textarea, select').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
field.insertAfter(fieldLocation, jQuery(this).closest('td'));
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount > 1 ) {
jQuery('.repeatable-remove').css('display','inline');
}
return false;
});
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount == 1 ) {
jQuery('.repeatable-remove').css('display','none');
}
jQuery('.repeatable-remove').live('click', function() {
jQuery(this).parent().remove();
var fieldsCount = jQuery('.repeatable-remove').length;
if( fieldsCount == 1 ) {
jQuery('.repeatable-remove').css('display','none');
}
return false;
});
jQuery('.custom_repeatable').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.sort'
});
// the upload image button, saves the id and outputs a preview of the image
var imageFrame;
$('.rg-bb_upload_image_button').live('click', function(event) {
event.preventDefault();
var options, attachment;
$self = $(event.target);
$div = $self.closest('div.rg-bb_image');
// if the frame already exists, open it
if ( imageFrame ) {
imageFrame.open();
return;
}
// set our settings
imageFrame = wp.media({
title: 'Choose Image',
multiple: true,
library: {
type: 'image'
},
button: {
text: 'Use This Image'
}
});
// set up our select handler
imageFrame.on( 'select', function() {
selection = imageFrame.state().get('selection');
if ( ! selection )
return;
// loop through the selected files
selection.each( function( attachment ) {
console.log(attachment);
var src = attachment.attributes.sizes.full.url;
var id = attachment.id;
$div.find('.rg-bb_preview_image').attr('src', src);
$div.find('.rg-bb_upload_image').val(id);
} );
});
// open the frame
imageFrame.open();
});
// the remove image link, removes the image id from the hidden field and replaces the image preview
$('.rg-bb_clear_image_button').live('click', function() {
var defaultImage = $(this).parent().siblings('.rg-bb_default_image').text();
$(this).parent().siblings('.rg-bb_upload_image').val('');
$(this).parent().siblings('.rg-bb_preview_image').attr('src', defaultImage);
return false;
});
// function to create an array of input values
function ids(inputs) {
var a = [];
for (var i = 0; i < inputs.length; i++) {
a.push(inputs[i].val);
}
//$("span").text(a.join(" "));
}
// repeatable fields
$('.toggle').on("click", function() {
console.log($(this).parent().siblings().toggleClass('closed'));
});
$('.meta_box_repeatable_add').live('click', function(e) {
e.preventDefault();
// clone
var row = $(this).closest('.meta_box_repeatable').find('tbody tr:last-child');
var clone = row.clone();
var defaultImage = clone.find('.meta_box_default_image').text();
clone.find('select.chosen').removeAttr('style', '').removeAttr('id', '').removeClass('chzn-done').data('chosen', null).next().remove();
// clone.find('input.regular-text, textarea, select').val('');
clone.find('.meta_box_preview_image').attr('src', defaultImage).removeClass('loaded');
clone.find('input[type=checkbox], input[type=radio]').attr('checked', false);
row.after(clone);
// increment name and id
clone.find('input, textarea, select').attr('name', function(index, name) {
return name.replace(/(\d+)/, function(fullMatch, n) {
return Number(n) + 1;
});
});
var arr = [];
$('input.repeatable_id:text').each(function(){ arr.push($(this).val()); });
clone.find('input.repeatable_id')
.val(Number(Math.max.apply( Math, arr )) + 1);
if (!!$.prototype.chosen) {
clone.find('select.chosen')
.chosen({allow_single_deselect: true});
}
});
$('.meta_box_repeatable_remove').live('click', function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
$('.meta_box_repeatable tbody').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.hndle'
});
// post_drop_sort
$('.sort_list').sortable({
connectWith: '.sort_list',
opacity: 0.6,
revert: true,
cursor: 'move',
cancel: '.post_drop_sort_area_name',
items: 'li:not(.post_drop_sort_area_name)',
update: function(event, ui) {
var result = $(this).sortable('toArray');
var thisID = $(this).attr('id');
$('.store-' + thisID).val(result)
}
});
$('.sort_list').disableSelection();
// turn select boxes into something magical
if (!!$.prototype.chosen)
$('.chosen').chosen({ allow_single_deselect: true });
}); | StefanDindyal/wordpresser | wp-content/themes/bobbarnyc/inc/settings-panel/js/custom-admin.js | JavaScript | gpl-2.0 | 5,266 |
/* JavaScript User Interface Library -- Common datatypes for user elements
* Copyright 2010 Jaakko-Heikki Heusala <[email protected]>
* $Id: common.js 415 2010-10-15 05:00:51Z jheusala $
*/
/** Simple message box constructor
* @params type The message type: error, notice, info or success
* @params msg Message
*/
function UIMessage(type, msg) {
var undefined;
if(this instanceof arguments.callee) {
if(type === undefined) throw TypeError("type undefined");
if(msg === undefined) {
msg = type;
type = undefined;
}
this.type = type || "info";
this.msg = ""+msg;
} else {
return new UIMessage(type, msg);
}
}
/** Get the message as a string */
UIMessage.prototype.toString = function() {
return this.type + ": " + this.msg;
}
/** Convert to JSON using JSONObject extension */
UIMessage.prototype.toJSON = function() {
return new JSONObject("UIMessage", this.type + ":" + this.msg );
};
/* Setup reviver for JSONObject */
JSONObject.revivers.UIMessage = function(value) {
var parts = (""+value).split(":");
return new UIMessage(parts.shift(), parts.join(":"));
};
/* EOF */
| jheusala/jsui | lib/jsui/common.js | JavaScript | gpl-2.0 | 1,101 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
( function($) {
} )( jQuery );
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})(); | jsxmedia/jgm-wp-theme | js/global-functions.js | JavaScript | gpl-2.0 | 566 |
'use strict';
angular.module('eshttp')
.filter('unixtostr', function() {
return function(str){
var dt;
dt = Date.create(str * 1000).format('{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}');
if (dt == "Invalid Date") {
return 'N/A';
} else {
return dt;
}
};
});
| fangli/eshttp | eshttp_webmanager/cloudconfig/static/filters/unixtostr.js | JavaScript | gpl-2.0 | 323 |
/*
Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colordialog', 'en-gb', {
clear: 'Clear',
highlight: 'Highlight',
options: 'Colour Options',
selected: 'Selected Colour',
title: 'Select colour'
} );
| WBCE/WebsiteBaker_CommunityEdition | wbce/modules/ckeditor/ckeditor/plugins/colordialog/lang/en-gb.js | JavaScript | gpl-2.0 | 344 |
(function() {
var preview = true;
var themeShortcuts = {
insert: function(where) {
switch(where) {
case 'st_button_more':
var href = jQuery("#btn_more_src").val();
var what = '[st_button_more href="'+href+'"]';
break;
case 'st_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'"]'+text+'[/st_button]';
break;
case 'st_hover_fill_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var hover_bg = jQuery("#hover_bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var hover_direction = jQuery("#hover_direction").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_fill_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" hover_background="'+hover_bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" hover_direction="'+hover_direction+'"]'+text+'[/st_hover_fill_button]';
break;
case 'st_hover_fancy_icon_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var icon_color = jQuery("#icon_color").val();
var icon_bg = jQuery("#icon_bg").val();
var target = jQuery("#target").val();
var icon_position = jQuery("#icon_pos").val();
var icon_separator = jQuery("#icon_sep").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_fancy_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_color="'+icon_color+'" icon_background="'+icon_bg+'" icon_position="'+icon_position+'" icon_separator="'+icon_separator+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_fancy_icon_button]';
break;
case 'st_hover_arrows_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var arrow_direction = jQuery("#arrow_direction").val();
var what = '[st_hover_arrows_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" arrow_direction="'+arrow_direction+'"]'+text+'[/st_hover_arrows_button]';
break;
case 'st_hover_icon_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var icon_direction = jQuery("#icon_direction").val();
var what = '[st_hover_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_direction="'+icon_direction+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_icon_button]';
break;
case 'st_hover_bordered_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_type = jQuery("#border_type").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_bordered_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" border_type="'+border_type+'"]'+text+'[/st_hover_bordered_button]';
break;
case 'st_unordered':
var list = '<li>First list item</li>';
var listicon = jQuery("#listicon").val();
var what = '[st_unordered listicon="'+listicon+'"]'+list+'[/st_unordered]';
break;
case 'st_box':
var title = jQuery("#box_title").val();
var text = jQuery("#text").val();
var type = jQuery("#box_type").val();
var what = '[st_box title="'+title+'" type="'+type+'"]'+text+'[/st_box]';
break;
case 'st_callout':
var title = jQuery("#callout_title").val();
var text = jQuery("#text").val();
var btn_text = jQuery("#btn_text").val();
var btn_link = jQuery("#btn_link").val();
var text_color = jQuery("#color").val();
var bg = jQuery("#bg").val();
var what = '[st_callout title="'+title+'" button_text="'+btn_text+'" link="'+btn_link+'" text_color="'+text_color+'" background="'+bg+'"]'+text+'[/st_callout]';
break;
case 'st_tooltip':
var text = jQuery("#text").val();
var tooltip_text = jQuery("#tooltip_text").val();
var type = jQuery("#tooltip_type").val();
var what = '[st_tooltip type="'+type+'" tooltip_text="'+tooltip_text+'"]'+text+'[/st_tooltip]';
break;
case 'st_popover':
var content = 'Your text here';
var title = jQuery("#popover_title").val();
var text = jQuery("#popover_text").val();
var type = jQuery("#popover_type").val();
var what = '[st_popover type="'+type+'" popover_title="'+title+'" text="'+text+'"]'+content+'[/st_popover]';
break;
case 'st_modal':
var title = jQuery("#modal_title").val();
var content = jQuery("#modal_text").val();
var modal_link = jQuery("#modal_link").val();
var primary_text = jQuery("#primary").val();
var primary_link = jQuery("#primary_link").val();
var what = '[st_modal modal_link="'+modal_link+'" primary_text="'+primary_text+'" primary_link="'+primary_link+'" modal_title="'+title+'"]'+content+'[/st_modal]';
break;
case 'st_tables':
var colsEl = jQuery("#cols");
var rowsEl = jQuery("#rows");
var cols = new Array();
var rows = new Array();
for(var i=0; i<jQuery(rowsEl).val(); i++) {
for(var j=0; j<jQuery(colsEl).val(); j++) {
if(i == 0) {
cols.push(jQuery('#input_'+i+''+j).val());
} else if (i == 1) {
rows.push(jQuery('#input_'+i+''+j).val());
j = jQuery(colsEl).val();
} else {
rows.push(jQuery('#input_'+i+''+j).val());
}
}
}
var what = '[st_table cols="'+cols.join('||')+'" data="'+rows.join('||')+'"]';
break;
case 'st_tabs':
var tabs = '';
var boxes = jQuery(".box");
boxes.splice(0,1);
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
tabs += '[st_tab title="'+title+'"]'+text+'[/st_tab]';
});
var what = '[st_tabs]'+tabs+'[/st_tabs]';
break;
case 'st_toggle':
var accs = '';
var boxes = jQuery(".box");
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
var state = jQuery(this).find('select').val();
accs += '[st_panel title="'+title+'" state="'+state+'"]'+text+'[/st_panel]<br />';
});
var what = '[st_toggle]<br />'+accs+'[/st_toggle]';
break;
case 'st_accordion':
var accs = '';
var boxes = jQuery(".box");
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
var state = jQuery(this).find('select').val();
accs += '[st_acc_panel title="'+title+'" state="'+state+'"]'+text+'[/st_acc_panel]<br />';
});
var what = '[st_accordion]<br />'+accs+'[/st_accordion]';
break;
case 'st_progress_bar':
var width = jQuery("#width").val();
var style = jQuery("#style").val();
var striped = jQuery("#striped").val();
var active = jQuery("#active").val();
var what = '[st_progress_bar width="'+width+'" style="'+style+'" striped="'+striped+'" active="'+active+'"]';
break;
case 'st_related_posts':
var limit = jQuery("#limit").val();
var what = '[st_related_posts limit="'+limit+'"]';
break;
case 'st_highlight':
var background_color = jQuery("#background_color").val();
var text_color = jQuery("#text_color").val();
var what = '[st_highlight background_color="'+background_color+'" text_color="'+text_color+'"]Highlighted text[/st_highlight]';
break;
case 'st_loginout':
var text_col = jQuery("#color").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var type = jQuery("#login_type").val();
var target = jQuery("#target").val();
var login_msg = jQuery("#login_msg").val();
var logout_msg = jQuery("#logout_msg").val();
var what = '[st_loginout text_col="'+text_col+'" background="'+bg+'" size="'+size+'" login_msg="'+login_msg+'" logout_msg="'+logout_msg+'"]';
break;
case 'st_quote':
var author = jQuery("#author-name").val();
var content = jQuery("#text").val();
var what = '[st_quote author="'+author+'"]' +content+ '[/st_quote]';
break;
case 'st_abbreviation':
var text = jQuery("#text").val();
var abbreviation = jQuery("#abbreviation").val();
var what = '[st_abbr title="'+abbreviation+'"]' + text + '[/st_abbr]';
break;
case 'st_twitter':
var style = jQuery("#style").val();
var url = jQuery("#url").val();
var sourceVal = jQuery("#source").val();
var related = jQuery("#related").val();
var text = jQuery("#text").val();
var lang = jQuery("#lang").val();
var what = '[st_twitter style="'+style+'" url="'+url+'" source="'+sourceVal+'" related="'+related+'" text="'+text+'" lang="'+lang+'"]';
break;
case 'st_digg':
var style = jQuery("#style").val();
var link = jQuery("#link").val();
var title = jQuery("#digg_title").val();
var what = '[st_digg style="'+style+'" title="'+title+'" link="'+link+'"]';
break;
case 'st_fblike':
var style = jQuery("#style").val();
var url = jQuery("#url").val();
var show_faces = jQuery("#show_faces").val();
var width = jQuery("#width").val();
var verb = jQuery("#verb_to_display").val();
var font = jQuery("#font").val();
var what = '[st_fblike url="'+url+'" style="'+style+'" showfaces="'+show_faces+'" width="'+width+'" verb="'+verb+'" font="'+font+'"]';
break;
case 'st_fbshare':
var url = jQuery("#link").val();
var what = '[st_fbshare url="'+url+'"]';
break;
case 'st_lishare':
var style = jQuery("#style").val();
var url = jQuery("#link").val();
var sourceVal = jQuery("#source").val();
var related = jQuery("#related").val();
var text = jQuery("#text").val();
var lang = jQuery("#lang").val();
var what = '[st_linkedin_share url="'+url+'" style="'+style+'"]';
break;
case 'st_gplus':
var style = jQuery("#style").val();
var size = jQuery("#size").val();
var what = '[st_gplus style="'+style+'" size="'+size+'"]';
break;
case 'st_pinterest_pin':
var style = jQuery("#style").val();
var what = '[st_pinterest_pin style="'+style+'"]';
break;
case 'st_tumblr':
var style = jQuery("#style").val();
var what = '[st_tumblr style="'+style+'"]';
break;
case 'st_pricingTable':
var content = '';
var columns = jQuery("#columns").val();
var highlighted = jQuery("#highlighted").val();
for(x=0;x<columns;x++) {
var highlight = ((x+1) == highlighted) ? " highlight='true'" : '';
content += "\n[st_pricing_column title='Column " + (x+1) + "'" + highlight + "]\n[st_price_info cost='$14.99/month'][/st_price_info]<ul><li>Item description and details...</li>\n<li>Item description and details...</li>\n<li>Some more info...</li>\n<li>[st_button text_color='#444444' link='#' background='#E6E6E6' size='small']Button text[/st_button]</li></ul>\n[/st_pricing_column]\n";
}
var what = "[st_pricing_table columns='"+columns+"']\n" + content + "\n[/st_pricing_table]";
break;
case 'st_gmap':
var additional = '';
additional = (jQuery("#latitude").val() != '') ? additional + ' latitude="'+ jQuery("#latitude").val() +'"' : additional;
additional = (jQuery("#longitute").val() != '') ? additional + ' longitute="'+ jQuery("#longitute").val() +'"' : additional;
additional = (jQuery("#html").val() != '') ? additional + ' html="'+ jQuery("#html").val() +'"' : additional;
additional = (jQuery("#zoom").val() != '') ? additional + ' zoom="'+ jQuery("#zoom").val() +'"' : additional;
additional = (jQuery("#gheight").val() != '') ? additional + ' height="'+ jQuery("#gheight").val() +'"' : additional;
additional = (jQuery("#gwidth").val() != '') ? additional + ' width="'+ jQuery("#gwidth").val() +'"' : additional;
additional = (jQuery("#maptype").val() != '') ? additional + ' maptype="'+ jQuery("#maptype").val() +'"' : additional;
additional = (jQuery("#color").val() != '') ? additional + ' color="'+ jQuery("#color").val() +'"' : additional;
var what = '[st_gmap '+additional+']';
break;
case 'st_trends':
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var query = jQuery("#query").val();
var geo = jQuery("#geo").val();
var what = '[st_trends width="'+width+'" height="'+height+'" query="'+query+'" geo="'+geo+'"]';
break;
case 'st_gchart':
var data = jQuery("#data").val();
var title = jQuery("#g_title").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var series_type = jQuery("#series_type").val();
var vAxis = jQuery("#vAxis").val();
var hAxis = jQuery("#hAxis").val();
var type = jQuery("#gchart_type").val();
var red_from = jQuery("#red_from").val();
var red_to = jQuery("#red_to").val();
var yellow_from = jQuery("#yellow_from").val();
var yellow_to = jQuery("#yellow_to").val();
var gauge_minor_ticks = jQuery("#gauge_minor_ticks").val();
var what = '[st_chart title="'+title+'" data="'+data+'" width="'+width+'" height="'+height+'" type="'+type+'" series_type="'+series_type+'" vAxis="'+vAxis+'" hAxis="'+hAxis+'" red_from="'+red_from+'" red_to="'+red_to+'" yellow_from="'+yellow_from+'" yellow_to="'+yellow_to+'" gauge_minor_ticks="'+gauge_minor_ticks+'"]';
break;
case 'st_chart_pie':
var data = jQuery("#data").val();
var title = jQuery("#pie_title").val();
var what = '[st_chart_pie title="'+title+'" data="'+data+'"]';
break;
case 'st_chart_bar':
var data = jQuery("#data").val();
var title = jQuery("#bar_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var what = '[st_chart_bar title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]';
break;
case 'st_chart_area':
var data = jQuery("#data").val();
var title = jQuery("#area_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var what = '[st_chart_area title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]';
break;
case 'st_chart_geo':
var data = jQuery("#data").val();
var title = jQuery("#geo_title").val();
var primary = jQuery("#primary").val();
var secondary = jQuery("#secondary").val();
var what = '[st_chart_geo title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]';
break;
case 'st_chart_combo':
var data = jQuery("#data").val();
var title = jQuery("#combo_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var series = jQuery("#series").val();
var what = '[st_chart_combo title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'" series="'+series+'"]';
break;
case 'st_chart_org':
var data = jQuery("#data").val();
var what = '[st_chart_org data="'+data+'"]';
break;
case 'st_chart_bubble':
var data = jQuery("#data").val();
var title = jQuery("#bubble_title").val();
var primary = jQuery("#primary").val();
var secondary = jQuery("#secondary").val();
var what = '[st_chart_bubble title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]';
break;
case 'st_gdocs':
var url = jQuery("#url").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var what = "[st_gdocs width='"+width+"' height='"+height+"' url='"+ url +"']";
break;
case 'st_children':
var parent = jQuery("#page").val();
var what = "[st_children of='"+ parent +"']";
break;
case 'st_contact_form_dark':
var email_d = jQuery("#email_d").val();
var what = "[st_contact_form_dark email='"+ email_d +"']";
break;
case 'st_contact_form_light':
var email_l = jQuery("#email_l").val();
var what = "[st_contact_form_light email='"+ email_l +"']";
break;
case 'st_fancyboxImages':
var href = jQuery("#href").val();
var thumb = jQuery("#thumb").val();
var thumb_width = jQuery("#thumb_width").val();
var group = jQuery("#group").val();
var title = jQuery("#title_lb").val();
var what = "[st_fancyboxImages href='"+ href +"' thumb='"+thumb+"' thumb_width='"+thumb_width+"' group='"+group+"' title='"+title+"']";
break;
case 'st_fancyboxInline':
var title = jQuery("#in_title").val();
var content_title = jQuery("#content_title").val();
var content = jQuery("#in_content").val();
var what = "[st_fancyboxInline title='"+title+"' content_title='"+content_title+"' content='"+content+"']";
break;
case 'st_fancyboxIframe':
var title = jQuery("#iframe_title").val();
var href = jQuery("#iframe_href").val();
var what = "[st_fancyboxIframe title='"+title+"' href='"+ href +"']";
break;
case 'st_fancyboxPage':
var title = jQuery("#ipage_title").val();
var href = jQuery("#ipage").val();
var what = "[st_fancyboxPage title='"+title+"' href='"+ href +"']";
break;
case 'st_fancyboxSwf':
var title = jQuery("#swf_title").val();
var href = jQuery("#swf").val();
var what = "[st_fancyboxSwf title='"+title+"' href='"+href+"']";
break;
case 'st_video':
var title = jQuery("#video_title").val();
var display = jQuery("#display").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var type = jQuery("#video_type").val();
if (type == 'flash') {
var src = jQuery("#src").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']";
} else if (type == 'html5') {
var poster = jQuery("#poster").val();
var mp4 = jQuery("#mp4").val();
var webm = jQuery("#webm").val();
var ogg = jQuery("#ogg").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' poster='"+poster+"' mp4='"+mp4+"' webm='"+webm+"' ogg='"+ogg+"']";
} else {
var src = jQuery("#clip_id").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']";
}
var group = jQuery("#group").val();
var title = jQuery("#title_lb").val();
break;
case 'st_audio':
var title = jQuery("#audio_title").val();
var src = jQuery("#audio_src").val();
var what = "[st_audio title='"+title+"' src='"+src+"']";
break;
case 'st_soundcloud':
var src = jQuery("#sound_src").val();
var color = jQuery("#sound_color").val();
var what = "[st_soundcloud color='"+color+"' src='"+src+"']";
break;
case 'st_mixcloud':
var src = jQuery("#mix_src").val();
var width = jQuery("#mix_width").val();
var height = jQuery("#mix_height").val();
var what = "[st_mixcloud width='"+width+"' height='"+height+"' src='"+src+"']";
break;
case 'st_section_image':
var image_id = jQuery("#imageid").val();
var bg_color = jQuery("#bg_color").val();
var type = jQuery("#section_image_type").val();
var bg_position = jQuery("#bg_position").val();
var bg_size = jQuery("#bg_size").val();
var repeat = jQuery("#repeat").val();
var padding = jQuery("#img_padding").val();
var what = "[st_section_image image_id='"+image_id+"' bg_color='"+bg_color+"' type='"+type+"' position='"+bg_position+"' bg_size='"+bg_size+"' repeat='"+repeat+"' padding='"+padding+"']Section content goes here[/st_section_image]";
break;
case 'st_section_color':
var color = jQuery("#color").val();
var padding = jQuery("#col_padding").val();
var what = "[st_section_color color='"+color+"' padding='"+padding+"']Section content goes here[/st_section_color]";
break;
case 'st_text_color':
var color = jQuery("#color").val();
var what = "[st_text_color color='"+color+"']Text goes here[/st_text_color]";
break;
case 'st_posts_carousel':
var posts = jQuery("#posts").val();
var number = jQuery("#number").val();
var cat = jQuery("#cat").val();
var display_title = jQuery("#display_title").val();
var what = "[st_posts_carousel posts='"+posts+"' number='"+number+"' cat='"+cat+"' display_title='"+display_title+"']";
break;
case 'st_swiper':
var posts = jQuery("#swiper_posts").val();
var number = jQuery("#swiper_number").val();
var category = jQuery("#category").val();
var display_title = jQuery("#display_title").val();
var what = "[st_swiper posts='"+posts+"' number='"+number+"' category='"+category+"' display_title='"+display_title+"']";
break;
case 'st_animated':
var type = jQuery("#animated_type").val();
var trigger = jQuery("#trigger").val();
var precent = jQuery("#precent").val();
var what = "[st_animated type='"+type+"' trigger='"+trigger+"' precent='"+precent+"']Animated element goes here[/st_animated]";
break;
case 'st_svg_drawing':
var type = jQuery("#drawing_type").val();
var image_id = jQuery("#image_id").val();
var color = jQuery("#drawing_color").val();
var what = "[st_svg_drawing type='"+type+"' image_id='"+image_id+"' color='"+color+"']";
break;
case 'st_animated_boxes':
var posts = jQuery("#posts").val();
var what = "[st_animated_boxes posts='"+posts+"']";
break;
case 'st_icon':
var name = jQuery("#name").val();
var size = jQuery("#size").val();
var type = jQuery("#icon_type").val();
var color = jQuery("#icon_color").val();
var bg_color = jQuery("#icon_bg_color").val();
var border_color = jQuery("#icon_border_color").val();
var align = jQuery("#align").val();
var what = "[st_icon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']";
break;
case 'st_icon_melon':
var name = jQuery("#name").val();
var size = jQuery("#size").val();
var type = jQuery("#icon_type").val();
var color = jQuery("#icon_color").val();
var bg_color = jQuery("#icon_bg_color").val();
var border_color = jQuery("#icon_border_color").val();
var align = jQuery("#align").val();
var what = "[st_icon_melon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']";
break;
case 'st_social_icon':
var name = jQuery("#name").val();
var href = jQuery("#href").val();
var target = jQuery("#target").val();
var align = jQuery("#align").val();
var what = "[st_social_icon name='"+name+"' href='"+href+"' target='"+target+"' align='"+align+"']";
break;
case 'st_divider_text':
var type = jQuery("#divider_type").val();
var text = jQuery("#text").val();
var what = "[st_divider_text position='"+type+"' text='"+text+"']";
break;
case 'st_countdown':
var id = jQuery("#event_id").val();
var align = jQuery("#countdown_align").val();
var what = "[st_countdown id='"+id+"' align='"+align+"']";
break;
case 'st_testimonials':
var color = jQuery("#color").val();
var number = jQuery("#number").val();
var what = "[st_testimonials color='"+color+"' number='"+number+"']";
break;
}
if(this.validate()) {
if(preview === true) {
var values = {
'data': what
};
jQuery.ajax({
url: stPluginUrl + '/ajaxPlugin.php?act=preview',
type: 'POST',
data: values,
loading: function() {
jQuery("#previewDiv").empty().html('<div class="loading"> </div>')
},
success: function(response) {
jQuery("#previewDiv").empty().html(response);
}
});
} else {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, what);
}
}
},
validate: function() {
ret = true;
jQuery('.req').each(function() {
if(jQuery(this).find('input').val() == '') {
ret = false;
jQuery(this).find('input').addClass('errorInput');
} else {
jQuery(this).find('input').removeClass('errorInput');
}
if(jQuery(this).find('textarea').val() == '') {
ret = false;
jQuery(this).find('textarea').addClass('errorInput');
} else {
jQuery(this).find('textarea').removeClass('errorInput');
}
});
return ret;
},
readMore: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=readMore&preview');
what = 'st_button_more';
},
breakLine: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_break_line]");
},
horizontalLine: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_horizontal_line]");
},
divClear: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_clear]");
},
createDividerDotted: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dotted]");
},
createDividerDashed: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dashed]");
},
createDividerTop: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_top]");
},
createDividerShadow: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_shadow]");
},
insertButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertButton&preview');
what = 'st_button';
},
insertHoverFillButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFillButton&preview');
what = 'st_hover_fill_button';
},
insertHoverFancyIconButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFancyIconButton&preview');
what = 'st_hover_fancy_icon_button';
},
insertHoverArrowsButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverArrowsButton&preview');
what = 'st_hover_arrows_button';
},
insertHoverIconOnHoverButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverIconOnHoverButton&preview');
what = 'st_hover_icon_button';
},
insertHoverBorderedButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverBorderedButton&preview');
what = 'st_hover_bordered_button';
},
insertBox: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertBox&preview');
what = 'st_box';
},
dividerText: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview');
what = 'st_divider_text';
},
eventCountdown: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=eventCountdown');
what = 'st_countdown';
},
createTestimonials: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=testimonials');
what = 'st_testimonials';
},
insertCallout: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertCallout&preview');
what = 'st_callout';
},
insertTooltip: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertTooltip&preview=remove');
what = 'st_tooltip';
},
insertPopover: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertPopover&preview=remove');
what = 'st_popover';
},
insertModal: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertModal&preview=remove');
what = 'st_modal';
},
createTabs: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTabs&preview=remove');
what = 'st_tabs';
},
createUnorderedList: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createUnorderedList&preview');
what = 'st_unordered';
},
createOrderedList: function() {
var content = (tinyMCE.activeEditor.selection.getContent() != '') ? tinyMCE.activeEditor.selection.getContent() : '<ol><li>First list item</li></ol>';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_ordered]"+ content +"[/st_ordered]");
},
createToggle: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=toggle&preview');
what = 'st_toggle';
},
createAccordion: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createAccordion&preview');
what = 'st_accordion';
},
createProgressBar: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=progress_bar&preview');
what = 'st_progress_bar';
},
createTables: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTable&preview');
what = 'st_tables';
},
relatedPosts: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=related&preview=remove');
what = 'st_related_posts';
},
logInOut: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=logInOut&preview');
what = 'st_loginout';
},
dropCap: function(type) {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_dropcap type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_dropcap]");
},
highlight: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=highlight&preview');
what = 'st_highlight';
},
labels: function(type) {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_label type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_label]");
},
quote: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=quote&preview');
what = 'st_quote';
},
abbreviation: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=abbreviation&preview');
what = 'st_abbreviation';
},
createTwitterButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=twitter&preview');
what = 'st_twitter';
},
createDiggButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=digg&preview');
what = 'st_digg';
},
createFBlikeButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fblike&preview');
what = 'st_fblike';
},
createFBShareButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fbshare&preview');
what = 'st_fbshare';
},
createLIShareButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=lishare&preview');
what = 'st_lishare';
},
createGplusButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gplus&preview');
what = 'st_gplus';
},
createPinButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pinterest_pin&preview');
what = 'st_pinterest_pin';
},
createTumblrButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=tumblr&preview');
what = 'st_tumblr';
},
createSocialIcon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=social_icon&preview');
what = 'st_social_icon';
},
createPricingTables: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pricingTable&preview');
what = 'st_pricingTable';
},
createFancyboxImages: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxImages&preview=remove');
what = 'st_fancyboxImages';
},
createFancyboxInline: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxInline&preview=remove');
what = 'st_fancyboxInline';
},
createFancyboxIframe: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxIframe&preview=remove');
what = 'st_fancyboxIframe';
},
createFancyboxPage: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxPage&preview=remove');
what = 'st_fancyboxPage';
},
createFancyboxSwf: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxSwf&preview=remove');
what = 'st_fancyboxSwf';
},
createVideo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=video&preview');
what = 'st_video';
},
createAudio: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=audio&preview');
what = 'st_audio';
},
createSoundcloud: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=soundcloud&preview');
what = 'st_soundcloud';
},
createMixcloud: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=mixcloud&preview');
what = 'st_mixcloud';
},
createSectionImage: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_image&preview=remove');
what = 'st_section_image';
},
createSectionColor: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_color&preview=remove');
what = 'st_section_color';
},
createContainer: function(){
var currentVal = 'Put your content here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_container]"+ currentVal +"[/st_container]");
},
createTextColor: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=text_color&preview=remove');
what = 'st_text_color';
},
createRow: function(){
var currentVal = 'Put your columns here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_row]"+ currentVal +"[/st_row]");
},
createColumnLayout: function(n) {
var col = '';
var values = {
'st_column1': 'st_column1',
'st_column2': 'st_column2',
'st_column3': 'st_column3',
'st_column4': 'st_column4',
'st_column5': 'st_column5',
'st_column6': 'st_column6',
'st_column7': 'st_column7',
'st_column8': 'st_column8',
'st_column9': 'st_column9',
'st_column10': 'st_column10',
'st_column11': 'st_column11',
'st_column12': 'st_column12',
}
col = values[n];
var currentVal = 'Your content goes here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "["+col+"]"+ currentVal +"[/"+col+"]");
},
createGoogleMaps: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gmap&preview=remove');
what = 'st_gmap';
},
createGoogleTrends: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=trends&preview=remove');
what = 'st_trends';
},
createChartPie: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_pie&preview=remove');
what = 'st_chart_pie';
},
createChartBar: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bar&preview=remove');
what = 'st_chart_bar';
},
createChartArea: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_area&preview=remove');
what = 'st_chart_area';
},
createChartGeo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_geo&preview=remove');
what = 'st_chart_geo';
},
createChartCombo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_combo&preview=remove');
what = 'st_chart_combo';
},
createChartOrg: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_org&preview=remove');
what = 'st_chart_org';
},
createChartBubble: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bubble&preview=remove');
what = 'st_chart_bubble';
},
createGoogleDocs: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gdocs&preview=remove');
what = 'st_gdocs';
},
pageSiblings: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_siblings]");
},
children: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=children&preview');
what = 'st_children';
},
contactFormDark: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_dark&preview');
what = 'st_contact_form_dark';
},
contactFormLight: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_light&preview');
what = 'st_contact_form_light';
},
createCarousel: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=posts_carousel&preview=remove');
what = 'st_posts_carousel';
},
createSwiper: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=swiper&preview=remove');
what = 'st_swiper';
},
insertAnimated: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=animated&preview=remove');
what = 'st_animated';
},
insertDrawing: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=svg_drawing&preview=remove');
what = 'st_svg_drawing';
},
createIcon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=icon&preview');
what = 'st_icon';
},
createIconMelon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=melonIcon&preview');
what = 'st_icon_melon';
},
createCode: function() {
var currentVal = 'Put your code here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_code]"+ currentVal +"[/st_code]");
}
};
var what = '';
jQuery('#insert').live('click', function(e) {
preview = false;
e.preventDefault();
themeShortcuts.insert(what);
tb_remove();
return false;
});
jQuery('#preview').live('click', function(e) {
preview = true;
e.preventDefault();
themeShortcuts.insert(what);
return false;
});
jQuery('#SupremeSocialTheme_preview input').live('blur', function() {
preview = true;
setTimeout(function() {
themeShortcuts.insert(what);
}, 300);
});
jQuery('#SupremeSocialTheme_preview select').live('change', function() {
preview = true;
setTimeout(function() {
themeShortcuts.insert(what);
}, 300);
});
jQuery('#cancel').live('click', function(e) {
tb_remove();
return false;
});
///////////////////////////////////////
// CHECK THE VERSION OF TINYMCE !!
///////////////////////////////////////
if (tinymce.majorVersion < 4) {
//////////////////////////////
// IF IS TINYMCE VERSION 3
//////////////////////////////
tinymce.create('tinymce.plugins.themeShortcuts', {
init: function(ed, url) {
},
createControl: function(n, cm) {
switch (n) {
case 'themeShortcuts':
var c = cm.createSplitButton('themeShortcuts', {
title : 'Theme shortcuts',
image : stPluginUrl + '/images/supremetheme-logo-19x19.png',
onclick : function() {
c.showMenu();
}
});
c.onRenderMenu.add(function(c,m) {
e = m.addMenu({title : 'Lines'});
e.add({title : 'Break Line', onclick : themeShortcuts.breakLine});
e.add({title : 'Horizontal Line', onclick : themeShortcuts.horizontalLine});
e.add({title : 'Clear', onclick : themeShortcuts.divClear});
var ea = e.addMenu({title : 'Dividers'});
ea.add({title : 'Dotted', onclick : themeShortcuts.createDividerDotted});
ea.add({title : 'Dashed', onclick : themeShortcuts.createDividerDashed});
ea.add({title : 'To Top', onclick : themeShortcuts.createDividerTop});
ea.add({title : 'Shadow', onclick : themeShortcuts.createDividerShadow});
ea.add({title : 'Text', onclick : themeShortcuts.dividerText});
b = m.addMenu({title : 'Buttons'});
b.add({title : 'Button', onclick : function() { themeShortcuts.insertButton() }});
var ba = b.addMenu({title : 'Hover Buttons'});
ba.add({title: 'Fill In', onclick : themeShortcuts.insertHoverFillButton});
ba.add({title: 'Fancy Icon', onclick : themeShortcuts.insertHoverFancyIconButton});
ba.add({title: 'Arrows', onclick : themeShortcuts.insertHoverArrowsButton});
ba.add({title: 'Icon on hover', onclick : themeShortcuts.insertHoverIconOnHoverButton});
ba.add({title: 'Bordered', onclick : themeShortcuts.insertHoverBorderedButton});
b.add({title : 'Read More', onclick : themeShortcuts.readMore});
var be = b.addMenu({title : 'Share Buttons'});
be.add({title: 'Twitter', onclick : themeShortcuts.createTwitterButton});
be.add({title: 'Digg', onclick : themeShortcuts.createDiggButton});
be.add({title: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton});
be.add({title: 'Facebook Share', onclick : themeShortcuts.createFBShareButton});
be.add({title: 'LinkedIn', onclick : themeShortcuts.createLIShareButton});
be.add({title: 'Google+', onclick : themeShortcuts.createGplusButton});
be.add({title: 'Pinterest', onclick : themeShortcuts.createPinButton});
be.add({title: 'Tumbler', onclick : themeShortcuts.createTumblrButton});
b.add({title : 'Log in / out button', onclick : themeShortcuts.logInOut});
i = m.addMenu({title : 'Boxes'});
i.add({title : 'Box', onclick : themeShortcuts.insertBox});
i.add({title : 'Callout', onclick : themeShortcuts.insertCallout});
p = m.addMenu({title : 'Icons'});
p.add({title : 'Font Awesome', onclick : themeShortcuts.createIcon});
p.add({title : 'Icon Melon', onclick : themeShortcuts.createIconMelon});
p.add({title : 'Social Icons', onclick : themeShortcuts.createSocialIcon});
m.add({title : 'Animated', onclick : themeShortcuts.insertAnimated});
m.add({title : 'SVG Drawing', onclick : themeShortcuts.insertDrawing});
s = m.addMenu({title : 'Elements'});
s.add({title : 'Tooltip', onclick : themeShortcuts.insertTooltip});
s.add({title : 'Popover', onclick : themeShortcuts.insertPopover});
s.add({title : 'Modal', onclick : themeShortcuts.insertModal});
s.add({title : 'Tabs', onclick : themeShortcuts.createTabs});
s.add({title : 'Toggle', onclick : themeShortcuts.createToggle});
s.add({title : 'Accordion', onclick : themeShortcuts.createAccordion});
s.add({title : 'Progress Bar', onclick : themeShortcuts.createProgressBar});
r = m.addMenu({title : 'Section'});
r.add({title : 'Image', onclick : themeShortcuts.createSectionImage});
r.add({title : 'Color', onclick : themeShortcuts.createSectionColor});
m.add({title : 'Container', onclick : themeShortcuts.createContainer});
h = m.addMenu({title : 'Responsive'});
h.add({title : 'Row', onclick : themeShortcuts.createRow});
h.add({title: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }});
h.add({title: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }});
h.add({title: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }});
h.add({title: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }});
h.add({title: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }});
h.add({title: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }});
h.add({title: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }});
h.add({title: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }});
h.add({title: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }});
h.add({title: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }});
h.add({title: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }});
h.add({title: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }});
d = m.addMenu({title : 'Google'});
d.add({title : 'Google Maps', onclick : themeShortcuts.createGoogleMaps});
d.add({title : 'Google Trends', onclick : themeShortcuts.createGoogleTrends});
d.add({title : 'Google Docs', onclick : themeShortcuts.createGoogleDocs});
var da = d.addMenu({title : 'Google Charts'});
da.add({title : 'Pie', onclick : themeShortcuts.createChartPie});
da.add({title : 'Bar', onclick : themeShortcuts.createChartBar});
da.add({title : 'Area', onclick : themeShortcuts.createChartArea});
da.add({title : 'Geo', onclick : themeShortcuts.createChartGeo});
da.add({title : 'Combo', onclick : themeShortcuts.createChartCombo});
da.add({title : 'Org', onclick : themeShortcuts.createChartOrg});
da.add({title : 'Bubble', onclick : themeShortcuts.createChartBubble});
f = m.addMenu({title: 'Lists'});
f.add({title : 'Unordered list', onclick : themeShortcuts.createUnorderedList});
f.add({title : 'Ordered list', onclick : themeShortcuts.createOrderedList});
o = m.addMenu({title: 'Tables'});
o.add({title : 'Styled table', onclick : themeShortcuts.createTables});
o.add({title : 'Pricing table', onclick : themeShortcuts.createPricingTables});
l = m.addMenu({title : 'Media'});
l.add({title : 'Video', onclick : themeShortcuts.createVideo});
var la = l.addMenu({title : 'Audio'});
la.add({title : 'Soundcloud', onclick : themeShortcuts.createSoundcloud});
la.add({title : 'Mixcloud', onclick : themeShortcuts.createMixcloud});
la.add({title : 'Other', onclick : themeShortcuts.createAudio});
d = m.addMenu({title: 'Typography'});
var dc = d.addMenu({title : 'Dropcap'});
dc.add({title : 'Light', onclick : function() { themeShortcuts.dropCap('light') }});
dc.add({title : 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}});
dc.add({title : 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}});
dc.add({title : 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}});
d.add({title : 'Quote', onclick : themeShortcuts.quote});
d.add({title : 'Highlight', onclick : themeShortcuts.highlight});
var df = d.addMenu({title: 'Label'});
df.add({title : 'Default', onclick : function() { themeShortcuts.labels('default') }});
df.add({title : 'New', onclick : function() {themeShortcuts.labels('success')}});
df.add({title : 'Warning', onclick : function() {themeShortcuts.labels('warning')}});
df.add({title : 'Important', onclick : function() {themeShortcuts.labels('important')}});
df.add({title : 'Notice', onclick : function() {themeShortcuts.labels('notice')}});
d.add({title : 'Colored Text', onclick : themeShortcuts.createTextColor});
d.add({title : 'Abbreviation', onclick : themeShortcuts.abbreviation});
p = m.addMenu({title : 'Related'});
p.add({title : 'Related posts', onclick : themeShortcuts.relatedPosts});
p.add({title : 'Siblings', onclick : themeShortcuts.pageSiblings});
p.add({title : 'Children', onclick : themeShortcuts.children});
k = m.addMenu({title : 'Fancybox'});
k.add({title : 'Images', onclick : themeShortcuts.createFancyboxImages});
k.add({title : 'Inline', onclick : themeShortcuts.createFancyboxInline});
k.add({title : 'iFrame', onclick : themeShortcuts.createFancyboxIframe});
k.add({title : 'Page', onclick : themeShortcuts.createFancyboxPage});
k.add({title : 'Swf', onclick : themeShortcuts.createFancyboxSwf});
j = m.addMenu({title : 'Contact form'});
j.add({title : 'Light', onclick : themeShortcuts.contactFormLight});
j.add({title : 'Dark', onclick : themeShortcuts.contactFormDark});
t = m.addMenu({title : 'Carousel'});
t.add({title : 'Post Carousel', onclick : themeShortcuts.createCarousel});
t.add({title : 'Swiper', onclick : themeShortcuts.createSwiper});
//t.add({title : 'Testimonial', onclick : themeShortcuts.createTestimonials});
//m.add({title : 'Countdown', onclick : themeShortcuts.eventCountdown});
m.add({title : 'Code', onclick : themeShortcuts.createCode});
});
return c;
}
return null;
},
});
}else{
//////////////////////////////
// IF IS TINYMCE VERSION 4+
//////////////////////////////
tinymce.create('tinymce.plugins.themeShortcuts', {
init : function(ed, url) {
ed.addButton( 'themeShortcuts', {
type: 'listbox',
text: 'Supreme',
icon: 'supreme',
classes: 'mce-btn supreme-class',
tooltip: 'Supreme Shortcodes',
onselect: function(e) {
},
values: [
{
type: 'listbox',
text: 'Lines',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Break Line', onclick : themeShortcuts.breakLine},
{ text: 'Horizontal Line', onclick : themeShortcuts.horizontalLine},
{ text: 'Clear', onclick : themeShortcuts.divClear},
{
type: 'listbox',
text: 'Dividers',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Dotted', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_dotted]');
}},
{ text: 'Dashed', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_dashed]');
}},
{ text: 'To Top', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_top]');
}},
{ text: 'Shadow', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_shadow]');
}},
{text: 'Text', onclick : function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview');
what = 'st_divider_text';
}},
]
},
]
},
{
type: 'listbox',
text: 'Buttons',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Button', onclick : function() { themeShortcuts.insertButton() }},
{
type: 'listbox',
text: 'Hover Button',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Fill In', onclick : function() { themeShortcuts.insertHoverFillButton() }},
{text: 'Fancy Icon', onclick : function() { themeShortcuts.insertHoverFancyIconButton() }},
{text: 'Arrows', onclick : function() { themeShortcuts.insertHoverArrowsButton() }},
{text: 'Icon on hover', onclick : function() { themeShortcuts.insertHoverIconOnHoverButton() }},
{text: 'Bordered', onclick : function() { themeShortcuts.insertHoverBorderedButton() }},
]
},
{text: 'Read more', onclick : themeShortcuts.readMore},
{
type: 'listbox',
text: 'Share buttons',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Twitter', onclick : themeShortcuts.createTwitterButton},
{ text: 'Digg', onclick : themeShortcuts.createDiggButton},
{ text: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton},
{ text: 'Facebook Share', onclick : themeShortcuts.createFBShareButton},
{ text: 'LinkedIn', onclick : themeShortcuts.createLIShareButton},
{ text: 'Google+', onclick : themeShortcuts.createGplusButton},
{ text: 'Pinterest', onclick : themeShortcuts.createPinButton},
{ text: 'Tumbler', onclick : themeShortcuts.createTumblrButton},
]
},
{text: 'Log in / out button', onclick : themeShortcuts.logInOut},
]
},
{
type: 'listbox',
text: 'Boxes',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Info Box', onclick : themeShortcuts.insertBox},
{text: 'Callout', onclick : themeShortcuts.insertCallout},
]
},
{
type: 'listbox',
text: 'Icons',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Font Awesome', onclick : themeShortcuts.createIcon},
{text: 'Icon Melon', onclick : themeShortcuts.createIconMelon},
{text: 'Social Icons', onclick : themeShortcuts.createSocialIcon},
]
},
{classes: 'no-dropdown', text: 'Animated', onclick : themeShortcuts.insertAnimated},
{classes: 'no-dropdown', text: 'SVG Drawing', onclick : themeShortcuts.insertDrawing},
{
type: 'listbox',
text: 'Elements',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Tooltip', onclick : themeShortcuts.insertTooltip},
{text: 'Popover', onclick : themeShortcuts.insertPopover},
{text: 'Modal', onclick : themeShortcuts.insertModal},
{text: 'Tabs', onclick : themeShortcuts.createTabs},
{text: 'Toggle', onclick : themeShortcuts.createToggle},
{text: 'Accordion', onclick : themeShortcuts.createAccordion},
{text: 'Progress Bar', onclick : themeShortcuts.createProgressBar},
]
},
{
type: 'listbox',
text: 'Section',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Image', onclick : themeShortcuts.createSectionImage},
{text: 'Color', onclick : themeShortcuts.createSectionColor},
]
},
{classes: 'no-dropdown', text: 'Container', onclick : themeShortcuts.createContainer},
{
type: 'listbox',
text: 'Responsive',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Row', onclick : themeShortcuts.createRow},
{text: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }},
{text: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }},
{text: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }},
{text: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }},
{text: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }},
{text: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }},
{text: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }},
{text: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }},
{text: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }},
{text: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }},
{text: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }},
{text: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }},
]
},
{
type: 'listbox',
text: 'Google',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Google Maps', onclick : themeShortcuts.createGoogleMaps},
{text: 'Google Trends', onclick : themeShortcuts.createGoogleTrends},
{text: 'Google Docs', onclick : themeShortcuts.createGoogleDocs},
{
type: 'listbox',
text: 'Google Charts',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Pie', onclick : themeShortcuts.createChartPie},
{text: 'Bar', onclick : themeShortcuts.createChartBar},
{text: 'Area', onclick : themeShortcuts.createChartArea},
{text: 'Geo', onclick : themeShortcuts.createChartGeo},
{text: 'Combo', onclick : themeShortcuts.createChartCombo},
{text: 'Org', onclick : themeShortcuts.createChartOrg},
{text: 'Bubble', onclick : themeShortcuts.createChartBubble},
]
},
]
},
{
type: 'listbox',
text: 'Lists',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Unordered list', onclick : themeShortcuts.createUnorderedList},
{text: 'Ordered list', onclick : themeShortcuts.createOrderedList},
]
},
{
type: 'listbox',
text: 'Tables',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Styled table', onclick : themeShortcuts.createTables},
{text: 'Pricing table', onclick : themeShortcuts.createPricingTables},
]
},
{
type: 'listbox',
text: 'Media',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Video', onclick : themeShortcuts.createVideo},
{
type: 'listbox',
text: 'Audio',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Soundcloud', onclick : themeShortcuts.createSoundcloud},
{text: 'Mixcloud', onclick : themeShortcuts.createMixcloud},
{text: 'Other', onclick : themeShortcuts.createAudio},
]
},
]
},
{
type: 'listbox',
text: 'Typography',
icon: false,
classes: 'has-dropdown',
values: [
{
type: 'listbox',
text: 'Dropcap',
icon: false,
values: [
{text: 'Light', onclick : function() {themeShortcuts.dropCap('light')}},
{text: 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}},
{text: 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}},
{text: 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}},
]
},
{text: 'Quote', onclick : themeShortcuts.quote},
{text: 'Highlight', onclick : themeShortcuts.highlight},
{
type: 'listbox',
text: 'Label',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Default', onclick : function() { themeShortcuts.labels('default') }},
{text: 'New', onclick : function() { themeShortcuts.labels('success') }},
{text: 'Warning', onclick : function() { themeShortcuts.labels('warning') }},
{text: 'Important', onclick : function() { themeShortcuts.labels('important') }},
{text: 'Notice', onclick : function() { themeShortcuts.labels('notice') }},
]
},
{text: 'Colored Text', onclick : themeShortcuts.createTextColor},
{text: 'Abbreviation', onclick : themeShortcuts.abbreviation},
]
},
{
type: 'listbox',
text: 'Related',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Related posts', onclick : themeShortcuts.relatedPosts},
{text: 'Siblings', onclick : themeShortcuts.pageSiblings},
{text: 'Children', onclick : themeShortcuts.children},
]
},
{
type: 'listbox',
text: 'Fancybox',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Images', onclick : themeShortcuts.createFancyboxImages},
{text: 'Inline', onclick : themeShortcuts.createFancyboxInline},
{text: 'iFrame', onclick : themeShortcuts.createFancyboxIframe},
{text: 'Page', onclick : themeShortcuts.createFancyboxPage},
{text: 'Swf', onclick : themeShortcuts.createFancyboxSwf},
]
},
{
type: 'listbox',
text: 'Contact form',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Light', onclick : themeShortcuts.contactFormLight},
{text: 'Dark', onclick : themeShortcuts.contactFormDark},
]
},
{
type: 'listbox',
text: 'Carousel',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Post Carousel', onclick : themeShortcuts.createCarousel},
{text: 'Swiper', onclick : themeShortcuts.createSwiper},
//{text: 'Testimonial', onclick : themeShortcuts.createTestimonials},
]
},
//{classes: 'no-dropdown', text: 'Countdown', onclick : themeShortcuts.eventCountdown},
{classes: 'no-dropdown', text: 'Code', onclick : themeShortcuts.createCode},
]
});
},
});
};//end else
tinymce.PluginManager.add('themeShortcuts', tinymce.plugins.themeShortcuts);
})() | vinciteng/bookitforward | wp-content/plugins/SupremeShortcodes/js/editor_plugin.js | JavaScript | gpl-2.0 | 66,280 |
import Backbone from 'backbone';
export default class Router extends Backbone.Router {
get routes() {
return {
'(/)': 'home',
'login': 'login',
'access_token=*token': 'token',
'activity': 'activity',
'swim': 'swim',
'sleep': 'sleep',
'about': 'about',
'privacy': 'privacy'
};
}
}
| clementprdhomme/misfit-dashboard | src/js/router.js | JavaScript | gpl-2.0 | 443 |
/*jslint browser: true */ /*global jQuery: true */
/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
// TODO JsDoc
/**
* Create a cookie with the given key and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String key The key of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/[email protected]
*/
/**
* Get the value of a cookie with the given key.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String key The key of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/[email protected]
*/
jQuery.cookie = function (key, value, options) {
// key and value given, set cookie...
if (arguments.length > 1 && (value === null || typeof value !== "object")) {
options = jQuery.extend({}, options);
if (value === null) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? String(value) : encodeURIComponent(String(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(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
;
(function ($) {
/**
* This script transforms a set of fieldsets into a stack of vertical
* tabs. Another tab pane can be selected by clicking on the respective
* tab.
*
* Each tab may have a summary which can be updated by another
* script. For that to work, each fieldset has an associated
* 'verticalTabCallback' (with jQuery.data() attached to the fieldset),
* which is called every time the user performs an update to a form
* element inside the tab pane.
*/
Drupal.behaviors.verticalTabs = {
attach: function (context) {
$('.vertical-tabs-panes', context).once('vertical-tabs', function () {
var focusID = $(':hidden.vertical-tabs-active-tab', this).val();
var tab_focus;
// Check if there are some fieldsets that can be converted to vertical-tabs
var $fieldsets = $('> fieldset', this);
if ($fieldsets.length == 0) {
return;
}
// Create the tab column.
var tab_list = $('<ul class="vertical-tabs-list"></ul>');
$(this).wrap('<div class="vertical-tabs clearfix"></div>').before(tab_list);
// Transform each fieldset into a tab.
$fieldsets.each(function () {
var vertical_tab = new Drupal.verticalTab({
title: $('> legend', this).text(),
fieldset: $(this)
});
tab_list.append(vertical_tab.item);
$(this)
.removeClass('collapsible collapsed')
.addClass('vertical-tabs-pane')
.data('verticalTab', vertical_tab);
if (this.id == focusID) {
tab_focus = $(this);
}
});
$('> li:first', tab_list).addClass('first');
$('> li:last', tab_list).addClass('last');
if (!tab_focus) {
// If the current URL has a fragment and one of the tabs contains an
// element that matches the URL fragment, activate that tab.
if (window.location.hash && $(this).find(window.location.hash).length) {
tab_focus = $(this).find(window.location.hash).closest('.vertical-tabs-pane');
}
else {
tab_focus = $('> .vertical-tabs-pane:first', this);
}
}
if (tab_focus.length) {
tab_focus.data('verticalTab').focus();
}
});
}
};
/**
* The vertical tab object represents a single tab within a tab group.
*
* @param settings
* An object with the following keys:
* - title: The name of the tab.
* - fieldset: The jQuery object of the fieldset that is the tab pane.
*/
Drupal.verticalTab = function (settings) {
var self = this;
$.extend(this, settings, Drupal.theme('verticalTab', settings));
this.link.click(function () {
self.focus();
return false;
});
// Keyboard events added:
// Pressing the Enter key will open the tab pane.
this.link.keydown(function(event) {
if (event.keyCode == 13) {
self.focus();
// Set focus on the first input field of the visible fieldset/tab pane.
$("fieldset.vertical-tabs-pane :input:visible:enabled:first").focus();
return false;
}
});
this.fieldset
.bind('summaryUpdated', function () {
self.updateSummary();
})
.trigger('summaryUpdated');
};
Drupal.verticalTab.prototype = {
/**
* Displays the tab's content pane.
*/
focus: function () {
this.fieldset
.siblings('fieldset.vertical-tabs-pane')
.each(function () {
var tab = $(this).data('verticalTab');
tab.fieldset.hide();
tab.item.removeClass('selected');
})
.end()
.show()
.siblings(':hidden.vertical-tabs-active-tab')
.val(this.fieldset.attr('id'));
this.item.addClass('selected');
// Mark the active tab for screen readers.
$('#active-vertical-tab').remove();
this.link.append('<span id="active-vertical-tab" class="element-invisible">' + Drupal.t('(active tab)') + '</span>');
},
/**
* Updates the tab's summary.
*/
updateSummary: function () {
this.summary.html(this.fieldset.drupalGetSummary());
},
/**
* Shows a vertical tab pane.
*/
tabShow: function () {
// Display the tab.
this.item.show();
// Update .first marker for items. We need recurse from parent to retain the
// actual DOM element order as jQuery implements sortOrder, but not as public
// method.
this.item.parent().children('.vertical-tab-button').removeClass('first')
.filter(':visible:first').addClass('first');
// Display the fieldset.
this.fieldset.removeClass('vertical-tab-hidden').show();
// Focus this tab.
this.focus();
return this;
},
/**
* Hides a vertical tab pane.
*/
tabHide: function () {
// Hide this tab.
this.item.hide();
// Update .first marker for items. We need recurse from parent to retain the
// actual DOM element order as jQuery implements sortOrder, but not as public
// method.
this.item.parent().children('.vertical-tab-button').removeClass('first')
.filter(':visible:first').addClass('first');
// Hide the fieldset.
this.fieldset.addClass('vertical-tab-hidden').hide();
// Focus the first visible tab (if there is one).
var $firstTab = this.fieldset.siblings('.vertical-tabs-pane:not(.vertical-tab-hidden):first');
if ($firstTab.length) {
$firstTab.data('verticalTab').focus();
}
return this;
}
};
/**
* Theme function for a vertical tab.
*
* @param settings
* An object with the following keys:
* - title: The name of the tab.
* @return
* This function has to return an object with at least these keys:
* - item: The root tab jQuery element
* - link: The anchor tag that acts as the clickable area of the tab
* (jQuery version)
* - summary: The jQuery element that contains the tab summary
*/
Drupal.theme.prototype.verticalTab = function (settings) {
var tab = {};
tab.item = $('<li class="vertical-tab-button" tabindex="-1"></li>')
.append(tab.link = $('<a href="#"></a>')
.append(tab.title = $('<strong></strong>').text(settings.title))
.append(tab.summary = $('<span class="summary"></span>')
)
);
return tab;
};
})(jQuery);
;
(function ($) {
/**
* The base States namespace.
*
* Having the local states variable allows us to use the States namespace
* without having to always declare "Drupal.states".
*/
var states = Drupal.states = {
// An array of functions that should be postponed.
postponed: []
};
/**
* Attaches the states.
*/
Drupal.behaviors.states = {
attach: function (context, settings) {
var $context = $(context);
for (var selector in settings.states) {
for (var state in settings.states[selector]) {
new states.Dependent({
element: $context.find(selector),
state: states.State.sanitize(state),
constraints: settings.states[selector][state]
});
}
}
// Execute all postponed functions now.
while (states.postponed.length) {
(states.postponed.shift())();
}
}
};
/**
* Object representing an element that depends on other elements.
*
* @param args
* Object with the following keys (all of which are required):
* - element: A jQuery object of the dependent element
* - state: A State object describing the state that is dependent
* - constraints: An object with dependency specifications. Lists all elements
* that this element depends on. It can be nested and can contain arbitrary
* AND and OR clauses.
*/
states.Dependent = function (args) {
$.extend(this, { values: {}, oldValue: null }, args);
this.dependees = this.getDependees();
for (var selector in this.dependees) {
this.initializeDependee(selector, this.dependees[selector]);
}
};
/**
* Comparison functions for comparing the value of an element with the
* specification from the dependency settings. If the object type can't be
* found in this list, the === operator is used by default.
*/
states.Dependent.comparisons = {
'RegExp': function (reference, value) {
return reference.test(value);
},
'Function': function (reference, value) {
// The "reference" variable is a comparison function.
return reference(value);
},
'Number': function (reference, value) {
// If "reference" is a number and "value" is a string, then cast reference
// as a string before applying the strict comparison in compare(). Otherwise
// numeric keys in the form's #states array fail to match string values
// returned from jQuery's val().
return (typeof value === 'string') ? compare(reference.toString(), value) : compare(reference, value);
}
};
states.Dependent.prototype = {
/**
* Initializes one of the elements this dependent depends on.
*
* @param selector
* The CSS selector describing the dependee.
* @param dependeeStates
* The list of states that have to be monitored for tracking the
* dependee's compliance status.
*/
initializeDependee: function (selector, dependeeStates) {
var state;
// Cache for the states of this dependee.
this.values[selector] = {};
for (var i in dependeeStates) {
if (dependeeStates.hasOwnProperty(i)) {
state = dependeeStates[i];
// Make sure we're not initializing this selector/state combination twice.
if ($.inArray(state, dependeeStates) === -1) {
continue;
}
state = states.State.sanitize(state);
// Initialize the value of this state.
this.values[selector][state.name] = null;
// Monitor state changes of the specified state for this dependee.
$(selector).bind('state:' + state, $.proxy(function (e) {
this.update(selector, state, e.value);
}, this));
// Make sure the event we just bound ourselves to is actually fired.
new states.Trigger({ selector: selector, state: state });
}
}
},
/**
* Compares a value with a reference value.
*
* @param reference
* The value used for reference.
* @param selector
* CSS selector describing the dependee.
* @param state
* A State object describing the dependee's updated state.
*
* @return
* true or false.
*/
compare: function (reference, selector, state) {
var value = this.values[selector][state.name];
if (reference.constructor.name in states.Dependent.comparisons) {
// Use a custom compare function for certain reference value types.
return states.Dependent.comparisons[reference.constructor.name](reference, value);
}
else {
// Do a plain comparison otherwise.
return compare(reference, value);
}
},
/**
* Update the value of a dependee's state.
*
* @param selector
* CSS selector describing the dependee.
* @param state
* A State object describing the dependee's updated state.
* @param value
* The new value for the dependee's updated state.
*/
update: function (selector, state, value) {
// Only act when the 'new' value is actually new.
if (value !== this.values[selector][state.name]) {
this.values[selector][state.name] = value;
this.reevaluate();
}
},
/**
* Triggers change events in case a state changed.
*/
reevaluate: function () {
// Check whether any constraint for this dependent state is satisifed.
var value = this.verifyConstraints(this.constraints);
// Only invoke a state change event when the value actually changed.
if (value !== this.oldValue) {
// Store the new value so that we can compare later whether the value
// actually changed.
this.oldValue = value;
// Normalize the value to match the normalized state name.
value = invert(value, this.state.invert);
// By adding "trigger: true", we ensure that state changes don't go into
// infinite loops.
this.element.trigger({ type: 'state:' + this.state, value: value, trigger: true });
}
},
/**
* Evaluates child constraints to determine if a constraint is satisfied.
*
* @param constraints
* A constraint object or an array of constraints.
* @param selector
* The selector for these constraints. If undefined, there isn't yet a
* selector that these constraints apply to. In that case, the keys of the
* object are interpreted as the selector if encountered.
*
* @return
* true or false, depending on whether these constraints are satisfied.
*/
verifyConstraints: function(constraints, selector) {
var result;
if ($.isArray(constraints)) {
// This constraint is an array (OR or XOR).
var hasXor = $.inArray('xor', constraints) === -1;
for (var i = 0, len = constraints.length; i < len; i++) {
if (constraints[i] != 'xor') {
var constraint = this.checkConstraints(constraints[i], selector, i);
// Return if this is OR and we have a satisfied constraint or if this
// is XOR and we have a second satisfied constraint.
if (constraint && (hasXor || result)) {
return hasXor;
}
result = result || constraint;
}
}
}
// Make sure we don't try to iterate over things other than objects. This
// shouldn't normally occur, but in case the condition definition is bogus,
// we don't want to end up with an infinite loop.
else if ($.isPlainObject(constraints)) {
// This constraint is an object (AND).
for (var n in constraints) {
if (constraints.hasOwnProperty(n)) {
result = ternary(result, this.checkConstraints(constraints[n], selector, n));
// False and anything else will evaluate to false, so return when any
// false condition is found.
if (result === false) { return false; }
}
}
}
return result;
},
/**
* Checks whether the value matches the requirements for this constraint.
*
* @param value
* Either the value of a state or an array/object of constraints. In the
* latter case, resolving the constraint continues.
* @param selector
* The selector for this constraint. If undefined, there isn't yet a
* selector that this constraint applies to. In that case, the state key is
* propagates to a selector and resolving continues.
* @param state
* The state to check for this constraint. If undefined, resolving
* continues.
* If both selector and state aren't undefined and valid non-numeric
* strings, a lookup for the actual value of that selector's state is
* performed. This parameter is not a State object but a pristine state
* string.
*
* @return
* true or false, depending on whether this constraint is satisfied.
*/
checkConstraints: function(value, selector, state) {
// Normalize the last parameter. If it's non-numeric, we treat it either as
// a selector (in case there isn't one yet) or as a trigger/state.
if (typeof state !== 'string' || (/[0-9]/).test(state[0])) {
state = null;
}
else if (typeof selector === 'undefined') {
// Propagate the state to the selector when there isn't one yet.
selector = state;
state = null;
}
if (state !== null) {
// constraints is the actual constraints of an element to check for.
state = states.State.sanitize(state);
return invert(this.compare(value, selector, state), state.invert);
}
else {
// Resolve this constraint as an AND/OR operator.
return this.verifyConstraints(value, selector);
}
},
/**
* Gathers information about all required triggers.
*/
getDependees: function() {
var cache = {};
// Swivel the lookup function so that we can record all available selector-
// state combinations for initialization.
var _compare = this.compare;
this.compare = function(reference, selector, state) {
(cache[selector] || (cache[selector] = [])).push(state.name);
// Return nothing (=== undefined) so that the constraint loops are not
// broken.
};
// This call doesn't actually verify anything but uses the resolving
// mechanism to go through the constraints array, trying to look up each
// value. Since we swivelled the compare function, this comparison returns
// undefined and lookup continues until the very end. Instead of lookup up
// the value, we record that combination of selector and state so that we
// can initialize all triggers.
this.verifyConstraints(this.constraints);
// Restore the original function.
this.compare = _compare;
return cache;
}
};
states.Trigger = function (args) {
$.extend(this, args);
if (this.state in states.Trigger.states) {
this.element = $(this.selector);
// Only call the trigger initializer when it wasn't yet attached to this
// element. Otherwise we'd end up with duplicate events.
if (!this.element.data('trigger:' + this.state)) {
this.initialize();
}
}
};
states.Trigger.prototype = {
initialize: function () {
var trigger = states.Trigger.states[this.state];
if (typeof trigger == 'function') {
// We have a custom trigger initialization function.
trigger.call(window, this.element);
}
else {
for (var event in trigger) {
if (trigger.hasOwnProperty(event)) {
this.defaultTrigger(event, trigger[event]);
}
}
}
// Mark this trigger as initialized for this element.
this.element.data('trigger:' + this.state, true);
},
defaultTrigger: function (event, valueFn) {
var oldValue = valueFn.call(this.element);
// Attach the event callback.
this.element.bind(event, $.proxy(function (e) {
var value = valueFn.call(this.element, e);
// Only trigger the event if the value has actually changed.
if (oldValue !== value) {
this.element.trigger({ type: 'state:' + this.state, value: value, oldValue: oldValue });
oldValue = value;
}
}, this));
states.postponed.push($.proxy(function () {
// Trigger the event once for initialization purposes.
this.element.trigger({ type: 'state:' + this.state, value: oldValue, oldValue: null });
}, this));
}
};
/**
* This list of states contains functions that are used to monitor the state
* of an element. Whenever an element depends on the state of another element,
* one of these trigger functions is added to the dependee so that the
* dependent element can be updated.
*/
states.Trigger.states = {
// 'empty' describes the state to be monitored
empty: {
// 'keyup' is the (native DOM) event that we watch for.
'keyup': function () {
// The function associated to that trigger returns the new value for the
// state.
return this.val() == '';
}
},
checked: {
'change': function () {
return this.attr('checked');
}
},
// For radio buttons, only return the value if the radio button is selected.
value: {
'keyup': function () {
// Radio buttons share the same :input[name="key"] selector.
if (this.length > 1) {
// Initial checked value of radios is undefined, so we return false.
return this.filter(':checked').val() || false;
}
return this.val();
},
'change': function () {
// Radio buttons share the same :input[name="key"] selector.
if (this.length > 1) {
// Initial checked value of radios is undefined, so we return false.
return this.filter(':checked').val() || false;
}
return this.val();
}
},
collapsed: {
'collapsed': function(e) {
return (typeof e !== 'undefined' && 'value' in e) ? e.value : this.is('.collapsed');
}
}
};
/**
* A state object is used for describing the state and performing aliasing.
*/
states.State = function(state) {
// We may need the original unresolved name later.
this.pristine = this.name = state;
// Normalize the state name.
while (true) {
// Iteratively remove exclamation marks and invert the value.
while (this.name.charAt(0) == '!') {
this.name = this.name.substring(1);
this.invert = !this.invert;
}
// Replace the state with its normalized name.
if (this.name in states.State.aliases) {
this.name = states.State.aliases[this.name];
}
else {
break;
}
}
};
/**
* Creates a new State object by sanitizing the passed value.
*/
states.State.sanitize = function (state) {
if (state instanceof states.State) {
return state;
}
else {
return new states.State(state);
}
};
/**
* This list of aliases is used to normalize states and associates negated names
* with their respective inverse state.
*/
states.State.aliases = {
'enabled': '!disabled',
'invisible': '!visible',
'invalid': '!valid',
'untouched': '!touched',
'optional': '!required',
'filled': '!empty',
'unchecked': '!checked',
'irrelevant': '!relevant',
'expanded': '!collapsed',
'readwrite': '!readonly'
};
states.State.prototype = {
invert: false,
/**
* Ensures that just using the state object returns the name.
*/
toString: function() {
return this.name;
}
};
/**
* Global state change handlers. These are bound to "document" to cover all
* elements whose state changes. Events sent to elements within the page
* bubble up to these handlers. We use this system so that themes and modules
* can override these state change handlers for particular parts of a page.
*/
$(document).bind('state:disabled', function(e) {
// Only act when this change was triggered by a dependency and not by the
// element monitoring itself.
if (e.trigger) {
$(e.target)
.attr('disabled', e.value)
.closest('.form-item, .form-submit, .form-wrapper').toggleClass('form-disabled', e.value)
.find('select, input, textarea').attr('disabled', e.value);
// Note: WebKit nightlies don't reflect that change correctly.
// See https://bugs.webkit.org/show_bug.cgi?id=23789
}
});
$(document).bind('state:required', function(e) {
if (e.trigger) {
if (e.value) {
$(e.target).closest('.form-item, .form-wrapper').find('label').append('<span class="form-required">*</span>');
}
else {
$(e.target).closest('.form-item, .form-wrapper').find('label .form-required').remove();
}
}
});
$(document).bind('state:visible', function(e) {
if (e.trigger) {
$(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value);
}
});
$(document).bind('state:checked', function(e) {
if (e.trigger) {
$(e.target).attr('checked', e.value);
}
});
$(document).bind('state:collapsed', function(e) {
if (e.trigger) {
if ($(e.target).is('.collapsed') !== e.value) {
$('> legend a', e.target).click();
}
}
});
/**
* These are helper functions implementing addition "operators" and don't
* implement any logic that is particular to states.
*/
// Bitwise AND with a third undefined state.
function ternary (a, b) {
return typeof a === 'undefined' ? b : (typeof b === 'undefined' ? a : a && b);
}
// Inverts a (if it's not undefined) when invert is true.
function invert (a, invert) {
return (invert && typeof a !== 'undefined') ? !a : a;
}
// Compares two values while ignoring undefined values.
function compare (a, b) {
return (a === b) ? (typeof a === 'undefined' ? a : true) : (typeof a === 'undefined' || typeof b === 'undefined');
}
})(jQuery);
;
(function ($) {
/**
* Retrieves the summary for the first element.
*/
$.fn.drupalGetSummary = function () {
var callback = this.data('summaryCallback');
return (this[0] && callback) ? $.trim(callback(this[0])) : '';
};
/**
* Sets the summary for all matched elements.
*
* @param callback
* Either a function that will be called each time the summary is
* retrieved or a string (which is returned each time).
*/
$.fn.drupalSetSummary = function (callback) {
var self = this;
// To facilitate things, the callback should always be a function. If it's
// not, we wrap it into an anonymous function which just returns the value.
if (typeof callback != 'function') {
var val = callback;
callback = function () { return val; };
}
return this
.data('summaryCallback', callback)
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.unbind('formUpdated.summary')
.bind('formUpdated.summary', function () {
self.trigger('summaryUpdated');
})
// The actual summaryUpdated handler doesn't fire when the callback is
// changed, so we have to do this manually.
.trigger('summaryUpdated');
};
/**
* Sends a 'formUpdated' event each time a form element is modified.
*/
Drupal.behaviors.formUpdated = {
attach: function (context) {
// These events are namespaced so that we can remove them later.
var events = 'change.formUpdated click.formUpdated blur.formUpdated keyup.formUpdated';
$(context)
// Since context could be an input element itself, it's added back to
// the jQuery object and filtered again.
.find(':input').andSelf().filter(':input')
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.unbind(events).bind(events, function () {
$(this).trigger('formUpdated');
});
}
};
/**
* Prepopulate form fields with information from the visitor cookie.
*/
Drupal.behaviors.fillUserInfoFromCookie = {
attach: function (context, settings) {
$('form.user-info-from-cookie').once('user-info-from-cookie', function () {
var formContext = this;
$.each(['name', 'mail', 'homepage'], function () {
var $element = $('[name=' + this + ']', formContext);
var cookie = $.cookie('Drupal.visitor.' + this);
if ($element.length && cookie) {
$element.val(cookie);
}
});
});
}
};
})(jQuery);
;
| tungcan1501/hdtv | sites/default/files/js/js_FxzL6y_vG1Dd9B-MsolHGVlVoN_lbUIGopU6FCDDV9U.js | JavaScript | gpl-2.0 | 29,612 |
var wocs_loading_first_time = true;//simply flag var
jQuery(function () {
if (woocs_drop_down_view == 'chosen') {
try {
if (jQuery("select.woocommerce-currency-switcher").length) {
jQuery("select.woocommerce-currency-switcher").chosen({
disable_search_threshold: 10
});
jQuery.each(jQuery('.woocommerce-currency-switcher-form .chosen-container'), function (index, obj) {
jQuery(obj).css({'width': jQuery(this).prev('select').data('width')});
});
}
} catch (e) {
console.log(e);
}
}
if (woocs_drop_down_view == 'ddslick') {
try {
jQuery.each(jQuery('select.woocommerce-currency-switcher'), function (index, obj) {
var width = jQuery(obj).data('width');
var flag_position = jQuery(obj).data('flag-position');
jQuery(obj).ddslick({
//data: ddData,
width: width,
imagePosition: flag_position,
selectText: "Select currency",
//background:'#ff0000',
onSelected: function (data) {
if (!wocs_loading_first_time) {
jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').find('input[name="woocommerce-currency-switcher"]').eq(0).val(data.selectedData.value);
jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').submit();
}
}
});
});
} catch (e) {
console.log(e);
}
}
//for flags view instead of drop-down
jQuery('.woocs_flag_view_item').click(function () {
if (jQuery(this).hasClass('woocs_flag_view_item_current')) {
return false;
}
//***
if (woocs_is_get_empty) {
window.location = window.location.href + '?currency=' + jQuery(this).data('currency');
} else {
var l = window.location.href;
l = l.replace(/(\?currency=[a-zA-Z]+)/g, '?');
l = l.replace(/(¤cy=[a-zA-Z]+)/g, '');
window.location = l + '¤cy=' + jQuery(this).data('currency');
}
return false;
});
wocs_loading_first_time = false;
});
| asshurimrepo/mont8 | wp-content/plugins/woocommerce-currency-switcher/js/front.js | JavaScript | gpl-2.0 | 2,447 |
var elixir = require('laravel-elixir');
var gulp = require("gulp");
require('laravel-elixir-wiredep');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
var bowerDir = "public/vendor/";
var lessPaths = [
bowerDir + "bootstrap/less/"
]
var templatePaths = [
"resources/assets/js/app/components/*/*.html",
];
elixir.extend("templates", function(src, base, dest) {
gulp.task("templates", function () {
// the base option sets the relative root for the set of files,
// preserving the folder structure
gulp.src(src, {base: base})
.pipe(gulp.dest(dest));
});
// Watch each glob in src
for (idx in src){
var glob = src[idx];
this.registerWatcher("templates", glob);
}
return this.queueTask("templates");
});
elixir(function(mix) {
// Complile LESS into CSS
mix.less("main.less", "public/css/", {paths: lessPaths});
// Inject dependencies into layout (except bootstrap css, since that is compiled into main css)
mix.wiredep({src: "master.blade.php"}, {exclude: "vendor/bootstrap/dist/css/bootstrap.css"});
// Combine app js into one file
mix.scriptsIn("resources/assets/js/", "public/js/main.js");
// Copy angular templates to public folder
mix.templates(templatePaths, "resources/assets/js/app/components/", "public");
});
| levofski/web-2-cv | gulpfile.js | JavaScript | gpl-2.0 | 1,696 |
(function ($) {
$(document).ready(function(){
$("#edit-title-0-value").change(update);
$("#edit-field-carac1-0-value").click(update);
$("#edit-field-carac1-0-value").change(update);
$("#edit-field-carac2-0-value").change(update);
$("#edit-field-carac3-0-value").change(update);
$("#edit-field-carac4-0-value").change(update);
$("#edit-field-skill-0-value").change(update);
$("#edit-field-question-0-value").change(update);
$("#edit-field-answer-0-value").change(update);
$("#edit-field-img-game-card-0-upload").change(update);
$("#edit-field-upload_image_verso").change(update);
var bgimagerecto = undefined;
var bgimageverso = undefined;
if($('span.file--image > a').length == 1) {
if($('#edit-field-img-game-card-0-remove-button')) {
console.log("length11");
bgimagerecto = $("span.file--image > a:eq(0)").attr('href');
}
else {
console.log("length12");
bgimageverso = $("span.file--image > a:eq(0)").attr('href');
}
}
if($('span.file--image > a').length == 2) {
console.log("length2");
bgimagerecto = $("span.file--image > a:eq(0)").attr('href');
bgimageverso = $("span.file--image > a:eq(1)").attr('href');
}
if (bgimagerecto !== undefined) {
console.log("imagerecto");
$('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')');
$('.field--name-field-img-game-card .ajax-new-content').addClass('processed');
}
if (bgimageverso !== undefined) {
console.log("imageverso");
$('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')');
$('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed');
}
$(document).ajaxComplete(function(event, xhr, settings) {
//RECTO
console.log(event.target);
console.log("azer " + bgimagerecto);
console.log("qsdf " + bgimageverso);
if(~settings.url.indexOf("field_img_game_card")) {
console.log('entering recto');
if ($('.field--name-field-img-game-card .ajax-new-content').hasClass('processed')) {
console.log("remove recto");
//$('.ajax-new-content').remove();
$('#gamecardrectolayout').removeAttr('style');
$('.field--name-field-img-game-card .ajax-new-content').removeClass('processed');
return;
}
if(!$('#edit-field-img-game-card-0-remove-button')) {
console.log("remoooooove");
$('#gamecardrectolayout').removeAttr('style');
$('.field--name-field-img-game-card .ajax-new-content').removeClass('processed');
return;
}
console.log("addingrecto");
$('.field--name-field-img-game-card .ajax-new-content').addClass('processed');
bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); //Manage here when single or double
if (bgimagerecto !== undefined) {
console.log("gorecto");
$('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')');
}
return;
}
//VERSO
if(~settings.url.indexOf("field_upload_image_verso")) {
if ($('.field--name-field-upload-image-verso .ajax-new-content').hasClass('processed') || !$('#edit-field-upload-image-verso-0-remove-button')) {
console.log("remove verso");
//$('.ajax-new-content').remove();
$('#gamecardversolayout').removeAttr('style');
$('.field--name-field-upload-image-verso .ajax-new-content').removeClass('processed');
return;
}
console.log("adding verso");
$('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed');
if($('span.file--image > a').length == 1) bgimageverso = $("span.file--image > a:eq(0)").attr('href');
if($('span.file--image > a').length == 2) bgimageverso = $("span.file--image > a:eq(1)").attr('href');
if (bgimageverso !== undefined) {
console.log("Verso added");
$('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')');
}
}
});
});
function update(){
var cardname = (($("#edit-title-0-value").val() != "") ? $("#edit-title-0-value").val() : "");
var carac1 = (($("#edit-field-carac1-0-value").val() != "") ? $("#edit-field-carac1-0-value").val() : "");
var carac2 = (($("#edit-field-carac2-0-value").val() != "") ? $("#edit-field-carac2-0-value").val() : "");
var carac3 = (($("#edit-field-carac3-0-value").val() != "") ? $("#edit-field-carac3-0-value").val() : "");
var carac4 = (($("#edit-field-carac4-0-value").val() != "") ? $("#edit-field-carac4-0-value").val() : "");
var skill = (($("#edit-field-skill-0-value").val() != "") ? $("#edit-field-skill-0-value").val() : "") ;
var question = (($("#edit-field-question-0-value").val() != "") ? $("#edit-field-question-0-value").val() : "");
var answer = (($("#edit-field-answer-0-value").val() != "") ? $("#edit-field-answer-0-value").val() : "") ;
var rectoImg = (($("#edit-field-img-game-card-0-upload").val() != "") ? $("#edit-field-img-game-card-0-upload").val() : "");
var versoImg = (($("#edit-field-upload_image_verso").val() != "") ? $("#edit-field-upload_image_verso").val() : "");
if(rectoImg !== undefined) {
if (rectoImg != null) {
$('#gamecardrectolayout').css('background-image', 'url("' + rectoImg + '")');
}
else {
rectoImg = $("span.file--image > a:eq(0)").attr('href');
$('#gamecardrectolayout').css('background-image', 'url( ' + rectoImg + ')');
}
}
if(versoImg !== undefined) {
if (versoImg != null) {
$('#gamecardrectolayout').css('background-image', 'url("' + versoImg + '")');
}
else {
versoImg = $("span.file--image > a:eq(1)").attr('href');
$('#gamecardrectolayout').css('background-image', 'url( ' + versoImg + ')');
}
}
$('#displayCardname').html(cardname);
$('#displayCarac1').html(carac1);
$('#displayCarac2').html(carac2);
$('#displayCarac3').html(carac3);
$('#displayCarac4').html(carac4);
$('#displaySkill').html(skill);
$('#displayQuestion').html(question);
$('#displayAnswer').html(answer);
}
})(jQuery);
| TGR05/POEI-mini-projet | modules/custom/cardform/js/gamecards.js | JavaScript | gpl-2.0 | 6,227 |
define(["require", "exports"], function (require, exports) {
"use strict";
exports.ZaOverviewPanelController = ZaOverviewPanelController;
});
| ZeXtras/zimbra-lib-ts | zimbraAdmin/common/ZaOverviewPanelController.js | JavaScript | gpl-2.0 | 146 |
function playAudioVisualize(track) {
var bars = 50;
var waveResolution = 128;
var style = "bars"; //set default style upon loading here
var audio = new Audio();
var canvas, source, context, analyser, fFrequencyData, barX, barWidth, barHeight, red, green, blue, ctx;
audio.controls = true;
audio.src = track;
audio.loop = false;
audio.autoplay = false;
window.addEventListener("load", initPlayer, false);
function initPlayer() {
document.getElementById('audio-container').appendChild(audio);
context = new AudioContext();
analyser = context.createAnalyser();
canvas = document.getElementById('audio-display');
canvas.addEventListener("click", toggleStyle);
ctx = canvas.getContext('2d');
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
drawFrames();
function toggleStyle() {
style = (style === "wave" ? "bars" : "wave");
}
}
var k = 0; //keep track of total number of frames drawn
function drawFrames() {
window.requestAnimationFrame(drawFrames);
analyser.fftsize = 128;
fFrequencyData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fFrequencyData);
ctx.clearRect(0,0,canvas.width,canvas.height);
numBarsBars = 16;
//calculate average frequency for color
var total = 0;
for(var j = 0; j < fFrequencyData.length; j++) {
total += fFrequencyData[j];
}
var avg = total / fFrequencyData.length;
avg = avg / 1.2;
//bar style visual representation
function drawBars(numBars) {
for(var i = 0; i < numBars; i++) {
barX = i * (canvas.width / numBars);
barWidth = (canvas.width / numBars - 1);
barHeight = -(fFrequencyData[i] / 2);
//reduce frequency of color changing to avoid flickering
if(k % 15 === 0) {
getColors();
k = 0;
}
ctx.fillStyle = 'rgb('+red+','+green+','+blue+')';
ctx.fillRect(barX, canvas.height, barWidth, barHeight);
}
}
//waveform visualization
function drawWave(resolution, lineWidth) {
ctx.beginPath();
ctx.lineWidth = lineWidth;
var barX, barY;
for(var i = 0; i < resolution; i++) {
barX = i * (Math.ceil(canvas.width / resolution));
barY = -(fFrequencyData[i] / 2);
getColors();
k = 0;
ctx.strokeStyle = 'rgb('+red+','+green+','+blue+')';
ctx.lineTo(barX, barY + canvas.height );
ctx.stroke();
}
}
function getColors() {
//can edit these values to get overall different coloration!!
red = Math.round(Math.sin(avg/29.0 + 6.1) * 127 + 128);
green = Math.round(Math.sin(avg/42.0 - 7.4) * 127 + 128);
blue = Math.round(Math.sin(avg/34.0 - 3.8) * 127 + 128);
}
if(style === "wave") {
drawWave(waveResolution, 2);
}
if(style === "bars") {
drawBars(bars);
}
k++;
}
}
| cp2846/audio-visualizer | visualizer.js | JavaScript | gpl-2.0 | 3,591 |
/*global chrome */
// Check if the feature is enable
let promise = new Promise(function (resolve) {
chrome.storage.sync.get({
isEdEnable: true
}, function (items) {
if (items.isEdEnable === true) {
resolve();
}
});
});
promise.then(function () {
/*global removeIfExist */
/*eslint no-undef: "error"*/
removeIfExist(".blockheader");
removeIfExist(".blockcontent .upload-infos");
removeIfExist(".blockfooter");
}); | hochgenug/BADW | scripts/ed.js | JavaScript | gpl-2.0 | 481 |
PUMP_SELECTOR.CoordSlicer = function( parameters ) {
var image = parameters.image;
var coord = parameters.coord;
var name = parameters.name;
var obj = {};
if( image === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Cannot slice image, image missing.");
return undefined;
}else if (coord === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Warn: No coordinate data given. Returning image.");
return obj[name] = obj;
}else{
var coords = coord.split("\n");
coords.clean("");
for(var i=0;i<coords.length;i++) {
var coordinate = coords[i].split(" ");
obj[coordinate[0]] = PUMP_SELECTOR.CropImage(image,coordinate[1],coordinate[2],coordinate[3],coordinate[4]);
}
return obj;
}
};
| racerxdl/f2rank | jsselector/coord.js | JavaScript | gpl-2.0 | 823 |
/**
* Provides a DataSchema implementation which can be used to work with
* delimited text data.
*
* @module dataschema
* @submodule dataschema-text
*/
/**
Provides a DataSchema implementation which can be used to work with
delimited text data.
See the `apply` method for usage.
@class DataSchema.Text
@extends DataSchema.Base
@static
**/
var Lang = Y.Lang,
isString = Lang.isString,
isUndef = Lang.isUndefined,
SchemaText = {
////////////////////////////////////////////////////////////////////////
//
// DataSchema.Text static methods
//
////////////////////////////////////////////////////////////////////////
/**
Applies a schema to a string of delimited data, returning a normalized
object with results in the `results` property. The `meta` property of
the response object is present for consistency, but is assigned an
empty object. If the input data is absent or not a string, an `error`
property will be added.
Use _schema.resultDelimiter_ and _schema.fieldDelimiter_ to instruct
`apply` how to split up the string into an array of data arrays for
processing.
Use _schema.resultFields_ to specify the keys in the generated result
objects in `response.results`. The key:value pairs will be assigned
in the order of the _schema.resultFields_ array, assuming the values
in the data records are defined in the same order.
_schema.resultFields_ field identifiers are objects with the following
properties:
* `key` : <strong>(required)</strong> The property name you want
the data value assigned to in the result object (String)
* `parser`: A function or the name of a function on `Y.Parsers` used
to convert the input value into a normalized type. Parser
functions are passed the value as input and are expected to
return a value.
If no value parsing is needed, you can use just the desired property
name string as the field identifier instead of an object (see example
below).
@example
// Process simple csv
var schema = {
resultDelimiter: "\n",
fieldDelimiter: ",",
resultFields: [ 'fruit', 'color' ]
},
data = "Banana,yellow\nOrange,orange\nEggplant,purple";
var response = Y.DataSchema.Text.apply(schema, data);
// response.results[0] is { fruit: "Banana", color: "yellow" }
// Use parsers
schema.resultFields = [
{
key: 'fruit',
parser: function (val) { return val.toUpperCase(); }
},
'color' // mix and match objects and strings
];
response = Y.DataSchema.Text.apply(schema, data);
// response.results[0] is { fruit: "BANANA", color: "yellow" }
@method apply
@param {Object} schema Schema to apply. Supported configuration
properties are:
@param {String} schema.resultDelimiter Character or character
sequence that marks the end of one record and the start of
another.
@param {String} [schema.fieldDelimiter] Character or character
sequence that marks the end of a field and the start of
another within the same record.
@param {Array} [schema.resultFields] Field identifiers to
assign values in the response records. See above for details.
@param {String} data Text data.
@return {Object} An Object with properties `results` and `meta`
@static
**/
apply: function(schema, data) {
var data_in = data,
data_out = { results: [], meta: {} };
if (isString(data) && schema && isString(schema.resultDelimiter)) {
// Parse results data
data_out = SchemaText._parseResults.call(this, schema, data_in, data_out);
} else {
Y.log("Text data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-text");
data_out.error = new Error("Text schema parse failure");
}
return data_out;
},
/**
* Schema-parsed list of results from full data
*
* @method _parseResults
* @param schema {Array} Schema to parse against.
* @param text_in {String} Text to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Parsed data object.
* @static
* @protected
*/
_parseResults: function(schema, text_in, data_out) {
var resultDelim = schema.resultDelimiter,
fieldDelim = isString(schema.fieldDelimiter) &&
schema.fieldDelimiter,
fields = schema.resultFields || [],
results = [],
parse = Y.DataSchema.Base.parse,
results_in, fields_in, result, item,
field, key, value, i, j;
// Delete final delimiter at end of string if there
if (text_in.slice(-resultDelim.length) === resultDelim) {
text_in = text_in.slice(0, -resultDelim.length);
}
// Split into results
results_in = text_in.split(schema.resultDelimiter);
if (fieldDelim) {
for (i = results_in.length - 1; i >= 0; --i) {
result = {};
item = results_in[i];
fields_in = item.split(schema.fieldDelimiter);
for (j = fields.length - 1; j >= 0; --j) {
field = fields[j];
key = (!isUndef(field.key)) ? field.key : field;
// FIXME: unless the key is an array index, this test
// for fields_in[key] is useless.
value = (!isUndef(fields_in[key])) ?
fields_in[key] :
fields_in[j];
result[key] = parse.call(this, value, field);
}
results[i] = result;
}
} else {
results = results_in;
}
data_out.results = results;
return data_out;
}
};
Y.DataSchema.Text = Y.mix(SchemaText, Y.DataSchema.Base);
| schancel/gameserver | public/js/yui3-3.12.0/src/dataschema/js/dataschema-text.js | JavaScript | gpl-2.0 | 6,718 |
define(['jquery', 'util.tooltips', 'helper.boxes', 'modules/panel'], function($, tooltips, panel) {
/* Grid */
tourStepsGrid = [
{
beginning: true,
title: 'Welcome to the Blox Visual Editor!',
content: '<p>If this is your first time in the Blox Visual Editor, <strong>we recommend following this tour so you can get the most out of Blox</strong>.</p><p>Or, if you\'re experienced or want to dive in right away, just click the close button in the top right at any time.</p>'
},
{
target: $('li#mode-grid'),
title: 'Mode Selector',
content: '<p>The Blox Visual Editor is split up into 2 modes.</p><p><ul><li><strong>Grid</strong> – Build your layouts</li><li><strong>Design</strong> – Add colors, customize fonts, and more!</li></ul></p>',
position: {
my: 'top left',
at: 'bottom center'
}
},
{
target: $('#layout-selector-select-content'),
title: 'Layout Selector',
content: '<p style="font-size:12px;">Since you may not want every page to be the same, you may use the Layout Selector to select which page, post, or archive to edit.</p><p style="font-size:12px;">The Layout Selector is based off of inheritance. For example, you can customize the "Page" layout and all pages will follow that layout. Plus, you can customize a specific page and it\'ll be different than all other pages.</p><p style="font-size:12px;">The layout selector will allow you to be as precise or broad as you wish. It\'s completely up to you!</p>',
position: {
my: 'top center',
at: 'bottom center'
}
},
{
target: $('div#box-grid-wizard'),
title: 'The Blox Grid',
content: '<p>Now we\'re ready to get started with the Blox Grid. In other words, the good stuff.</p><p>To build your first layout, please select a preset to the right to pre-populate the grid. Or, you may select "Use Empty Grid" to start with a completely blank grid.</p><p>Once you have a preset selected, click "Finish".</p>',
position: {
my: 'right top',
at: 'left center'
},
nextHandler: {
showButton: false,
clickElement: '#grid-wizard-button-preset-use-preset, span.grid-wizard-use-empty-grid',
message: 'Please click <strong>"Finish"</strong> or <strong>"Use Empty Grid"</strong> to continue.'
}
},
{
iframeTarget: 'div.grid-container',
title: 'Adding Blocks',
content: '<p>To add a block, simply place your mouse into the grid then click at where you\'d like the top-left point of the block to be.</p><p>Drag your mouse and the block will appear! Once the block appears, you may choose the block type.</p><p>Hint: Don\'t worry about being precise, you may always move or resize the block.</p>',
position: {
my: 'right top',
at: 'left top',
adjustY: 100
},
maxWidth: 280
},
{
iframeTarget: 'div.grid-container',
title: 'Modifying Blocks',
content: '\
<p style="font-size:12px;">After you\'ve added the desired blocks to your layout, you may move, resize, delete, or change the options of the block at any time.</p>\
<ul style="font-size:12px;">\
<li><strong>Moving Blocks</strong> – Click and drag the block. If you wish to move multiple blocks simultaneously, double-click on a block to enter <em>Mass Block Selection Mode</em>.</li>\
<li><strong>Resizing Blocks</strong> – Grab the border or corner of the block and drag your mouse.</li>\
<li><strong>Block Options (e.g. header image)</strong> – Hover over the block then click the block options icon in the top-right.</li>\
<li><strong>Deleting Blocks</strong> – Move your mouse over the desired block, then click the <em>X</em> icon in the top-right.</li>\
</ul>',
position: {
my: 'right top',
at: 'left top',
adjustY: 100
},
maxWidth: 280
},
{
target: $('#save-button-container'),
title: 'Saving',
content: '<p>Now that you hopefully have a few changes to be saved, you can save using this spiffy Save button.</p><p>For those of you who like hotkeys, use <strong>Ctrl + S</strong> to save.</p>',
position: {
my: 'top right',
at: 'bottom center'
},
tip: 'top right'
},
{
target: $('li#mode-design a'),
title: 'Design Mode',
content: '<p>Thanks for sticking with us!</p><p>Now that you have an understanding of the Grid Mode, we hope you stick with us and head on over to the Design Mode.</p>',
position: {
my: 'top left',
at: 'bottom center',
adjustY: 5
},
tip: 'top left',
buttonText: 'Continue to Design Mode',
buttonCallback: function () {
$.post(Blox.ajaxURL, {
security: Blox.security,
action: 'blox_visual_editor',
method: 'ran_tour',
mode: 'grid',
complete: function () {
Blox.ranTour['grid'] = true;
/* Advance to Design Editor */
$('li#mode-design a').trigger('click');
window.location = $('li#mode-design a').attr('href');
}
});
}
}
];
/* Design */
tourStepsDesign = [
{
beginning: true,
title: 'Welcome to the Blox Design Editor!',
content: "<p>In the <strong>Design Editor</strong>, you can style your elements however you'd like.</p><p>Whether it's fonts, colors, padding, borders, shadows, or rounded corners, you can use the design editor.</p><p>Stick around to learn more!</p>"
},
{
target: '#side-panel-top',
title: 'Element Selector',
content: '<p>The element selector allows you choose which element to edit.</p>',
position: {
my: 'right top',
at: 'left center'
},
callback: function () {
$('li#element-block-header > span.element-name').trigger('click');
}
},
{
target: '#toggle-inspector',
title: 'Inspector',
content: "\
<p>Instead of using the <em>Element Selector</em>, let the Inspector do the work for you.</p>\
<p><strong>Try it out!</strong> Point and right-click on the element you wish to edit and it will become selected!</p>\
",
position: {
my: 'top right',
at: 'bottom center',
adjustX: 10,
adjustY: 5
}
},
{
target: 'window',
title: 'Have fun building with Blox!',
content: '<p>We hope you find Blox to the most powerful and easy-to-use WordPress framework around.</p><p>If you have any questions, please don\'t hesitate to visit the <a href="http://support.bloxtheme.com/?utm_source=visualeditor&utm_medium=blox&utm_campaign=tour" target="_blank">support forums</a>.</p>',
end: true
}
];
return {
start: function () {
if ( Blox.mode == 'grid' ) {
var steps = tourStepsGrid;
hidePanel();
openBox('grid-wizard');
} else if ( Blox.mode == 'design' ) {
var steps = tourStepsDesign;
showPanel();
require(['modules/design/mode-design'], function() {
showDesignEditor();
});
if ( typeof $('div#panel').data('ui-tabs') != 'undefined' )
selectTab('editor-tab', $('div#panel'));
} else {
return;
}
$('<div class="black-overlay"></div>')
.hide()
.attr('id', 'black-overlay-tour')
.css('zIndex', 15)
.appendTo('body')
.fadeIn(500);
$(document.body).qtip({
id: 'tour', // Give it an ID of qtip-tour so we an identify it easily
content: {
text: steps[0].content + '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">Continue Tour <span class="arrow">›</span></span></div>',
title: {
text: steps[0].title, // ...and title
button: 'Skip Tour'
}
},
style: {
classes: 'qtip-tour',
tip: {
width: 18,
height: 10,
mimic: 'center',
offset: 10
}
},
position: {
my: 'center',
at: 'center',
target: $(window), // Also use first steps position target...
viewport: $(window), // ...and make sure it stays on-screen if possible
adjust: {
y: 5,
method: 'shift shift'
}
},
show: {
event: false, // Only show when show() is called manually
ready: true, // Also show on page load,
effect: function () {
$(this).fadeIn(500);
}
},
hide: false, // Don't hide unless we call hide()
events: {
render: function (event, api) {
$('#iframe-notice').remove();
hideIframeOverlay();
openBox('grid-wizard');
// Grab tooltip element
var tooltip = api.elements.tooltip;
// Track the current step in the API
api.step = 0;
// Bind custom custom events we can fire to step forward/back
tooltip.bind('next', function (event) {
/* For some reason trigger window resizing helps tooltip positioning */
$(window).trigger('resize');
// Increase/decrease step depending on the event fired
api.step += 1;
api.step = Math.min(steps.length - 1, Math.max(0, api.step));
// Set new step properties
currentTourStep = steps[api.step];
$('div#black-overlay-tour').fadeOut(100, function () {
$(this).remove();
});
//Run the callback if it exists
if ( typeof currentTourStep.callback === 'function' ) {
currentTourStep.callback.apply(api);
}
if ( currentTourStep.target == 'window' ) {
currentTourStep.target = $(window);
} else if ( typeof currentTourStep.target == 'string' ) {
currentTourStep.target = $(currentTourStep.target);
} else if ( typeof currentTourStep.iframeTarget == 'string' ) {
currentTourStep.target = $i(currentTourStep.iframeTarget).first();
}
api.set('position.target', currentTourStep.target);
if ( typeof currentTourStep.maxWidth !== 'undefined' && window.innerWidth < 1440 ) {
$('.qtip-tour').css('maxWidth', currentTourStep.maxWidth);
} else {
$('.qtip-tour').css('maxWidth', 350);
}
/* Set up button */
var buttonText = 'Next';
if ( typeof currentTourStep.buttonText == 'string' )
var buttonText = currentTourStep.buttonText;
if ( typeof currentTourStep.end !== 'undefined' && currentTourStep.end === true ) {
var button = '<div id="tour-next-container"><span id="tour-finish" class="tour-button button button-blue">Close Tour <span class="arrow">›</span></div>';
} else if ( typeof currentTourStep.nextHandler === 'undefined' || currentTourStep.nextHandler.showButton ) {
var button = '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">' + buttonText + ' <span class="arrow">›</span></div>';
} else {
var button = '<div id="tour-next-container"><p>' + currentTourStep.nextHandler.message + '</p></div>';
}
/* Next Handler Callback... Be able to use something other than the button */
if ( typeof currentTourStep.nextHandler !== 'undefined' && $(currentTourStep.nextHandler.clickElement) ) {
var nextHandlerCallback = function (event) {
$('.qtip-tour').triggerHandler('next');
event.preventDefault();
$(this).unbind('click', nextHandlerCallback);
}
$(currentTourStep.nextHandler.clickElement).bind('click', nextHandlerCallback);
}
/* Set the Content */
api.set('content.text', currentTourStep.content + button);
api.set('content.title', currentTourStep.title);
if ( typeof currentTourStep.end === 'undefined' ) {
/* Position */
if ( typeof currentTourStep.position !== 'undefined' ) {
api.set('position.my', currentTourStep.position.my);
api.set('position.at', currentTourStep.position.at);
/* Offset/Adjust */
if ( typeof currentTourStep.position.adjustX !== 'undefined' ) {
api.set('position.adjust.x', currentTourStep.position.adjustX);
} else {
api.set('position.adjust.x', 0);
}
if ( typeof currentTourStep.position.adjustY !== 'undefined' ) {
api.set('position.adjust.y', currentTourStep.position.adjustY);
} else {
api.set('position.adjust.y', 0);
}
} else {
api.set('position.my', 'top center');
api.set('position.at', 'bottom center');
}
if ( typeof currentTourStep.tip !== 'undefined' )
api.set('style.tip.corner', currentTourStep.tip);
} else {
api.set('position.my', 'center');
api.set('position.at', 'center');
}
});
/* Tour Button Bindings */
$('div.qtip-tour').on('click', 'span#tour-next', function (event) {
/* Callback that fires upon button click... Used for advancing to Design Editor */
if ( typeof currentTourStep == 'object' && typeof currentTourStep.buttonCallback == 'function' )
currentTourStep.buttonCallback.call();
$('.qtip-tour').triggerHandler('next');
event.preventDefault();
});
$('div.qtip-tour').on('click', 'span#tour-finish', function (event) {
$('.qtip-tour').qtip('hide');
});
},
// Destroy the tooltip after it hides as its no longer needed
hide: function (event, api) {
$('div#tour-overlay').remove();
$('div#black-overlay-tour').fadeOut(100, function () {
$(this).remove();
});
$('.qtip-tour').fadeOut(100, function () {
$(this).qtip('destroy');
});
//Tell the DB that the tour has been ran
if ( Blox.ranTour[Blox.mode] == false && Blox.ranTour.legacy != true ) {
$.post(Blox.ajaxURL, {
security: Blox.security,
action: 'blox_visual_editor',
method: 'ran_tour',
mode: Blox.mode
});
Blox.ranTour[Blox.mode] = true;
}
}
}
});
}
}
}); | bloxtheme/BloxTheme | bloxtheme/library/visual-editor/scripts-src/util.tour.js | JavaScript | gpl-2.0 | 13,717 |
/**
* Created by inwebo on 05/02/15.
*/
alert('local');
| inwebo/Libre | demos/assets/instances/www.test.fr/themes/default/public/js/demo.js | JavaScript | gpl-2.0 | 58 |
/**
Select
# What? #
Part of my "Responsive Menu Concepts" article on CSS-Tricks
http://css-tricks.com/responsive-menu-concepts
# 2012 by Tim Pietrusky
# timpietrusky.com
**/ | evasmidt/allsafe-drupal | themes/custom/allsafe/js/scripts.js | JavaScript | gpl-2.0 | 191 |
(function ($) {
function getCsrfTokenForFullShotImage(callback) {
$
.get(Drupal.url('rest/session/token'))
.done(function (data) {
var csrfToken = data;
callback(csrfToken);
});
}
function patchImageFullShot(csrfToken, file, fid) {
//document.getElementById('msg-up').innerHTML = 'Image marked as fullshot ....';
$.ajax({
url: Drupal.url('file/' + fid + '?_format=hal_json'),
method: 'PATCH',
headers: {
'Content-Type': 'application/hal+json',
'X-CSRF-Token': csrfToken
},
data: JSON.stringify(file),
success: function (file) {
//console.log(node);
//document.getElementById('msg-up').innerHTML = 'Image Fullshot started!';
swal({
title: "Full Shot",
text: "Image has been selected as full shot. Scan next ID",
type: "success",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: true
});
},
error: function(){
swal({
title: "Full Shot",
text: "There was an error, please try again.",
type: "error",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: true
});
}
});
// setTimeout(function(){
// document.getElementById('msg-up').innerHTML = '';
// }, 3300);
}
/*
* tag value 1 means tag
* tag value 0 means undo tag
*
*/
function update_image_fullshot(tag,fidinput) {
var nid = fidinput;
var Node_imgs = {
_links: {
type: {
href: Drupal.url.toAbsolute(drupalSettings.path.baseUrl + 'rest/type/file/image')
}
},
// type: {
// target_id: 'products'
// },
field_full_shoot: {
value:tag
}
};
getCsrfTokenForFullShotImage(function (csrfToken) {
if (nid) {
patchImageFullShot(csrfToken, Node_imgs, nid);
}else{
alert('Node product found, pls refresh the page.');
}
});
}
$(".studio-img-fullshot").click(function () {
var id = $(this).parents('span').attr('id');
console.log('fullshot');
update_image_fullshot(1,id);
});
$(document).on("click",".studio-img-fullshot",function(){
var id = $(this).parents('span').attr('id');
console.log('fullshot');
update_image_fullshot(1,id);
});
})(jQuery);
| asharnb/dawn | modules/custom/studiobridge_store_images/js/studio-bridge-fullshot-image.js | JavaScript | gpl-2.0 | 3,011 |
showWord(["v. ","vin jòn.<br>"]) | georgejhunt/HaitiDictionary.activity | data/words/joni.js | JavaScript | gpl-2.0 | 33 |
document.addEventListener("DOMContentLoaded", function (event) {
'use strict';
var paragraph, url, proxy;
paragraph = document.querySelectorAll('p.error_text');
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
url = tabs[0].url;
if (url.indexOf('chrome://') == 0) {
paragraph[0].innerHTML = 'Sorry, you can\'t activate Browse Google Cache on a page with a "chrome://" URL.';
} else if (url.indexOf('https://chrome.google.com/webstore') == 0) {
paragraph[0].innerHTML = 'Sorry, you can\'t activate Browse Google Cache on the Chrome Web Store.';
} else {
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
chrome.runtime.sendMessage({
action : 'extensionButtonClicked',
'tab': tabs[0]
});
window.close();
});
}
});
}); | joelself/GoogleCacheBrowser | src/popup.js | JavaScript | gpl-2.0 | 815 |
showWord(["","Wayòm ki te nan pati Sidwès peyi Ispayola. Se Boyekyo ki te chèf endyen nan wayòm sa a. Kapital wayòm sa a te Lagwana, kounye a yo rele l Leogàn."
]) | georgejhunt/HaitiDictionary.activity | data/words/zaragwa.js | JavaScript | gpl-2.0 | 169 |
/**!
* The MIT License
*
* Copyright (c) 2010-2012 Google, Inc. http://angularjs.org
*
* 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.
*
* angular-google-maps
* https://github.com/nlaplante/angular-google-maps
*
* @author Nicolas Laplante https://plus.google.com/108189012221374960701
*/
(function () {
"use strict";
/*
* Utility functions
*/
/**
* Check if 2 floating point numbers are equal
*
* @see http://stackoverflow.com/a/588014
*/
function floatEqual (f1, f2) {
return (Math.abs(f1 - f2) < 0.000001);
}
/*
* Create the model in a self-contained class where map-specific logic is
* done. This model will be used in the directive.
*/
var MapModel = (function () {
var _defaults = {
zoom: 8,
draggable: false,
container: null
};
/**
*
*/
function PrivateMapModel(opts) {
var _instance = null,
_markers = [], // caches the instances of google.maps.Marker
_handlers = [], // event handlers
_windows = [], // InfoWindow objects
o = angular.extend({}, _defaults, opts),
that = this,
currentInfoWindow = null;
this.center = opts.center;
this.zoom = o.zoom;
this.draggable = o.draggable;
this.dragging = false;
this.selector = o.container;
this.markers = [];
this.options = o.options;
this.draw = function () {
if (that.center == null) {
// TODO log error
return;
}
if (_instance == null) {
// Create a new map instance
_instance = new google.maps.Map(that.selector, angular.extend(that.options, {
center: that.center,
zoom: that.zoom,
draggable: that.draggable,
mapTypeId : google.maps.MapTypeId.ROADMAP
}));
google.maps.event.addListener(_instance, "dragstart",
function () {
that.dragging = true;
}
);
google.maps.event.addListener(_instance, "idle",
function () {
that.dragging = false;
}
);
google.maps.event.addListener(_instance, "drag",
function () {
that.dragging = true;
}
);
google.maps.event.addListener(_instance, "zoom_changed",
function () {
that.zoom = _instance.getZoom();
that.center = _instance.getCenter();
}
);
google.maps.event.addListener(_instance, "center_changed",
function () {
that.center = _instance.getCenter();
}
);
// Attach additional event listeners if needed
if (_handlers.length) {
angular.forEach(_handlers, function (h, i) {
google.maps.event.addListener(_instance,
h.on, h.handler);
});
}
}
else {
// Refresh the existing instance
google.maps.event.trigger(_instance, "resize");
var instanceCenter = _instance.getCenter();
if (!floatEqual(instanceCenter.lat(), that.center.lat())
|| !floatEqual(instanceCenter.lng(), that.center.lng())) {
_instance.setCenter(that.center);
}
if (_instance.getZoom() != that.zoom) {
_instance.setZoom(that.zoom);
}
}
};
this.fit = function () {
if (_instance && _markers.length) {
var bounds = new google.maps.LatLngBounds();
angular.forEach(_markers, function (m, i) {
bounds.extend(m.getPosition());
});
_instance.fitBounds(bounds);
}
};
this.on = function(event, handler) {
_handlers.push({
"on": event,
"handler": handler
});
};
this.addMarker = function (lat, lng, icon, infoWindowContent, label, url,
thumbnail) {
if (that.findMarker(lat, lng) != null) {
return;
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: _instance,
icon: icon
});
if (label) {
}
if (url) {
}
if (infoWindowContent != null) {
var infoWindow = new google.maps.InfoWindow({
content: infoWindowContent
});
google.maps.event.addListener(marker, 'click', function() {
if (currentInfoWindow != null) {
currentInfoWindow.close();
}
infoWindow.open(_instance, marker);
currentInfoWindow = infoWindow;
});
}
// Cache marker
_markers.unshift(marker);
// Cache instance of our marker for scope purposes
that.markers.unshift({
"lat": lat,
"lng": lng,
"draggable": false,
"icon": icon,
"infoWindowContent": infoWindowContent,
"label": label,
"url": url,
"thumbnail": thumbnail
});
// Return marker instance
return marker;
};
this.findMarker = function (lat, lng) {
for (var i = 0; i < _markers.length; i++) {
var pos = _markers[i].getPosition();
if (floatEqual(pos.lat(), lat) && floatEqual(pos.lng(), lng)) {
return _markers[i];
}
}
return null;
};
this.findMarkerIndex = function (lat, lng) {
for (var i = 0; i < _markers.length; i++) {
var pos = _markers[i].getPosition();
if (floatEqual(pos.lat(), lat) && floatEqual(pos.lng(), lng)) {
return i;
}
}
return -1;
};
this.addInfoWindow = function (lat, lng, html) {
var win = new google.maps.InfoWindow({
content: html,
position: new google.maps.LatLng(lat, lng)
});
_windows.push(win);
return win;
};
this.hasMarker = function (lat, lng) {
return that.findMarker(lat, lng) !== null;
};
this.getMarkerInstances = function () {
return _markers;
};
this.removeMarkers = function (markerInstances) {
var s = this;
angular.forEach(markerInstances, function (v, i) {
var pos = v.getPosition(),
lat = pos.lat(),
lng = pos.lng(),
index = s.findMarkerIndex(lat, lng);
// Remove from local arrays
_markers.splice(index, 1);
s.markers.splice(index, 1);
// Remove from map
v.setMap(null);
});
};
}
// Done
return PrivateMapModel;
}());
// End model
// Start Angular directive
var googleMapsModule = angular.module("google-maps", []);
/**
* Map directive
*/
googleMapsModule.directive("googleMap", ["$log", "$timeout", "$filter", function ($log, $timeout,
$filter) {
var controller = function ($scope, $element) {
var _m = $scope.map;
self.addInfoWindow = function (lat, lng, content) {
_m.addInfoWindow(lat, lng, content);
};
};
controller.$inject = ['$scope', '$element'];
return {
restrict: "EC",
priority: 100,
transclude: true,
template: "<div class='angular-google-map' ng-transclude></div>",
replace: false,
scope: {
center: "=center", // required
markers: "=markers", // optional
latitude: "=latitude", // required
longitude: "=longitude", // required
zoom: "=zoom", // required
refresh: "&refresh", // optional
windows: "=windows" // optional"
},
controller: controller,
link: function (scope, element, attrs, ctrl) {
// Center property must be specified and provide lat &
// lng properties
if (!angular.isDefined(scope.center) ||
(!angular.isDefined(scope.center.lat) ||
!angular.isDefined(scope.center.lng))) {
$log.error("angular-google-maps: ould not find a valid center property");
return;
}
if (!angular.isDefined(scope.zoom)) {
$log.error("angular-google-maps: map zoom property not set");
return;
}
angular.element(element).addClass("angular-google-map");
// Parse options
var opts = {options: {}};
if (attrs.options) {
opts.options = angular.fromJson(attrs.options);
}
// Create our model
var _m = new MapModel(angular.extend(opts, {
container: element[0],
center: new google.maps.LatLng(scope.center.lat, scope.center.lng),
draggable: attrs.draggable == "true",
zoom: scope.zoom
}));
_m.on("drag", function () {
var c = _m.center;
$timeout(function () {
scope.$apply(function (s) {
scope.center.lat = c.lat();
scope.center.lng = c.lng();
});
});
});
_m.on("zoom_changed", function () {
if (scope.zoom != _m.zoom) {
$timeout(function () {
scope.$apply(function (s) {
scope.zoom = _m.zoom;
});
});
}
});
_m.on("center_changed", function () {
var c = _m.center;
$timeout(function () {
scope.$apply(function (s) {
if (!_m.dragging) {
scope.center.lat = c.lat();
scope.center.lng = c.lng();
}
});
});
});
if (attrs.markClick == "true") {
(function () {
var cm = null;
_m.on("click", function (e) {
if (cm == null) {
cm = {
latitude: e.latLng.lat(),
longitude: e.latLng.lng()
};
scope.markers.push(cm);
}
else {
cm.latitude = e.latLng.lat();
cm.longitude = e.latLng.lng();
}
$timeout(function () {
scope.latitude = cm.latitude;
scope.longitude = cm.longitude;
scope.$apply();
});
});
}());
}
// Put the map into the scope
scope.map = _m;
// Check if we need to refresh the map
if (angular.isUndefined(scope.refresh())) {
// No refresh property given; draw the map immediately
_m.draw();
}
else {
scope.$watch("refresh()", function (newValue, oldValue) {
if (newValue && !oldValue) {
_m.draw();
}
});
}
// Markers
scope.$watch("markers", function (newValue, oldValue) {
$timeout(function () {
angular.forEach(newValue, function (v, i) {
if (!_m.hasMarker(v.latitude, v.longitude)) {
_m.addMarker(v.latitude, v.longitude, v.icon, v.infoWindow);
}
});
// Clear orphaned markers
var orphaned = [];
angular.forEach(_m.getMarkerInstances(), function (v, i) {
// Check our scope if a marker with equal latitude and longitude.
// If not found, then that marker has been removed form the scope.
var pos = v.getPosition(),
lat = pos.lat(),
lng = pos.lng(),
found = false;
// Test against each marker in the scope
for (var si = 0; si < scope.markers.length; si++) {
var sm = scope.markers[si];
if (floatEqual(sm.latitude, lat) && floatEqual(sm.longitude, lng)) {
// Map marker is present in scope too, don't remove
found = true;
}
}
// Marker in map has not been found in scope. Remove.
if (!found) {
orphaned.push(v);
}
});
orphaned.length && _m.removeMarkers(orphaned);
// Fit map when there are more than one marker.
// This will change the map center coordinates
if (attrs.fit == "true" && newValue.length > 1) {
_m.fit();
}
});
}, true);
// Update map when center coordinates change
scope.$watch("center", function (newValue, oldValue) {
if (newValue === oldValue) {
return;
}
if (!_m.dragging) {
_m.center = new google.maps.LatLng(newValue.lat,
newValue.lng);
_m.draw();
}
}, true);
scope.$watch("zoom", function (newValue, oldValue) {
if (newValue === oldValue) {
return;
}
_m.zoom = newValue;
_m.draw();
});
}
};
}]);
}()); | HediMaiza/SmoothieParis | js/vendor/google-maps.js | JavaScript | gpl-2.0 | 15,335 |
showWord(["np. ","Avoka, politisyen. Madanm prezidan Jean Bertrand Aristide."
]) | georgejhunt/HaitiDictionary.activity | data/words/TwouyoMildr~ed_Trouillot.js | JavaScript | gpl-2.0 | 80 |
$('.attach_detach').on('click', function(){
var device_id = $(this).attr('device_id');
$('#device_id').val(device_id);
});
$('.detach_customer').on('click', function(){
//get the attached customer name
var customer_name = $(this).attr('cust_name');
if(confirm('Are you sure you want to detach('+customer_name+') from the device?')){
return true;
}else{
return false;
}
}); | toxicaliens/rental | src/js/allocate_devices.js | JavaScript | gpl-3.0 | 399 |
var gulp = require('gulp')
var mocha = require('gulp-mocha')
var nodemon = require('gulp-nodemon')
var env = require('gulp-env');
gulp.task('API-Server', (cb) => {
let started = false
env({
vars: {
httpPort: 8080
}
});
return nodemon({
script: 'index.js'
})
.on('start', () => {
if (!started) {
started = true
return cb()
}
})
.on('restart', () => {
console.log('restarting')
})
})
gulp.task('test', ['API-Server'], function() {
return gulp.src('./test/index.js')
.pipe(mocha())
.once('error', function() {
process.exit(1)
})
.once('end', function() {
process.exit()
})
})
| HeyYZU/HeyYZU-server | gulpfile.js | JavaScript | gpl-3.0 | 690 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
(function(){var l={_attachScript:function(e,c){var d=new CKEDITOR.dom.element("script");d.setAttribute("src",e);d.on("error",c);CKEDITOR.document.getBody().append(d);return d},sendRequest:function(e,c,d,a){function b(){g&&(g.remove(),delete CKEDITOR._.jsonpCallbacks[h],g=null)}var k={};c=c||{};var h=CKEDITOR.tools.getNextNumber(),g;c.callback="CKEDITOR._.jsonpCallbacks["+h+"]";CKEDITOR._.jsonpCallbacks[h]=function(a){setTimeout(function(){b();d(a)})};g=this._attachScript(e.output(c),function(){b();
a&&a()});k.cancel=b;return k}};CKEDITOR.plugins.add("embedbase",{lang:"az,ca,cs,da,de,de-ch,en,eo,es,es-mx,eu,fr,gl,hr,hu,id,it,ja,ko,ku,nb,nl,oc,pl,pt,pt-br,ru,sk,sv,tr,ug,uk,zh,zh-cn",requires:"dialog,widget,notificationaggregator",onLoad:function(){CKEDITOR._.jsonpCallbacks={}},init:function(){CKEDITOR.dialog.add("embedBase",this.path+"dialogs/embedbase.js")}});CKEDITOR.plugins.embedBase={createWidgetBaseDefinition:function(e){var c,d=e.lang.embedbase;return{mask:!0,template:"\x3cdiv\x3e\x3c/div\x3e",
pathName:d.pathName,_cache:{},urlRegExp:/^((https?:)?\/\/|www\.)/i,init:function(){this.on("sendRequest",function(a){this._sendRequest(a.data)},this,null,999);this.on("dialog",function(a){a.data.widget=this},this);this.on("handleResponse",function(a){if(!a.data.html){var b=this._responseToHtml(a.data.url,a.data.response);null!==b?a.data.html=b:(a.data.errorMessage="unsupportedUrl",a.cancel())}},this,null,999)},loadContent:function(a,b){function c(e){f.response=e;d.editor.widgets.instances[d.id]?d._handleResponse(f)&&
(d._cacheResponse(a,e),b.callback&&b.callback()):(CKEDITOR.warn("embedbase-widget-invalid"),f.task&&f.task.done())}b=b||{};var d=this,e=this._getCachedResponse(a),f={noNotifications:b.noNotifications,url:a,callback:c,errorCallback:function(a){d._handleError(f,a);b.errorCallback&&b.errorCallback(a)}};if(e)setTimeout(function(){c(e)});else return b.noNotifications||(f.task=this._createTask()),this.fire("sendRequest",f),f},isUrlValid:function(a){return this.urlRegExp.test(a)&&!1!==this.fire("validateUrl",
a)},getErrorMessage:function(a,b,c){(c=e.lang.embedbase[a+(c||"")])||(c=a);return(new CKEDITOR.template(c)).output({url:b||""})},_sendRequest:function(a){var b=this,c=l.sendRequest(this.providerUrl,{url:encodeURIComponent(a.url)},a.callback,function(){a.errorCallback("fetchingFailed")});a.cancel=function(){c.cancel();b.fire("requestCanceled",a)}},_handleResponse:function(a){var b={url:a.url,html:"",response:a.response};if(!1!==this.fire("handleResponse",b))return a.task&&a.task.done(),this._setContent(a.url,
b.html),!0;a.errorCallback(b.errorMessage);return!1},_handleError:function(a,b){a.task&&(a.task.cancel(),a.noNotifications||e.showNotification(this.getErrorMessage(b,a.url),"warning"))},_responseToHtml:function(a,b){return"photo"==b.type?'\x3cimg src\x3d"'+CKEDITOR.tools.htmlEncodeAttr(b.url)+'" alt\x3d"'+CKEDITOR.tools.htmlEncodeAttr(b.title||"")+'" style\x3d"max-width:100%;height:auto" /\x3e':"video"==b.type||"rich"==b.type?(b.html=b.html.replace(/<iframe/g,'\x3ciframe tabindex\x3d"-1"'),b.html):
null},_setContent:function(a,b){this.setData("url",a);this.element.setHtml(b)},_createTask:function(){if(!c||c.isFinished())c=new CKEDITOR.plugins.notificationAggregator(e,d.fetchingMany,d.fetchingOne),c.on("finished",function(){c.notification.hide()});return c.createTask()},_cacheResponse:function(a,b){this._cache[a]=b},_getCachedResponse:function(a){return this._cache[a]}}},_jsonp:l}})(); | Daniel-KM/Omeka-S | application/asset/vendor/ckeditor/plugins/embedbase/plugin.js | JavaScript | gpl-3.0 | 3,601 |
Ext.define('Omni.view.sizes.Explorer', {
extend: 'Buildit.ux.explorer.Panel',
alias: 'widget.omni-sizes-Explorer',
initComponent: function() {
var me = this;
// EXPLORER INIT (Start) ===============================================================
Ext.apply(this, {
allowFind: true,
store: Ext.create('Omni.store.Size'),
contextMenuConfig: {
xtype: 'omni-app-ExplorerContextMenu'
},
newForms: [{
xtype: 'omni-sizes-Form',
windowConfig: {}
}],
inspectorConfig: {
xtype: 'omni-sizes-Inspector'
}
});
// EXPLORER INIT (End)
// LABELS (Start) ======================================================================
Ext.applyIf(this, {
size_nbrLabel: Omni.i18n.model.Size.size_nbr,
size_typeLabel: Omni.i18n.model.Size.size_type,
displayLabel: Omni.i18n.model.Size.display,
concatenated_nameLabel: Omni.i18n.model.Size.concatenated_name,
dimension_1Label: Omni.i18n.model.Size.dimension_1,
dimension_2Label: Omni.i18n.model.Size.dimension_2,
is_enabledLabel: Omni.i18n.model.Size.is_enabled
});
// LABELS (End)
// COLUMNS (Start) =====================================================================
Ext.apply(this, {
columns: [{
header: this.displayLabel,
dataIndex: 'display',
flex: 1,
sortable: false
}, {
header: this.concatenated_nameLabel,
dataIndex: 'concatenated_name',
flex: 1,
sortable: false
}, {
header: this.dimension_1Label,
dataIndex: 'dimension_1',
flex: 1,
sortable: false
}, {
header: this.dimension_2Label,
dataIndex: 'dimension_2',
flex: 1,
sortable: false
}, {
header: this.size_typeLabel,
dataIndex: 'size_type',
flex: 1,
sortable: false,
renderer: Buildit.util.Format.lookupRenderer('SIZE_TYPE')
}, {
header: this.size_nbrLabel,
dataIndex: 'size_nbr',
flex: 1,
sortable: false
}, {
header: this.is_enabledLabel,
dataIndex: 'is_enabled',
flex: 1,
sortable: false
}, ]
});
// COLUMNS (End)
// TITLES (Start) ======================================================================
Ext.apply(this, {
title: 'Size',
subtitle: 'All Product Sizes that are valid in the system'
});
// TITLES (End)
this.callParent();
}
});
| tunacasserole/omni | app/assets/javascripts/omni/view/sizes/Explorer.js | JavaScript | gpl-3.0 | 2,541 |
/*
* Copyright (c) 2011-2013 Lp digital system
*
* This file is part of BackBee.
*
* BackBee is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BackBee 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with BackBee. If not, see <http://www.gnu.org/licenses/>.
*/
define(['Core', 'Core/Renderer', 'BackBone'], function (Core, Renderer, Backbone) {
'use strict';
var HiddenView = Backbone.View.extend({
initialize: function (template, formTag, element) {
this.el = formTag;
this.template = template;
this.element = element;
this.bindEvents();
},
bindEvents: function () {
var self = this;
Core.Mediator.subscribe('before:form:submit', function (form) {
if (form.attr('id') === self.el) {
var element = form.find('.element_' + self.element.getKey()),
input = element.find('input[name="' + self.element.getKey() + '"]'),
span = element.find('span.updated'),
oldValue = self.element.value;
if (input.val() !== oldValue) {
span.text('updated');
} else {
span.text('');
}
}
});
},
/**
* Render the template into the DOM with the Renderer
* @returns {String} html
*/
render: function () {
return Renderer.render(this.template, {element: this.element});
}
});
return HiddenView;
}); | ndufreche/BbCoreJs | src/tb/component/formbuilder/form/element/views/form.element.view.hidden.js | JavaScript | gpl-3.0 | 2,067 |
var _i_x_n_annotation_format_8h =
[
[ "IXNAnnotationFormat", "_i_x_n_annotation_format_8h.html#a607464fe85fc01c26df0c51826fd4841", [
[ "IXNAnnotationFormatPlainString", "_i_x_n_annotation_format_8h.html#a607464fe85fc01c26df0c51826fd4841a7b4fb91d85f0776a7abe6e0623f6b0fc", null ],
[ "IXNAnnotationFormatJson", "_i_x_n_annotation_format_8h.html#a607464fe85fc01c26df0c51826fd4841a91b8ae8f1bcb5c68a714026c4674231d", null ],
[ "IXNAnnotationFormatOsc", "_i_x_n_annotation_format_8h.html#a607464fe85fc01c26df0c51826fd4841a611da1ac0a3eccbea277aad5ca3d57f1", null ]
] ]
]; | BrainModes/BM.Muse | libmuse_5.8.0/ios/doc/_i_x_n_annotation_format_8h.js | JavaScript | gpl-3.0 | 590 |
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
* Website: http://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
Espo.define('Views.EmailAccount.Record.Edit', ['Views.Record.Edit', 'Views.EmailAccount.Record.Detail'], function (Dep, Detail) {
return Dep.extend({
afterRender: function () {
Dep.prototype.afterRender.call(this);
Detail.prototype.initSslFieldListening.call(this);
},
});
});
| lucasmattos/crm | client/src/views/email-account/record/edit.js | JavaScript | gpl-3.0 | 1,286 |
var Connection = require("./db/db-connection").Connection;
var Tables = require("./db/tables");
const R = require("ramda");
var QUERY_MATCHES = {
$or: [
{percent_name: {$gt: 0.9}},
{
distance: {$lt: 1}
},
{
percent_name: {$gt: 0.8},
distance: {$lt: 30}
},
{
percent_name: {$gt: 0.8},
percent_address_phonetic: 1,
distance: {$lt: 50}
}
]
};
var connection = new Connection();
connection.connect()
.then(connection.collection.bind(connection, Tables.FUZZY_MATCHES_FB))
.then(coll=> {
return coll.find(QUERY_MATCHES).toArray()
})
.then(matches=> {
var promises = matches.map(match=> {
return Promise.resolve(R.filter(item=>(item.id_p1 == match.id_p1 || item.id_p2 == match.id_p1), matches)).then(response=> {
return {
id: match.id_p1.toString(),
name: match.name_p1,
response: R.compose(
R.sortBy(R.identity),
R.uniq,
R.flatten,
R.map(place=> {
return [place.id_p1.toString(), place.id_p2.toString()]
})
)(response)
}
})
});
return Promise.all(promises);
})
.then(matches=> {
matches = R.groupBy(item=>item.id, matches);
matches = Object.keys(matches).map((key)=> {
var get_ids = R.compose(
R.reduce((prev, id)=> {
prev.id_facebook.push(id);
return prev;
}, {id_facebook: [], id_google: [], id_opendata: [], id_imprese: []}),
R.sortBy(R.identity),
R.uniq,
R.flatten
, R.map(R.prop("response"))
);
var ids = get_ids(matches[key]);
return Object.assign({
name: matches[key][0].name
}, ids)
});
var uniq_matches = [];
for (var i = 0; i < matches.length; i++) {
var match = matches[i];
var found = R.find(nm=> {
var has_fb = match.id_facebook.filter(id=>nm.id_facebook.includes(id)).length;
return has_fb;
})(uniq_matches);
if (!found) {
uniq_matches.push(match);
}else {
found.id_facebook=R.uniq(found.id_facebook.concat(match.id_facebook));
}
}
var fuzzyMatchColl = connection.db.collection(Tables.FUZZY_MATCHES_FB_ONE_TO_MANY);
return fuzzyMatchColl.drop().then(_=>{
return fuzzyMatchColl.insertMany(uniq_matches);
})
})
.then(_=> {
connection.db.close();
console.log("DONE");
process.exit(0);
})
.catch(_=> {
console.log(_);
connection.db.close();
process.exit(1);
}); | marcog83/cesena-online-demo | dati-jobs/fuzzy-match-fb-places-step_2.js | JavaScript | gpl-3.0 | 3,057 |
ace.require("ace/ext/language_tools");
var editor = ace.edit("editor");
editor.setOptions({
enableBasicAutocompletion: true
});
editor.setTheme("ace/theme/eclipse");
editor.getSession().setMode("ace/mode/java");
document.getElementById('editor').style.fontSize = '18px';
editor.setAutoScrollEditorIntoView(true);
var codeTemplates = {};
var viewConfig = {
showOutput: false,
showInput: false
};
var prevLang;
function showOutput(output) {
var stdout = '';
var stderr = '';
if (output.status === 0) {
stdout = output.output;
} else if (output.status === 1) {
stderr = '<p class="error">Compiler error !</p>';
stderr += output.error;
} else if (output.status === 2) {
stderr = '<p class="error">Runtime error !</p>';
stderr += output.error;
} else if (output.status === 3) {
stderr = '<p class="error">Timeout !</p>';
stderr += output.error;
}
var out = '';
if (stderr) {
out += '<b>Stderror</b>\n' + stderr;
}
if (stdout) {
out += stdout;
}
if (!viewConfig.showOutput) {
$('#btn-show-output').click();
}
$('#output-p').html(out);
// $('#output-data').show();
// if (!$('#bottom-pane').hasClass('opened')) {
// $('#bottom-pane').addClass('opened');
// }
windowResized();
}
function loadLangs() {
$('#btn-run').prop('disabled', true);
$.ajax({
type: "GET",
url: '/apis/langs'
}).done(function (data) {
showLangs(data);
$('#btn-run').prop('disabled', false);
}).fail(function (data) {
alert("error");
$('#btn-run').prop('disabled', false);
});
}
function showLangs(langs) {
for (var i = 0; i < langs.supportedLangs.length; i++) {
var supportedLang = langs.supportedLangs[i];
$('#lang').append($('<option>', {
value: supportedLang.id,
text: supportedLang.name
}));
codeTemplates[supportedLang.id] = supportedLang.template;
}
$('#lang').val(langs.supportedLangs[0].id);
onLangChanged();
}
$(document).ready(function () {
$('#btn-output').click(function () {
$('#output-data').toggle();
$('#bottom-pane').toggleClass('opened');
windowResized();
});
$('#btn-run').click(function () {
onRunning();
var codeRunRequest = {
lang: $('#lang').find(":selected").val(),
code: editor.getValue(),
input: $('#text-input').val()
};
runCode(codeRunRequest);
// $.ajax({
// type: "POST",
// url: '/apis/run',
// data: JSON.stringify(codeRunRequest),
// contentType: 'application/json'
// }).done(function (data) {
// showOutput(data);
// $('#btn-run').prop('disabled', false);
// }).fail(function (data) {
// alert("error");
// $('#btn-run').prop('disabled', false);
// });
});
$('#btn-hide-output').click(function () {
$('#btn-hide-output').hide();
$('#btn-show-output').show();
viewConfig.showOutput = false;
windowResized();
});
$('#btn-show-output').click(function () {
$('#btn-hide-output').show();
$('#btn-show-output').hide();
viewConfig.showOutput = true;
windowResized();
});
$('#btn-hide-input').click(function () {
$('#btn-hide-input').hide();
$('#btn-show-input').show();
viewConfig.showInput = false;
windowResized();
});
$('#btn-show-input').click(function () {
$('#btn-hide-input').show();
$('#btn-show-input').hide();
viewConfig.showInput = true;
windowResized();
});
loadLangs();
$(window).resize(function () {
windowResized();
});
windowResized();
});
$('#lang').change(function () {
onLangChanged();
});
function onLangChanged() {
var lang = $('#lang').find(":selected").val();
if (prevLang) {
codeTemplates[prevLang] = editor.getValue();
}
editor.setValue(codeTemplates[lang], -1);
prevLang = lang;
if (lang === 'java7') {
editor.getSession().setMode("ace/mode/java");
} else if (lang === 'python3') {
editor.getSession().setMode("ace/mode/python");
} else if (lang === 'c' || lang === 'c++') {
editor.getSession().setMode("ace/mode/c_cpp");
} else if (lang === 'c#') {
editor.getSession().setMode("ace/mode/csharp");
}
}
function windowResized() {
var aceWrapper = $('#ace_wrapper');
var aceEditor = $('#editor');
var outputWrapper = $('#output-wrapper');
var outputData = $('#output-data');
var inputWrapper = $('#input-wrapper');
var textInput = $('#text-input');
var rightDiff;
var inputHeight;
var outputHeight;
var textInputWidth;
var textInputHeight;
if (viewConfig.showInput || viewConfig.showOutput) {
rightDiff = outputWrapper.width() + 4;
} else {
rightDiff = 0;
}
var aceHeight = window.innerHeight - aceWrapper.position().top;// - bottomPane.height();
var aceWidth = window.innerWidth - rightDiff;
if (viewConfig.showOutput) {
outputWrapper.show();
outputHeight = aceHeight;
} else {
outputWrapper.hide();
outputHeight = 0;
}
if (viewConfig.showInput) {
inputWrapper.show();
inputHeight = 225;
if (viewConfig.showOutput) {
outputHeight -= inputHeight;
} else {
inputHeight = aceHeight;
}
textInputHeight = inputHeight - 62;
textInputWidth = rightDiff - 23;
} else {
inputWrapper.hide();
inputHeight = 0;
}
// var bottomPane = $('#bottom-pane');
// var outputWrapperHeight = aceHeight - inputWrapper.height() - 2;
var outputTextHeight = outputHeight - 52;
aceWrapper.css('height', aceHeight + 'px');
aceWrapper.css('width', aceWidth + 'px');
aceEditor.css('height', aceHeight + 'px');
aceEditor.css('width', aceWidth + 'px');
editor.resize();
if (viewConfig.showOutput) {
outputWrapper.css('height', outputHeight + 'px');
outputData.css('max-height', outputTextHeight + 'px');
}
if (viewConfig.showInput) {
inputWrapper.css('height', inputHeight + 'px');
textInput.css('width', textInputWidth + 'px');
textInput.css('height', textInputHeight + 'px');
// outputData.css('max-height', outputTextHeight + 'px');
}
}
var stompClient;
function connect() {
var socket = new SockJS('/coderun');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
// window.alert("connected !");
stompClient.subscribe('/user/queue/reply', function (reply) {
showOutput(JSON.parse(reply.body));
onFinished();
});
});
}
function runCode(codeRunRequest) {
stompClient.send('/iapis/run', {}, JSON.stringify(codeRunRequest));
}
function onRunning() {
$('#btn-run').prop('disabled', true);
$('#icon-running').show();
$('#icon-run').hide();
}
function onFinished() {
$('#btn-run').prop('disabled', false);
$('#icon-running').hide();
$('#icon-run').show();
}
connect(); | AbdallaMahmoud/codeyard | src/main/resources/webapp/js/main.js | JavaScript | gpl-3.0 | 7,360 |
require('dotenv').config({ silent: true });
var Express = require('express');
var path = require('path');
var fs = require('fs');
var merge = require('lodash/merge');
var proxy = require('proxy-middleware');
var ejs = require('ejs');
var config = require('./config');
var server = new Express();
server.set('port', config.PORT);
server.engine('html', require('ejs').renderFile);
server.set('view engine', 'ejs');
server.set('views', path.resolve(__dirname, '../www'));
server.locals.CONFIG = escape(JSON.stringify(config));
server.use(config.API_PROXY_PATH, proxy(config.API_ENDPOINT));
server.get('/', function (req, res) {
res.render('index.html');
});
server.use(Express.static(path.resolve(__dirname, '../www')));
server.get('/404', function (req, res) {
res.render('404.html');
});
server.listen(server.get('port'), function (err) {
if (err) {
console.log('error while starting server', err);
}
console.log('Gandalf is started to listen at localhost:' + server.get('port'));
});
| Nebo15/gandalf.web | server/index.js | JavaScript | gpl-3.0 | 1,008 |
import moment from 'moment';
import PublicationsController from './controller/publications.controller.js';
import AuthorsController from './controller/authors.controller.js';
import PublishersController from './controller/publishers.controller.js';
/*
* Application routing
*/
function routing($routeProvider) {
$routeProvider
.when('/publications', {
template: require('./view/publications.html'),
controller: PublicationsController,
controllerAs: 'vm'
})
.when('/authors', {
template: require('./view/authors.html'),
controller: AuthorsController,
controllerAs: 'vm'
})
.when('/publishers', {
template: require('./view/publishers.html'),
controller: PublishersController,
controllerAs: 'vm'
})
.otherwise({ redirectTo: '/publications' });
}
routing.$inject = ['$routeProvider'];
/*
* Theming configuration for Material AngularJS
*/
function theming($mdThemingProvider) {
$mdThemingProvider
.theme('default')
.primaryPalette('indigo')
.accentPalette('red');
}
theming.$inject = ['$mdThemingProvider'];
/*
* Date localization configuration
*/
function dateLocalization($mdDateLocaleProvider) {
const dateFmt = 'YYYY-MM-DD';
$mdDateLocaleProvider.formatDate = (date) => {
return moment(date).format(dateFmt);
};
$mdDateLocaleProvider.parseDate = (str) => {
const m = moment(str, dateFmt);
return m.isValid() ? m.toDate() : new Date(NaN);
};
}
dateLocalization.$inject = ['$mdDateLocaleProvider'];
export { routing, theming, dateLocalization };
| enric-sinh/publication-library | web/src/app/app.config.js | JavaScript | gpl-3.0 | 1,574 |
/*
* Copyright (C) 2013 Huub de Beer
*
* 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.
*/
var model = function(name, config) {
"use strict";
var _model = {name: name},
_appendix = {};
// ## Data invariant and initialization
//
// This model describes a dynamic phenomenon in terms of changing
// quantities over time.
//
//
// This description starts at `T_START` milliseconds
// (ms), defaulting to 0 ms and ends at `T_END` ms. If no end is specified
// it is assumed that the phenomenon does not end or is still ongoing in
// the real world (RW). The phenomenon's change is tracked by "measuring"
// the changing quantities at consecutive moments in time. These moments
// are `T_STEP` apart, defaulting to 1 ms, and are tracked by order
// number.
var T_START = config.time.start || 0,
T_END = config.time.end || Infinity,
T_STEP = config.time.step || 1;
function set_end(seconds) {
T_END = seconds*1000;
}
_model.set_end = set_end;
// To translate from a moment's order number to its corresponding time in
// ms and vice versa, two helper functions are defined, `time_to_moment`
// and `moment_to_time`, as well as a shorthand name for these two helper
// functions, respectively, `t2m` and `m2t`.
_model.time_to_moment = function(time) {
return Math.floor(time / T_STEP);
};
var t2m = _model.time_to_moment;
_model.moment_to_time = function(moment) {
return moment * T_STEP;
};
var m2t = _model.moment_to_time;
// When I use "measured" I mean to denote that the values of the
// quantities describing the phenomenon have been captured, computed,
// downloaded, measured, or otherwise obtained. This `model` function is
// intended to be applicable for describing purely theoretical models of a
// phenomenon as well as real-time measurements of a phenomenon.
//
// "Measuring" a moment is left to the `measure_moment` function. Each
// model has to (re)implement this function to specify the relationship
// between the phenomenon's quantities of interest at each moment during
// the phenomenon.
_model.measure_moment = function(moment) {
// to be implemented in an object implementing model
};
// The model has the following data invariant:
//
// (∀m: 0 ≤ m ≤ |`moments`|: `moment_computed`(`moments`[m]))
//
// stating that the phenomenon has been described quantitatively for all
// moments. These "measurements" are stored in a list of `moments` and can
// be accessed through a moment's order number.
var moments = [];
_model.get_moment = function(moment) {
return moments[moment];
};
_model.number_of_moments = function() {
return moments.length;
};
// A moment can only be inspected if it already has been "measured".
// Following the data invariant, a moment has been measured when its order
// number is smaller or equal to the number of measured moments.
_model.moment_measured = function(moment) {
return (moment <= (moments.length - 1));
};
// Furthermore, the current moment of interest, or `now`, points to an
// already "measured" moment during the phenomenon's duration. Hence, the
// data invariant is extended as follows:
//
// `t2m`(`T_START`) ≤ `now` ≤ `t2m`(`T_END`) → `moment_computed`(`now`)
var now;
// To ensure this data invariant, `now` is set to a moment before the
// phenomenon started.
now = t2m(T_START) - 1;
// ## Inspecting and running a model
// Inspection through registerd views
var views = [];
var update_views = function() {
var update_view = function(view) {
view.update(_model.name);
};
views.forEach(update_view);
};
_model.update_views = update_views;
var update_all_views = function() {
var update_view = function(view) {
if (view.update_all) {
view.update_all();
} else {
view.update(_model.name);
}
};
views.forEach(update_view);
};
_model.update_all_views = update_all_views;
_model.register = function(view) {
var view_found = views.indexOf(view);
if (view_found === -1) {
views.push(view);
views.forEach(function(v) { if(v.update_all) v.update_all();});
}
};
_model.get_views_of_type = function(view_type) {
return views.filter(function(v) {
return v.type === view_type;
});
};
_model.unregister = function(view) {
if (arguments.length === 0) {
var unregister = function(view) {
view.unregister(_model.name);
};
views.forEach(unregister);
} else {
var view_found = views.indexOf(view);
if (view_found !== -1) {
views.slice(view_found, 1);
}
}
};
// As a model can be inspected repeatedly, as is one
// of the reasons to model a phenomenon using a computer, we introduce a
// `reset` function to resets `now` to a moment before the phenomenon
// started.
_model.reset = function() {
now = t2m(T_START) - 1;
_model.step();
update_views();
};
// Once a model has been started, the current moment will be measured as
// well as all moments before since the start. These moments can be
// inspected.
//
_model.has_started = function() {
return now >= 0;
};
// The `step` function will advance `now` to the next moment if the end of
// the phenomenon has not been reached yet. If that moment has not been
// "measured" earlier, "measure" it now.
_model.step = function(do_not_update_views) {
if (m2t(now) + T_STEP <= T_END) {
now++;
if (!_model.moment_measured(now)) {
var moment = _model.measure_moment(now);
moment._time_ = m2t(now);
moments.push(moment);
}
}
if (!do_not_update_views) {
update_views();
}
return now;
};
// If the phenomenon is a finite process or the "measuring" process cannot
// go further `T_END` will have a value that is not `Infinity`.
_model.can_finish = function() {
return Math.abs(T_END) !== Infinity;
};
// To inspect the whole phenomenon at once or inspect the last moment,
// `finish`ing the model will ensure that all moments during the
// phenomenon have been "measured".
_model.finish = function() {
var DO_NOT_UPDATE_VIEWS = true;
if (_model.can_finish()) {
while ((moments.length - 1) < t2m(T_END)) {
_model.step(DO_NOT_UPDATE_VIEWS);
}
}
now = moments.length - 1;
_model.update_views();
return now;
};
// We call the model finished if the current moment, or `now`, is the
// phenomenon's last moment.
_model.is_finished = function() {
return _model.can_finish() && m2t(now) >= T_END;
};
function reset_model() {
moments = [];
_model.action("reset").callback(_model)();
// _model.reset();
}
_model.reset_model = reset_model;
/**
* ## Actions on the model
*
*/
_model.actions = {};
_model.add_action = function( action ) {
_model.actions[action.name] = action;
_model.actions[action.name].install = function() {
return action.callback(_model);
};
};
if (config.actions) {
var add_action = function(action_name) {
_model.add_action(config.actions[action_name]);
};
Object.keys(config.actions).forEach(add_action);
}
_model.action = function( action_name ) {
if (_model.actions[action_name]) {
return _model.actions[action_name];
}
};
_model.remove_action = function( action ) {
if (_model.actions[action.name]) {
delete _model.actions[action.name];
}
};
_model.disable_action = function( action_name ) {
if (_model.actions[action_name]) {
_model.actions[action_name].enabled = false;
}
};
_model.enable_action = function( action_name ) {
if (_model.actions[action_name]) {
_model.actions[action_name].enabled = true;
}
};
_model.toggle_action = function( action_name ) {
if (_model.actions[action_name]) {
_model.actions[action_name].enabled =
!_model.action[action_name].enabled;
}
};
// ## Coordinating quantities
//
// All quantities that describe the phenomenon being modeled change in
// coordination with time's change. Add the model's time as a quantity to
// the list with quantities. To allow people to model time as part of
// their model, for example to describe the phenomenon accelerated, the
// internal time is added as quantity `_time_` and, as a result, "_time_"
// is not allowed as a quantity name.
_model.quantities = config.quantities || {};
_model.quantities._time_ = {
hidden: true,
minimum: T_START,
maximum: T_END,
value: m2t(now),
stepsize: T_STEP,
unit: "ms",
label: "internal time",
monotone: true
};
_model.get_minimum = function(quantity) {
if (arguments.length===0) {
// called without any arguments: return all minima
var minima = {},
add_minimum = function(quantity) {
minima[quantity] = parseFloat(_model.quantities[quantity].minimum);
};
Object.keys(_model.quantities).forEach(add_minimum);
return minima;
} else {
// return quantity's minimum
return parseFloat(_model.quantities[quantity].minimum);
}
};
_model.get_maximum = function(quantity) {
if (arguments.length===0) {
// called without any arguments: return all minima
var maxima = {},
add_maximum = function(quantity) {
maxima[quantity] = parseFloat(_model.quantities[quantity].maximum);
};
Object.keys(_model.quantities).forEach(add_maximum);
return maxima;
} else {
// return quantity's minimum
return parseFloat(_model.quantities[quantity].maximum);
}
};
_model.find_moment = function(quantity, value, EPSILON) {
if (moments.length === 0) {
// no moment are measured yet, so there is nothing to be found
return -1;
} else {
var val = _appendix.quantity_value(quantity);
// pre: quantity is monotone
// determine if it is increasing or decreasing
// determine type of monotone
//
// As the first moment has been measured and we do know the
// minimum of this quantity, type of monotone follows.
var start = val(0),
INCREASING = (start !== _model.get_maximum(quantity));
// Use a stupid linear search to find the moment that approaches the
// value best
var m = 0,
n = moments.length - 1,
lowerbound,
upperbound;
if (INCREASING) {
lowerbound = function(moment) {
return val(moment) < value;
};
upperbound = function(moment) {
return val(moment) > value;
};
} else {
lowerbound = function(moment) {
return val(moment) > value;
};
upperbound = function(moment) {
return val(moment) < value;
};
}
// Increasing "function", meaning
//
// (∀m: 0 ≤ m < |`moments`|: `val`(m) <= `val`(m+1))
//
// Therefore,
//
// (∃m, n: 0 ≤ m < n ≤ |`moments`|:
// `val`(m) ≤ value ≤ `val`(n) ⋀
// (∀p: m < p < n: `val`(p) = value))
//
// `find_moment` finds those moments m and n and returns the
// one closest to value or, when even close, the last moment
// decreasing is reverse.
while (lowerbound(m)) {
m++;
if (m>n) {
//
return -1;
}
}
return m;
//m--;
/*
while (upperbound(n)) {
n--;
if (n<m) {
return -1;
}
}
//n++;
return (Math.abs(val(n)-value) < Math.abs(val(m)-value))?n:m;
*/
}
};
_model.get = function(quantity) {
if (now < 0) {
return undefined;
} else {
return moments[now][quantity];
}
};
_model.set = function(quantity, value) {
var q = _model.quantities[quantity];
if (value < parseFloat(q.minimum)) {
value = parseFloat(q.minimum);
} else if (value > parseFloat(q.maximum)) {
value = parseFloat(q.maximum);
}
// q.minimum ≤ value ≤ q.maximum
// has value already been "measured"?
// As some quantities can have the same value more often, there are
// potentially many moments that fit the bill. There can be an unknown
// amount of moments that aren't measured as well.
//
// However, some quantities will be strictly increasing or decreasing
// and no value will appear twice. For example, the internal time will
// only increase. Those quantities with property `monotone`
// `true`, only one value will be searched for
var approx = _appendix.approximates(),
moment = -1;
if (q.monotone) {
moment = _model.find_moment(quantity, value);
if (moment === -1) {
// not yet "measured"
var DO_NOT_UPDATE_VIEWS = true;
_model.step(DO_NOT_UPDATE_VIEWS);
// THIS DOES WORK ONLY FOR INCREASING QUANTITIES. CHANGE THIS
// ALTER WITH FIND FUNCTION !!!!
while((moments[now][quantity] < value) && !_model.is_finished()) {
_model.step(DO_NOT_UPDATE_VIEWS);
}
} else {
now = moment;
}
update_views();
return moments[now];
}
};
_model.data = function() {
return moments.slice(0, now + 1);
};
_model.current_moment = function(moment_only) {
if (moment_only) {
return now;
} else {
return moments[now];
}
};
_model.graphs_shown = {
tailpoints: false,
line: false,
arrows: false
};
_model.show_graph = function(kind) {
var graphs = _model.get_views_of_type("graph");
function show_this_graph(g) {
switch(kind) {
case "line":
g.show_line(_model.name);
break;
case "tailpoints":
g.show_tailpoints(_model.name);
break;
case "arrows":
g.show_arrows(_model.name);
break;
}
}
graphs.forEach(show_this_graph);
_model.graphs_shown[kind] = true;
};
_model.hide_graph = function(kind) {
var graphs = _model.get_views_of_type("graph");
function hide_this_graph(g) {
switch(kind) {
case "line":
g.hide_line(_model.name);
break;
case "tailpoints":
g.hide_tailpoints(_model.name);
break;
case "arrows":
g.hide_arrows(_model.name);
break;
}
}
graphs.forEach(hide_this_graph);
_model.graphs_shown[kind] = false;
};
_model.graph_is_shown = function(kind) {
return _model.graphs_shown[kind];
};
// ## _appendix H: helper functions
_appendix.approximates = function(epsilon) {
var EPSILON = epsilon || 0.001,
fn = function(a, b) {
return Math.abs(a - b) <= EPSILON;
};
fn.EPSILON = EPSILON;
return fn;
};
_appendix.quantity_value = function(quantity) {
return function(moment) {
return moments[moment][quantity];
};
};
var step = (config.step_size || T_STEP)*5 ;
function step_size(size) {
if (arguments.length === 1) {
step = size;
}
return step;
}
_model.step_size = step_size;
function random_color() {
var hexes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'],
colors = [],
i = 0;
while (i < 6) {
colors.push(hexes[Math.round(Math.random()*(hexes.length - 1))]);
i++;
}
return "#"+ colors.join("");
}
var color = random_color();
_model.color = function(c) {
if (arguments.length === 1) {
if (c === "random") {
color = random_color();
} else {
color = c;
}
}
return color;
};
return _model;
};
module.exports = model;
| htdebeer/PhD-DE3 | src/models/model.js | JavaScript | gpl-3.0 | 19,172 |
// needs Markdown.Converter.js at the moment
(function () {
var util = {},
position = {},
ui = {},
doc = window.document,
re = window.RegExp,
nav = window.navigator,
SETTINGS = { lineLength: 72 },
// Used to work around some browser bugs where we can't use feature testing.
uaSniffed = {
isIE: /msie/.test(nav.userAgent.toLowerCase()),
isIE_5or6: /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase()),
isOpera: /opera/.test(nav.userAgent.toLowerCase())
};
// -------------------------------------------------------------------
// YOUR CHANGES GO HERE
//
// I've tried to localize the things you are likely to change to
// this area.
// -------------------------------------------------------------------
// The text that appears on the upper part of the dialog box when
// entering links.
var linkDialogText = "<p><b>Insert Hyperlink</b></p><p>http://example.com/ \"optional title\"</p>";
var imageDialogText = "<p><b>Insert Image</b></p><p>http://example.com/images/diagram.jpg \"optional title\"<br></p>";
// The default text that appears in the dialog input box when entering
// links.
var imageDefaultText = "http://";
var linkDefaultText = "http://";
var defaultHelpHoverTitle = "Markdown Editing Help";
// -------------------------------------------------------------------
// END OF YOUR CHANGES
// -------------------------------------------------------------------
// help, if given, should have a property "handler", the click handler for the help button,
// and can have an optional property "title" for the button's tooltip (defaults to "Markdown Editing Help").
// If help isn't given, not help button is created.
//
// The constructed editor object has the methods:
// - getConverter() returns the markdown converter object that was passed to the constructor
// - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op.
// - refreshPreview() forces the preview to be updated. This method is only available after run() was called.
Markdown.Editor = function (markdownConverter, idPostfix, help) {
idPostfix = idPostfix || "";
var hooks = this.hooks = new Markdown.HookCollection();
hooks.addNoop("onPreviewRefresh"); // called with no arguments after the preview has been refreshed
hooks.addNoop("postBlockquoteCreation"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text
hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates
* its own image insertion dialog, this hook should return true, and the callback should be called with the chosen
* image url (or null if the user cancelled). If this hook returns false, the default dialog will be used.
*/
this.getConverter = function () { return markdownConverter; }
var that = this,
panels;
this.run = function () {
if (panels)
return; // already initialized
panels = new PanelCollection(idPostfix);
var commandManager = new CommandManager(hooks);
var previewManager = new PreviewManager(markdownConverter, panels, function () { hooks.onPreviewRefresh(); });
var undoManager, uiManager;
if (!/\?noundo/.test(doc.location.href)) {
undoManager = new UndoManager(function () {
previewManager.refresh();
if (uiManager) // not available on the first call
uiManager.setUndoRedoButtonStates();
}, panels);
this.textOperation = function (f) {
undoManager.setCommandMode();
f();
that.refreshPreview();
}
}
uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, help);
uiManager.setUndoRedoButtonStates();
var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); };
forceRefresh();
};
}
// before: contains all the text in the input box BEFORE the selection.
// after: contains all the text in the input box AFTER the selection.
function Chunks() { }
// startRegex: a regular expression to find the start tag
// endRegex: a regular expresssion to find the end tag
Chunks.prototype.findTags = function (startRegex, endRegex) {
var chunkObj = this;
var regex;
if (startRegex) {
regex = util.extendRegExp(startRegex, "", "$");
this.before = this.before.replace(regex,
function (match) {
chunkObj.startTag = chunkObj.startTag + match;
return "";
});
regex = util.extendRegExp(startRegex, "^", "");
this.selection = this.selection.replace(regex,
function (match) {
chunkObj.startTag = chunkObj.startTag + match;
return "";
});
}
if (endRegex) {
regex = util.extendRegExp(endRegex, "", "$");
this.selection = this.selection.replace(regex,
function (match) {
chunkObj.endTag = match + chunkObj.endTag;
return "";
});
regex = util.extendRegExp(endRegex, "^", "");
this.after = this.after.replace(regex,
function (match) {
chunkObj.endTag = match + chunkObj.endTag;
return "";
});
}
};
// If remove is false, the whitespace is transferred
// to the before/after regions.
//
// If remove is true, the whitespace disappears.
Chunks.prototype.trimWhitespace = function (remove) {
var beforeReplacer, afterReplacer, that = this;
if (remove) {
beforeReplacer = afterReplacer = "";
} else {
beforeReplacer = function (s) { that.before += s; return ""; }
afterReplacer = function (s) { that.after = s + that.after; return ""; }
}
this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer);
};
Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) {
if (nLinesBefore === undefined) {
nLinesBefore = 1;
}
if (nLinesAfter === undefined) {
nLinesAfter = 1;
}
nLinesBefore++;
nLinesAfter++;
var regexText;
var replacementText;
// chrome bug ... documented at: http://meta.stackoverflow.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985
if (navigator.userAgent.match(/Chrome/)) {
"X".match(/()./);
}
this.selection = this.selection.replace(/(^\n*)/, "");
this.startTag = this.startTag + re.$1;
this.selection = this.selection.replace(/(\n*$)/, "");
this.endTag = this.endTag + re.$1;
this.startTag = this.startTag.replace(/(^\n*)/, "");
this.before = this.before + re.$1;
this.endTag = this.endTag.replace(/(\n*$)/, "");
this.after = this.after + re.$1;
if (this.before) {
regexText = replacementText = "";
while (nLinesBefore--) {
regexText += "\\n?";
replacementText += "\n";
}
if (findExtraNewlines) {
regexText = "\\n*";
}
this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
}
if (this.after) {
regexText = replacementText = "";
while (nLinesAfter--) {
regexText += "\\n?";
replacementText += "\n";
}
if (findExtraNewlines) {
regexText = "\\n*";
}
this.after = this.after.replace(new re(regexText, ""), replacementText);
}
};
// end of Chunks
// A collection of the important regions on the page.
// Cached so we don't have to keep traversing the DOM.
// Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around
// this issue:
// Internet explorer has problems with CSS sprite buttons that use HTML
// lists. When you click on the background image "button", IE will
// select the non-existent link text and discard the selection in the
// textarea. The solution to this is to cache the textarea selection
// on the button's mousedown event and set a flag. In the part of the
// code where we need to grab the selection, we check for the flag
// and, if it's set, use the cached area instead of querying the
// textarea.
//
// This ONLY affects Internet Explorer (tested on versions 6, 7
// and 8) and ONLY on button clicks. Keyboard shortcuts work
// normally since the focus never leaves the textarea.
function PanelCollection(postfix) {
this.buttonBar = doc.getElementById("wmd-button-bar" + postfix);
this.preview = doc.getElementById("wmd-preview" + postfix);
this.input = doc.getElementById("wmd-input" + postfix);
};
// Returns true if the DOM element is visible, false if it's hidden.
// Checks if display is anything other than none.
util.isVisible = function (elem) {
if (window.getComputedStyle) {
// Most browsers
return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
}
else if (elem.currentStyle) {
// IE
return elem.currentStyle["display"] !== "none";
}
};
// Adds a listener callback to a DOM element which is fired on a specified
// event.
util.addEvent = function (elem, event, listener) {
if (elem.attachEvent) {
// IE only. The "on" is mandatory.
elem.attachEvent("on" + event, listener);
}
else {
// Other browsers.
elem.addEventListener(event, listener, false);
}
};
// Removes a listener callback from a DOM element which is fired on a specified
// event.
util.removeEvent = function (elem, event, listener) {
if (elem.detachEvent) {
// IE only. The "on" is mandatory.
elem.detachEvent("on" + event, listener);
}
else {
// Other browsers.
elem.removeEventListener(event, listener, false);
}
};
// Converts \r\n and \r to \n.
util.fixEolChars = function (text) {
text = text.replace(/\r\n/g, "\n");
text = text.replace(/\r/g, "\n");
return text;
};
// Extends a regular expression. Returns a new RegExp
// using pre + regex + post as the expression.
// Used in a few functions where we have a base
// expression and we want to pre- or append some
// conditions to it (e.g. adding "$" to the end).
// The flags are unchanged.
//
// regex is a RegExp, pre and post are strings.
util.extendRegExp = function (regex, pre, post) {
if (pre === null || pre === undefined) {
pre = "";
}
if (post === null || post === undefined) {
post = "";
}
var pattern = regex.toString();
var flags;
// Replace the flags with empty space and store them.
pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) {
flags = flagsPart;
return "";
});
// Remove the slash delimiters on the regular expression.
pattern = pattern.replace(/(^\/|\/$)/g, "");
pattern = pre + pattern + post;
return new re(pattern, flags);
}
// UNFINISHED
// The assignment in the while loop makes jslint cranky.
// I'll change it to a better loop later.
position.getTop = function (elem, isInner) {
var result = elem.offsetTop;
if (!isInner) {
while (elem = elem.offsetParent) {
result += elem.offsetTop;
}
}
return result;
};
position.getHeight = function (elem) {
return elem.offsetHeight || elem.scrollHeight;
};
position.getWidth = function (elem) {
return elem.offsetWidth || elem.scrollWidth;
};
position.getPageSize = function () {
var scrollWidth, scrollHeight;
var innerWidth, innerHeight;
// It's not very clear which blocks work with which browsers.
if (self.innerHeight && self.scrollMaxY) {
scrollWidth = doc.body.scrollWidth;
scrollHeight = self.innerHeight + self.scrollMaxY;
}
else if (doc.body.scrollHeight > doc.body.offsetHeight) {
scrollWidth = doc.body.scrollWidth;
scrollHeight = doc.body.scrollHeight;
}
else {
scrollWidth = doc.body.offsetWidth;
scrollHeight = doc.body.offsetHeight;
}
if (self.innerHeight) {
// Non-IE browser
innerWidth = self.innerWidth;
innerHeight = self.innerHeight;
}
else if (doc.documentElement && doc.documentElement.clientHeight) {
// Some versions of IE (IE 6 w/ a DOCTYPE declaration)
innerWidth = doc.documentElement.clientWidth;
innerHeight = doc.documentElement.clientHeight;
}
else if (doc.body) {
// Other versions of IE
innerWidth = doc.body.clientWidth;
innerHeight = doc.body.clientHeight;
}
var maxWidth = Math.max(scrollWidth, innerWidth);
var maxHeight = Math.max(scrollHeight, innerHeight);
return [maxWidth, maxHeight, innerWidth, innerHeight];
};
// Handles pushing and popping TextareaStates for undo/redo commands.
// I should rename the stack variables to list.
function UndoManager(callback, panels) {
var undoObj = this;
var undoStack = []; // A stack of undo states
var stackPtr = 0; // The index of the current state
var mode = "none";
var lastState; // The last state
var timer; // The setTimeout handle for cancelling the timer
var inputStateObj;
// Set the mode for later logic steps.
var setMode = function (newMode, noSave) {
if (mode != newMode) {
mode = newMode;
if (!noSave) {
saveState();
}
}
if (!uaSniffed.isIE || mode != "moving") {
timer = setTimeout(refreshState, 1);
}
else {
inputStateObj = null;
}
};
var refreshState = function (isInitialState) {
inputStateObj = new TextareaState(panels, isInitialState);
timer = undefined;
};
this.setCommandMode = function () {
mode = "command";
saveState();
timer = setTimeout(refreshState, 0);
};
this.canUndo = function () {
return stackPtr > 1;
};
this.canRedo = function () {
if (undoStack[stackPtr + 1]) {
return true;
}
return false;
};
// Removes the last state and restores it.
this.undo = function () {
if (undoObj.canUndo()) {
if (lastState) {
// What about setting state -1 to null or checking for undefined?
lastState.restore();
lastState = null;
}
else {
undoStack[stackPtr] = new TextareaState(panels);
undoStack[--stackPtr].restore();
if (callback) {
callback();
}
}
}
mode = "none";
panels.input.focus();
refreshState();
};
// Redo an action.
this.redo = function () {
if (undoObj.canRedo()) {
undoStack[++stackPtr].restore();
if (callback) {
callback();
}
}
mode = "none";
panels.input.focus();
refreshState();
};
// Push the input area state to the stack.
var saveState = function () {
var currState = inputStateObj || new TextareaState(panels);
if (!currState) {
return false;
}
if (mode == "moving") {
if (!lastState) {
lastState = currState;
}
return;
}
if (lastState) {
if (undoStack[stackPtr - 1].text != lastState.text) {
undoStack[stackPtr++] = lastState;
}
lastState = null;
}
undoStack[stackPtr++] = currState;
undoStack[stackPtr + 1] = null;
if (callback) {
callback();
}
};
var handleCtrlYZ = function (event) {
var handled = false;
if (event.ctrlKey || event.metaKey) {
// IE and Opera do not support charCode.
var keyCode = event.charCode || event.keyCode;
var keyCodeChar = String.fromCharCode(keyCode);
switch (keyCodeChar) {
case "y":
undoObj.redo();
handled = true;
break;
case "z":
if (!event.shiftKey) {
undoObj.undo();
}
else {
undoObj.redo();
}
handled = true;
break;
}
}
if (handled) {
if (event.preventDefault) {
event.preventDefault();
}
if (window.event) {
window.event.returnValue = false;
}
return;
}
};
// Set the mode depending on what is going on in the input area.
var handleModeChange = function (event) {
if (!event.ctrlKey && !event.metaKey) {
var keyCode = event.keyCode;
if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
// 33 - 40: page up/dn and arrow keys
// 63232 - 63235: page up/dn and arrow keys on safari
setMode("moving");
}
else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
// 8: backspace
// 46: delete
// 127: delete
setMode("deleting");
}
else if (keyCode == 13) {
// 13: Enter
setMode("newlines");
}
else if (keyCode == 27) {
// 27: escape
setMode("escape");
}
else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
// 16-20 are shift, etc.
// 91: left window key
// I think this might be a little messed up since there are
// a lot of nonprinting keys above 20.
setMode("typing");
}
}
};
var setEventHandlers = function () {
util.addEvent(panels.input, "keypress", function (event) {
// keyCode 89: y
// keyCode 90: z
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
event.preventDefault();
}
});
var handlePaste = function () {
if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) {
if (timer == undefined) {
mode = "paste";
saveState();
refreshState();
}
}
};
util.addEvent(panels.input, "keydown", handleCtrlYZ);
util.addEvent(panels.input, "keydown", handleModeChange);
util.addEvent(panels.input, "mousedown", function () {
setMode("moving");
});
panels.input.onpaste = handlePaste;
panels.input.ondrop = handlePaste;
};
var init = function () {
setEventHandlers();
refreshState(true);
saveState();
};
init();
}
// end of UndoManager
// The input textarea state/contents.
// This is used to implement undo/redo by the undo manager.
function TextareaState(panels, isInitialState) {
// Aliases
var stateObj = this;
var inputArea = panels.input;
this.init = function () {
if (!util.isVisible(inputArea)) {
return;
}
if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box
return;
}
this.setInputAreaSelectionStartEnd();
this.scrollTop = inputArea.scrollTop;
if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
this.text = inputArea.value;
}
}
// Sets the selected text in the input box after we've performed an
// operation.
this.setInputAreaSelection = function () {
if (!util.isVisible(inputArea)) {
return;
}
if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) {
inputArea.focus();
inputArea.selectionStart = stateObj.start;
inputArea.selectionEnd = stateObj.end;
inputArea.scrollTop = stateObj.scrollTop;
}
else if (doc.selection) {
if (doc.activeElement && doc.activeElement !== inputArea) {
return;
}
inputArea.focus();
var range = inputArea.createTextRange();
range.moveStart("character", -inputArea.value.length);
range.moveEnd("character", -inputArea.value.length);
range.moveEnd("character", stateObj.end);
range.moveStart("character", stateObj.start);
range.select();
}
};
this.setInputAreaSelectionStartEnd = function () {
if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) {
stateObj.start = inputArea.selectionStart;
stateObj.end = inputArea.selectionEnd;
}
else if (doc.selection) {
stateObj.text = util.fixEolChars(inputArea.value);
// IE loses the selection in the textarea when buttons are
// clicked. On IE we cache the selection. Here, if something is cached,
// we take it.
var range = panels.ieCachedRange || doc.selection.createRange();
var fixedRange = util.fixEolChars(range.text);
var marker = "\x07";
var markedRange = marker + fixedRange + marker;
range.text = markedRange;
var inputText = util.fixEolChars(inputArea.value);
range.moveStart("character", -markedRange.length);
range.text = fixedRange;
stateObj.start = inputText.indexOf(marker);
stateObj.end = inputText.lastIndexOf(marker) - marker.length;
var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
if (len) {
range.moveStart("character", -fixedRange.length);
while (len--) {
fixedRange += "\n";
stateObj.end += 1;
}
range.text = fixedRange;
}
if (panels.ieCachedRange)
stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange
panels.ieCachedRange = null;
this.setInputAreaSelection();
}
};
// Restore this state into the input area.
this.restore = function () {
if (stateObj.text != undefined && stateObj.text != inputArea.value) {
inputArea.value = stateObj.text;
}
this.setInputAreaSelection();
inputArea.scrollTop = stateObj.scrollTop;
};
// Gets a collection of HTML chunks from the inptut textarea.
this.getChunks = function () {
var chunk = new Chunks();
chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
chunk.startTag = "";
chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
chunk.endTag = "";
chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
chunk.scrollTop = stateObj.scrollTop;
return chunk;
};
// Sets the TextareaState properties given a chunk of markdown.
this.setChunks = function (chunk) {
chunk.before = chunk.before + chunk.startTag;
chunk.after = chunk.endTag + chunk.after;
this.start = chunk.before.length;
this.end = chunk.before.length + chunk.selection.length;
this.text = chunk.before + chunk.selection + chunk.after;
this.scrollTop = chunk.scrollTop;
};
this.init();
};
function PreviewManager(converter, panels, previewRefreshCallback) {
var managerObj = this;
var timeout;
var elapsedTime;
var oldInputText;
var maxDelay = 3000;
var startType = "delayed"; // The other legal value is "manual"
// Adds event listeners to elements
var setupEvents = function (inputElem, listener) {
util.addEvent(inputElem, "input", listener);
inputElem.onpaste = listener;
inputElem.ondrop = listener;
util.addEvent(inputElem, "keypress", listener);
util.addEvent(inputElem, "keydown", listener);
};
var getDocScrollTop = function () {
var result = 0;
if (window.innerHeight) {
result = window.pageYOffset;
}
else
if (doc.documentElement && doc.documentElement.scrollTop) {
result = doc.documentElement.scrollTop;
}
else
if (doc.body) {
result = doc.body.scrollTop;
}
return result;
};
var makePreviewHtml = function () {
// If there is no registered preview panel
// there is nothing to do.
if (!panels.preview)
return;
var text = panels.input.value;
if (text && text == oldInputText) {
return; // Input text hasn't changed.
}
else {
oldInputText = text;
}
var prevTime = new Date().getTime();
text = converter.makeHtml(text);
// Calculate the processing time of the HTML creation.
// It's used as the delay time in the event listener.
var currTime = new Date().getTime();
elapsedTime = currTime - prevTime;
pushPreviewHtml(text);
};
// setTimeout is already used. Used as an event listener.
var applyTimeout = function () {
if (timeout) {
clearTimeout(timeout);
timeout = undefined;
}
if (startType !== "manual") {
var delay = 0;
if (startType === "delayed") {
delay = elapsedTime;
}
if (delay > maxDelay) {
delay = maxDelay;
}
timeout = setTimeout(makePreviewHtml, delay);
}
};
var getScaleFactor = function (panel) {
if (panel.scrollHeight <= panel.clientHeight) {
return 1;
}
return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
};
var setPanelScrollTops = function () {
if (panels.preview) {
panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview);
}
};
this.refresh = function (requiresRefresh) {
if (requiresRefresh) {
oldInputText = "";
makePreviewHtml();
}
else {
applyTimeout();
}
};
this.processingTime = function () {
return elapsedTime;
};
var isFirstTimeFilled = true;
// IE doesn't let you use innerHTML if the element is contained somewhere in a table
// (which is the case for inline editing) -- in that case, detach the element, set the
// value, and reattach. Yes, that *is* ridiculous.
var ieSafePreviewSet = function (text) {
var preview = panels.preview;
var parent = preview.parentNode;
var sibling = preview.nextSibling;
parent.removeChild(preview);
preview.innerHTML = text;
if (!sibling)
parent.appendChild(preview);
else
parent.insertBefore(preview, sibling);
}
var nonSuckyBrowserPreviewSet = function (text) {
panels.preview.innerHTML = text;
}
var previewSetter;
var previewSet = function (text) {
if (previewSetter)
return previewSetter(text);
try {
nonSuckyBrowserPreviewSet(text);
previewSetter = nonSuckyBrowserPreviewSet;
} catch (e) {
previewSetter = ieSafePreviewSet;
previewSetter(text);
}
};
var pushPreviewHtml = function (text) {
var emptyTop = position.getTop(panels.input) - getDocScrollTop();
if (panels.preview) {
previewSet(text);
previewRefreshCallback();
}
setPanelScrollTops();
if (isFirstTimeFilled) {
isFirstTimeFilled = false;
return;
}
var fullTop = position.getTop(panels.input) - getDocScrollTop();
if (uaSniffed.isIE) {
setTimeout(function () {
window.scrollBy(0, fullTop - emptyTop);
}, 0);
}
else {
window.scrollBy(0, fullTop - emptyTop);
}
};
var init = function () {
setupEvents(panels.input, applyTimeout);
makePreviewHtml();
if (panels.preview) {
panels.preview.scrollTop = 0;
}
};
init();
};
// Creates the background behind the hyperlink text entry box.
// And download dialog
// Most of this has been moved to CSS but the div creation and
// browser-specific hacks remain here.
ui.createBackground = function () {
var background = doc.createElement("div"),
style = background.style;
background.className = "wmd-prompt-background";
style.position = "absolute";
style.top = "0";
style.zIndex = "1000";
if (uaSniffed.isIE) {
style.filter = "alpha(opacity=50)";
}
else {
style.opacity = "0.5";
}
var pageSize = position.getPageSize();
style.height = pageSize[1] + "px";
if (uaSniffed.isIE) {
style.left = doc.documentElement.scrollLeft;
style.width = doc.documentElement.clientWidth;
}
else {
style.left = "0";
style.width = "100%";
}
doc.body.appendChild(background);
return background;
};
// This simulates a modal dialog box and asks for the URL when you
// click the hyperlink or image buttons.
//
// text: The html for the input box.
// defaultInputText: The default value that appears in the input box.
// callback: The function which is executed when the prompt is dismissed, either via OK or Cancel.
// It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel
// was chosen).
ui.prompt = function (text, defaultInputText, callback) {
// These variables need to be declared at this level since they are used
// in multiple functions.
var dialog; // The dialog box.
var input; // The text box where you enter the hyperlink.
if (defaultInputText === undefined) {
defaultInputText = "";
}
// Used as a keydown event handler. Esc dismisses the prompt.
// Key code 27 is ESC.
var checkEscape = function (key) {
var code = (key.charCode || key.keyCode);
if (code === 27) {
close(true);
}
};
// Dismisses the hyperlink input box.
// isCancel is true if we don't care about the input text.
// isCancel is false if we are going to keep the text.
var close = function (isCancel) {
util.removeEvent(doc.body, "keydown", checkEscape);
var text = input.value;
if (isCancel) {
text = null;
}
else {
// Fixes common pasting errors.
text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://');
if (!/^(?:https?|ftp):\/\//.test(text))
text = 'http://' + text;
}
dialog.parentNode.removeChild(dialog);
callback(text);
return false;
};
// Create the text input box form/window.
var createDialog = function () {
// The main dialog box.
dialog = doc.createElement("div");
dialog.className = "wmd-prompt-dialog";
dialog.style.padding = "10px;";
dialog.style.position = "fixed";
dialog.style.width = "400px";
dialog.style.zIndex = "1001";
// The dialog text.
var question = doc.createElement("div");
question.innerHTML = text;
question.style.padding = "5px";
dialog.appendChild(question);
// The web form container for the text box and buttons.
var form = doc.createElement("form"),
style = form.style;
form.onsubmit = function () { return close(false); };
style.padding = "0";
style.margin = "0";
style.cssFloat = "left";
style.width = "100%";
style.textAlign = "center";
style.position = "relative";
dialog.appendChild(form);
// The input text box
input = doc.createElement("input");
input.type = "text";
input.value = defaultInputText;
style = input.style;
style.display = "block";
style.width = "80%";
style.marginLeft = style.marginRight = "auto";
form.appendChild(input);
// The ok button
var okButton = doc.createElement("input");
okButton.type = "button";
okButton.onclick = function () { return close(false); };
okButton.value = "OK";
style = okButton.style;
style.margin = "10px";
style.display = "inline";
style.width = "7em";
// The cancel button
var cancelButton = doc.createElement("input");
cancelButton.type = "button";
cancelButton.onclick = function () { return close(true); };
cancelButton.value = "Cancel";
style = cancelButton.style;
style.margin = "10px";
style.display = "inline";
style.width = "7em";
form.appendChild(okButton);
form.appendChild(cancelButton);
util.addEvent(doc.body, "keydown", checkEscape);
dialog.style.top = "50%";
dialog.style.left = "50%";
dialog.style.display = "block";
if (uaSniffed.isIE_5or6) {
dialog.style.position = "absolute";
dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
dialog.style.left = "50%";
}
doc.body.appendChild(dialog);
// This has to be done AFTER adding the dialog to the form if you
// want it to be centered.
dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
};
// Why is this in a zero-length timeout?
// Is it working around a browser bug?
setTimeout(function () {
createDialog();
var defTextLen = defaultInputText.length;
if (input.selectionStart !== undefined) {
input.selectionStart = 0;
input.selectionEnd = defTextLen;
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(false);
range.moveStart("character", -defTextLen);
range.moveEnd("character", defTextLen);
range.select();
}
input.focus();
}, 0);
};
function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions) {
var inputBox = panels.input,
buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements.
makeSpritedButtonRow();
var keyEvent = "keydown";
if (uaSniffed.isOpera) {
keyEvent = "keypress";
}
util.addEvent(inputBox, keyEvent, function (key) {
// Check to see if we have a button key and, if so execute the callback.
if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) {
var keyCode = key.charCode || key.keyCode;
var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
switch (keyCodeStr) {
case "b":
doClick(buttons.bold);
break;
case "i":
doClick(buttons.italic);
break;
case "l":
doClick(buttons.link);
break;
case "q":
doClick(buttons.quote);
break;
case "k":
doClick(buttons.code);
break;
case "g":
doClick(buttons.image);
break;
case "o":
doClick(buttons.olist);
break;
case "u":
doClick(buttons.ulist);
break;
case "h":
doClick(buttons.heading);
break;
case "r":
doClick(buttons.hr);
break;
case "y":
doClick(buttons.redo);
break;
case "z":
if (key.shiftKey) {
doClick(buttons.redo);
}
else {
doClick(buttons.undo);
}
break;
default:
return;
}
if (key.preventDefault) {
key.preventDefault();
}
if (window.event) {
window.event.returnValue = false;
}
}
});
// Auto-indent on shift-enter
util.addEvent(inputBox, "keyup", function (key) {
if (key.shiftKey && !key.ctrlKey && !key.metaKey) {
var keyCode = key.charCode || key.keyCode;
// Character 13 is Enter
if (keyCode === 13) {
var fakeButton = {};
fakeButton.textOp = bindCommand("doAutoindent");
doClick(fakeButton);
}
}
});
// special handler because IE clears the context of the textbox on ESC
if (uaSniffed.isIE) {
util.addEvent(inputBox, "keydown", function (key) {
var code = key.keyCode;
if (code === 27) {
return false;
}
});
}
// Perform the button's action.
function doClick(button) {
inputBox.focus();
if (button.textOp) {
if (undoManager) {
undoManager.setCommandMode();
}
var state = new TextareaState(panels);
if (!state) {
return;
}
var chunks = state.getChunks();
// Some commands launch a "modal" prompt dialog. Javascript
// can't really make a modal dialog box and the WMD code
// will continue to execute while the dialog is displayed.
// This prevents the dialog pattern I'm used to and means
// I can't do something like this:
//
// var link = CreateLinkDialog();
// makeMarkdownLink(link);
//
// Instead of this straightforward method of handling a
// dialog I have to pass any code which would execute
// after the dialog is dismissed (e.g. link creation)
// in a function parameter.
//
// Yes this is awkward and I think it sucks, but there's
// no real workaround. Only the image and link code
// create dialogs and require the function pointers.
var fixupInputArea = function () {
inputBox.focus();
if (chunks) {
state.setChunks(chunks);
}
state.restore();
previewManager.refresh();
};
var noCleanup = button.textOp(chunks, fixupInputArea);
if (!noCleanup) {
fixupInputArea();
}
}
if (button.execute) {
button.execute(undoManager);
}
};
function setupButton(button, isEnabled) {
var normalYShift = "0px";
var disabledYShift = "-20px";
var highlightYShift = "-40px";
var image = button.getElementsByTagName("span")[0];
if (isEnabled) {
image.style.backgroundPosition = button.XShift + " " + normalYShift;
button.onmouseover = function () {
image.style.backgroundPosition = this.XShift + " " + highlightYShift;
};
button.onmouseout = function () {
image.style.backgroundPosition = this.XShift + " " + normalYShift;
};
// IE tries to select the background image "button" text (it's
// implemented in a list item) so we have to cache the selection
// on mousedown.
if (uaSniffed.isIE) {
button.onmousedown = function () {
if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection
return;
}
panels.ieCachedRange = document.selection.createRange();
panels.ieCachedScrollTop = panels.input.scrollTop;
};
}
if (!button.isHelp) {
button.onclick = function () {
if (this.onmouseout) {
this.onmouseout();
}
doClick(this);
return false;
}
}
}
else {
image.style.backgroundPosition = button.XShift + " " + disabledYShift;
button.onmouseover = button.onmouseout = button.onclick = function () { };
}
}
function bindCommand(method) {
if (typeof method === "string")
method = commandManager[method];
return function () { method.apply(commandManager, arguments); }
}
function makeSpritedButtonRow() {
var buttonBar = panels.buttonBar;
var normalYShift = "0px";
var disabledYShift = "-20px";
var highlightYShift = "-40px";
var buttonRow = document.createElement("ul");
buttonRow.id = "wmd-button-row" + postfix;
buttonRow.className = 'wmd-button-row';
buttonRow = buttonBar.appendChild(buttonRow);
var xPosition = 0;
var makeButton = function (id, title, XShift, textOp) {
var button = document.createElement("li");
button.className = "wmd-button";
button.style.left = xPosition + "px";
xPosition += 25;
var buttonImage = document.createElement("span");
button.id = id + postfix;
button.appendChild(buttonImage);
button.title = title;
button.XShift = XShift;
if (textOp)
button.textOp = textOp;
setupButton(button, true);
buttonRow.appendChild(button);
return button;
};
var makeSpacer = function (num) {
var spacer = document.createElement("li");
spacer.className = "wmd-spacer wmd-spacer" + num;
spacer.id = "wmd-spacer" + num + postfix;
buttonRow.appendChild(spacer);
xPosition += 25;
}
buttons.bold = makeButton("wmd-bold-button", "Strong <strong> Ctrl+B", "0px", bindCommand("doBold"));
buttons.italic = makeButton("wmd-italic-button", "Emphasis <em> Ctrl+I", "-20px", bindCommand("doItalic"));
makeSpacer(1);
buttons.link = makeButton("wmd-link-button", "Hyperlink <a> Ctrl+L", "-40px", bindCommand(function (chunk, postProcessing) {
return this.doLinkOrImage(chunk, postProcessing, false);
}));
buttons.quote = makeButton("wmd-quote-button", "Blockquote <blockquote> Ctrl+Q", "-60px", bindCommand("doBlockquote"));
buttons.code = makeButton("wmd-code-button", "Code Sample <pre><code> Ctrl+K", "-80px", bindCommand("doCode"));
buttons.image = makeButton("wmd-image-button", "Image <img> Ctrl+G", "-100px", bindCommand(function (chunk, postProcessing) {
return this.doLinkOrImage(chunk, postProcessing, true);
}));
makeSpacer(2);
buttons.olist = makeButton("wmd-olist-button", "Numbered List <ol> Ctrl+O", "-120px", bindCommand(function (chunk, postProcessing) {
this.doList(chunk, postProcessing, true);
}));
buttons.ulist = makeButton("wmd-ulist-button", "Bulleted List <ul> Ctrl+U", "-140px", bindCommand(function (chunk, postProcessing) {
this.doList(chunk, postProcessing, false);
}));
buttons.heading = makeButton("wmd-heading-button", "Heading <h1>/<h2> Ctrl+H", "-160px", bindCommand("doHeading"));
buttons.hr = makeButton("wmd-hr-button", "Horizontal Rule <hr> Ctrl+R", "-180px", bindCommand("doHorizontalRule"));
makeSpacer(3);
buttons.undo = makeButton("wmd-undo-button", "Undo - Ctrl+Z", "-200px", null);
buttons.undo.execute = function (manager) { if (manager) manager.undo(); };
var redoTitle = /win/.test(nav.platform.toLowerCase()) ?
"Redo - Ctrl+Y" :
"Redo - Ctrl+Shift+Z"; // mac and other non-Windows platforms
buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null);
buttons.redo.execute = function (manager) { if (manager) manager.redo(); };
if (helpOptions) {
var helpButton = document.createElement("li");
var helpButtonImage = document.createElement("span");
helpButton.appendChild(helpButtonImage);
helpButton.className = "wmd-button wmd-help-button";
helpButton.id = "wmd-help-button" + postfix;
helpButton.XShift = "-240px";
helpButton.isHelp = true;
helpButton.style.right = "0px";
helpButton.title = helpOptions.title || defaultHelpHoverTitle;
helpButton.onclick = helpOptions.handler;
setupButton(helpButton, true);
buttonRow.appendChild(helpButton);
buttons.help = helpButton;
}
setUndoRedoButtonStates();
}
function setUndoRedoButtonStates() {
if (undoManager) {
setupButton(buttons.undo, undoManager.canUndo());
setupButton(buttons.redo, undoManager.canRedo());
}
};
this.setUndoRedoButtonStates = setUndoRedoButtonStates;
}
function CommandManager(pluginHooks) {
this.hooks = pluginHooks;
}
var commandProto = CommandManager.prototype;
// The markdown symbols - 4 spaces = code, > = blockquote, etc.
commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
// Remove markdown symbols from the chunk selection.
commandProto.unwrap = function (chunk) {
var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g");
chunk.selection = chunk.selection.replace(txt, "$1 $2");
};
commandProto.wrap = function (chunk, len) {
this.unwrap(chunk);
var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"),
that = this;
chunk.selection = chunk.selection.replace(regex, function (line, marked) {
if (new re("^" + that.prefixes, "").test(line)) {
return line;
}
return marked + "\n";
});
chunk.selection = chunk.selection.replace(/\s+$/, "");
};
commandProto.doBold = function (chunk, postProcessing) {
return this.doBorI(chunk, postProcessing, 2, "strong text");
};
commandProto.doItalic = function (chunk, postProcessing) {
return this.doBorI(chunk, postProcessing, 1, "emphasized text");
};
// chunk: The selected region that will be enclosed with */**
// nStars: 1 for italics, 2 for bold
// insertText: If you just click the button without highlighting text, this gets inserted
commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) {
// Get rid of whitespace and fixup newlines.
chunk.trimWhitespace();
chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
// Look for stars before and after. Is the chunk already marked up?
// note that these regex matches cannot fail
var starsBefore = /(\**$)/.exec(chunk.before)[0];
var starsAfter = /(^\**)/.exec(chunk.after)[0];
var prevStars = Math.min(starsBefore.length, starsAfter.length);
// Remove stars if we have to since the button acts as a toggle.
if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
}
else if (!chunk.selection && starsAfter) {
// It's not really clear why this code is necessary. It just moves
// some arbitrary stuff around.
chunk.after = chunk.after.replace(/^([*_]*)/, "");
chunk.before = chunk.before.replace(/(\s?)$/, "");
var whitespace = re.$1;
chunk.before = chunk.before + starsAfter + whitespace;
}
else {
// In most cases, if you don't have any selected text and click the button
// you'll get a selected, marked up region with the default text inserted.
if (!chunk.selection && !starsAfter) {
chunk.selection = insertText;
}
// Add the true markup.
var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
chunk.before = chunk.before + markup;
chunk.after = markup + chunk.after;
}
return;
};
commandProto.stripLinkDefs = function (text, defsToAdd) {
text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
function (totalMatch, id, link, newlines, title) {
defsToAdd[id] = totalMatch.replace(/\s*$/, "");
if (newlines) {
// Strip the title and return that separately.
defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
return newlines + title;
}
return "";
});
return text;
};
commandProto.addLinkDef = function (chunk, linkDef) {
var refNumber = 0; // The current reference number
var defsToAdd = {}; //
// Start with a clean slate by removing all previous link definitions.
chunk.before = this.stripLinkDefs(chunk.before, defsToAdd);
chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd);
chunk.after = this.stripLinkDefs(chunk.after, defsToAdd);
var defs = "";
var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
var addDefNumber = function (def) {
refNumber++;
def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
defs += "\n" + def;
};
// note that
// a) the recursive call to getLink cannot go infinite, because by definition
// of regex, inner is always a proper substring of wholeMatch, and
// b) more than one level of nesting is neither supported by the regex
// nor making a lot of sense (the only use case for nesting is a linked image)
var getLink = function (wholeMatch, before, inner, afterInner, id, end) {
inner = inner.replace(regex, getLink);
if (defsToAdd[id]) {
addDefNumber(defsToAdd[id]);
return before + inner + afterInner + refNumber + end;
}
return wholeMatch;
};
chunk.before = chunk.before.replace(regex, getLink);
if (linkDef) {
addDefNumber(linkDef);
}
else {
chunk.selection = chunk.selection.replace(regex, getLink);
}
var refOut = refNumber;
chunk.after = chunk.after.replace(regex, getLink);
if (chunk.after) {
chunk.after = chunk.after.replace(/\n*$/, "");
}
if (!chunk.after) {
chunk.selection = chunk.selection.replace(/\n*$/, "");
}
chunk.after += "\n\n" + defs;
return refOut;
};
// takes the line as entered into the add link/as image dialog and makes
// sure the URL and the optinal title are "nice".
function properlyEncoded(linkdef) {
return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) {
link = link.replace(/\?.*$/, function (querypart) {
return querypart.replace(/\+/g, " "); // in the query string, a plus and a space are identical
});
link = decodeURIComponent(link); // unencode first, to prevent double encoding
link = encodeURI(link).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
link = link.replace(/\?.*$/, function (querypart) {
return querypart.replace(/\+/g, "%2b"); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded
});
if (title) {
title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, "");
title = $.trim(title).replace(/"/g, "quot;").replace(/\(/g, "(").replace(/\)/g, ")").replace(/</g, "<").replace(/>/g, ">");
}
return title ? link + ' "' + title + '"' : link;
});
}
commandProto.doLinkOrImage = function (chunk, postProcessing, isImage) {
chunk.trimWhitespace();
chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
var background;
if (chunk.endTag.length > 1 && chunk.startTag.length > 0) {
chunk.startTag = chunk.startTag.replace(/!?\[/, "");
chunk.endTag = "";
this.addLinkDef(chunk, null);
}
else {
// We're moving start and end tag back into the selection, since (as we're in the else block) we're not
// *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the
// link text. linkEnteredCallback takes care of escaping any brackets.
chunk.selection = chunk.startTag + chunk.selection + chunk.endTag;
chunk.startTag = chunk.endTag = "";
if (/\n\n/.test(chunk.selection)) {
this.addLinkDef(chunk, null);
return;
}
var that = this;
// The function to be executed when you enter a link and press OK or Cancel.
// Marks up the link and adds the ref.
var linkEnteredCallback = function (link) {
background.parentNode.removeChild(background);
if (link !== null) {
// ( $1
// [^\\] anything that's not a backslash
// (?:\\\\)* an even number (this includes zero) of backslashes
// )
// (?= followed by
// [[\]] an opening or closing bracket
// )
//
// In other words, a non-escaped bracket. These have to be escaped now to make sure they
// don't count as the end of the link or similar.
// Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets),
// the bracket in one match may be the "not a backslash" character in the next match, so it
// should not be consumed by the first match.
// The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the
// start of the string, so this also works if the selection begins with a bracket. We cannot solve
// this by anchoring with ^, because in the case that the selection starts with two brackets, this
// would mean a zero-width match at the start. Since zero-width matches advance the string position,
// the first bracket could then not act as the "not a backslash" for the second.
chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1);
var linkDef = " [999]: " + properlyEncoded(link);
var num = that.addLinkDef(chunk, linkDef);
chunk.startTag = isImage ? "![" : "[";
chunk.endTag = "][" + num + "]";
if (!chunk.selection) {
if (isImage) {
chunk.selection = "enter image description here";
}
else {
chunk.selection = "enter link description here";
}
}
}
postProcessing();
};
background = ui.createBackground();
if (isImage) {
if (!this.hooks.insertImageDialog(linkEnteredCallback))
ui.prompt(imageDialogText, imageDefaultText, linkEnteredCallback);
}
else {
ui.prompt(linkDialogText, linkDefaultText, linkEnteredCallback);
}
return true;
}
};
// When making a list, hitting shift-enter will put your cursor on the next line
// at the current indent level.
commandProto.doAutoindent = function (chunk, postProcessing) {
var commandMgr = this,
fakeSelection = false;
chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
// There's no selection, end the cursor wasn't at the end of the line:
// The user wants to split the current list item / code line / blockquote line
// (for the latter it doesn't really matter) in two. Temporarily select the
// (rest of the) line to achieve this.
if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) {
chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) {
chunk.selection = wholeMatch;
return "";
});
fakeSelection = true;
}
if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) {
if (commandMgr.doList) {
commandMgr.doList(chunk);
}
}
if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) {
if (commandMgr.doBlockquote) {
commandMgr.doBlockquote(chunk);
}
}
if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
if (commandMgr.doCode) {
commandMgr.doCode(chunk);
}
}
if (fakeSelection) {
chunk.after = chunk.selection + chunk.after;
chunk.selection = "";
}
};
commandProto.doBlockquote = function (chunk, postProcessing) {
chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
function (totalMatch, newlinesBefore, text, newlinesAfter) {
chunk.before += newlinesBefore;
chunk.after = newlinesAfter + chunk.after;
return text;
});
chunk.before = chunk.before.replace(/(>[ \t]*)$/,
function (totalMatch, blankLine) {
chunk.selection = blankLine + chunk.selection;
return "";
});
chunk.selection = chunk.selection.replace(/^(\s|>)+$/, "");
chunk.selection = chunk.selection || "Blockquote";
// The original code uses a regular expression to find out how much of the
// text *directly before* the selection already was a blockquote:
/*
if (chunk.before) {
chunk.before = chunk.before.replace(/\n?$/, "\n");
}
chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
function (totalMatch) {
chunk.startTag = totalMatch;
return "";
});
*/
// This comes down to:
// Go backwards as many lines a possible, such that each line
// a) starts with ">", or
// b) is almost empty, except for whitespace, or
// c) is preceeded by an unbroken chain of non-empty lines
// leading up to a line that starts with ">" and at least one more character
// and in addition
// d) at least one line fulfills a)
//
// Since this is essentially a backwards-moving regex, it's susceptible to
// catstrophic backtracking and can cause the browser to hang;
// see e.g. http://meta.stackoverflow.com/questions/9807.
//
// Hence we replaced this by a simple state machine that just goes through the
// lines and checks for a), b), and c).
var match = "",
leftOver = "",
line;
if (chunk.before) {
var lines = chunk.before.replace(/\n$/, "").split("\n");
var inChain = false;
for (var i = 0; i < lines.length; i++) {
var good = false;
line = lines[i];
inChain = inChain && line.length > 0; // c) any non-empty line continues the chain
if (/^>/.test(line)) { // a)
good = true;
if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain
inChain = true;
} else if (/^[ \t]*$/.test(line)) { // b)
good = true;
} else {
good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain
}
if (good) {
match += line + "\n";
} else {
leftOver += match + line;
match = "\n";
}
}
if (!/(^|\n)>/.test(match)) { // d)
leftOver += match;
match = "";
}
}
chunk.startTag = match;
chunk.before = leftOver;
// end of change
if (chunk.after) {
chunk.after = chunk.after.replace(/^\n?/, "\n");
}
chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
function (totalMatch) {
chunk.endTag = totalMatch;
return "";
}
);
var replaceBlanksInTags = function (useBracket) {
var replacement = useBracket ? "> " : "";
if (chunk.startTag) {
chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
function (totalMatch, markdown) {
return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
});
}
if (chunk.endTag) {
chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
function (totalMatch, markdown) {
return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
});
}
};
if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) {
this.wrap(chunk, SETTINGS.lineLength - 2);
chunk.selection = chunk.selection.replace(/^/gm, "> ");
replaceBlanksInTags(true);
chunk.skipLines();
} else {
chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
this.unwrap(chunk);
replaceBlanksInTags(false);
if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) {
chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
}
if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) {
chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n");
}
}
chunk.selection = this.hooks.postBlockquoteCreation(chunk.selection);
if (!/\n/.test(chunk.selection)) {
chunk.selection = chunk.selection.replace(/^(> *)/,
function (wholeMatch, blanks) {
chunk.startTag += blanks;
return "";
});
}
};
commandProto.doCode = function (chunk, postProcessing) {
var hasTextBefore = /\S[ ]*$/.test(chunk.before);
var hasTextAfter = /^[ ]*\S/.test(chunk.after);
// Use 'four space' markdown if the selection is on its own
// line or is multiline.
if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) {
chunk.before = chunk.before.replace(/[ ]{4}$/,
function (totalMatch) {
chunk.selection = totalMatch + chunk.selection;
return "";
});
var nLinesBack = 1;
var nLinesForward = 1;
if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
nLinesBack = 0;
}
if (/^\n(\t|[ ]{4,})/.test(chunk.after)) {
nLinesForward = 0;
}
chunk.skipLines(nLinesBack, nLinesForward);
if (!chunk.selection) {
chunk.startTag = " ";
chunk.selection = "enter code here";
}
else {
if (/^[ ]{0,3}\S/m.test(chunk.selection)) {
if (/\n/.test(chunk.selection))
chunk.selection = chunk.selection.replace(/^/gm, " ");
else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior
chunk.before += " ";
}
else {
chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
}
}
}
else {
// Use backticks (`) to delimit the code block.
chunk.trimWhitespace();
chunk.findTags(/`/, /`/);
if (!chunk.startTag && !chunk.endTag) {
chunk.startTag = chunk.endTag = "`";
if (!chunk.selection) {
chunk.selection = "enter code here";
}
}
else if (chunk.endTag && !chunk.startTag) {
chunk.before += chunk.endTag;
chunk.endTag = "";
}
else {
chunk.startTag = chunk.endTag = "";
}
}
};
commandProto.doList = function (chunk, postProcessing, isNumberedList) {
// These are identical except at the very beginning and end.
// Should probably use the regex extension function to make this clearer.
var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
// The default bullet is a dash but others are possible.
// This has nothing to do with the particular HTML bullet,
// it's just a markdown bullet.
var bullet = "-";
// The number in a numbered list.
var num = 1;
// Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
var getItemPrefix = function () {
var prefix;
if (isNumberedList) {
prefix = " " + num + ". ";
num++;
}
else {
prefix = " " + bullet + " ";
}
return prefix;
};
// Fixes the prefixes of the other list items.
var getPrefixedItem = function (itemText) {
// The numbering flag is unset when called by autoindent.
if (isNumberedList === undefined) {
isNumberedList = /^\s*\d/.test(itemText);
}
// Renumber/bullet the list element.
itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
function (_) {
return getItemPrefix();
});
return itemText;
};
chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) {
chunk.before += chunk.startTag;
chunk.startTag = "";
}
if (chunk.startTag) {
var hasDigits = /\d+[.]/.test(chunk.startTag);
chunk.startTag = "";
chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
this.unwrap(chunk);
chunk.skipLines();
if (hasDigits) {
// Have to renumber the bullet points if this is a numbered list.
chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
}
if (isNumberedList == hasDigits) {
return;
}
}
var nLinesUp = 1;
chunk.before = chunk.before.replace(previousItemsRegex,
function (itemText) {
if (/^\s*([*+-])/.test(itemText)) {
bullet = re.$1;
}
nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
return getPrefixedItem(itemText);
});
if (!chunk.selection) {
chunk.selection = "List item";
}
var prefix = getItemPrefix();
var nLinesDown = 1;
chunk.after = chunk.after.replace(nextItemsRegex,
function (itemText) {
nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
return getPrefixedItem(itemText);
});
chunk.trimWhitespace(true);
chunk.skipLines(nLinesUp, nLinesDown, true);
chunk.startTag = prefix;
var spaces = prefix.replace(/./g, " ");
this.wrap(chunk, SETTINGS.lineLength - spaces.length);
chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
};
commandProto.doHeading = function (chunk, postProcessing) {
// Remove leading/trailing whitespace and reduce internal spaces to single spaces.
chunk.selection = chunk.selection.replace(/\s+/g, " ");
chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
// If we clicked the button with no selected text, we just
// make a level 2 hash header around some default text.
if (!chunk.selection) {
chunk.startTag = "## ";
chunk.selection = "Heading";
chunk.endTag = " ##";
return;
}
var headerLevel = 0; // The existing header level of the selected text.
// Remove any existing hash heading markdown and save the header level.
chunk.findTags(/#+[ ]*/, /[ ]*#+/);
if (/#+/.test(chunk.startTag)) {
headerLevel = re.lastMatch.length;
}
chunk.startTag = chunk.endTag = "";
// Try to get the current header level by looking for - and = in the line
// below the selection.
chunk.findTags(null, /\s?(-+|=+)/);
if (/=+/.test(chunk.endTag)) {
headerLevel = 1;
}
if (/-+/.test(chunk.endTag)) {
headerLevel = 2;
}
// Skip to the next line so we can create the header markdown.
chunk.startTag = chunk.endTag = "";
chunk.skipLines(1, 1);
// We make a level 2 header if there is no current header.
// If there is a header level, we substract one from the header level.
// If it's already a level 1 header, it's removed.
var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
if (headerLevelToCreate > 0) {
// The button only creates level 1 and 2 underline headers.
// Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
var len = chunk.selection.length;
if (len > SETTINGS.lineLength) {
len = SETTINGS.lineLength;
}
chunk.endTag = "\n";
while (len--) {
chunk.endTag += headerChar;
}
}
};
commandProto.doHorizontalRule = function (chunk, postProcessing) {
chunk.startTag = "----------\n";
chunk.selection = "";
chunk.skipLines(2, 1, true);
}
})();
| MitchellMcKenna/LifePress | public/scripts/pagedown/Markdown.Editor.js | JavaScript | gpl-3.0 | 80,757 |
import {
moduleForComponent,
test
} from 'ember-qunit';
moduleForComponent('hq-category', {
// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar']
});
test('it renders', function(assert) {
assert.expect(2);
// Creates the component instance
var component = this.subject();
assert.equal(component._state, 'preRender');
// Renders the component to the page
this.render();
assert.equal(component._state, 'inDOM');
});
| hugoruscitti/huayra-quotes | tests/unit/components/hq-category-test.js | JavaScript | gpl-3.0 | 487 |
class Block {
constructor(x, y, width, colour) {
this.x = x;
this.y = y;
this.width = width;
this.colour = colour;
this.occupied = false;
}
draw() {
fill(this.colour);
rect(this.x, this.y, this.width, this.width);
}
}
| DanielGilchrist/p5.js-snake | classes/block.js | JavaScript | gpl-3.0 | 255 |
define(['backbone', 'underscore'], function (Backbone, _) {
return Backbone.Model.extend({
idAttribute: 'username',
defaults: {
persona: {
personaPnombre: '',
personaSnombre: '',
personaApaterno: '',
personaAmaterno: '',
dni: ''
}
},
validate: function (attrs, options) {
console.log('persona', attrs.persona);
if (_.isUndefined(attrs.persona)) {
return {
field: 'persona',
error: 'Debe definir una persona'
};
}
if (_.isUndefined(attrs.persona.personaDni) || _.isEmpty(attrs.persona.personaDni.trim()) || attrs.persona.personaDni.trim().length != 8) {
return {
field: 'persona-personaDni',
error: 'El dni es un campo obligatorio y debe tener 8 caracteres.'
};
}
if (_.isUndefined(attrs.persona.personaPnombre) || _.isEmpty(attrs.persona.personaPnombre.trim())) {
return {
field: 'persona-personaPnombre',
error: 'El primer nombre es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaApaterno) || _.isEmpty(attrs.persona.personaApaterno.trim())) {
return {
field: 'persona-personaApaterno',
error: 'El apellido paterno es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaAmaterno) || _.isEmpty(attrs.persona.personaAmaterno.trim())) {
return {
field: 'persona-personaAmaterno',
error: 'El apellido materno es un campo obligatorio.'
};
}
}
});
}); | jaxkodex/edu-stat | src/main/webapp/resources/js/app/models/docente-model.js | JavaScript | gpl-3.0 | 1,442 |
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
class ParityBackground extends Component {
static propTypes = {
style: PropTypes.object.isRequired,
children: PropTypes.node,
className: PropTypes.string,
onClick: PropTypes.func
};
render () {
const { children, className, style, onClick } = this.props;
return (
<div
className={ className }
style={ style }
onTouchTap={ onClick }>
{ children }
</div>
);
}
}
function mapStateToProps (_, initProps) {
const { gradient, seed, muiTheme } = initProps;
let _seed = seed;
let _props = { style: muiTheme.parity.getBackgroundStyle(gradient, seed) };
return (state, props) => {
const { backgroundSeed } = state.settings;
const { seed } = props;
const newSeed = seed || backgroundSeed;
if (newSeed === _seed) {
return _props;
}
_seed = newSeed;
_props = { style: muiTheme.parity.getBackgroundStyle(gradient, newSeed) };
return _props;
};
}
export default connect(
mapStateToProps
)(ParityBackground);
| pdaian/parity | js/src/ui/ParityBackground/parityBackground.js | JavaScript | gpl-3.0 | 1,825 |
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function ($, require) {
var exports = require('piwik/UI');
/**
* Creates a new notifications.
*
* Example:
* var UI = require('piwik/UI');
* var notification = new UI.Notification();
* notification.show('My Notification Message', {title: 'Low space', context: 'warning'});
*/
var Notification = function () {
this.$node = null;
};
/**
* Makes the notification visible.
*
* @param {string} message The actual message that will be displayed. Must be set.
* @param {Object} [options]
* @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the
* frontend once the user closes the notifications. The notification has to
* be registered/notified under this name
* @param {string} [options.title] The title of the notification. For instance the plugin name.
* @param {bool} [options.animate=true] If enabled, the notification will be faded in.
* @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or
* 'error'
* @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent'
* @param {bool} [options.noclear=false] If set, the close icon is not displayed.
* @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'}
* @param {string} [options.placeat] By default, the notification will be displayed in the "stats bar".
* You can specify any other CSS selector to place the notifications
* wherever you want.
*/
Notification.prototype.show = function (message, options) {
checkMessage(message);
options = checkOptions(options);
var template = generateNotificationHtmlMarkup(options, message);
this.$node = placeNotification(template, options);
};
/**
* Removes a previously shown notification having the given notification id.
*
*
* @param {string} notificationId The id of a notification that was previously registered.
*/
Notification.prototype.remove = function (notificationId) {
$('[piwik-notification][notification-id=' + notificationId + ']').remove();
};
Notification.prototype.scrollToNotification = function () {
if (this.$node) {
piwikHelper.lazyScrollTo(this.$node, 250);
}
};
/**
* Shows a notification at a certain point with a quick upwards animation.
*
* TODO: if the materializecss version matomo uses is updated, should use their toasts.
*
* @type {Notification}
* @param {string} message The actual message that will be displayed. Must be set.
* @param {Object} options
* @param {string} options.placeat Where to place the notification. Required.
* @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the
* frontend once the user closes the notifications. The notification has to
* be registered/notified under this name
* @param {string} [options.title] The title of the notification. For instance the plugin name.
* @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or
* 'error'
* @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent'
* @param {bool} [options.noclear=false] If set, the close icon is not displayed.
* @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'}
*/
Notification.prototype.toast = function (message, options) {
checkMessage(message);
options = checkOptions(options);
var $placeat = $(options.placeat);
if (!$placeat.length) {
throw new Error("A valid selector is required for the placeat option when using Notification.toast().");
}
var $template = $(generateNotificationHtmlMarkup(options, message)).hide();
$('body').append($template);
compileNotification($template);
$template.css({
position: 'absolute',
left: $placeat.offset().left,
top: $placeat.offset().top
});
setTimeout(function () {
$template.animate(
{
top: $placeat.offset().top - $template.height()
},
{
duration: 300,
start: function () {
$template.show();
}
}
);
});
};
exports.Notification = Notification;
function generateNotificationHtmlMarkup(options, message) {
var attributeMapping = {
id: 'notification-id',
title: 'notification-title',
context: 'context',
type: 'type',
noclear: 'noclear',
class: 'class',
toastLength: 'toast-length'
},
html = '<div piwik-notification';
for (var key in attributeMapping) {
if (attributeMapping.hasOwnProperty(key)
&& options[key]
) {
html += ' ' + attributeMapping[key] + '="' + options[key].toString().replace(/"/g, """) + '"';
}
}
html += '>' + message + '</div>';
return html;
}
function compileNotification($node) {
angular.element(document).injector().invoke(function ($compile, $rootScope) {
$compile($node)($rootScope.$new(true));
});
}
function placeNotification(template, options) {
var $notificationNode = $(template);
// compile the template in angular
compileNotification($notificationNode);
if (options.style) {
$notificationNode.css(options.style);
}
var notificationPosition = '#notificationContainer';
var method = 'append';
if (options.placeat) {
notificationPosition = options.placeat;
} else {
// If a modal is open, we want to make sure the error message is visible and therefore show it within the opened modal
var modalSelector = '.modal.open .modal-content';
var modalOpen = $(modalSelector);
if (modalOpen.length) {
notificationPosition = modalSelector;
method = 'prepend';
}
}
$notificationNode = $notificationNode.hide();
$(notificationPosition)[method]($notificationNode);
if (false === options.animate) {
$notificationNode.show();
} else {
$notificationNode.fadeIn(1000);
}
return $notificationNode;
}
function checkMessage(message) {
if (!message) {
throw new Error('No message given, cannot display notification');
}
}
function checkOptions(options) {
if (options && !$.isPlainObject(options)) {
throw new Error('Options has the wrong format, cannot display notification');
} else if (!options) {
options = {};
}
return options;
}
})(jQuery, require); | piwik/piwik | plugins/CoreHome/javascripts/notification.js | JavaScript | gpl-3.0 | 7,980 |
(function() {
var app = angular.module('article-directive', ['ui.bootstrap.contextMenu']);
app.config(function($sceProvider) {
// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects.
$sceProvider.enabled(false);
});
app.directive('article', function () {
var controller = function () {
var vm = this;
};
var getSelectionText = function() {
if(window.getSelection) {
return window.getSelection().toString();
}
if(document.selection && document.selection.type != "Control") {
return document.selection.createRange().text;
}
return "";
};
var link = function link(scope, element, attrs) {
scope.toggleComments = function () {
scope.$broadcast("event:toggle");
}
scope.menuOptions = [['Copy', function ($itemScope) {
}],
null, // Dividier
['Comment', function ($itemScope) {
scope.toggleComments();
}]];
};
return {
restrict: 'EA', //Default for 1.3+
scope: {
text: '@text',
url: '@url'
},
controller: controller,
link: link,
controllerAs: 'vm',
bindToController: true, //required in 1.3+ with controllerAs
templateUrl: '/article/article.html'
};
});
}()); | lowdev/Article-Annotater | src/main/resources/static/article/angular-article-directive.js | JavaScript | gpl-3.0 | 1,330 |
/*
Copyright (C) 2014 PencilBlue, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Interface for managing topics
*/
function ManageTopics() {}
//inheritance
util.inherits(ManageTopics, pb.BaseController);
var SUB_NAV_KEY = 'manage_topics';
ManageTopics.prototype.render = function(cb) {
var self = this;
var dao = new pb.DAO();
dao.query('topic', pb.DAO.ANYWHERE, pb.DAO.PROJECT_ALL).then(function(topics) {
if (util.isError(topics)) {
//TODO handle this
}
//none to manage
if(topics.length === 0) {
self.redirect('/admin/content/topics/new', cb);
return;
}
//currently, mongo cannot do case-insensitive sorts. We do it manually
//until a solution for https://jira.mongodb.org/browse/SERVER-90 is merged.
topics.sort(function(a, b) {
var x = a.name.toLowerCase();
var y = b.name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
var angularObjects = pb.js.getAngularObjects(
{
navigation: pb.AdminNavigation.get(self.session, ['content', 'topics'], self.ls),
pills: pb.AdminSubnavService.get(SUB_NAV_KEY, self.ls, SUB_NAV_KEY),
topics: topics
});
self.setPageName(self.ls.get('MANAGE_TOPICS'));
self.ts.registerLocal('angular_objects', new pb.TemplateValue(angularObjects, false));
self.ts.load('admin/content/topics/manage_topics', function(err, data) {
var result = '' + data;
cb({content: result});
});
});
};
ManageTopics.getSubNavItems = function(key, ls, data) {
return [{
name: SUB_NAV_KEY,
title: ls.get('MANAGE_TOPICS'),
icon: 'refresh',
href: '/admin/content/topics'
}, {
name: 'import_topics',
title: '',
icon: 'upload',
href: '/admin/content/topics/import'
}, {
name: 'new_topic',
title: '',
icon: 'plus',
href: '/admin/content/topics/new'
}];
};
//register admin sub-nav
pb.AdminSubnavService.registerFor(SUB_NAV_KEY, ManageTopics.getSubNavItems);
//exports
module.exports = ManageTopics;
| shihokoui/pencilblue | plugins/pencilblue/controllers/admin/content/topics/manage_topics.js | JavaScript | gpl-3.0 | 2,715 |
function print_last_modif_date(v) {
document.write("Last updated " + v.substr(7, 19));
}
| francois-a/fastqtl | doc/script/print_last_modif_date.js | JavaScript | gpl-3.0 | 89 |
import { defineMessages } from 'react-intl';
export default defineMessages({
save: {
id: 'cboard.components.FormDialog.save',
defaultMessage: 'Save'
},
cancel: {
id: 'cboard.components.FormDialog.cancel',
defaultMessage: 'Cancel'
}
});
| shayc/cboard | src/components/UI/FormDialog/FormDialog.messages.js | JavaScript | gpl-3.0 | 261 |
const { nativeImage } = require('electron')
const { resolve } = require('path')
exports.size16 = nativeImage.createFromPath(resolve(__dirname, '../icon16.png'))
exports.size16.setTemplateImage(true)
| Gerhut/Meibo | lib/icon.js | JavaScript | gpl-3.0 | 201 |
document.addEventListener("DOMContentLoaded", function(event) {
if (/android|blackberry|iPhone|iPad|iPod|webOS/i.test(navigator.userAgent) === false) {
var linkDescrs = document.querySelectorAll('.link-descr');
Array.prototype.forEach.call(linkDescrs, function(el, i) {
el.parentNode.addEventListener('mouseenter', animateTypeText);
el.parentNode.addEventListener('mouseleave', destroyTypeText);
});
} else {
var linkDescrs = document.querySelectorAll('.link-descr');
Array.prototype.forEach.call(linkDescrs, function(el, i) {
removeClass(el, 'link-descr');
});
}
});
var addClass = function(elem, add_class) {
elem.setAttribute("class", elem.getAttribute("class") + ' ' + add_class);
};
var removeClass = function(elem, rem_class) {
var origClass = elem.getAttribute("class");
var remClassRegex = new Regexp("(\\s*)"+rem_class+"(\\s*)");
var classMatch = origClass.match(remClassRegex);
var replaceString = '';
if (classMatch[1].length > 0 || classMatch[2].length > 0) {
replaceString = ' ';
}
var newClass = origClass.replace(remClassRegex, replaceString);
elem.setAttribute("class", newClass);
};
var animateTypeText = function() {
var elem = this;
var typeArea = document.createElement("span");
typeArea.setAttribute("class", "link-subtext");
elem.insertBefore(typeArea, elem.querySelector("span:last-of-type"));
setTimeout(addLetter(elem), 40);
};
var addLetter = function(elem) {
// if (elem.parentElement.querySelector(":hover") === elem) {
var subtextSpan = elem.querySelector(".link-subtext");
var descrText = elem.querySelector(".link-descr").textContent;
if (subtextSpan === null) {
return;
}
var currentText = subtextSpan.textContent.slice(0,-1);
var currentPos = currentText.length;
subtextSpan.textContent = currentText +
descrText.slice(currentPos, currentPos+1) + "\u258B";
if (currentText.length < descrText.length) {
setTimeout(function(){addLetter(elem)}, 40);
}
// }
};
var destroyTypeText = function() {
var elem = this;
elem.removeChild(elem.querySelector('.link-subtext'));
};
| thedanielgray/thedanielgray.github.io | js/gray.js | JavaScript | gpl-3.0 | 2,070 |
var gulp = require('gulp');
var browserSync = require('browser-sync');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
// 静态服务器
gulp.task('browser-sync', function() {
browserSync.init({
files: "src/**",
server: {
baseDir: "src/"
}
});
});
// js语法检查
gulp.task('jshint', function() {
return gulp.src('src/js/*.js')
.on('error')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// js文件合并及压缩
gulp.task('minifyjs', function() {
return gulp.src('src/js/*.js')
.pipe(concat('all.js'))
.pipe(gulp.dest('dist/js'))
.pipe(uglify())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('dist/js'));
});
// 事件监听
gulp.task('watch', function() {
gulp.watch('src/js/*.js', ['jshint','minifyjs']);
});
gulp.task('default',['browser-sync','watch']); | bdSpring/zhou-task02 | 26/gulpfile.js | JavaScript | gpl-3.0 | 946 |
// mailer.js
var nodemailer = require('nodemailer');
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Mandrill",
debug: true,
auth: {
user: "[email protected]",
pass: "k-AdDVcsNJ9oj8QYATVNGQ"
}
});
exports.sendEmailConfirmation = function(emailaddress, username, firstname, expiremoment, token){
var mailOptions = {
from: "[email protected]", // sender address
to: emailaddress, // list of receivers
subject: "Confirm email and start Ativinos", // Subject line
text: 'Hi '
+firstname+
', your account, '
+username+
', will be enabled after you confirm your email. Your account will be deleted by '
+ expiremoment +
' if you do not verify email before then. To verify your email, visit http://www.ativinos.com/emailverify?token='
+ token +
'&username='
+ username,
html: 'Hi '
+firstname+
', your account, '
+username+
', will be enabled after you confirm your email. Your account will be deleted by '
+ expiremoment +
' if you do not verify email before then. To verify your email, visit <a href="http://www.ativinos.com/emailverify?token='
+ token +
'&username='
+ username +
'">http://www.ativinos.com/emailverify?token='
+ token +
'&username='
+ username +
'</a>',
}
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}
})
}
| evrom/ativinos---deprecated | local_modules/mailer.js | JavaScript | gpl-3.0 | 1,602 |
$(function(){
$('#telefone').mask('(99)9999-9999');
$('.editar').on({
click : function(){
var url = URI+"sistema/editar/"+$(this).attr('data-item');
window.location.href = url;
}
});
$('.deletar').on({
click : function(){
var $selecionados = get_selecionados();
if($selecionados.length > 0)
{
var $url = URI+"sistema/remover/";
if (window.confirm("deseja apagar os ("+$selecionados.length+") itens selecionados? "))
{
$.post($url, { 'selecionados': $selecionados}, function(data){
pop_up(data, setTimeout(function(){location.reload()}, 100));
});
}
}
else
{
pop_up('nenhum item selecionado');
}
}
});
$('#description').on('keyup',function(){
var alvo = $("#char-digitado");
var max = 140;
var digitados = $(this).val().length;
var restante = max - digitados;
if(digitados > max)
{
var val = $(this).val();
$(this).val(val.substr(0, max));
restante = 0;
}
alvo.html(restante);
});
});
| Carlos-Claro/admin2_0 | js/sistema.js | JavaScript | gpl-3.0 | 1,437 |
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package enrol_attributes
* @author Julien Furrer <[email protected]>
* @copyright 2012-2015 Université de Lausanne (@link http://www.unil.ch}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
;
(function ($) {
$.booleanEditor = {
defaults: {
rules: [],
change: null
},
paramList: M.enrol_attributes.paramList,
operatorList: [
{label: " = ", value: "=="},
// {label: "=/=", value: "!="},
// {label: "contains", value: "contains"},
]
};
$.fn.extend({
booleanEditor: function (options) {
var isMethodCall = (typeof options == 'string'), // is it a method call or booleanEditor instantiation ?
args = Array.prototype.slice.call(arguments, 1);
if (isMethodCall) switch (options) {
case 'serialize':
var mode = ( args[0] ) ? args[0].mode : '',
ser_obj = serialize(this);
switch (mode) {
case 'json':
return $.toJSON(ser_obj);
break;
case 'object':
default:
return ser_obj;
}
break;
case 'getExpression':
return getBooleanExpression(this);
break;
default:
return;
}
settings = $.extend({}, $.booleanEditor.defaults, options);
return this.each(function () {
if (settings.change) {
$(this).data('change', settings.change)
}
$(this)
.addClass("enrol-attributes-boolean-editor")
.append(createRuleList($('<ul></ul>'), settings.rules));
changed(this);
});
}
});
function serialize(root_elem) {
var ser_obj = {rules: []};
var group_c_op = $("select:first[name='cond-operator']", root_elem).val();
if (group_c_op)
ser_obj.cond_op = group_c_op;
$("ul:first > li", root_elem).each(function () {
r = $(this);
if (r.hasClass('group')) {
ser_obj['rules'].push(serialize(this));
}
else {
var cond_obj = {
param: $("select[name='comparison-param'] option:selected", r).val(),
comp_op: $("select[name='comparison-operator']", r).val(),
value: $("input[name='value']", r).val()
};
var cond_op = $("select[name='cond-operator']", r).val();
if (cond_op)
cond_obj.cond_op = cond_op;
ser_obj['rules'].push(cond_obj);
}
});
return ser_obj;
}
function getBooleanExpression(editor) {
var expression = "";
$("ul:first > li", editor).each(function () {
r = $(this);
var c_op = $("select[name='cond-operator']", r).val();
if (c_op != undefined) c_op = '<span class="cond-op"> ' + c_op + ' </span>';
if (r.hasClass('group')) {
expression += c_op + '<span class="group-op group-group">(</span>' + getBooleanExpression(this) + '<span class="group-op group-group">)</span>';
}
else {
expression += [
c_op,
'<span class="group-op group-cond">(</span>',
'<span class="comp-param">' + $("select[name='comparison-param'] option:selected", r).text() + '</span>',
'<span class="comp-op"> ' + $("select[name='comparison-operator']", r).val() + ' </span>',
'<span class="comp-val">' + '\'' + $("input[name='value']", r).val() + '\'' + '</span>',
'<span class="group-op group-cond">)</span>'
].join("");
}
});
return expression;
}
function changed(o) {
$o = $(o);
if (!$o.hasClass('enrol-attributes-boolean-editor')) {
$o = $o.parents('.enrol-attributes-boolean-editor').eq(0);
}
if ($o.data('change')) {
$o.data('change').apply($o.get(0));
}
}
function createRuleList(list_elem, rules) {
//var list_elem = $(list_elem);
if (list_elem.parent("li").eq(0).hasClass("group")) {
console.log("inside a group");
return;
}
if (rules.length == 0) {
// No rules, create a new one
list_elem.append(getRuleConditionElement({first: true}));
} else {
// Read all rules
for (var r_idx = 0; r_idx < rules.length; r_idx++) {
var r = rules[r_idx];
r['first'] = (r_idx == 0);
// If the rule is an array, create a group of rules
if (r.rules && (typeof r.rules[0] == 'object')) {
r.group = true;
var rg = getRuleConditionElement(r);
list_elem.append(rg);
createRuleList($("ul:first", rg), r.rules);
}
else {
list_elem.append(getRuleConditionElement(r));
}
}
}
return list_elem;
};
/**
* Build the HTML code for editing a rule condition.
* A rule is composed of one or more rule conditions linked by boolean operators
*/
function getRuleConditionElement(config) {
config = $.extend({},
{
first: false,
group: false,
cond_op: null,
param: null,
comp_op: null,
value: ''
},
config
);
// If group flag is set, wrap content with <ul></ul>, content is obtained by a recursive call
// to the function, passing a copy of config with flag group set to false
var cond_block_content = $('<div class="sre-condition-box"></div>');
if (config.group) {
cond_block_content.append('<ul></ul>');
} else {
cond_block_content
.append(makeSelectList({ // The list of parameters to be compared
name: 'comparison-param',
params: $.booleanEditor.paramList,
selected_value: config.param
}).addClass("comp-param"))
.append($('<span>').addClass("comp-op").text('='))
// .append( makeSelectList({ // The comparison operator
// name: 'comparison-operator',
// params: $.booleanEditor.operatorList,
// selected_value: config.comp_op
// }).addClass("comp-op"))
.append($('<input type="text" name="value" value="' + config.value + '"/>')
.change(function () {
changed(this)
})
); // The value of the comparions
}
var ruleConditionElement = $('<li></li>')
.addClass((config.group) ? 'group' : 'rule')
.append(createRuleOperatorSelect(config))
.append(cond_block_content)
.append(createButtonPannel())
return ruleConditionElement;
};
function createRuleOperatorSelect(config) {
return (config.first) ? '' :
makeSelectList({
'name': 'cond-operator',
params: [
{label: 'AND', value: 'and'},
{label: 'OR', value: 'or'}
],
selected_value: config.cond_op
}).addClass('sre-condition-rule-operator');
}
function createButtonPannel() {
var buttonPannel = $('<div class="button-pannel"></div>')
.append($('<button type="button" class="button-add-cond">'+ M.util.get_string('addcondition', 'enrol_attributes') +'</button>')
.click(function () {
addNewConditionAfter($(this).parents('li').get(0));
})
)
.append($('<button type="button" class="button-add-group">'+ M.util.get_string('addgroup', 'enrol_attributes') +'</button>')
.click(function () {
addNewGroupAfter($(this).parents('li').get(0));
})
)
.append($('<button type="button" class="button-del-cond">'+ M.util.get_string('deletecondition', 'enrol_attributes') +'</button>')
.click(function () {
deleteCondition($(this).parents('li').eq(0));
})
);
$('button', buttonPannel).each(function () {
$(this)
.focus(function () {
this.blur()
})
.attr("title", $(this).text())
.wrapInner('<span/>');
});
return buttonPannel;
}
function makeSelectList(config) {
config = $.extend({},
{
name: 'list_name',
params: [{label: 'label', value: 'value'}],
selected_value: null
},
config);
var selectList = $('<select name="' + config.name + '"></select>')
.change(function () {
changed(this);
});
$.each(config.params, function (i, p) {
var p_obj = $('<option></option>')
.attr({label: p.label, value: p.value})
.text(p.label);
if (p.value == config.selected_value) {
p_obj.attr("selected", "selected");
}
p_obj.appendTo(selectList);
});
return selectList;
}
//
// -->> Conditions manipulation <<--
//
function addNewConditionAfter(elem, config) {
getRuleConditionElement(config)
.hide()
.insertAfter(elem)
.fadeIn("normal", function () {
changed(elem)
});
}
function addNewGroupAfter(elem, config) {
getRuleConditionElement({group: true})
.hide()
.insertAfter(elem)
.find("ul:first")
.append(getRuleConditionElement($.extend({}, config, {first: true})))
.end()
.fadeIn("normal", function () {
changed(elem)
});
}
/*
*
* Supprimer une condition : supprimer éventuellement le parent si dernier enfant,
* mettre à jour le parent dans tous les cas.
*
*/
function deleteCondition(elem) {
if (elem.parent().parent().hasClass('enrol-attributes-boolean-editor')) {
// Level 1
if (elem.siblings().length == 0) {
return;
}
} else {
// Higher level
if (elem.siblings().length == 0) {
// The last cond of the group, target the group itself, to be removed
elem = elem.parents('li').eq(0);
}
}
p = elem.parent();
elem.fadeOut("normal", function () {
$(this).remove();
$("li:first .sre-condition-rule-operator", ".enrol-attributes-boolean-editor ul").remove();
changed(p);
});
}
})(jQuery);
| nitro2010/moodle | enrol/attributes/js/jquery.booleanEditor.js | JavaScript | gpl-3.0 | 12,496 |
/*
Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
(function(){function w(a){for(var f=0,p=0,n=0,q,d=a.$.rows.length;n<d;n++){q=a.$.rows[n];for(var e=f=0,b,c=q.cells.length;e<c;e++)b=q.cells[e],f+=b.colSpan;f>p&&(p=f)}return p}function t(a){return function(){var f=this.getValue(),f=!!(CKEDITOR.dialog.validate.integer().call(this,f)&&0<f);f||(alert(a),this.select());return f}}function r(a,f){var p=function(d){return new CKEDITOR.dom.element(d,a.document)},r=a.editable(),q=a.plugins.dialogadvtab;return{title:a.lang.table.title,minWidth:310,minHeight:CKEDITOR.env.ie?
310:280,getModel:function(d){return"tableProperties"!==this.dialog.getName()?null:(d=(d=d.getSelection())&&d.getRanges()[0])?d._getTableElement({table:1}):null},onLoad:function(){var d=this,a=d.getContentElement("advanced","advStyles");if(a)a.on("change",function(){var a=this.getStyle("width",""),c=d.getContentElement("info","txtWidth");c&&c.setValue(a,!0);a=this.getStyle("height","");(c=d.getContentElement("info","txtHeight"))&&c.setValue(a,!0)})},onShow:function(){var d=a.getSelection(),e=d.getRanges(),
b,c=this.getContentElement("info","txtRows"),h=this.getContentElement("info","txtCols"),u=this.getContentElement("info","txtWidth"),l=this.getContentElement("info","txtHeight");"tableProperties"==f&&((d=d.getSelectedElement())&&d.is("table")?b=d:0<e.length&&(CKEDITOR.env.webkit&&e[0].shrink(CKEDITOR.NODE_ELEMENT),b=a.elementPath(e[0].getCommonAncestor(!0)).contains("table",1)),this._.selectedElement=b);b?(this.setupContent(b),c&&c.disable(),h&&h.disable()):(c&&c.enable(),h&&h.enable());u&&u.onChange();
l&&l.onChange()},onOk:function(){var d=a.getSelection(),e=this._.selectedElement&&d.createBookmarks(),b=this._.selectedElement||p("table"),c={};this.commitContent(c,b);if(c.info){c=c.info;if(!this._.selectedElement)for(var h=b.append(p("tbody")),f=parseInt(c.txtRows,10)||0,l=parseInt(c.txtCols,10)||0,k=0;k<f;k++)for(var g=h.append(p("tr")),m=0;m<l;m++)g.append(p("td")).appendBogus();f=c.selHeaders;if(!b.$.tHead&&("row"==f||"both"==f)){g=b.getElementsByTag("thead").getItem(0);h=b.getElementsByTag("tbody").getItem(0);
l=h.getElementsByTag("tr").getItem(0);g||(g=new CKEDITOR.dom.element("thead"),g.insertBefore(h));for(k=0;k<l.getChildCount();k++)h=l.getChild(k),h.type!=CKEDITOR.NODE_ELEMENT||h.data("cke-bookmark")||(h.renameNode("th"),h.setAttribute("scope","col"));g.append(l.remove())}if(null!==b.$.tHead&&"row"!=f&&"both"!=f){g=new CKEDITOR.dom.element(b.$.tHead);for(h=b.getElementsByTag("tbody").getItem(0);0<g.getChildCount();){l=g.getFirst();for(k=0;k<l.getChildCount();k++)m=l.getChild(k),m.type==CKEDITOR.NODE_ELEMENT&&
(m.renameNode("td"),m.removeAttribute("scope"));h.append(l,!0)}g.remove()}if(!this.hasColumnHeaders&&("col"==f||"both"==f))for(g=0;g<b.$.rows.length;g++)m=new CKEDITOR.dom.element(b.$.rows[g].cells[0]),m.renameNode("th"),m.setAttribute("scope","row");if(this.hasColumnHeaders&&"col"!=f&&"both"!=f)for(k=0;k<b.$.rows.length;k++)g=new CKEDITOR.dom.element(b.$.rows[k]),"tbody"==g.getParent().getName()&&(m=new CKEDITOR.dom.element(g.$.cells[0]),m.renameNode("td"),m.removeAttribute("scope"));c.txtHeight?
b.setStyle("height",c.txtHeight):b.removeStyle("height");c.txtWidth?b.setStyle("width",c.txtWidth):b.removeStyle("width");b.getAttribute("style")||b.removeAttribute("style")}if(this._.selectedElement)try{d.selectBookmarks(e)}catch(n){}else a.insertElement(b),setTimeout(function(){var d=new CKEDITOR.dom.element(b.$.rows[0].cells[0]),c=a.createRange();c.moveToPosition(d,CKEDITOR.POSITION_AFTER_START);c.select()},0)},contents:[{id:"info",label:a.lang.table.title,elements:[{type:"hbox",widths:[null,null],
styles:["vertical-align:top"],children:[{type:"vbox",padding:0,children:[{type:"text",id:"txtRows","default":3,label:a.lang.table.rows,required:!0,controlStyle:"width:5em",validate:t(a.lang.table.invalidRows),setup:function(d){this.setValue(d.$.rows.length)},commit:n},{type:"text",id:"txtCols","default":2,label:a.lang.table.columns,required:!0,controlStyle:"width:5em",validate:t(a.lang.table.invalidCols),setup:function(d){this.setValue(w(d))},commit:n},{type:"html",html:"\x26nbsp;"},{type:"select",
id:"selHeaders",requiredContent:"th","default":"",label:a.lang.table.headers,items:[[a.lang.table.headersNone,""],[a.lang.table.headersRow,"row"],[a.lang.table.headersColumn,"col"],[a.lang.table.headersBoth,"both"]],setup:function(d){var a=this.getDialog();a.hasColumnHeaders=!0;for(var b=0;b<d.$.rows.length;b++){var c=d.$.rows[b].cells[0];if(c&&"th"!=c.nodeName.toLowerCase()){a.hasColumnHeaders=!1;break}}null!==d.$.tHead?this.setValue(a.hasColumnHeaders?"both":"row"):this.setValue(a.hasColumnHeaders?
"col":"")},commit:n},{type:"text",id:"txtBorder",requiredContent:"table[border]","default":a.filter.check("table[border]")?1:0,label:a.lang.table.border,controlStyle:"width:3em",validate:CKEDITOR.dialog.validate.number(a.lang.table.invalidBorder),setup:function(d){this.setValue(d.getAttribute("border")||"")},commit:function(d,a){this.getValue()?a.setAttribute("border",this.getValue()):a.removeAttribute("border")}},{id:"cmbAlign",type:"select",requiredContent:"table[align]","default":"",label:a.lang.common.align,
items:[[a.lang.common.notSet,""],[a.lang.common.left,"left"],[a.lang.common.center,"center"],[a.lang.common.right,"right"]],setup:function(a){this.setValue(a.getAttribute("align")||"")},commit:function(a,e){this.getValue()?e.setAttribute("align",this.getValue()):e.removeAttribute("align")}}]},{type:"vbox",padding:0,children:[{type:"hbox",widths:["5em"],children:[{type:"text",id:"txtWidth",requiredContent:"table{width}",controlStyle:"width:5em",label:a.lang.common.width,title:a.lang.common.cssLengthTooltip,
"default":a.filter.check("table{width}")?500>r.getSize("width")?"100%":500:0,getValue:v,validate:CKEDITOR.dialog.validate.cssLength(a.lang.common.invalidCssLength.replace("%1",a.lang.common.width)),onChange:function(){var a=this.getDialog().getContentElement("advanced","advStyles");a&&a.updateStyle("width",this.getValue())},setup:function(a){a=a.getStyle("width");this.setValue(a)},commit:n}]},{type:"hbox",widths:["5em"],children:[{type:"text",id:"txtHeight",requiredContent:"table{height}",controlStyle:"width:5em",
label:a.lang.common.height,title:a.lang.common.cssLengthTooltip,"default":"",getValue:v,validate:CKEDITOR.dialog.validate.cssLength(a.lang.common.invalidCssLength.replace("%1",a.lang.common.height)),onChange:function(){var a=this.getDialog().getContentElement("advanced","advStyles");a&&a.updateStyle("height",this.getValue())},setup:function(a){(a=a.getStyle("height"))&&this.setValue(a)},commit:n}]},{type:"html",html:"\x26nbsp;"},{type:"text",id:"txtCellSpace",requiredContent:"table[cellspacing]",
controlStyle:"width:3em",label:a.lang.table.cellSpace,"default":a.filter.check("table[cellspacing]")?1:0,validate:CKEDITOR.dialog.validate.number(a.lang.table.invalidCellSpacing),setup:function(a){this.setValue(a.getAttribute("cellSpacing")||"")},commit:function(a,e){this.getValue()?e.setAttribute("cellSpacing",this.getValue()):e.removeAttribute("cellSpacing")}},{type:"text",id:"txtCellPad",requiredContent:"table[cellpadding]",controlStyle:"width:3em",label:a.lang.table.cellPad,"default":a.filter.check("table[cellpadding]")?
1:0,validate:CKEDITOR.dialog.validate.number(a.lang.table.invalidCellPadding),setup:function(a){this.setValue(a.getAttribute("cellPadding")||"")},commit:function(a,e){this.getValue()?e.setAttribute("cellPadding",this.getValue()):e.removeAttribute("cellPadding")}}]}]},{type:"html",align:"right",html:""},{type:"vbox",padding:0,children:[{type:"text",id:"txtCaption",requiredContent:"caption",label:a.lang.table.caption,setup:function(a){this.enable();a=a.getElementsByTag("caption");if(0<a.count()){a=
a.getItem(0);var e=a.getFirst(CKEDITOR.dom.walker.nodeType(CKEDITOR.NODE_ELEMENT));e&&!e.equals(a.getBogus())?(this.disable(),this.setValue(a.getText())):(a=CKEDITOR.tools.trim(a.getText()),this.setValue(a))}},commit:function(d,e){if(this.isEnabled()){var b=this.getValue(),c=e.getElementsByTag("caption");if(b)0<c.count()?(c=c.getItem(0),c.setHtml("")):(c=new CKEDITOR.dom.element("caption",a.document),e.append(c,!0)),c.append(new CKEDITOR.dom.text(b,a.document));else if(0<c.count())for(b=c.count()-
1;0<=b;b--)c.getItem(b).remove()}}},{type:"text",id:"txtSummary",bidi:!0,requiredContent:"table[summary]",label:a.lang.table.summary,setup:function(a){this.setValue(a.getAttribute("summary")||"")},commit:function(a,e){this.getValue()?e.setAttribute("summary",this.getValue()):e.removeAttribute("summary")}}]}]},q&&q.createAdvancedTab(a,null,"table")]}}var v=CKEDITOR.tools.cssLength,n=function(a){var f=this.id;a.info||(a.info={});a.info[f]=this.getValue()};CKEDITOR.dialog.add("table",function(a){return r(a,
"table")});CKEDITOR.dialog.add("tableProperties",function(a){return r(a,"tableProperties")})})(); | omeka/omeka-s | application/asset/vendor/ckeditor/plugins/table/dialogs/table.js | JavaScript | gpl-3.0 | 8,955 |
$(function() {
$("#childGrid").jqGrid(
{
url : "TBCcnsizePrm.html?getGridData",datatype : "json",mtype : "GET",colNames : [ 'Conn Id',getLocalMessage('water.connsize.frmDt'), getLocalMessage('water.connsize.toDt'), getLocalMessage('water.connsize.frm'),getLocalMessage('water.connsize.to'), getLocalMessage('edit.msg'), getLocalMessage('master.view')],
colModel : [ {name : "cnsId",width : 10,sortable : false,searchoptions: { "sopt": [ "eq"] }},
{name : "cnsFrmdt",width : 20,sortable : true,searchoptions: { "sopt": ["bw", "eq"] },formatter : dateTemplate},
{name : "cnsTodt",width : 20,sortable : true, searchoptions: { "sopt": ["bw", "eq"] },formatter : dateTemplate},
{name : "cnsFrom",width : 20,sortable : false,searchoptions: { "sopt": [ "eq"] }},
{name : "cnsTo",width : 20,sortable : false,searchoptions: { "sopt": [ "eq"] }},
{name : 'cnsId',index : 'cnsId',width : 20,align : 'center',formatter : returnEditUrl,editoptions : {value : "Yes:No"},formatoptions : {disabled : false},search:false },
{name : 'cnsId',index : 'cnsId',width : 20,align : 'center',formatter : returnViewUrl,editoptions : {value : "Yes:No"},formatoptions : {disabled : false},search:false}
],
pager : "#pagered",
rowNum : 30,
rowList : [ 5, 10, 20, 30 ],
sortname : "dsgid",
sortorder : "desc",
height : 'auto',
viewrecords : true,
gridview : true,
loadonce : true,
jsonReader : {
root : "rows",
page : "page",
total : "total",
records : "records",
repeatitems : false,
},
autoencode : true,
caption : getLocalMessage('water.connsize.gridTtl')
});
jQuery("#grid").jqGrid('navGrid','#pagered',{edit:false,add:false,del:false,search:true,refresh:false});
$("#pagered_left").css("width", "");
});
function returnEditUrl(cellValue, options, rowdata, action) {
return "<a href='#' return false; class='editClass' value='"+rowdata.cnsId+"' ><img src='css/images/edit.png' width='20px' alt='Edit Charge Master' title='Edit Scrutiny Data' /></a>";
}
function returnViewUrl(cellValue, options, rowdata, action) {
return "<a href='#' return false; class='viewConnectionClass' value='"+rowdata.cnsId+"'><img src='css/images/grid/view-icon.png' width='20px' alt='View Master' title='View Master' /></a>";
}
function returnisdeletedUrl(cellValue, options, rowdata, action) {
if (rowdata.isdeleted == '0') {
return "<a href='#' class='fa fa-check-circle fa-2x green ' value='"+rowdata.isdeleted+"' alt='Designation is Active' title='Designation is Active'></a>";
} else {
return "<a href='#' class='fa fa-times-circle fa-2x red ' value='"+rowdata.isdeleted+"' alt='Designation is INActive' title='Designation is InActive'></a>";
}
}
$(function() {
$(document)
.on('click','.addConnectionClass',function() {
var $link = $(this);
var cnsId = $link.closest('tr').find('td:eq(0)').text();
var url = "TBCcnsizePrm.html?formForUpdate";
var requestData = "cnsId=" + cnsId + "&MODE1=" + "EDIT";
var returnData =__doAjaxRequest(url,'post',requestData,false);
$('.content').html(returnData);
prepareDateTag();
});
});
$(function() {
$(document).on('click', '.editClass', function() {
var $link = $(this);
var cnsId = $link.closest('tr').find('td:eq(0)').text();
var url = "TBCcnsizePrm.html?formForUpdate";
var requestData = "cnsId=" + cnsId + "&MODE1=" + "EDIT";
var returnData =__doAjaxRequest(url,'post',requestData,false);
$('.content').html(returnData);
prepareDateTag();
});
});
$(function() {
$(document).on('click', '.viewConnectionClass', function() {
var $link = $(this);
var cnsId = $link.closest('tr').find('td:eq(0)').text();
var url = "TBCcnsizePrm.html?formForUpdate";
var requestData = "cnsId=" + cnsId + "&MODE1=" + "VIEW";
var returnData =__doAjaxRequest(url,'post',requestData,false);
$('.content').html(returnData);
prepareDateTag();
});
});
/*ADD Form*/
function saveConnectionSizeDetails(obj){
return saveOrUpdateForm(obj, 'Saved Successfully', 'TBCcnsizePrm.html', 'create');
}
function updateConnectionSizeDetails(obj){
return saveOrUpdateForm(obj, 'Saved Successfully', 'TBCcnsizePrm.html', 'update');
}
function showConfirmBox(){
var errMsgDiv = '.msg-dialog-box';
var message='';
var cls = 'Yes';
message +='<p>Record Saved Successfully..</p>';
message +='<p style=\'text-align:center;margin: 5px;\'>'+
'<br/><input type=\'button\' value=\''+cls+'\' id=\'btnNo\' class=\'css_btn \' '+
' onclick="ShowView()"/>'+
'</p>';
$(errMsgDiv).addClass('ok-msg').removeClass('warn-msg');
$(errMsgDiv).html(message);
$(errMsgDiv).show();
$('#btnNo').focus();
showModalBox(errMsgDiv);
}
function ShowView(){
window.location.href='TBCcnsizePrm.html';
}
$(".datepicker").datepicker({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true
});
$(".warning-div ul").each(function () {
var lines = $(this).html().split("<br>");
$(this).html('<li>' + lines.join("</li><li><i class='fa fa-exclamation-circle'></i> ") + '</li>');
});
$('html,body').animate({ scrollTop: 0 }, 'slow'); | abmindiarepomanager/ABMOpenMainet | Mainet1.1/MainetServiceParent/MainetServiceWeb/src/main/webapp/js/masters/connectionsize/connectionSizeScript.js | JavaScript | gpl-3.0 | 5,451 |
/**
* @file Map places of interest
* @author Tom Jenkins [email protected]
*/
module.exports = {
castle: {
title: 'Rowton Castle',
lat: 52.708739,
lng: -2.9228567,
icon: 'pin_castle.png',
main: true,
description: 'Where it all happens! Rowton Castle is a small castle manor house roughly halfway between Shrewsbury and Welshpool.',
link: 'https://rowtoncastle.com'
},
barns: {
title: 'Rowton Barns',
lat: 52.709265,
lng: -2.9255,
icon: 'pin_hotel.png',
description: 'Just a <del>drunken stumble</del> <ins>short stroll</ins> from the castle, Rowton Barns offers rooms in their beautifully converted farm buildings.',
link: 'http://www.rowtonbarns.co.uk/'
},
wollaston: {
title: 'Wollaston Lodge',
lat: 52.7036,
lng: -2.9943,
icon: 'pin_hotel.png',
description: 'A boutique bed and breakfast with individually themed rooms.',
link: 'http://www.wollastonlodge.co.uk/'
},
travelodge: {
title: 'Shrewsbury Travelodge',
lat: 52.6817939,
lng: -2.7645268,
icon: 'pin_hotel.png',
description: 'On Bayston Hill services, with free parking.',
link: 'https://www.travelodge.co.uk/hotels/175/Shrewsbury-Bayston-Hill-hotel'
}
}; | itsravenous/lizandtomgetmarried | src/components/map/places.js | JavaScript | gpl-3.0 | 1,179 |
var struct_create_packets_1_1__2 =
[
[ "angle", "struct_create_packets_1_1__2.html#a425d33bd27790066ff7edb4a608a8149", null ],
[ "buttons", "struct_create_packets_1_1__2.html#a6b7d2d6c0a3a063f873420c010063b33", null ],
[ "distance", "struct_create_packets_1_1__2.html#afb30de28ec41190d0cb278640d4782ab", null ],
[ "ir", "struct_create_packets_1_1__2.html#ac834057741105e898b3d4613b96c6eb1", null ]
]; | kipr/harrogate | shared/client/doc/struct_create_packets_1_1__2.js | JavaScript | gpl-3.0 | 416 |
!function(namespace) {
'use strict';
function Modal(elem, params) {
this.$element = jQuery(elem);
this.params = params || {};
this.cssReadyElement = this.params.cssReadyElement || 'JS-Modal-ready';
this.cssActiveElement = this.params.cssActiveElement || 'JS-Modal-active';
this.__construct();
}
Modal.prototype.__construct = function __construct() {
this.$box = this.$element.find('.JS-Modal-Box');
this.$close = this.$element.find('.JS-Modal-Close');
this.$title = this.$element.find('.JS-Modal-Title');
this.$container = this.$element.find('.JS-Modal-Container');
this._init();
};
Modal.prototype._init = function _init() {
var _this = this;
this.$close.on('click.JS-Modal', function() { _this._close.apply(_this, []); });
$('body').on("keyup", function(e) {
if ((e.keyCode == 27)) {
_this._close.apply(_this, []);
}
});
$('.JS-Gannt-Modal').click(function() {
if (_this.$element.hasClass('JS-Modal-active'))
_this._close.apply(_this, []);
});
$('.JS-Modal-Box').click(function(event){
event.stopPropagation();
});
/* API. Events */
this.$element.on('modal:setContent', function(e, data) { _this.setContent.apply(_this, [data]); });
this.$element.on('modal:open', function() { _this.open.apply(_this, []); });
this.$element.on('modal:close', function() { _this.close.apply(_this, []); });
this.$element.on('modal:clear', function() { _this.clear.apply(_this, []); });
this._ready();
} ;
Modal.prototype._ready = function _ready() {
this.$element
.addClass(this.cssReadyElement)
.addClass('JS-Modal-ready');
};
Modal.prototype._setContent = function _setContent(content) {
this.$container.html(content);
};
Modal.prototype._open = function _open() {
if (!this.$element.hasClass('JS-Modal-active')) {
this.$element
.addClass(this.cssActiveElement)
.addClass('JS-Modal-active')
}
};
Modal.prototype._close = function _close() {
if (this.$element.hasClass('JS-Modal-active')) {
this.$element
.removeClass(this.cssActiveElement)
.removeClass('JS-Modal-active');
}
};
Modal.prototype._clear = function _clear() {
};
/* API. Methods */
Modal.prototype.setContent = function setContent(content) {
if (!arguments.length) {
return false;
}
this._setContent(content);
};
Modal.prototype.open = function open() {
this._open();
};
Modal.prototype.close = function close() {
this._close();
};
Modal.prototype.clear = function clear() {
this._clear();
};
namespace.Modal = Modal;
}(this);
| subuk/bakapy | front/scripts/modal.js | JavaScript | gpl-3.0 | 2,698 |
var __v=[
{
"Id": 3568,
"Panel": 1763,
"Name": "紋理動畫",
"Sort": 0,
"Str": ""
},
{
"Id": 3569,
"Panel": 1763,
"Name": "相關API",
"Sort": 0,
"Str": ""
},
{
"Id": 3570,
"Panel": 1763,
"Name": "Example",
"Sort": 0,
"Str": ""
}
] | zuiwuchang/king-document | data/panels/1763.js | JavaScript | gpl-3.0 | 291 |
var events = require('events'),
koanize = require('koanizer'),
util = require('util');
koanize(this);
// Standard and RFC set these values
var REFERENCE_CLOCK_FREQUENCY = 90000;
// RTP packet constants and masks
var RTP_HEADER_SIZE = 12;
var RTP_FRAGMENTATION_HEADER_SIZE = 4;
var SAMPLES_PER_FRAME = 1152; // ISO 11172-3
var SAMPLING_FREQUENCY = 44100;
var TIMESTAMP_DELTA = Math.floor(SAMPLES_PER_FRAME * REFERENCE_CLOCK_FREQUENCY / SAMPLING_FREQUENCY);
var SECONDS_PER_FRAME = SAMPLES_PER_FRAME / SAMPLING_FREQUENCY;
var RTPProtocol = function(){
events.EventEmitter.call(this);
this.setMarker = false;
this.ssrc = Math.floor(Math.random() * 100000);
this.seqNum = Math.floor(Math.random() * 1000);
this.timestamp = Math.floor(Math.random() * 1000);
};
util.inherits(RTPProtocol, events.EventEmitter);
RTPProtocol.prototype.pack = function(payload){
++this.seqNum;
// RFC3550 says it must increase by the number of samples
// sent in a block in case of CBR audio streaming
this.timestamp += TIMESTAMP_DELTA;
if (!payload) {
// Tried to send a packet, but packet was not ready.
// Timestamp and Sequence Number should be increased
// anyway 'cause interval callback was called and
// that's like sending silence
this.setMarker = true;
return;
}
var RTPPacket = new Buffer(RTP_HEADER_SIZE + RTP_FRAGMENTATION_HEADER_SIZE + payload.length);
// version = 2: 10
// padding = 0: 0
// extension = 0: 0
// CRSCCount = 0: 0000
/*
KOAN #1
should write Version, Padding, Extension and Count
*/
RTPPacket.writeUInt8(128, 0);
// Marker = 0: 0
// RFC 1890: RTP Profile for Audio and Video Conferences with Minimal Control
// Payload = 14: (MPEG Audio Only) 0001110
RTPPacket.writeUInt8(this.setMarker? 142 : 14, 1);
this.setMarker = false;
// SequenceNumber
/*
KOAN #2
should write Sequence Number
*/
RTPPacket.writeUInt16BE(this.seqNum, 2);
// Timestamp
/*
KOAN #3
should write Timestamp...
*/
RTPPacket.writeUInt32BE(this.timestamp, 4);
// SSRC
/*
KOAN #3
...SSRC and...
*/
RTPPacket.writeUInt32BE(this.ssrc, 8);
// RFC 2250: RTP Payload Format for MPEG1/MPEG2 Video
// 3.5 MPEG Audio-specific header
/*
KOAN #3
...payload Format
*/
RTPPacket.writeUInt32BE(0, 12);
payload.copy(RTPPacket, 16);
this.emit('packet', RTPPacket);
//return RTPPacket;
};
module.exports = exports.RTPProtocol = RTPProtocol;
| rfines/NodeKoans | 2_dgram/buffer-koans.js | JavaScript | gpl-3.0 | 2,619 |
var searchData=
[
['handler_5fallocator',['handler_allocator',['../classwebsocketpp_1_1transport_1_1asio_1_1handler__allocator.html',1,'websocketpp::transport::asio']]],
['hash32',['Hash32',['../classnfd_1_1name__tree_1_1Hash32.html',1,'nfd::name_tree']]],
['hash64',['Hash64',['../classnfd_1_1name__tree_1_1Hash64.html',1,'nfd::name_tree']]],
['hash_3c_20ndn_3a_3aname_20_3e',['hash< ndn::Name >',['../structstd_1_1hash_3_01ndn_1_1Name_01_4.html',1,'std']]],
['hash_3c_20ndn_3a_3autil_3a_3aethernet_3a_3aaddress_20_3e',['hash< ndn::util::ethernet::Address >',['../structstd_1_1hash_3_01ndn_1_1util_1_1ethernet_1_1Address_01_4.html',1,'std']]],
['hashable',['Hashable',['../classndn_1_1Hashable.html',1,'ndn']]],
['header',['Header',['../classndn_1_1lp_1_1field__location__tags_1_1Header.html',1,'ndn::lp::field_location_tags']]],
['hierarchicalchecker',['HierarchicalChecker',['../classndn_1_1security_1_1conf_1_1HierarchicalChecker.html',1,'ndn::security::conf']]],
['hijacker',['Hijacker',['../classns3_1_1Hijacker.html',1,'ns3']]],
['httpexception',['HttpException',['../classHttpException.html',1,'']]],
['hybi00',['hybi00',['../classwebsocketpp_1_1processor_1_1hybi00.html',1,'websocketpp::processor']]],
['hybi00_3c_20stub_5fconfig_20_3e',['hybi00< stub_config >',['../classwebsocketpp_1_1processor_1_1hybi00.html',1,'websocketpp::processor']]],
['hybi07',['hybi07',['../classwebsocketpp_1_1processor_1_1hybi07.html',1,'websocketpp::processor']]],
['hybi08',['hybi08',['../classwebsocketpp_1_1processor_1_1hybi08.html',1,'websocketpp::processor']]],
['hybi13',['hybi13',['../classwebsocketpp_1_1processor_1_1hybi13.html',1,'websocketpp::processor']]],
['hybi13_3c_20stub_5fconfig_20_3e',['hybi13< stub_config >',['../classwebsocketpp_1_1processor_1_1hybi13.html',1,'websocketpp::processor']]],
['hybi13_3c_20stub_5fconfig_5fext_20_3e',['hybi13< stub_config_ext >',['../classwebsocketpp_1_1processor_1_1hybi13.html',1,'websocketpp::processor']]],
['hyperkeylocatornamechecker',['HyperKeyLocatorNameChecker',['../classndn_1_1security_1_1conf_1_1HyperKeyLocatorNameChecker.html',1,'ndn::security::conf']]]
];
| nsol-nmsu/ndnSIM | docs/icens/html/search/classes_7.js | JavaScript | gpl-3.0 | 2,179 |
// Search script generated by doxygen
// Copyright (C) 2009 by Dimitri van Heesch.
// The code in this file is loosly based on main.js, part of Natural Docs,
// which is Copyright (C) 2003-2008 Greg Valure
// Natural Docs is licensed under the GPL.
var indexSectionsWithContent =
{
0: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111001110111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
1: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011010000001010110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
2: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111100010001110111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
3: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111001110111101010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
4: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000101111111001110111110111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
5: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010010000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
6: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011110000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
7: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "files",
3: "functions",
4: "variables",
5: "typedefs",
6: "defines",
7: "pages"
};
function convertToId(search)
{
var result = '';
for (i=0;i<search.length;i++)
{
var c = search.charAt(i);
var cn = c.charCodeAt(0);
if (c.match(/[a-z0-9]/))
{
result+=c;
}
else if (cn<16)
{
result+="_0"+cn.toString(16);
}
else
{
result+="_"+cn.toString(16);
}
}
return result;
}
function getXPos(item)
{
var x = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
x += item.offsetLeft;
item = item.offsetParent;
}
}
return x;
}
function getYPos(item)
{
var y = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
y += item.offsetTop;
item = item.offsetParent;
}
}
return y;
}
/* A class handling everything associated with the search panel.
Parameters:
name - The name of the global variable that will be
storing this instance. Is needed to be able to set timeouts.
resultPath - path to use for external files
*/
function SearchBox(name, resultsPath, inFrame, label)
{
if (!name || !resultsPath) { alert("Missing parameters to SearchBox."); }
// ---------- Instance variables
this.name = name;
this.resultsPath = resultsPath;
this.keyTimeout = 0;
this.keyTimeoutLength = 500;
this.closeSelectionTimeout = 300;
this.lastSearchValue = "";
this.lastResultsPage = "";
this.hideTimeout = 0;
this.searchIndex = 0;
this.searchActive = false;
this.insideFrame = inFrame;
this.searchLabel = label;
// ----------- DOM Elements
this.DOMSearchField = function()
{ return document.getElementById("MSearchField"); }
this.DOMSearchSelect = function()
{ return document.getElementById("MSearchSelect"); }
this.DOMSearchSelectWindow = function()
{ return document.getElementById("MSearchSelectWindow"); }
this.DOMPopupSearchResults = function()
{ return document.getElementById("MSearchResults"); }
this.DOMPopupSearchResultsWindow = function()
{ return document.getElementById("MSearchResultsWindow"); }
this.DOMSearchClose = function()
{ return document.getElementById("MSearchClose"); }
this.DOMSearchBox = function()
{ return document.getElementById("MSearchBox"); }
// ------------ Event Handlers
// Called when focus is added or removed from the search field.
this.OnSearchFieldFocus = function(isActive)
{
this.Activate(isActive);
}
this.OnSearchSelectShow = function()
{
var searchSelectWindow = this.DOMSearchSelectWindow();
var searchField = this.DOMSearchSelect();
if (this.insideFrame)
{
var left = getXPos(searchField);
var top = getYPos(searchField);
left += searchField.offsetWidth + 6;
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
left -= searchSelectWindow.offsetWidth;
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
else
{
var left = getXPos(searchField);
var top = getYPos(searchField);
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
// stop selection hide timer
if (this.hideTimeout)
{
clearTimeout(this.hideTimeout);
this.hideTimeout=0;
}
return false; // to avoid "image drag" default event
}
this.OnSearchSelectHide = function()
{
this.hideTimeout = setTimeout(this.name +".CloseSelectionWindow()",
this.closeSelectionTimeout);
}
// Called when the content of the search field is changed.
this.OnSearchFieldChange = function(evt)
{
if (this.keyTimeout) // kill running timer
{
clearTimeout(this.keyTimeout);
this.keyTimeout = 0;
}
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 || e.keyCode==13)
{
if (e.shiftKey==1)
{
this.OnSearchSelectShow();
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
child.focus();
return;
}
}
return;
}
else if (window.frames.MSearchResults.searchResults)
{
var elem = window.frames.MSearchResults.searchResults.NavNext(0);
if (elem) elem.focus();
}
}
else if (e.keyCode==27) // Escape out of the search field
{
this.DOMSearchField().blur();
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
this.Activate(false);
return;
}
// strip whitespaces
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue != this.lastSearchValue) // search value has changed
{
if (searchValue != "") // non-empty search
{
// set timer for search update
this.keyTimeout = setTimeout(this.name + '.Search()',
this.keyTimeoutLength);
}
else // empty search field
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
}
}
}
this.SelectItemCount = function(id)
{
var count=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
count++;
}
}
return count;
}
this.SelectItemSet = function(id)
{
var i,j=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
var node = child.firstChild;
if (j==id)
{
node.innerHTML='•';
}
else
{
node.innerHTML=' ';
}
j++;
}
}
}
// Called when an search filter selection is made.
// set item with index id as the active item
this.OnSelectItem = function(id)
{
this.searchIndex = id;
this.SelectItemSet(id);
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue!="" && this.searchActive) // something was found -> do a search
{
this.Search();
}
}
this.OnSearchSelectKey = function(evt)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 && this.searchIndex<this.SelectItemCount()) // Down
{
this.searchIndex++;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==38 && this.searchIndex>0) // Up
{
this.searchIndex--;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==13 || e.keyCode==27)
{
this.OnSelectItem(this.searchIndex);
this.CloseSelectionWindow();
this.DOMSearchField().focus();
}
return false;
}
// --------- Actions
// Closes the results window.
this.CloseResultsWindow = function()
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.Activate(false);
}
this.CloseSelectionWindow = function()
{
this.DOMSearchSelectWindow().style.display = 'none';
}
// Performs a search.
this.Search = function()
{
this.keyTimeout = 0;
// strip leading whitespace
var searchValue = this.DOMSearchField().value.replace(/^ +/, "");
var code = searchValue.toLowerCase().charCodeAt(0);
var hexCode;
if (code<16)
{
hexCode="0"+code.toString(16);
}
else
{
hexCode=code.toString(16);
}
var resultsPage;
var resultsPageWithSearch;
var hasResultsPage;
if (indexSectionsWithContent[this.searchIndex].charAt(code) == '1')
{
resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html';
resultsPageWithSearch = resultsPage+'?'+escape(searchValue);
hasResultsPage = true;
}
else // nothing available for this search term
{
resultsPage = this.resultsPath + '/nomatches.html';
resultsPageWithSearch = resultsPage;
hasResultsPage = false;
}
window.frames.MSearchResults.location = resultsPageWithSearch;
var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow();
if (domPopupSearchResultsWindow.style.display!='block')
{
var domSearchBox = this.DOMSearchBox();
this.DOMSearchClose().style.display = 'inline';
if (this.insideFrame)
{
var domPopupSearchResults = this.DOMPopupSearchResults();
domPopupSearchResultsWindow.style.position = 'relative';
domPopupSearchResultsWindow.style.display = 'block';
var width = document.body.clientWidth - 8; // the -8 is for IE :-(
domPopupSearchResultsWindow.style.width = width + 'px';
domPopupSearchResults.style.width = width + 'px';
}
else
{
var domPopupSearchResults = this.DOMPopupSearchResults();
var left = getXPos(domSearchBox) + 150; // domSearchBox.offsetWidth;
var top = getYPos(domSearchBox) + 20; // domSearchBox.offsetHeight + 1;
domPopupSearchResultsWindow.style.display = 'block';
left -= domPopupSearchResults.offsetWidth;
domPopupSearchResultsWindow.style.top = top + 'px';
domPopupSearchResultsWindow.style.left = left + 'px';
}
}
this.lastSearchValue = searchValue;
this.lastResultsPage = resultsPage;
}
// -------- Activation Functions
// Activates or deactivates the search panel, resetting things to
// their default values if necessary.
this.Activate = function(isActive)
{
if (isActive || // open it
this.DOMPopupSearchResultsWindow().style.display == 'block'
)
{
this.DOMSearchBox().className = 'MSearchBoxActive';
var searchField = this.DOMSearchField();
if (searchField.value == this.searchLabel) // clear "Search" term upon entry
{
searchField.value = '';
this.searchActive = true;
}
}
else if (!isActive) // directly remove the panel
{
this.DOMSearchBox().className = 'MSearchBoxInactive';
this.DOMSearchField().value = this.searchLabel;
this.searchActive = false;
this.lastSearchValue = ''
this.lastResultsPage = '';
}
}
}
// -----------------------------------------------------------------------
// The class that handles everything on the search results page.
function SearchResults(name)
{
// The number of matches from the last run of <Search()>.
this.lastMatchCount = 0;
this.lastKey = 0;
this.repeatOn = false;
// Toggles the visibility of the passed element ID.
this.FindChildElement = function(id)
{
var parentElement = document.getElementById(id);
var element = parentElement.firstChild;
while (element && element!=parentElement)
{
if (element.nodeName == 'DIV' && element.className == 'SRChildren')
{
return element;
}
if (element.nodeName == 'DIV' && element.hasChildNodes())
{
element = element.firstChild;
}
else if (element.nextSibling)
{
element = element.nextSibling;
}
else
{
do
{
element = element.parentNode;
}
while (element && element!=parentElement && !element.nextSibling);
if (element && element!=parentElement)
{
element = element.nextSibling;
}
}
}
}
this.Toggle = function(id)
{
var element = this.FindChildElement(id);
if (element)
{
if (element.style.display == 'block')
{
element.style.display = 'none';
}
else
{
element.style.display = 'block';
}
}
}
// Searches for the passed string. If there is no parameter,
// it takes it from the URL query.
//
// Always returns true, since other documents may try to call it
// and that may or may not be possible.
this.Search = function(search)
{
if (!search) // get search word from URL
{
search = window.location.search;
search = search.substring(1); // Remove the leading '?'
search = unescape(search);
}
search = search.replace(/^ +/, ""); // strip leading spaces
search = search.replace(/ +$/, ""); // strip trailing spaces
search = search.toLowerCase();
search = convertToId(search);
var resultRows = document.getElementsByTagName("div");
var matches = 0;
var i = 0;
while (i < resultRows.length)
{
var row = resultRows.item(i);
if (row.className == "SRResult")
{
var rowMatchName = row.id.toLowerCase();
rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_'
if (search.length<=rowMatchName.length &&
rowMatchName.substr(0, search.length)==search)
{
row.style.display = 'block';
matches++;
}
else
{
row.style.display = 'none';
}
}
i++;
}
document.getElementById("Searching").style.display='none';
if (matches == 0) // no results
{
document.getElementById("NoMatches").style.display='block';
}
else // at least one result
{
document.getElementById("NoMatches").style.display='none';
}
this.lastMatchCount = matches;
return true;
}
// return the first item with index index or higher that is visible
this.NavNext = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index++;
}
return focusItem;
}
this.NavPrev = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index--;
}
return focusItem;
}
this.ProcessKeys = function(e)
{
if (e.type == "keydown")
{
this.repeatOn = false;
this.lastKey = e.keyCode;
}
else if (e.type == "keypress")
{
if (!this.repeatOn)
{
if (this.lastKey) this.repeatOn = true;
return false; // ignore first keypress after keydown
}
}
else if (e.type == "keyup")
{
this.lastKey = 0;
this.repeatOn = false;
}
return this.lastKey!=0;
}
this.Nav = function(evt,itemIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
var newIndex = itemIndex-1;
var focusItem = this.NavPrev(newIndex);
if (focusItem)
{
var child = this.FindChildElement(focusItem.parentNode.parentNode.id);
if (child && child.style.display == 'block') // children visible
{
var n=0;
var tmpElem;
while (1) // search for last child
{
tmpElem = document.getElementById('Item'+newIndex+'_c'+n);
if (tmpElem)
{
focusItem = tmpElem;
}
else // found it!
{
break;
}
n++;
}
}
}
if (focusItem)
{
focusItem.focus();
}
else // return focus to search field
{
parent.document.getElementById("MSearchField").focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = itemIndex+1;
var focusItem;
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem && elem.style.display == 'block') // children visible
{
focusItem = document.getElementById('Item'+itemIndex+'_c0');
}
if (!focusItem) focusItem = this.NavNext(newIndex);
if (focusItem) focusItem.focus();
}
else if (this.lastKey==39) // Right
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'block';
}
else if (this.lastKey==37) // Left
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'none';
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
this.NavChild = function(evt,itemIndex,childIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
if (childIndex>0)
{
var newIndex = childIndex-1;
document.getElementById('Item'+itemIndex+'_c'+newIndex).focus();
}
else // already at first child, jump to parent
{
document.getElementById('Item'+itemIndex).focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = childIndex+1;
var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex);
if (!elem) // last child, jump to parent next parent
{
elem = this.NavNext(itemIndex+1);
}
if (elem)
{
elem.focus();
}
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
}
function setKeyActions(elem,action)
{
elem.setAttribute('onkeydown',action);
elem.setAttribute('onkeypress',action);
elem.setAttribute('onkeyup',action);
}
function setClassAttr(elem,attr)
{
elem.setAttribute('class',attr);
elem.setAttribute('className',attr);
}
function createResults()
{
var results = document.getElementById("SRResults");
for (var e=0; e<searchData.length; e++)
{
var id = searchData[e][0];
var srResult = document.createElement('div');
srResult.setAttribute('id','SR_'+id);
setClassAttr(srResult,'SRResult');
var srEntry = document.createElement('div');
setClassAttr(srEntry,'SREntry');
var srLink = document.createElement('a');
srLink.setAttribute('id','Item'+e);
setKeyActions(srLink,'return searchResults.Nav(event,'+e+')');
setClassAttr(srLink,'SRSymbol');
srLink.innerHTML = searchData[e][1][0];
srEntry.appendChild(srLink);
if (searchData[e][1].length==2) // single result
{
srLink.setAttribute('href',searchData[e][1][1][0]);
if (searchData[e][1][1][1])
{
srLink.setAttribute('target','_parent');
}
var srScope = document.createElement('span');
setClassAttr(srScope,'SRScope');
srScope.innerHTML = searchData[e][1][1][2];
srEntry.appendChild(srScope);
}
else // multiple results
{
srLink.setAttribute('href','javascript:searchResults.Toggle("SR_'+id+'")');
var srChildren = document.createElement('div');
setClassAttr(srChildren,'SRChildren');
for (var c=0; c<searchData[e][1].length-1; c++)
{
var srChild = document.createElement('a');
srChild.setAttribute('id','Item'+e+'_c'+c);
setKeyActions(srChild,'return searchResults.NavChild(event,'+e+','+c+')');
setClassAttr(srChild,'SRScope');
srChild.setAttribute('href',searchData[e][1][c+1][0]);
if (searchData[e][1][c+1][1])
{
srChild.setAttribute('target','_parent');
}
srChild.innerHTML = searchData[e][1][c+1][2];
srChildren.appendChild(srChild);
}
srEntry.appendChild(srChildren);
}
srResult.appendChild(srEntry);
results.appendChild(srResult);
}
}
| hungly/Pacman | html/search/search.js | JavaScript | gpl-3.0 | 24,120 |
var __v=[
{
"Id": 2046,
"Chapter": 630,
"Name": "c++",
"Sort": 0
}
] | zuiwuchang/king-document | data/chapters/630.js | JavaScript | gpl-3.0 | 85 |
import React from 'react';
import { mount } from 'enzyme';
import { Link, HashRouter as Router } from 'react-router-dom';
import { Button } from 'react-bootstrap';
import BackHomeButton from '../BackHomeButton';
describe('<BackHomeButton/>', () => {
it('<BackHomeButton /> should render <Router/>', () => {
const component = mount(<BackHomeButton />);
expect(component.find(Router)).toHaveLength(1);
});
it('<BackHomeButton /> should render <Link/> with correct props', () => {
const component = mount(<BackHomeButton />);
expect(component.find(Router)).toHaveLength(1);
expect(component.find(Link)).toHaveLength(1);
const props = component.find(Link).props();
expect(props).toEqual({ to: '/', children: expect.anything() });
expect(component.find(Link)).toHaveLength(1);
});
it('<BackHomeButton /> should render <Button/> with correct props', () => {
const component = mount(<BackHomeButton />);
expect(component.find(Router)).toHaveLength(1);
expect(component.find(Link)).toHaveLength(1);
expect(component.find(Button)).toHaveLength(1);
const ButtonProps = component.find(Button).props();
expect(ButtonProps).toEqual({
variant: 'primary',
children: 'Back Home',
active: false,
disabled: false,
type: 'button',
});
});
});
| gcallah/Indra | webapp/src/components/__tests__/BackHomeButton.test.js | JavaScript | gpl-3.0 | 1,329 |
'use strict';
var Ose = require('ose');
var M = Ose.class(module, './index');
/** Docs {{{1
* @submodule bb.pagelet
*/
/**
* @caption Dashboard pagelet
*
* @readme
* Pagelet for creating dashboard content.
*
* @class bb.lib.pagelet.dashboard
* @type class
* @extends bb.lib.pagelet
*/
// Public {{{1
exports.loadData = function(cb) { // {{{2
/**
* Has a new list widget created and appends it to the main pagelet
* element. It also calls the "Ose.ui.dashboard()"
* method. "Ose.ui.dashboard()" governs what is diaplayed on the
* dashboard.
*
* @method loadData
*/
if (cb) {
this.doAfterDisplay = cb;
}
this.$('header').html('Dashboard');
this.$()
.empty()
.append(this.newWidget('list', 'list'))
;
if (Ose.ui.configData.dashboard) {
this.addContents(Ose.ui.configData.dashboard);
}
if (Ose.ui.dashboard) {
Ose.ui.dashboard(this, this.afterDisplay.bind(this));
} else {
this.afterDisplay();
}
};
exports.addContent = function(caption, stateObj) { // {{{2
/**
* Adds an item to the dashboard.
*
* @param caption {String} Text to be displayed
* @param stateObj {Object} State object that should be displayed when the user taps on this item.
*/
return this.addItem(caption, Ose.ui.bindContent(stateObj));
};
exports.addContents = function(data) { // {{{2
/**
* Adds items to the dashboard.
*
* @param data {Array} Array of items
*/
for (var i = 0; i < data.length; i++) {
var item = data[i];
this.addContent(item.caption, item.data);
}
};
exports.addItem = function(caption, onTap) { // {{{2
/**
* Adds an item to the dashboard.
*
* @param caption {String} Text to be displayed
* @param onTap {Function} Function to be called when the user taps on this item.
*/
return this.$('list > ul').append(
this.newWidget('listItem', null, {
tap: onTap,
caption: caption
})
);
};
exports.addPagelet = function(params, cb) { // {{{2
/**
* Adds an item to the dashboardk.
*
* @param caption {String} Text to be displayed
* @param cb {Function} Function to be called when the user taps on this item.
*/
var result = this.newPagelet(params);
$('<li>')
.append(result.html())
.appendTo(this.$('list > ul'))
;
result.loadData();
cb(); // TODO Send "cb" to loadData.
return result;
};
exports.verifyStateObj = function(data) { // {{{2
/**
* Verifies that data correspond to the displayed pagelet.
*
* @param data {Object} State object to be compared
*
* @returns {Boolean} Whether data correspond to the displayed pagelet
* @method verifyStateObj
*/
return data.pagelet === 'dashboard';
};
// }}}1
| FredRooks/ose-bb | lib/pagelet/dashboard.js | JavaScript | gpl-3.0 | 2,656 |
var express = require('express'),
router = express.Router(),
adminModel = require('../models/adminModel'),
moment = require('moment'),
helperFun = require('../lib/helperFunc'),
md5 = require('md5');
router
.get('',function (request,response){
adminModel.find({},{"__v" : 0, "password" : 0, "emailCode" : 0},function (err,result){
if(err){
return response.status(500).send({"message" : "Internal Server Error" , "err" : err}).end();
}
response.status(200).send(result).end();
})
})
.post('/login',function (request,response){
var username = request.body.username;
var password = md5(request.body.password);
if((username == null || '') || (password == '' || null)){
return response.status(400).send({'message' : 'Parameters are missing'}).end();
}
adminModel.findOne({ $and:[ {'username':username}, {'password':password}]}, function (err,admin){
if(err){
return response.status(500).send({'message' : 'Internal Server error. Please try again later','err' :err}).end();
}
if(admin == null){
return response.status(400).send({'message' : 'Invalid Username OR Password'}).end();
}
response.status(200).send(admin).end();
})
})
.post('/update',function (request,response){
var adminObj = request.body.admin;
if(adminObj == null){
return response.status(400).send({'message' : 'Parameters are missing'}).end();
}
adminModel.findOne({"_id" : adminObj._id,'password' : md5(adminObj.password)},function (err,admin){
if(err){
return response.status(500).send({'message' : 'Internal Server error. Please try again later','err' :err}).end();
}
if(admin == null){
return response.status(400).send({'message' : 'Invalid Password'}).end();
}
admin.password = md5(adminObj.password);
admin.username = adminObj.username;
admin.firstName = adminObj.firstName;
admin.lastName = adminObj.lastName;
admin.email = adminObj.email;
admin.save(function (error,adminNew){
if(error){
return response.status(500).send({'message' : 'Internal Server error. Please try again later','err' :err}).end();
}
response.status(200).send(adminNew).end();
})
})
})
.post('/addAdmin', function (request,response){
var admin = request.body.admin;
if(admin == null || ''){
return response.status(400).send({'message' : 'Parameters are missing'}).end();
}
admin.password = md5(admin.password);
// admin.createdOn = moment().format('MM-DD-YYYY hh:mm a');
var newAdmin = new adminModel(admin);
newAdmin.save(function (err,result){
if(err){
return response.status(500).send({'message' : 'Internal Server error. Please try again later','err' :err}).end();
}
response.status(200).send(result).end();
});
})
module.exports = router; | adeeldev/courts | routers/adminRouter.js | JavaScript | gpl-3.0 | 2,766 |
Ember.Handlebars.helper('headTitle', function(title) {
Ember.$('head').find('title').text(title);
}, 'title'); | therabble/yahara | app/helpers/head-title.js | JavaScript | gpl-3.0 | 112 |
/**
* JSONDB - JSON Database Manager
*
* Manage JSON files as databases with JSONDB Query Language (JQL)
*
* This content is released under the GPL License (GPL-3.0)
*
* Copyright (c) 2016, Centers Technologies
*
* @package JSONDB
* @author Nana Axel
* @copyright Copyright (c) 2016, Centers Technologies
* @license http://spdx.org/licenses/GPL-3.0 GPL License
* @filesource
*/
/**
* Class Cache
*
* @package Database
* @subpackage Utilities
* @category Cache
* @author Nana Axel
*/
var Cache = (function () {
function Cache() { }
/**
* Cache array
* @access private
* @static {object}
*/
Cache.cache = {};
/**
* Gets cached data
* @param {object|string} path The path to the table
* @return {object|*}
*/
Cache.prototype.get = function (path) {
if (typeof path === "object") {
var results = [];
for (var id in path) {
results.push(this.get(id));
}
return results;
}
if (!Cache.cache.hasOwnProperty(path)) {
var Util = new (require('./Util'))();
Cache.cache[path] = Util.getTableData(path);
}
return Cache.cache[path];
};
/**
* Updates the cached data for a table
* @param {string} path The path to the table
* @param {object|null} data The data to cache
* @return {object}
*/
Cache.prototype.update = function (path, data) {
data = data || null;
if (null !== data) {
Cache.cache[path] = data;
} else {
var Util = new (require('./Util'))();
Cache.cache[path] = Util.getTableData(path);
}
};
/**
* Resets the cache
* @return Cache
*/
Cache.prototype.reset = function () {
Cache.cache = {};
return this;
};
return Cache;
})();
// Exports the module
module.exports = new Cache();
| na2axl/jsondb-js | src/Cache.js | JavaScript | gpl-3.0 | 1,980 |
// port.js
class SingleData {
constructor (port, order, type, value) {
this.port = port
this.order = order
this.type = type
this.value = value
}
}
export let inputVariables = []
export let countVariables = []
// Add a new port
export function Add (countInputPort) {
countInputPort++
inputVariables[countInputPort] = []
countVariables[countInputPort] = 0
$('div#inputPortList').append(
`<div class="list-group-item list-group-item-action" data-toggle="modal"
data-target="#addNewModal${countInputPort}" id="inputPort${countInputPort}">
Port ${countInputPort}</div>`
)
$(`#inputPort${countInputPort}`).click(function () {
portDetail(countInputPort)
})
return true
}
// Show Details of Port
export function portDetail (countInputPort) {
let container = ''
let order = countVariables[countInputPort]
// Show exist variables
for (let variable of inputVariables[countInputPort]) {
container += `<li class="list-group-item list-group-item-action">
<p class="mb-1 float-left text-primary">${variable.order + 1} </p>
<p class="mb-1 float-left variable-type"><label class="variable-type" order="${variable.order}">
${variable.type}</label> </p>
<p class="mb-1 float-left">
<input type="text" class="form-control variable-value" order="${variable.order}" value="${variable.value}">
</p>
</li>`
}
// Show variables list
$('div#modalArea').html(
`<div class="modal fade" id="addNewModal${countInputPort}" tabindex="-1" role="dialog"
aria-labelledby="addNewModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addNewModalLabel">Port ${countInputPort}</h5>
<button class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-row" id="globalDt">
<select class="form-control col-md-7 mx-sm-3 mb-3" id="dt">
<option value="Numeric">Numeric</option>
<option value="Character">Character</option>
<option value="Enumeration">Enumeration</option>
<option value="Boolean">Boolean</option>
<option value="Set">Set</option>
<option value="Sequence">Sequence</option>
<option value="String">String</option>
<option value="Composite">Composite</option>
<option value="Product">Product</option>
<option value="Map">Map</option>
<option value="Union">Union</option>
<option value="Class">Class</option>
</select>
<button class="btn btn-outline-primary col-md-4 mb-3" id="addVariable">Add</button>
</div>
<!-- list of data types -->
<div>
<ul class="list-group" id="variables">
${container}
</ul>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="savePort">Save changes</button>
<button class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>`
)
// Add a new variables
$('button#addVariable').click(function () {
let selectedValue = $('select#dt').val()
console.log(order)
$('ul#variables').append(
`<li class="list-group-item list-group-item-action">
<p class="mb-1 float-left text-primary">${order + 1} </p>
<p class="mb-1 float-left variable-type"><label class="variable-type" order=${order}>
${selectedValue}</label> </p>
<p class="mb-1 float-left">
<input type="text" class="form-control variable-value" order="${order}" placeholder="${selectedValue}">
</p>
</li>`
)
order++
})
// Save port
$('button#savePort').click(function () {
let i
for (i = 0; i < order; i++) {
let type = $(`label.variable-type[order$="${i}"]`).text()
let value = $(`input.variable-value[order$="${i}"]`).val()
// console.log(type + '\n' + value)
inputVariables[countInputPort][i] = new SingleData(countInputPort, i, type, value)
console.log(`saved:
port: ${countInputPort}
order: ${i}
type: ${type}
value: ${value}`)
}
countVariables[countInputPort] = i
console.log('total: ' + countVariables[countInputPort])
})
}
export function Update (id, value) {
let editId = 'div#' + id
$(editId).text(value)
}
| cy92830/DataTypeGUI | src/scripts/port1.js | JavaScript | gpl-3.0 | 4,832 |
function createDownloadLink(data,filename,componentId){
let a = document.createElement('a');
a.href = 'data:' + data;
a.download = filename;
a.innerHTML = 'Export';
a.class = 'btn'
let container = document.getElementById(componentId);
container.appendChild(a);
}
function closest(array, num) {
let i = 0;
let minDiff = 1000;
let ans;
for (i in array) {
let m = Math.abs(num - array[i]);
if (m < minDiff) {
minDiff = m;
ans = array[i];
}
}
return ans;
}
export {createDownloadLink, closest} | alvcarmona/efficiencycalculatorweb | effcalculator/frontend/assets/js/utils.js | JavaScript | gpl-3.0 | 678 |
/*
* Copyright (C) 2015 Max Planck Institute for Psycholinguistics
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
function init_cmdi() {
$("a.toggle").click(function () {
$(this).parent().parent().toggleClass('collapsed');
$(this).parent().parent().toggleClass('expanded');
});
}
function expand_highlighted_cmdi() {
$(".searchword").parents('.IMDI_group.cmdi').removeClass('collapsed');
$(".searchword").parents('.IMDI_group.cmdi').addClass('expanded');
}
$(document).ready(init_cmdi);
| TheLanguageArchive/ASV | metadata-browser-hybrid/src/main/java/nl/mpi/metadatabrowser/services/cmdi/impl/res/cmdi2html.js | JavaScript | gpl-3.0 | 1,134 |
/**
Template Controllers
@module Templates
*/
/**
The execute contract template
@class [template] elements_executeContract
@constructor
*/
Template['elements_executeContract'].onCreated(function(){
var template = this;
// Set Defaults
TemplateVar.set('sending', false);
// show execute part if its a custom contract
if(CustomContracts.findOne({address: template.data.address}))
TemplateVar.set('executionVisible', true);
// check address for code
web3.eth.getCode(template.data.address, function(e, code) {
if(!e && code.length > 2) {
TemplateVar.set(template, 'hasCode', true);
}
});
});
Template['elements_executeContract'].helpers({
/**
Reruns when the data context changes
@method (reactiveContext)
*/
'reactiveContext': function() {
var contractInstance = web3.eth.contract(this.jsonInterface).at(this.address);
var contractFunctions = [];
var contractConstants = [];
_.each(this.jsonInterface, function(func, i){
func = _.clone(func);
// Walk throught the jsonInterface and extract functions and constants
if(func.type == 'function') {
func.contractInstance = contractInstance;
func.inputs = _.map(func.inputs, Helpers.createTemplateDataFromInput);
if(func.constant){
// if it's a constant
contractConstants.push(func);
} else {
//if its a variable
contractFunctions.push(func);
}
}
});
TemplateVar.set('contractConstants', contractConstants);
TemplateVar.set('contractFunctions', contractFunctions);
}
});
Template['elements_executeContract'].events({
/**
Select a contract function
@event 'change .select-contract-function
*/
'change .select-contract-function': function(e, template){
TemplateVar.set('executeData', null);
// change the inputs and data field
TemplateVar.set('selectedFunction', _.find(TemplateVar.get('contractFunctions'), function(contract){
return contract.name === e.currentTarget.value;
}));
Tracker.afterFlush(function(){
$('.abi-input').trigger('change');
});
},
/**
Click the show hide button
@event click .toggle-visibility
*/
'click .toggle-visibility': function(){
TemplateVar.set('executionVisible', !TemplateVar.get('executionVisible'));
}
});
/**
The contract constants template
@class [template] elements_executeContract_constant
@constructor
*/
/**
Formats the values for display
@method formatOutput
*/
var formatOutput = function(val) {
if(_.isArray(val))
return _.map(val, formatOutput);
else {
// stringify boolean
if(_.isBoolean(val))
val = val ? 'YES' : 'NO';
// convert bignumber objects
val = (_.isObject(val) && val.toString)
? val.toString(10)
: val;
return val;
}
};
Template['elements_executeContract_constant'].onCreated(function(){
var template = this;
// initialize our input data prior to the first call
TemplateVar.set('inputs', _.map(template.data.inputs, function(input) {
return Helpers.addInputValue([input], input, {})[0];
}));
// call the contract functions when data changes and on new blocks
this.autorun(function() {
// make reactive to the latest block
EthBlocks.latest;
// get args for the constant function
var args = TemplateVar.get('inputs') || [];
// add callback
args.push(function(e, r) {
if(!e) {
var outputs = [];
// single return value
if(template.data.outputs.length === 1) {
template.data.outputs[0].value = r;
outputs.push(template.data.outputs[0]);
// multiple return values
} else {
outputs = _.map(template.data.outputs, function(output, i) {
output.value = r[i];
return output;
});
}
TemplateVar.set(template, 'outputs', outputs);
}
});
template.data.contractInstance[template.data.name].apply(null, args);
});
});
Template['elements_executeContract_constant'].helpers({
/**
Formats the value if its a big number or array
@method (value)
*/
'value': function() {
return _.isArray(this.value) ? formatOutput(this.value) : [formatOutput(this.value)];
},
/**
Figures out extra data
@method (extra)
*/
'extra': function() {
var data = formatOutput(this); // 1000000000
if (data > 1400000000 && data < 1800000000 && Math.floor(data/1000) != data/1000) {
return '(' + moment(data*1000).fromNow() + ')';
}
if (data == 'YES') {
return '<span class="icon icon-check"></span>';
} else if (data == 'NO') {
return '<span class="icon icon-ban"></span>'
}
return;
}
});
Template['elements_executeContract_constant'].events({
/**
React on user input on the constant functions
@event change .abi-input, input .abi-input
*/
'change .abi-input, input .abi-input': function(e, template) {
var inputs = Helpers.addInputValue(template.data.inputs, this, e.currentTarget);
TemplateVar.set('inputs', inputs);
}
});
/**
The contract function template
@class [template] elements_executeContract_function
@constructor
*/
Template['elements_executeContract_function'].onCreated(function(){
var template = this;
// change the amount when the currency unit is changed
template.autorun(function(c){
var unit = EthTools.getUnit();
if(!c.firstRun) {
TemplateVar.set('amount', EthTools.toWei(template.find('input[name="amount"]').value.replace(',','.'), unit));
}
});
});
Template['elements_executeContract_function'].onRendered(function(){
// Run all inputs through formatter to catch bools
this.$('.abi-input').trigger('change');
});
Template['elements_executeContract_function'].helpers({
'reactiveDataContext': function(){
if(this.inputs.length === 0)
TemplateVar.set('executeData', this.contractInstance[this.name].getData());
}
});
Template['elements_executeContract_function'].events({
/**
Set the amount while typing
@event keyup input[name="amount"], change input[name="amount"], input input[name="amount"]
*/
'keyup input[name="amount"], change input[name="amount"], input input[name="amount"]': function(e, template){
var wei = EthTools.toWei(e.currentTarget.value.replace(',','.'));
TemplateVar.set('amount', wei || '0');
},
/**
React on user input on the execute functions
@event change .abi-input, input .abi-input
*/
'change .abi-input, input .abi-input': function(e, template) {
var inputs = Helpers.addInputValue(template.data.inputs, this, e.currentTarget);
TemplateVar.set('executeData', template.data.contractInstance[template.data.name].getData.apply(null, inputs));
},
/**
Executes a transaction on contract
@event click .execute
*/
'click .execute': function(e, template){
var to = template.data.contractInstance.address,
gasPrice = 50000000000,
estimatedGas = undefined, /* (typeof mist == 'undefined')not working */
amount = TemplateVar.get('amount') || 0,
selectedAccount = Helpers.getAccountByAddress(TemplateVar.getFrom('.execute-contract select[name="dapp-select-account"]', 'value')),
data = TemplateVar.get('executeData');
var latestTransaction = Transactions.findOne({}, {sort: {timestamp: -1}});
if (latestTransaction && latestTransaction.gasPrice)
gasPrice = latestTransaction.gasPrice;
if(selectedAccount) {
console.log('Providing gas: ', estimatedGas ,' + 100000');
if(selectedAccount.balance === '0')
return GlobalNotification.warning({
content: 'i18n:wallet.send.error.emptyWallet',
duration: 2
});
// The function to send the transaction
var sendTransaction = function(estimatedGas){
TemplateVar.set('sending', true);
// CONTRACT TX
if(contracts['ct_'+ selectedAccount._id]) {
// Load the accounts owned by user and sort by balance
var accounts = EthAccounts.find({name: {$exists: true}}, {sort: {name: 1}}).fetch();
accounts.sort(Helpers.sortByBalance);
// Looks for them among the wallet account owner
var fromAccount = _.find(accounts, function(acc){
return (selectedAccount.owners.indexOf(acc.address)>=0);
})
contracts['ct_'+ selectedAccount._id].execute.sendTransaction(to || '', amount || '', data || '', {
from: fromAccount.address,
gasPrice: gasPrice,
gas: estimatedGas
}, function(error, txHash){
TemplateVar.set(template, 'sending', false);
console.log(error, txHash);
if(!error) {
console.log('SEND from contract', amount);
addTransactionAfterSend(txHash, amount, selectedAccount.address, to, gasPrice, estimatedGas, data);
FlowRouter.go('dashboard');
} else {
// EthElements.Modal.hide();
GlobalNotification.error({
content: error.message,
duration: 8
});
}
});
// SIMPLE TX
} else {
web3.eth.sendTransaction({
from: selectedAccount.address,
to: to,
data: data,
value: amount,
gasPrice: gasPrice,
gas: estimatedGas
}, function(error, txHash){
TemplateVar.set(template, 'sending', false);
console.log(error, txHash);
if(!error) {
console.log('SEND simple');
addTransactionAfterSend(txHash, amount, selectedAccount.address, to, gasPrice, estimatedGas, data);
// FlowRouter.go('dashboard');
GlobalNotification.success({
content: 'i18n:wallet.send.transactionSent',
duration: 2
});
} else {
// EthElements.Modal.hide();
GlobalNotification.error({
content: error.message,
duration: 8
});
}
});
}
};
sendTransaction(estimatedGas);
}
}
});
| EarthDollar/ed-meteor-dapp-wallet | app/client/templates/elements/executeContract.js | JavaScript | gpl-3.0 | 11,818 |
Subsets and Splits