code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*global ajaxurl, isRtl */
var wpWidgets;
(function($) {
wpWidgets = {
init : function() {
var rem, the_id,
self = this,
chooser = $('.widgets-chooser'),
selectSidebar = chooser.find('.widgets-chooser-sidebars'),
sidebars = $('div.widgets-sortables'),
isRTL = !! ( 'undefined' !== typeof isRtl && isRtl );
$('#widgets-right .sidebar-name').click( function() {
var $this = $(this),
$wrap = $this.closest('.widgets-holder-wrap');
if ( $wrap.hasClass('closed') ) {
$wrap.removeClass('closed');
$this.parent().sortable('refresh');
} else {
$wrap.addClass('closed');
}
});
$('#widgets-left .sidebar-name').click( function() {
$(this).closest('.widgets-holder-wrap').toggleClass('closed');
});
$(document.body).bind('click.widgets-toggle', function(e) {
var target = $(e.target),
css = { 'z-index': 100 },
widget, inside, targetWidth, widgetWidth, margin;
if ( target.parents('.widget-top').length && ! target.parents('#available-widgets').length ) {
widget = target.closest('div.widget');
inside = widget.children('.widget-inside');
targetWidth = parseInt( widget.find('input.widget-width').val(), 10 ),
widgetWidth = widget.parent().width();
if ( inside.is(':hidden') ) {
if ( targetWidth > 250 && ( targetWidth + 30 > widgetWidth ) && widget.closest('div.widgets-sortables').length ) {
if ( widget.closest('div.widget-liquid-right').length ) {
margin = isRTL ? 'margin-right' : 'margin-left';
} else {
margin = isRTL ? 'margin-left' : 'margin-right';
}
css[ margin ] = widgetWidth - ( targetWidth + 30 ) + 'px';
widget.css( css );
}
inside.slideDown('fast');
} else {
inside.slideUp('fast', function() {
widget.attr( 'style', '' );
});
}
e.preventDefault();
} else if ( target.hasClass('widget-control-save') ) {
wpWidgets.save( target.closest('div.widget'), 0, 1, 0 );
e.preventDefault();
} else if ( target.hasClass('widget-control-remove') ) {
wpWidgets.save( target.closest('div.widget'), 1, 1, 0 );
e.preventDefault();
} else if ( target.hasClass('widget-control-close') ) {
wpWidgets.close( target.closest('div.widget') );
e.preventDefault();
}
});
sidebars.children('.widget').each( function() {
var $this = $(this);
wpWidgets.appendTitle( this );
if ( $this.find( 'p.widget-error' ).length ) {
$this.find( 'a.widget-action' ).trigger('click');
}
});
$('#widget-list').children('.widget').draggable({
connectToSortable: 'div.widgets-sortables',
handle: '> .widget-top > .widget-title',
distance: 2,
helper: 'clone',
zIndex: 100,
containment: 'document',
start: function( event, ui ) {
var chooser = $(this).find('.widgets-chooser');
ui.helper.find('div.widget-description').hide();
the_id = this.id;
if ( chooser.length ) {
// Hide the chooser and move it out of the widget
$( '#wpbody-content' ).append( chooser.hide() );
// Delete the cloned chooser from the drag helper
ui.helper.find('.widgets-chooser').remove();
self.clearWidgetSelection();
}
},
stop: function() {
if ( rem ) {
$(rem).hide();
}
rem = '';
}
});
sidebars.sortable({
placeholder: 'widget-placeholder',
items: '> .widget',
handle: '> .widget-top > .widget-title',
cursor: 'move',
distance: 2,
containment: 'document',
start: function( event, ui ) {
var height, $this = $(this),
$wrap = $this.parent(),
inside = ui.item.children('.widget-inside');
if ( inside.css('display') === 'block' ) {
inside.hide();
$(this).sortable('refreshPositions');
}
if ( ! $wrap.hasClass('closed') ) {
// Lock all open sidebars min-height when starting to drag.
// Prevents jumping when dragging a widget from an open sidebar to a closed sidebar below.
height = ui.item.hasClass('ui-draggable') ? $this.height() : 1 + $this.height();
$this.css( 'min-height', height + 'px' );
}
},
stop: function( event, ui ) {
var addNew, widgetNumber, $sidebar, $children, child, item,
$widget = ui.item,
id = the_id;
if ( $widget.hasClass('deleting') ) {
wpWidgets.save( $widget, 1, 0, 1 ); // delete widget
$widget.remove();
return;
}
addNew = $widget.find('input.add_new').val();
widgetNumber = $widget.find('input.multi_number').val();
$widget.attr( 'style', '' ).removeClass('ui-draggable');
the_id = '';
if ( addNew ) {
if ( 'multi' === addNew ) {
$widget.html(
$widget.html().replace( /<[^<>]+>/g, function( tag ) {
return tag.replace( /__i__|%i%/g, widgetNumber );
})
);
$widget.attr( 'id', id.replace( '__i__', widgetNumber ) );
widgetNumber++;
$( 'div#' + id ).find( 'input.multi_number' ).val( widgetNumber );
} else if ( 'single' === addNew ) {
$widget.attr( 'id', 'new-' + id );
rem = 'div#' + id;
}
wpWidgets.save( $widget, 0, 0, 1 );
$widget.find('input.add_new').val('');
$( document ).trigger( 'widget-added', [ $widget ] );
}
$sidebar = $widget.parent();
if ( $sidebar.parent().hasClass('closed') ) {
$sidebar.parent().removeClass('closed');
$children = $sidebar.children('.widget');
// Make sure the dropped widget is at the top
if ( $children.length > 1 ) {
child = $children.get(0);
item = $widget.get(0);
if ( child.id && item.id && child.id !== item.id ) {
$( child ).before( $widget );
}
}
}
if ( addNew ) {
$widget.find( 'a.widget-action' ).trigger('click');
} else {
wpWidgets.saveOrder( $sidebar.attr('id') );
}
},
activate: function() {
$(this).parent().addClass( 'widget-hover' );
},
deactivate: function() {
// Remove all min-height added on "start"
$(this).css( 'min-height', '' ).parent().removeClass( 'widget-hover' );
},
receive: function( event, ui ) {
var $sender = $( ui.sender );
// Don't add more widgets to orphaned sidebars
if ( this.id.indexOf('orphaned_widgets') > -1 ) {
$sender.sortable('cancel');
return;
}
// If the last widget was moved out of an orphaned sidebar, close and remove it.
if ( $sender.attr('id').indexOf('orphaned_widgets') > -1 && ! $sender.children('.widget').length ) {
$sender.parents('.orphan-sidebar').slideUp( 400, function(){ $(this).remove(); } );
}
}
}).sortable( 'option', 'connectWith', 'div.widgets-sortables' );
$('#available-widgets').droppable({
tolerance: 'pointer',
accept: function(o){
return $(o).parent().attr('id') !== 'widget-list';
},
drop: function(e,ui) {
ui.draggable.addClass('deleting');
$('#removing-widget').hide().children('span').html('');
},
over: function(e,ui) {
ui.draggable.addClass('deleting');
$('div.widget-placeholder').hide();
if ( ui.draggable.hasClass('ui-sortable-helper') ) {
$('#removing-widget').show().children('span')
.html( ui.draggable.find('div.widget-title').children('h4').html() );
}
},
out: function(e,ui) {
ui.draggable.removeClass('deleting');
$('div.widget-placeholder').show();
$('#removing-widget').hide().children('span').html('');
}
});
// Area Chooser
$( '#widgets-right .widgets-holder-wrap' ).each( function( index, element ) {
var $element = $( element ),
name = $element.find( '.sidebar-name h3' ).text(),
id = $element.find( '.widgets-sortables' ).attr( 'id' ),
li = $('<li tabindex="0">').text( $.trim( name ) );
if ( index === 0 ) {
li.addClass( 'widgets-chooser-selected' );
}
selectSidebar.append( li );
li.data( 'sidebarId', id );
});
$( '#available-widgets .widget .widget-title' ).on( 'click.widgets-chooser', function() {
var $widget = $(this).closest( '.widget' );
if ( $widget.hasClass( 'widget-in-question' ) || $( '#widgets-left' ).hasClass( 'chooser' ) ) {
self.closeChooser();
} else {
// Open the chooser
self.clearWidgetSelection();
$( '#widgets-left' ).addClass( 'chooser' );
$widget.addClass( 'widget-in-question' ).children( '.widget-description' ).after( chooser );
chooser.slideDown( 300, function() {
selectSidebar.find('.widgets-chooser-selected').focus();
});
selectSidebar.find( 'li' ).on( 'focusin.widgets-chooser', function() {
selectSidebar.find('.widgets-chooser-selected').removeClass( 'widgets-chooser-selected' );
$(this).addClass( 'widgets-chooser-selected' );
} );
}
});
// Add event handlers
chooser.on( 'click.widgets-chooser', function( event ) {
var $target = $( event.target );
if ( $target.hasClass('button-primary') ) {
self.addWidget( chooser );
self.closeChooser();
} else if ( $target.hasClass('button-secondary') ) {
self.closeChooser();
}
}).on( 'keyup.widgets-chooser', function( event ) {
if ( event.which === $.ui.keyCode.ENTER ) {
if ( $( event.target ).hasClass('button-secondary') ) {
// Close instead of adding when pressing Enter on the Cancel button
self.closeChooser();
} else {
self.addWidget( chooser );
self.closeChooser();
}
} else if ( event.which === $.ui.keyCode.ESCAPE ) {
self.closeChooser();
}
});
},
saveOrder : function( sidebarId ) {
var data = {
action: 'widgets-order',
savewidgets: $('#_wpnonce_widgets').val(),
sidebars: []
};
if ( sidebarId ) {
$( '#' + sidebarId ).find('.spinner:first').css('display', 'inline-block');
}
$('div.widgets-sortables').each( function() {
if ( $(this).sortable ) {
data['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(',');
}
});
$.post( ajaxurl, data, function() {
$('.spinner').hide();
});
},
save : function( widget, del, animate, order ) {
var sidebarId = widget.closest('div.widgets-sortables').attr('id'),
data = widget.find('form').serialize(), a;
widget = $(widget);
$('.spinner', widget).show();
a = {
action: 'save-widget',
savewidgets: $('#_wpnonce_widgets').val(),
sidebar: sidebarId
};
if ( del ) {
a.delete_widget = 1;
}
data += '&' + $.param(a);
$.post( ajaxurl, data, function(r) {
var id;
if ( del ) {
if ( ! $('input.widget_number', widget).val() ) {
id = $('input.widget-id', widget).val();
$('#available-widgets').find('input.widget-id').each(function(){
if ( $(this).val() === id ) {
$(this).closest('div.widget').show();
}
});
}
if ( animate ) {
order = 0;
widget.slideUp('fast', function(){
$(this).remove();
wpWidgets.saveOrder();
});
} else {
widget.remove();
}
} else {
$('.spinner').hide();
if ( r && r.length > 2 ) {
$( 'div.widget-content', widget ).html( r );
wpWidgets.appendTitle( widget );
$( document ).trigger( 'widget-updated', [ widget ] );
}
}
if ( order ) {
wpWidgets.saveOrder();
}
});
},
appendTitle : function(widget) {
var title = $('input[id*="-title"]', widget).val() || '';
if ( title ) {
title = ': ' + title.replace(/<[^<>]+>/g, '').replace(/</g, '<').replace(/>/g, '>');
}
$(widget).children('.widget-top').children('.widget-title').children()
.children('.in-widget-title').html(title);
},
close : function(widget) {
widget.children('.widget-inside').slideUp('fast', function() {
widget.attr( 'style', '' );
});
},
addWidget: function( chooser ) {
var widget, widgetId, add, n, viewportTop, viewportBottom, sidebarBounds,
sidebarId = chooser.find( '.widgets-chooser-selected' ).data('sidebarId'),
sidebar = $( '#' + sidebarId );
widget = $('#available-widgets').find('.widget-in-question').clone();
widgetId = widget.attr('id');
add = widget.find( 'input.add_new' ).val();
n = widget.find( 'input.multi_number' ).val();
// Remove the cloned chooser from the widget
widget.find('.widgets-chooser').remove();
if ( 'multi' === add ) {
widget.html(
widget.html().replace( /<[^<>]+>/g, function(m) {
return m.replace( /__i__|%i%/g, n );
})
);
widget.attr( 'id', widgetId.replace( '__i__', n ) );
n++;
$( '#' + widgetId ).find('input.multi_number').val(n);
} else if ( 'single' === add ) {
widget.attr( 'id', 'new-' + widgetId );
$( '#' + widgetId ).hide();
}
// Open the widgets container
sidebar.closest( '.widgets-holder-wrap' ).removeClass('closed');
sidebar.append( widget );
sidebar.sortable('refresh');
wpWidgets.save( widget, 0, 0, 1 );
// No longer "new" widget
widget.find( 'input.add_new' ).val('');
$( document ).trigger( 'widget-added', [ widget ] );
/*
* Check if any part of the sidebar is visible in the viewport. If it is, don't scroll.
* Otherwise, scroll up to so the sidebar is in view.
*
* We do this by comparing the top and bottom, of the sidebar so see if they are within
* the bounds of the viewport.
*/
viewportTop = $(window).scrollTop();
viewportBottom = viewportTop + $(window).height();
sidebarBounds = sidebar.offset();
sidebarBounds.bottom = sidebarBounds.top + sidebar.outerHeight();
if ( viewportTop > sidebarBounds.bottom || viewportBottom < sidebarBounds.top ) {
$( 'html, body' ).animate({
scrollTop: sidebarBounds.top - 130
}, 200 );
}
window.setTimeout( function() {
// Cannot use a callback in the animation above as it fires twice,
// have to queue this "by hand".
widget.find( '.widget-title' ).trigger('click');
}, 250 );
},
closeChooser: function() {
var self = this;
$( '.widgets-chooser' ).slideUp( 200, function() {
$( '#wpbody-content' ).append( this );
self.clearWidgetSelection();
});
},
clearWidgetSelection: function() {
$( '#widgets-left' ).removeClass( 'chooser' );
$( '.widget-in-question' ).removeClass( 'widget-in-question' );
}
};
$(document).ready( function(){ wpWidgets.init(); } );
})(jQuery);
| JavaScript |
/* global isRtl */
(function($) {
var frame;
$( function() {
// Fetch available headers and apply jQuery.masonry
// once the images have loaded.
var $headers = $('.available-headers');
$headers.imagesLoaded( function() {
$headers.masonry({
itemSelector: '.default-header',
isRTL: !! ( 'undefined' != typeof isRtl && isRtl )
});
});
// Build the choose from library frame.
$('#choose-from-library-link').click( function( event ) {
var $el = $(this);
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create the media frame.
frame = wp.media.frames.customHeader = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Tell the modal to show only images.
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first(),
link = $el.data('updateLink');
// Tell the browser to navigate to the crop step.
window.location = link + '&file=' + attachment.id;
});
frame.open();
});
});
}(jQuery));
| JavaScript |
/* global ajaxurl */
var postboxes;
(function($) {
postboxes = {
add_postbox_toggles : function(page, args) {
var self = this;
self.init(page, args);
$('.postbox h3, .postbox .handlediv').bind('click.postboxes', function() {
var p = $(this).parent('.postbox'), id = p.attr('id');
if ( 'dashboard_browser_nag' == id )
return;
p.toggleClass('closed');
if ( page != 'press-this' )
self.save_state(page);
if ( id ) {
if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) )
self.pbshow(id);
else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) )
self.pbhide(id);
}
});
$('.postbox h3 a').click( function(e) {
e.stopPropagation();
});
$( '.postbox a.dismiss' ).bind( 'click.postboxes', function() {
var hide_id = $(this).parents('.postbox').attr('id') + '-hide';
$( '#' + hide_id ).prop('checked', false).triggerHandler('click');
return false;
});
$('.hide-postbox-tog').bind('click.postboxes', function() {
var box = $(this).val();
if ( $(this).prop('checked') ) {
$('#' + box).show();
if ( $.isFunction( postboxes.pbshow ) )
self.pbshow( box );
} else {
$('#' + box).hide();
if ( $.isFunction( postboxes.pbhide ) )
self.pbhide( box );
}
self.save_state(page);
self._mark_area();
});
$('.columns-prefs input[type="radio"]').bind('click.postboxes', function(){
var n = parseInt($(this).val(), 10);
if ( n ) {
self._pb_edit(n);
self.save_order(page);
}
});
},
init : function(page, args) {
var isMobile = $(document.body).hasClass('mobile');
$.extend( this, args || {} );
$('#wpbody-content').css('overflow','hidden');
$('.meta-box-sortables').sortable({
placeholder: 'sortable-placeholder',
connectWith: '.meta-box-sortables',
items: '.postbox',
handle: '.hndle',
cursor: 'move',
delay: ( isMobile ? 200 : 0 ),
distance: 2,
tolerance: 'pointer',
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
stop: function() {
if ( $(this).find('#dashboard_browser_nag').is(':visible') && 'dashboard_browser_nag' != this.firstChild.id ) {
$(this).sortable('cancel');
return;
}
postboxes.save_order(page);
},
receive: function(e,ui) {
if ( 'dashboard_browser_nag' == ui.item[0].id )
$(ui.sender).sortable('cancel');
postboxes._mark_area();
}
});
if ( isMobile ) {
$(document.body).bind('orientationchange.postboxes', function(){ postboxes._pb_change(); });
this._pb_change();
}
this._mark_area();
},
save_state : function(page) {
var closed = $('.postbox').filter('.closed').map(function() { return this.id; }).get().join(','),
hidden = $('.postbox').filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(ajaxurl, {
action: 'closed-postboxes',
closed: closed,
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: page
});
},
save_order : function(page) {
var postVars, page_columns = $('.columns-prefs input:checked').val() || 0;
postVars = {
action: 'meta-box-order',
_ajax_nonce: $('#meta-box-order-nonce').val(),
page_columns: page_columns,
page: page
};
$('.meta-box-sortables').each( function() {
postVars[ 'order[' + this.id.split( '-' )[0] + ']' ] = $( this ).sortable( 'toArray' ).join( ',' );
} );
$.post( ajaxurl, postVars );
},
_mark_area : function() {
var visible = $('div.postbox:visible').length, side = $('#post-body #side-sortables');
$( '#dashboard-widgets .meta-box-sortables:visible' ).each( function() {
var t = $(this);
if ( visible == 1 || t.children('.postbox:visible').length )
t.removeClass('empty-container');
else
t.addClass('empty-container');
});
if ( side.length ) {
if ( side.children('.postbox:visible').length )
side.removeClass('empty-container');
else if ( $('#postbox-container-1').css('width') == '280px' )
side.addClass('empty-container');
}
},
_pb_edit : function(n) {
var el = $('.metabox-holder').get(0);
if ( el ) {
el.className = el.className.replace(/columns-\d+/, 'columns-' + n);
}
},
_pb_change : function() {
var check = $( 'label.columns-prefs-1 input[type="radio"]' );
switch ( window.orientation ) {
case 90:
case -90:
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
break;
case 0:
case 180:
if ( $('#poststuff').length ) {
this._pb_edit(1);
} else {
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
}
break;
}
},
/* Callbacks */
pbshow : false,
pbhide : false
};
}(jQuery));
| JavaScript |
/* global inlineEditL10n, ajaxurl */
var inlineEditTax;
(function($) {
inlineEditTax = {
init : function() {
var t = this, row = $('#inline-edit');
t.type = $('#the-list').attr('data-wp-lists').substr(5);
t.what = '#'+t.type+'-';
$('#the-list').on('click', 'a.editinline', function(){
inlineEditTax.edit(this);
return false;
});
// prepare the edit row
row.keyup( function( e ) {
if ( e.which === 27 ) {
return inlineEditTax.revert();
}
});
$( 'a.cancel', row ).click( function() {
return inlineEditTax.revert();
});
$( 'a.save', row ).click( function() {
return inlineEditTax.save(this);
});
$( 'input, select', row ).keydown( function( e ) {
if ( e.which === 13 ) {
return inlineEditTax.save( this );
}
});
$( '#posts-filter input[type="submit"]' ).mousedown( function() {
t.revert();
});
},
toggle : function(el) {
var t = this;
$(t.what+t.getId(el)).css('display') === 'none' ? t.revert() : t.edit(el);
},
edit : function(id) {
var editRow, rowData,
t = this;
t.revert();
if ( typeof(id) === 'object' ) {
id = t.getId(id);
}
editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $( t.what + id ).hasClass( 'alternate' ) ) {
$(editRow).addClass('alternate');
}
$(t.what+id).hide().after(editRow);
$(':input[name="name"]', editRow).val( $('.name', rowData).text() );
$(':input[name="slug"]', editRow).val( $('.slug', rowData).text() );
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).eq(0).focus();
return false;
},
save : function(id) {
var params, fields, tax = $('input[name="taxonomy"]').val() || '';
if( typeof(id) === 'object' ) {
id = this.getId(id);
}
$('table.widefat .spinner').show();
params = {
action: 'inline-save-tax',
tax_type: this.type,
tax_ID: id,
taxonomy: tax
};
fields = $('#edit-'+id).find(':input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post( ajaxurl, params,
function(r) {
var row, new_id;
$('table.widefat .spinner').hide();
if (r) {
if ( -1 !== r.indexOf( '<tr' ) ) {
$(inlineEditTax.what+id).remove();
new_id = $(r).attr('id');
$('#edit-'+id).before(r).remove();
row = new_id ? $('#'+new_id) : $(inlineEditTax.what+id);
row.hide().fadeIn();
} else {
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
}
} else {
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
if ( $( row ).prev( 'tr' ).hasClass( 'alternate' ) ) {
$(row).removeClass('alternate');
}
}
);
return false;
},
revert : function() {
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .spinner').hide();
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
return false;
},
getId : function(o) {
var id = o.tagName === 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditTax.init();});
})(jQuery);
| JavaScript |
/* global ajaxurl, wpAjax */
(function($) {
var fs = {add:'ajaxAdd',del:'ajaxDel',dim:'ajaxDim',process:'process',recolor:'recolor'}, wpList;
wpList = {
settings: {
url: ajaxurl, type: 'POST',
response: 'ajax-response',
what: '',
alt: 'alternate', altOffset: 0,
addColor: null, delColor: null, dimAddColor: null, dimDelColor: null,
confirm: null,
addBefore: null, addAfter: null,
delBefore: null, delAfter: null,
dimBefore: null, dimAfter: null
},
nonce: function(e,s) {
var url = wpAjax.unserialize(e.attr('href'));
return s.nonce || url._ajax_nonce || $('#' + s.element + ' input[name="_ajax_nonce"]').val() || url._wpnonce || $('#' + s.element + ' input[name="_wpnonce"]').val() || 0;
},
parseData: function(e,t) {
var d = [], wpListsData;
try {
wpListsData = $(e).attr('data-wp-lists') || '';
wpListsData = wpListsData.match(new RegExp(t+':[\\S]+'));
if ( wpListsData )
d = wpListsData[0].split(':');
} catch(r) {}
return d;
},
pre: function(e,s,a) {
var bg, r;
s = $.extend( {}, this.wpList.settings, {
element: null,
nonce: 0,
target: e.get(0)
}, s || {} );
if ( $.isFunction( s.confirm ) ) {
if ( 'add' != a ) {
bg = $('#' + s.element).css('backgroundColor');
$('#' + s.element).css('backgroundColor', '#FF9966');
}
r = s.confirm.call(this, e, s, a, bg);
if ( 'add' != a )
$('#' + s.element).css('backgroundColor', bg );
if ( !r )
return false;
}
return s;
},
ajaxAdd: function( e, s ) {
e = $(e);
s = s || {};
var list = this, data = wpList.parseData(e,'add'), es, valid, formData, res, rres;
s = wpList.pre.call( list, e, s, 'add' );
s.element = data[2] || e.attr( 'id' ) || s.element || null;
if ( data[3] )
s.addColor = '#' + data[3];
else
s.addColor = s.addColor || '#FFFF33';
if ( !s )
return false;
if ( !e.is('[id="' + s.element + '-submit"]') )
return !wpList.add.call( list, e, s );
if ( !s.element )
return true;
s.action = 'add-' + s.what;
s.nonce = wpList.nonce(e,s);
es = $('#' + s.element + ' :input').not('[name="_ajax_nonce"], [name="_wpnonce"], [name="action"]');
valid = wpAjax.validateForm( '#' + s.element );
if ( !valid )
return false;
s.data = $.param( $.extend( { _ajax_nonce: s.nonce, action: s.action }, wpAjax.unserialize( data[4] || '' ) ) );
formData = $.isFunction(es.fieldSerialize) ? es.fieldSerialize() : es.serialize();
if ( formData )
s.data += '&' + formData;
if ( $.isFunction(s.addBefore) ) {
s = s.addBefore( s );
if ( !s )
return true;
}
if ( !s.data.match(/_ajax_nonce=[a-f0-9]+/) )
return true;
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors )
return false;
if ( true === res )
return true;
jQuery.each( res.responses, function() {
wpList.add.call( list, this.data, $.extend( {}, s, { // this.firstChild.nodevalue
pos: this.position || 0,
id: this.id || 0,
oldId: this.oldId || null
} ) );
} );
list.wpList.recolor();
$(list).trigger( 'wpListAddEnd', [ s, list.wpList ] );
wpList.clear.call(list,'#' + s.element);
};
s.complete = function(x, st) {
if ( $.isFunction(s.addAfter) ) {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.addAfter( rres, _s );
}
};
$.ajax( s );
return false;
},
ajaxDel: function( e, s ) {
e = $(e);
s = s || {};
var list = this, data = wpList.parseData(e,'delete'), element, res, rres;
s = wpList.pre.call( list, e, s, 'delete' );
s.element = data[2] || s.element || null;
if ( data[3] )
s.delColor = '#' + data[3];
else
s.delColor = s.delColor || '#faa';
if ( !s || !s.element )
return false;
s.action = 'delete-' + s.what;
s.nonce = wpList.nonce(e,s);
s.data = $.extend(
{ action: s.action, id: s.element.split('-').pop(), _ajax_nonce: s.nonce },
wpAjax.unserialize( data[4] || '' )
);
if ( $.isFunction(s.delBefore) ) {
s = s.delBefore( s, list );
if ( !s )
return true;
}
if ( !s.data._ajax_nonce )
return true;
element = $('#' + s.element);
if ( 'none' != s.delColor ) {
element.css( 'backgroundColor', s.delColor ).fadeOut( 350, function(){
list.wpList.recolor();
$(list).trigger( 'wpListDelEnd', [ s, list.wpList ] );
});
} else {
list.wpList.recolor();
$(list).trigger( 'wpListDelEnd', [ s, list.wpList ] );
}
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors ) {
element.stop().stop().css( 'backgroundColor', '#faa' ).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } );
return false;
}
};
s.complete = function(x, st) {
if ( $.isFunction(s.delAfter) ) {
element.queue( function() {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.delAfter( rres, _s );
}).dequeue();
}
};
$.ajax( s );
return false;
},
ajaxDim: function( e, s ) {
if ( $(e).parent().css('display') == 'none' ) // Prevent hidden links from being clicked by hotkeys
return false;
e = $(e);
s = s || {};
var list = this, data = wpList.parseData(e,'dim'), element, isClass, color, dimColor, res, rres;
s = wpList.pre.call( list, e, s, 'dim' );
s.element = data[2] || s.element || null;
s.dimClass = data[3] || s.dimClass || null;
if ( data[4] )
s.dimAddColor = '#' + data[4];
else
s.dimAddColor = s.dimAddColor || '#FFFF33';
if ( data[5] )
s.dimDelColor = '#' + data[5];
else
s.dimDelColor = s.dimDelColor || '#FF3333';
if ( !s || !s.element || !s.dimClass )
return true;
s.action = 'dim-' + s.what;
s.nonce = wpList.nonce(e,s);
s.data = $.extend(
{ action: s.action, id: s.element.split('-').pop(), dimClass: s.dimClass, _ajax_nonce : s.nonce },
wpAjax.unserialize( data[6] || '' )
);
if ( $.isFunction(s.dimBefore) ) {
s = s.dimBefore( s );
if ( !s )
return true;
}
element = $('#' + s.element);
isClass = element.toggleClass(s.dimClass).is('.' + s.dimClass);
color = wpList.getColor( element );
element.toggleClass( s.dimClass );
dimColor = isClass ? s.dimAddColor : s.dimDelColor;
if ( 'none' != dimColor ) {
element
.animate( { backgroundColor: dimColor }, 'fast' )
.queue( function() { element.toggleClass(s.dimClass); $(this).dequeue(); } )
.animate( { backgroundColor: color }, { complete: function() {
$(this).css( 'backgroundColor', '' );
$(list).trigger( 'wpListDimEnd', [ s, list.wpList ] );
}
});
} else {
$(list).trigger( 'wpListDimEnd', [ s, list.wpList ] );
}
if ( !s.data._ajax_nonce )
return true;
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors ) {
element.stop().stop().css( 'backgroundColor', '#FF3333' )[isClass?'removeClass':'addClass'](s.dimClass).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } );
return false;
}
};
s.complete = function(x, st) {
if ( $.isFunction(s.dimAfter) ) {
element.queue( function() {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.dimAfter( rres, _s );
}).dequeue();
}
};
$.ajax( s );
return false;
},
getColor: function( el ) {
var color = jQuery(el).css('backgroundColor');
return color || '#ffffff';
},
add: function( e, s ) {
if ( 'string' == typeof e ) {
e = $( $.trim( e ) ); // Trim leading whitespaces
} else {
e = $( e );
}
var list = $(this), old = false, _s = { pos: 0, id: 0, oldId: null }, ba, ref, color;
if ( 'string' == typeof s )
s = { what: s };
s = $.extend(_s, this.wpList.settings, s);
if ( !e.size() || !s.what )
return false;
if ( s.oldId )
old = $('#' + s.what + '-' + s.oldId);
if ( s.id && ( s.id != s.oldId || !old || !old.size() ) )
$('#' + s.what + '-' + s.id).remove();
if ( old && old.size() ) {
old.before(e);
old.remove();
} else if ( isNaN(s.pos) ) {
ba = 'after';
if ( '-' == s.pos.substr(0,1) ) {
s.pos = s.pos.substr(1);
ba = 'before';
}
ref = list.find( '#' + s.pos );
if ( 1 === ref.size() )
ref[ba](e);
else
list.append(e);
} else if ( 'comment' != s.what || 0 === $('#' + s.element).length ) {
if ( s.pos < 0 ) {
list.prepend(e);
} else {
list.append(e);
}
}
if ( s.alt ) {
if ( ( list.children(':visible').index( e[0] ) + s.altOffset ) % 2 ) { e.removeClass( s.alt ); }
else { e.addClass( s.alt ); }
}
if ( 'none' != s.addColor ) {
color = wpList.getColor( e );
e.css( 'backgroundColor', s.addColor ).animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); } } );
}
list.each( function() { this.wpList.process( e ); } );
return e;
},
clear: function(e) {
var list = this, t, tag;
e = $(e);
if ( list.wpList && e.parents( '#' + list.id ).size() )
return;
e.find(':input').each( function() {
if ( $(this).parents('.form-no-clear').size() )
return;
t = this.type.toLowerCase();
tag = this.tagName.toLowerCase();
if ( 'text' == t || 'password' == t || 'textarea' == tag )
this.value = '';
else if ( 'checkbox' == t || 'radio' == t )
this.checked = false;
else if ( 'select' == tag )
this.selectedIndex = null;
});
},
process: function(el) {
var list = this,
$el = $(el || document);
$el.delegate( 'form[data-wp-lists^="add:' + list.id + ':"]', 'submit', function(){
return list.wpList.add(this);
});
$el.delegate( 'a[data-wp-lists^="add:' + list.id + ':"], input[data-wp-lists^="add:' + list.id + ':"]', 'click', function(){
return list.wpList.add(this);
});
$el.delegate( '[data-wp-lists^="delete:' + list.id + ':"]', 'click', function(){
return list.wpList.del(this);
});
$el.delegate( '[data-wp-lists^="dim:' + list.id + ':"]', 'click', function(){
return list.wpList.dim(this);
});
},
recolor: function() {
var list = this, items, eo;
if ( !list.wpList.settings.alt )
return;
items = $('.list-item:visible', list);
if ( !items.size() )
items = $(list).children(':visible');
eo = [':even',':odd'];
if ( list.wpList.settings.altOffset % 2 )
eo.reverse();
items.filter(eo[0]).addClass(list.wpList.settings.alt).end().filter(eo[1]).removeClass(list.wpList.settings.alt);
},
init: function() {
var lists = this;
lists.wpList.process = function(a) {
lists.each( function() {
this.wpList.process(a);
} );
};
lists.wpList.recolor = function() {
lists.each( function() {
this.wpList.recolor();
} );
};
}
};
$.fn.wpList = function( settings ) {
this.each( function() {
var _this = this;
this.wpList = { settings: $.extend( {}, wpList.settings, { what: wpList.parseData(this,'list')[1] || '' }, settings ) };
$.each( fs, function(i,f) { _this.wpList[i] = function( e, s ) { return wpList[f].call( _this, e, s ); }; } );
} );
wpList.init.call(this);
this.wpList.process();
return this;
};
})(jQuery);
| JavaScript |
/*!
* hoverIntent r7 // 2013.03.11 // jQuery 1.9.1+
* http://cherne.net/brian/resources/jquery.hoverIntent.html
*
* You may use hoverIntent under the terms of the MIT license. Basically that
* means you are free to use hoverIntent as long as this header is left intact.
* Copyright 2007, 2013 Brian Cherne
*/
/* hoverIntent is similar to jQuery's built-in "hover" method except that
* instead of firing the handlerIn function immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the event. The handlerOut function is only
* called after a matching handlerIn.
*
* // basic usage ... just like .hover()
* .hoverIntent( handlerIn, handlerOut )
* .hoverIntent( handlerInOut )
*
* // basic usage ... with event delegation!
* .hoverIntent( handlerIn, handlerOut, selector )
* .hoverIntent( handlerInOut, selector )
*
* // using a basic configuration object
* .hoverIntent( config )
*
* @param handlerIn function OR configuration object
* @param handlerOut function OR selector for delegation OR undefined
* @param selector selector OR undefined
* @author Brian Cherne <brian(at)cherne(dot)net>
*/
(function($) {
$.fn.hoverIntent = function(handlerIn,handlerOut,selector) {
// default configuration values
var cfg = {
interval: 100,
sensitivity: 7,
timeout: 0
};
if ( typeof handlerIn === "object" ) {
cfg = $.extend(cfg, handlerIn );
} else if ($.isFunction(handlerOut)) {
cfg = $.extend(cfg, { over: handlerIn, out: handlerOut, selector: selector } );
} else {
cfg = $.extend(cfg, { over: handlerIn, out: handlerIn, selector: handlerOut } );
}
// instantiate variables
// cX, cY = current X and Y position of mouse, updated by mousemove event
// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
var cX, cY, pX, pY;
// A private function for getting mouse position
var track = function(ev) {
cX = ev.pageX;
cY = ev.pageY;
};
// A private function for comparing current and previous mouse position
var compare = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
// compare mouse positions to see if they've crossed the threshold
if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
$(ob).off("mousemove.hoverIntent",track);
// set hoverIntent state to true (so mouseOut can be called)
ob.hoverIntent_s = 1;
return cfg.over.apply(ob,[ev]);
} else {
// set previous coordinates for next time
pX = cX; pY = cY;
// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
}
};
// A private function for delaying the mouseOut function
var delay = function(ev,ob) {
ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
ob.hoverIntent_s = 0;
return cfg.out.apply(ob,[ev]);
};
// A private function for handling mouse 'hovering'
var handleHover = function(e) {
// copy objects to be passed into t (required for event object to be passed in IE)
var ev = jQuery.extend({},e);
var ob = this;
// cancel hoverIntent timer if it exists
if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }
// if e.type == "mouseenter"
if (e.type == "mouseenter") {
// set "previous" X and Y position based on initial entry point
pX = ev.pageX; pY = ev.pageY;
// update "current" X and Y position based on mousemove
$(ob).on("mousemove.hoverIntent",track);
// start polling interval (self-calling timeout) to compare mouse coordinates over time
if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}
// else e.type == "mouseleave"
} else {
// unbind expensive mousemove event
$(ob).off("mousemove.hoverIntent",track);
// if hoverIntent state is true, then call the mouseOut function after the specified delay
if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
}
};
// listen for mouseenter and mouseleave
return this.on({'mouseenter.hoverIntent':handleHover,'mouseleave.hoverIntent':handleHover}, cfg.selector);
};
})(jQuery);
| JavaScript |
/* global adminpage */
// Interim login dialog
(function($){
var wrap, next;
function show() {
var parent = $('#wp-auth-check'),
form = $('#wp-auth-check-form'),
noframe = wrap.find('.wp-auth-fallback-expired'),
frame, loaded = false;
if ( form.length ) {
// Add unload confirmation to counter (frame-busting) JS redirects
$(window).on( 'beforeunload.wp-auth-check', function(e) {
e.originalEvent.returnValue = window.authcheckL10n.beforeunload;
});
frame = $('<iframe id="wp-auth-check-frame" frameborder="0">').attr( 'title', noframe.text() );
frame.load( function() {
var height, body;
loaded = true;
try {
body = $(this).contents().find('body');
height = body.height();
} catch(e) {
wrap.addClass('fallback');
parent.css( 'max-height', '' );
form.remove();
noframe.focus();
return;
}
if ( height ) {
if ( body && body.hasClass('interim-login-success') )
hide();
else
parent.css( 'max-height', height + 40 + 'px' );
} else if ( ! body || ! body.length ) {
// Catch "silent" iframe origin exceptions in WebKit after another page is loaded in the iframe
wrap.addClass('fallback');
parent.css( 'max-height', '' );
form.remove();
noframe.focus();
}
}).attr( 'src', form.data('src') );
$('#wp-auth-check-form').append( frame );
}
wrap.removeClass('hidden');
if ( frame ) {
frame.focus();
// WebKit doesn't throw an error if the iframe fails to load because of "X-Frame-Options: DENY" header.
// Wait for 10 sec. and switch to the fallback text.
setTimeout( function() {
if ( ! loaded ) {
wrap.addClass('fallback');
form.remove();
noframe.focus();
}
}, 10000 );
} else {
noframe.focus();
}
}
function hide() {
$(window).off( 'beforeunload.wp-auth-check' );
// When on the Edit Post screen, speed up heartbeat after the user logs in to quickly refresh nonces
if ( typeof adminpage !== 'undefined' && ( adminpage === 'post-php' || adminpage === 'post-new-php' ) &&
typeof wp !== 'undefined' && wp.heartbeat ) {
wp.heartbeat.connectNow();
}
wrap.fadeOut( 200, function() {
wrap.addClass('hidden').css('display', '');
$('#wp-auth-check-frame').remove();
});
}
function schedule() {
var interval = parseInt( window.authcheckL10n.interval, 10 ) || 180; // in seconds, default 3 min.
next = ( new Date() ).getTime() + ( interval * 1000 );
}
$( document ).on( 'heartbeat-tick.wp-auth-check', function( e, data ) {
if ( 'wp-auth-check' in data ) {
schedule();
if ( ! data['wp-auth-check'] && wrap.hasClass('hidden') ) {
show();
} else if ( data['wp-auth-check'] && ! wrap.hasClass('hidden') ) {
hide();
}
}
}).on( 'heartbeat-send.wp-auth-check', function( e, data ) {
if ( ( new Date() ).getTime() > next ) {
data['wp-auth-check'] = true;
}
}).ready( function() {
schedule();
wrap = $('#wp-auth-check-wrap');
wrap.find('.wp-auth-check-close').on( 'click', function() {
hide();
});
});
}(jQuery));
| JavaScript |
/* global tinymce, wpCookies, autosaveL10n, switchEditors */
// Back-compat
window.autosave = function() {
return true;
};
( function( $, window ) {
function autosave() {
var initialCompareString,
lastTriggerSave = 0,
$document = $(document);
/**
* Returns the data saved in both local and remote autosave
*
* @return object Object containing the post data
*/
function getPostData( type ) {
var post_name, parent_id, data,
time = ( new Date() ).getTime(),
cats = [],
editor = typeof tinymce !== 'undefined' && tinymce.get('content');
// Don't run editor.save() more often than every 3 sec.
// It is resource intensive and might slow down typing in long posts on slow devices.
if ( editor && ! editor.isHidden() && time - 3000 > lastTriggerSave ) {
editor.save();
lastTriggerSave = time;
}
data = {
post_id: $( '#post_ID' ).val() || 0,
post_type: $( '#post_type' ).val() || '',
post_author: $( '#post_author' ).val() || '',
post_title: $( '#title' ).val() || '',
content: $( '#content' ).val() || '',
excerpt: $( '#excerpt' ).val() || ''
};
if ( type === 'local' ) {
return data;
}
$( 'input[id^="in-category-"]:checked' ).each( function() {
cats.push( this.value );
});
data.catslist = cats.join(',');
if ( post_name = $( '#post_name' ).val() ) {
data.post_name = post_name;
}
if ( parent_id = $( '#parent_id' ).val() ) {
data.parent_id = parent_id;
}
if ( $( '#comment_status' ).prop( 'checked' ) ) {
data.comment_status = 'open';
}
if ( $( '#ping_status' ).prop( 'checked' ) ) {
data.ping_status = 'open';
}
if ( $( '#auto_draft' ).val() === '1' ) {
data.auto_draft = '1';
}
return data;
}
// Concatenate title, content and excerpt. Used to track changes when auto-saving.
function getCompareString( postData ) {
if ( typeof postData === 'object' ) {
return ( postData.post_title || '' ) + '::' + ( postData.content || '' ) + '::' + ( postData.excerpt || '' );
}
return ( $('#title').val() || '' ) + '::' + ( $('#content').val() || '' ) + '::' + ( $('#excerpt').val() || '' );
}
function disableButtons() {
$document.trigger('autosave-disable-buttons');
// Re-enable 5 sec later. Just gives autosave a head start to avoid collisions.
setTimeout( enableButtons, 5000 );
}
function enableButtons() {
$document.trigger( 'autosave-enable-buttons' );
}
// Autosave in localStorage
function autosaveLocal() {
var restorePostData, undoPostData, blog_id, post_id, hasStorage, intervalTimer,
lastCompareString,
isSuspended = false;
// Check if the browser supports sessionStorage and it's not disabled
function checkStorage() {
var test = Math.random().toString(),
result = false;
try {
window.sessionStorage.setItem( 'wp-test', test );
result = window.sessionStorage.getItem( 'wp-test' ) === test;
window.sessionStorage.removeItem( 'wp-test' );
} catch(e) {}
hasStorage = result;
return result;
}
/**
* Initialize the local storage
*
* @return mixed False if no sessionStorage in the browser or an Object containing all postData for this blog
*/
function getStorage() {
var stored_obj = false;
// Separate local storage containers for each blog_id
if ( hasStorage && blog_id ) {
stored_obj = sessionStorage.getItem( 'wp-autosave-' + blog_id );
if ( stored_obj ) {
stored_obj = JSON.parse( stored_obj );
} else {
stored_obj = {};
}
}
return stored_obj;
}
/**
* Set the storage for this blog
*
* Confirms that the data was saved successfully.
*
* @return bool
*/
function setStorage( stored_obj ) {
var key;
if ( hasStorage && blog_id ) {
key = 'wp-autosave-' + blog_id;
sessionStorage.setItem( key, JSON.stringify( stored_obj ) );
return sessionStorage.getItem( key ) !== null;
}
return false;
}
/**
* Get the saved post data for the current post
*
* @return mixed False if no storage or no data or the postData as an Object
*/
function getSavedPostData() {
var stored = getStorage();
if ( ! stored || ! post_id ) {
return false;
}
return stored[ 'post_' + post_id ] || false;
}
/**
* Set (save or delete) post data in the storage.
*
* If stored_data evaluates to 'false' the storage key for the current post will be removed
*
* $param stored_data The post data to store or null/false/empty to delete the key
* @return bool
*/
function setData( stored_data ) {
var stored = getStorage();
if ( ! stored || ! post_id ) {
return false;
}
if ( stored_data ) {
stored[ 'post_' + post_id ] = stored_data;
} else if ( stored.hasOwnProperty( 'post_' + post_id ) ) {
delete stored[ 'post_' + post_id ];
} else {
return false;
}
return setStorage( stored );
}
function suspend() {
isSuspended = true;
}
function resume() {
isSuspended = false;
}
/**
* Save post data for the current post
*
* Runs on a 15 sec. interval, saves when there are differences in the post title or content.
* When the optional data is provided, updates the last saved post data.
*
* $param data optional Object The post data for saving, minimum 'post_title' and 'content'
* @return bool
*/
function save( data ) {
var postData, compareString,
result = false;
if ( isSuspended ) {
return false;
}
if ( data ) {
postData = getSavedPostData() || {};
$.extend( postData, data );
} else {
postData = getPostData('local');
}
compareString = getCompareString( postData );
if ( typeof lastCompareString === 'undefined' ) {
lastCompareString = initialCompareString;
}
// If the content, title and excerpt did not change since the last save, don't save again
if ( compareString === lastCompareString ) {
return false;
}
postData.save_time = ( new Date() ).getTime();
postData.status = $( '#post_status' ).val() || '';
result = setData( postData );
if ( result ) {
lastCompareString = compareString;
}
return result;
}
// Run on DOM ready
function run() {
post_id = $('#post_ID').val() || 0;
// Check if the local post data is different than the loaded post data.
if ( $( '#wp-content-wrap' ).hasClass( 'tmce-active' ) ) {
// If TinyMCE loads first, check the post 1.5 sec. after it is ready.
// By this time the content has been loaded in the editor and 'saved' to the textarea.
// This prevents false positives.
$document.on( 'tinymce-editor-init.autosave', function() {
window.setTimeout( function() {
checkPost();
}, 1500 );
});
} else {
checkPost();
}
// Save every 15 sec.
intervalTimer = window.setInterval( save, 15000 );
$( 'form#post' ).on( 'submit.autosave-local', function() {
var editor = typeof tinymce !== 'undefined' && tinymce.get('content'),
post_id = $('#post_ID').val() || 0;
if ( editor && ! editor.isHidden() ) {
// Last onSubmit event in the editor, needs to run after the content has been moved to the textarea.
editor.on( 'submit', function() {
save({
post_title: $( '#title' ).val() || '',
content: $( '#content' ).val() || '',
excerpt: $( '#excerpt' ).val() || ''
});
});
} else {
save({
post_title: $( '#title' ).val() || '',
content: $( '#content' ).val() || '',
excerpt: $( '#excerpt' ).val() || ''
});
}
wpCookies.set( 'wp-saving-post-' + post_id, 'check' );
});
}
// Strip whitespace and compare two strings
function compare( str1, str2 ) {
function removeSpaces( string ) {
return string.toString().replace(/[\x20\t\r\n\f]+/g, '');
}
return ( removeSpaces( str1 || '' ) === removeSpaces( str2 || '' ) );
}
/**
* Check if the saved data for the current post (if any) is different than the loaded post data on the screen
*
* Shows a standard message letting the user restore the post data if different.
*
* @return void
*/
function checkPost() {
var content, post_title, excerpt, $notice,
postData = getSavedPostData(),
cookie = wpCookies.get( 'wp-saving-post-' + post_id );
if ( ! postData ) {
return;
}
if ( cookie ) {
wpCookies.remove( 'wp-saving-post-' + post_id );
if ( cookie === 'saved' ) {
// The post was saved properly, remove old data and bail
setData( false );
return;
}
}
// There is a newer autosave. Don't show two "restore" notices at the same time.
if ( $( '#has-newer-autosave' ).length ) {
return;
}
content = $( '#content' ).val() || '';
post_title = $( '#title' ).val() || '';
excerpt = $( '#excerpt' ).val() || '';
// cookie == 'check' means the post was not saved properly, always show #local-storage-notice
if ( cookie !== 'check' && compare( content, postData.content ) &&
compare( post_title, postData.post_title ) && compare( excerpt, postData.excerpt ) ) {
return;
}
restorePostData = postData;
undoPostData = {
content: content,
post_title: post_title,
excerpt: excerpt
};
$notice = $( '#local-storage-notice' );
$('.wrap h2').first().after( $notice.addClass( 'updated' ).show() );
$notice.on( 'click.autosave-local', function( event ) {
var $target = $( event.target );
if ( $target.hasClass( 'restore-backup' ) ) {
restorePost( restorePostData );
$target.parent().hide();
$(this).find( 'p.undo-restore' ).show();
} else if ( $target.hasClass( 'undo-restore-backup' ) ) {
restorePost( undoPostData );
$target.parent().hide();
$(this).find( 'p.local-restore' ).show();
}
event.preventDefault();
});
}
// Restore the current title, content and excerpt from postData.
function restorePost( postData ) {
var editor;
if ( postData ) {
// Set the last saved data
lastCompareString = getCompareString( postData );
if ( $( '#title' ).val() !== postData.post_title ) {
$( '#title' ).focus().val( postData.post_title || '' );
}
$( '#excerpt' ).val( postData.excerpt || '' );
editor = typeof tinymce !== 'undefined' && tinymce.get('content');
if ( editor && ! editor.isHidden() && typeof switchEditors !== 'undefined' ) {
// Make sure there's an undo level in the editor
editor.undoManager.add();
editor.setContent( postData.content ? switchEditors.wpautop( postData.content ) : '' );
} else {
// Make sure the Text editor is selected
$( '#content-html' ).click();
$( '#content' ).val( postData.content );
}
return true;
}
return false;
}
// Initialize and run checkPost() on loading the script (before TinyMCE init)
blog_id = typeof window.autosaveL10n !== 'undefined' && window.autosaveL10n.blog_id;
// Check if the browser supports sessionStorage and it's not disabled
if ( ! checkStorage() ) {
return;
}
// Don't run if the post type supports neither 'editor' (textarea#content) nor 'excerpt'.
if ( ! blog_id || ( ! $('#content').length && ! $('#excerpt').length ) ) {
return;
}
$document.ready( run );
return {
hasStorage: hasStorage,
getSavedPostData: getSavedPostData,
save: save,
suspend: suspend,
resume: resume
};
}
// Autosave on the server
function autosaveServer() {
var _blockSave, _blockSaveTimer, previousCompareString, lastCompareString,
nextRun = 0,
isSuspended = false;
// Block saving for the next 10 sec.
function tempBlockSave() {
_blockSave = true;
window.clearTimeout( _blockSaveTimer );
_blockSaveTimer = window.setTimeout( function() {
_blockSave = false;
}, 10000 );
}
function suspend() {
isSuspended = true;
}
function resume() {
isSuspended = false;
}
// Runs on heartbeat-response
function response( data ) {
_schedule();
_blockSave = false;
lastCompareString = previousCompareString;
previousCompareString = '';
$document.trigger( 'after-autosave', [data] );
enableButtons();
if ( data.success ) {
// No longer an auto-draft
$( '#auto_draft' ).val('');
}
}
/**
* Save immediately
*
* Resets the timing and tells heartbeat to connect now
*
* @return void
*/
function triggerSave() {
nextRun = 0;
wp.heartbeat.connectNow();
}
/**
* Checks if the post content in the textarea has changed since page load.
*
* This also happens when TinyMCE is active and editor.save() is triggered by
* wp.autosave.getPostData().
*
* @return bool
*/
function postChanged() {
return getCompareString() !== initialCompareString;
}
// Runs on 'heartbeat-send'
function save() {
var postData, compareString;
// window.autosave() used for back-compat
if ( isSuspended || _blockSave || ! window.autosave() ) {
return false;
}
if ( ( new Date() ).getTime() < nextRun ) {
return false;
}
postData = getPostData();
compareString = getCompareString( postData );
// First check
if ( typeof lastCompareString === 'undefined' ) {
lastCompareString = initialCompareString;
}
// No change
if ( compareString === lastCompareString ) {
return false;
}
previousCompareString = compareString;
tempBlockSave();
disableButtons();
$document.trigger( 'wpcountwords', [ postData.content ] )
.trigger( 'before-autosave', [ postData ] );
postData._wpnonce = $( '#_wpnonce' ).val() || '';
return postData;
}
function _schedule() {
nextRun = ( new Date() ).getTime() + ( autosaveL10n.autosaveInterval * 1000 ) || 60000;
}
$document.on( 'heartbeat-send.autosave', function( event, data ) {
var autosaveData = save();
if ( autosaveData ) {
data.wp_autosave = autosaveData;
}
}).on( 'heartbeat-tick.autosave', function( event, data ) {
if ( data.wp_autosave ) {
response( data.wp_autosave );
}
}).on( 'heartbeat-connection-lost.autosave', function( event, error, status ) {
// When connection is lost, keep user from submitting changes.
if ( 'timeout' === error || 603 === status ) {
var $notice = $('#lost-connection-notice');
if ( ! wp.autosave.local.hasStorage ) {
$notice.find('.hide-if-no-sessionstorage').hide();
}
$notice.show();
disableButtons();
}
}).on( 'heartbeat-connection-restored.autosave', function() {
$('#lost-connection-notice').hide();
enableButtons();
}).ready( function() {
_schedule();
});
return {
tempBlockSave: tempBlockSave,
triggerSave: triggerSave,
postChanged: postChanged,
suspend: suspend,
resume: resume
};
}
// Wait for TinyMCE to initialize plus 1 sec. for any external css to finish loading,
// then 'save' to the textarea before setting initialCompareString.
// This avoids any insignificant differences between the initial textarea content and the content
// extracted from the editor.
$document.on( 'tinymce-editor-init.autosave', function( event, editor ) {
if ( editor.id === 'content' ) {
window.setTimeout( function() {
editor.save();
initialCompareString = getCompareString();
}, 1000 );
}
}).ready( function() {
// Set the initial compare string in case TinyMCE is not used or not loaded first
initialCompareString = getCompareString();
});
return {
getPostData: getPostData,
getCompareString: getCompareString,
disableButtons: disableButtons,
enableButtons: enableButtons,
local: autosaveLocal(),
server: autosaveServer()
};
}
window.wp = window.wp || {};
window.wp.autosave = autosave();
}( jQuery, window ));
| JavaScript |
/*
* imgAreaSelect jQuery plugin
* version 0.9.10
*
* Copyright (c) 2008-2013 Michal Wojciechowski (odyniec.net)
*
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://odyniec.net/projects/imgareaselect/
*
*/
(function($) {
/*
* Math functions will be used extensively, so it's convenient to make a few
* shortcuts
*/
var abs = Math.abs,
max = Math.max,
min = Math.min,
round = Math.round;
/**
* Create a new HTML div element
*
* @return A jQuery object representing the new element
*/
function div() {
return $('<div/>');
}
/**
* imgAreaSelect initialization
*
* @param img
* A HTML image element to attach the plugin to
* @param options
* An options object
*/
$.imgAreaSelect = function (img, options) {
var
/* jQuery object representing the image */
$img = $(img),
/* Has the image finished loading? */
imgLoaded,
/* Plugin elements */
/* Container box */
$box = div(),
/* Selection area */
$area = div(),
/* Border (four divs) */
$border = div().add(div()).add(div()).add(div()),
/* Outer area (four divs) */
$outer = div().add(div()).add(div()).add(div()),
/* Handles (empty by default, initialized in setOptions()) */
$handles = $([]),
/*
* Additional element to work around a cursor problem in Opera
* (explained later)
*/
$areaOpera,
/* Image position (relative to viewport) */
left, top,
/* Image offset (as returned by .offset()) */
imgOfs = { left: 0, top: 0 },
/* Image dimensions (as returned by .width() and .height()) */
imgWidth, imgHeight,
/*
* jQuery object representing the parent element that the plugin
* elements are appended to
*/
$parent,
/* Parent element offset (as returned by .offset()) */
parOfs = { left: 0, top: 0 },
/* Base z-index for plugin elements */
zIndex = 0,
/* Plugin elements position */
position = 'absolute',
/* X/Y coordinates of the starting point for move/resize operations */
startX, startY,
/* Horizontal and vertical scaling factors */
scaleX, scaleY,
/* Current resize mode ("nw", "se", etc.) */
resize,
/* Selection area constraints */
minWidth, minHeight, maxWidth, maxHeight,
/* Aspect ratio to maintain (floating point number) */
aspectRatio,
/* Are the plugin elements currently displayed? */
shown,
/* Current selection (relative to parent element) */
x1, y1, x2, y2,
/* Current selection (relative to scaled image) */
selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 },
/* Document element */
docElem = document.documentElement,
/* User agent */
ua = navigator.userAgent,
/* Various helper variables used throughout the code */
$p, d, i, o, w, h, adjusted;
/*
* Translate selection coordinates (relative to scaled image) to viewport
* coordinates (relative to parent element)
*/
/**
* Translate selection X to viewport X
*
* @param x
* Selection X
* @return Viewport X
*/
function viewX(x) {
return x + imgOfs.left - parOfs.left;
}
/**
* Translate selection Y to viewport Y
*
* @param y
* Selection Y
* @return Viewport Y
*/
function viewY(y) {
return y + imgOfs.top - parOfs.top;
}
/*
* Translate viewport coordinates to selection coordinates
*/
/**
* Translate viewport X to selection X
*
* @param x
* Viewport X
* @return Selection X
*/
function selX(x) {
return x - imgOfs.left + parOfs.left;
}
/**
* Translate viewport Y to selection Y
*
* @param y
* Viewport Y
* @return Selection Y
*/
function selY(y) {
return y - imgOfs.top + parOfs.top;
}
/*
* Translate event coordinates (relative to document) to viewport
* coordinates
*/
/**
* Get event X and translate it to viewport X
*
* @param event
* The event object
* @return Viewport X
*/
function evX(event) {
return event.pageX - parOfs.left;
}
/**
* Get event Y and translate it to viewport Y
*
* @param event
* The event object
* @return Viewport Y
*/
function evY(event) {
return event.pageY - parOfs.top;
}
/**
* Get the current selection
*
* @param noScale
* If set to <code>true</code>, scaling is not applied to the
* returned selection
* @return Selection object
*/
function getSelection(noScale) {
var sx = noScale || scaleX, sy = noScale || scaleY;
return { x1: round(selection.x1 * sx),
y1: round(selection.y1 * sy),
x2: round(selection.x2 * sx),
y2: round(selection.y2 * sy),
width: round(selection.x2 * sx) - round(selection.x1 * sx),
height: round(selection.y2 * sy) - round(selection.y1 * sy) };
}
/**
* Set the current selection
*
* @param x1
* X coordinate of the upper left corner of the selection area
* @param y1
* Y coordinate of the upper left corner of the selection area
* @param x2
* X coordinate of the lower right corner of the selection area
* @param y2
* Y coordinate of the lower right corner of the selection area
* @param noScale
* If set to <code>true</code>, scaling is not applied to the
* new selection
*/
function setSelection(x1, y1, x2, y2, noScale) {
var sx = noScale || scaleX, sy = noScale || scaleY;
selection = {
x1: round(x1 / sx || 0),
y1: round(y1 / sy || 0),
x2: round(x2 / sx || 0),
y2: round(y2 / sy || 0)
};
selection.width = selection.x2 - selection.x1;
selection.height = selection.y2 - selection.y1;
}
/**
* Recalculate image and parent offsets
*/
function adjust() {
/*
* Do not adjust if image has not yet loaded or if width is not a
* positive number. The latter might happen when imgAreaSelect is put
* on a parent element which is then hidden.
*/
if (!imgLoaded || !$img.width())
return;
/*
* Get image offset. The .offset() method returns float values, so they
* need to be rounded.
*/
imgOfs = { left: round($img.offset().left), top: round($img.offset().top) };
/* Get image dimensions */
imgWidth = $img.innerWidth();
imgHeight = $img.innerHeight();
imgOfs.top += ($img.outerHeight() - imgHeight) >> 1;
imgOfs.left += ($img.outerWidth() - imgWidth) >> 1;
/* Set minimum and maximum selection area dimensions */
minWidth = round(options.minWidth / scaleX) || 0;
minHeight = round(options.minHeight / scaleY) || 0;
maxWidth = round(min(options.maxWidth / scaleX || 1<<24, imgWidth));
maxHeight = round(min(options.maxHeight / scaleY || 1<<24, imgHeight));
/*
* Workaround for jQuery 1.3.2 incorrect offset calculation, originally
* observed in Safari 3. Firefox 2 is also affected.
*/
if ($().jquery == '1.3.2' && position == 'fixed' &&
!docElem['getBoundingClientRect'])
{
imgOfs.top += max(document.body.scrollTop, docElem.scrollTop);
imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft);
}
/* Determine parent element offset */
parOfs = /absolute|relative/.test($parent.css('position')) ?
{ left: round($parent.offset().left) - $parent.scrollLeft(),
top: round($parent.offset().top) - $parent.scrollTop() } :
position == 'fixed' ?
{ left: $(document).scrollLeft(), top: $(document).scrollTop() } :
{ left: 0, top: 0 };
left = viewX(0);
top = viewY(0);
/*
* Check if selection area is within image boundaries, adjust if
* necessary
*/
if (selection.x2 > imgWidth || selection.y2 > imgHeight)
doResize();
}
/**
* Update plugin elements
*
* @param resetKeyPress
* If set to <code>false</code>, this instance's keypress
* event handler is not activated
*/
function update(resetKeyPress) {
/* If plugin elements are hidden, do nothing */
if (!shown) return;
/*
* Set the position and size of the container box and the selection area
* inside it
*/
$box.css({ left: viewX(selection.x1), top: viewY(selection.y1) })
.add($area).width(w = selection.width).height(h = selection.height);
/*
* Reset the position of selection area, borders, and handles (IE6/IE7
* position them incorrectly if we don't do this)
*/
$area.add($border).add($handles).css({ left: 0, top: 0 });
/* Set border dimensions */
$border
.width(max(w - $border.outerWidth() + $border.innerWidth(), 0))
.height(max(h - $border.outerHeight() + $border.innerHeight(), 0));
/* Arrange the outer area elements */
$($outer[0]).css({ left: left, top: top,
width: selection.x1, height: imgHeight });
$($outer[1]).css({ left: left + selection.x1, top: top,
width: w, height: selection.y1 });
$($outer[2]).css({ left: left + selection.x2, top: top,
width: imgWidth - selection.x2, height: imgHeight });
$($outer[3]).css({ left: left + selection.x1, top: top + selection.y2,
width: w, height: imgHeight - selection.y2 });
w -= $handles.outerWidth();
h -= $handles.outerHeight();
/* Arrange handles */
switch ($handles.length) {
case 8:
$($handles[4]).css({ left: w >> 1 });
$($handles[5]).css({ left: w, top: h >> 1 });
$($handles[6]).css({ left: w >> 1, top: h });
$($handles[7]).css({ top: h >> 1 });
case 4:
$handles.slice(1,3).css({ left: w });
$handles.slice(2,4).css({ top: h });
}
if (resetKeyPress !== false) {
/*
* Need to reset the document keypress event handler -- unbind the
* current handler
*/
if ($.imgAreaSelect.onKeyPress != docKeyPress)
$(document).unbind($.imgAreaSelect.keyPress,
$.imgAreaSelect.onKeyPress);
if (options.keys)
/*
* Set the document keypress event handler to this instance's
* docKeyPress() function
*/
$(document)[$.imgAreaSelect.keyPress](
$.imgAreaSelect.onKeyPress = docKeyPress);
}
/*
* Internet Explorer displays 1px-wide dashed borders incorrectly by
* filling the spaces between dashes with white. Toggling the margin
* property between 0 and "auto" fixes this in IE6 and IE7 (IE8 is still
* broken). This workaround is not perfect, as it requires setTimeout()
* and thus causes the border to flicker a bit, but I haven't found a
* better solution.
*
* Note: This only happens with CSS borders, set with the borderWidth,
* borderOpacity, borderColor1, and borderColor2 options (which are now
* deprecated). Borders created with GIF background images are fine.
*/
if (msie && $border.outerWidth() - $border.innerWidth() == 2) {
$border.css('margin', 0);
setTimeout(function () { $border.css('margin', 'auto'); }, 0);
}
}
/**
* Do the complete update sequence: recalculate offsets, update the
* elements, and set the correct values of x1, y1, x2, and y2.
*
* @param resetKeyPress
* If set to <code>false</code>, this instance's keypress
* event handler is not activated
*/
function doUpdate(resetKeyPress) {
adjust();
update(resetKeyPress);
x1 = viewX(selection.x1); y1 = viewY(selection.y1);
x2 = viewX(selection.x2); y2 = viewY(selection.y2);
}
/**
* Hide or fade out an element (or multiple elements)
*
* @param $elem
* A jQuery object containing the element(s) to hide/fade out
* @param fn
* Callback function to be called when fadeOut() completes
*/
function hide($elem, fn) {
options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide();
}
/**
* Selection area mousemove event handler
*
* @param event
* The event object
*/
function areaMouseMove(event) {
var x = selX(evX(event)) - selection.x1,
y = selY(evY(event)) - selection.y1;
if (!adjusted) {
adjust();
adjusted = true;
$box.one('mouseout', function () { adjusted = false; });
}
/* Clear the resize mode */
resize = '';
if (options.resizable) {
/*
* Check if the mouse pointer is over the resize margin area and set
* the resize mode accordingly
*/
if (y <= options.resizeMargin)
resize = 'n';
else if (y >= selection.height - options.resizeMargin)
resize = 's';
if (x <= options.resizeMargin)
resize += 'w';
else if (x >= selection.width - options.resizeMargin)
resize += 'e';
}
$box.css('cursor', resize ? resize + '-resize' :
options.movable ? 'move' : '');
if ($areaOpera)
$areaOpera.toggle();
}
/**
* Document mouseup event handler
*
* @param event
* The event object
*/
function docMouseUp(event) {
/* Set back the default cursor */
$('body').css('cursor', '');
/*
* If autoHide is enabled, or if the selection has zero width/height,
* hide the selection and the outer area
*/
if (options.autoHide || selection.width * selection.height == 0)
hide($box.add($outer), function () { $(this).hide(); });
$(document).unbind('mousemove', selectingMouseMove);
$box.mousemove(areaMouseMove);
options.onSelectEnd(img, getSelection());
}
/**
* Selection area mousedown event handler
*
* @param event
* The event object
* @return false
*/
function areaMouseDown(event) {
if (event.which != 1) return false;
adjust();
if (resize) {
/* Resize mode is in effect */
$('body').css('cursor', resize + '-resize');
x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']);
y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']);
$(document).mousemove(selectingMouseMove)
.one('mouseup', docMouseUp);
$box.unbind('mousemove', areaMouseMove);
}
else if (options.movable) {
startX = left + selection.x1 - evX(event);
startY = top + selection.y1 - evY(event);
$box.unbind('mousemove', areaMouseMove);
$(document).mousemove(movingMouseMove)
.one('mouseup', function () {
options.onSelectEnd(img, getSelection());
$(document).unbind('mousemove', movingMouseMove);
$box.mousemove(areaMouseMove);
});
}
else
$img.mousedown(event);
return false;
}
/**
* Adjust the x2/y2 coordinates to maintain aspect ratio (if defined)
*
* @param xFirst
* If set to <code>true</code>, calculate x2 first. Otherwise,
* calculate y2 first.
*/
function fixAspectRatio(xFirst) {
if (aspectRatio)
if (xFirst) {
x2 = max(left, min(left + imgWidth,
x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)));
y2 = round(max(top, min(top + imgHeight,
y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))));
x2 = round(x2);
}
else {
y2 = max(top, min(top + imgHeight,
y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)));
x2 = round(max(left, min(left + imgWidth,
x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))));
y2 = round(y2);
}
}
/**
* Resize the selection area respecting the minimum/maximum dimensions and
* aspect ratio
*/
function doResize() {
/*
* Make sure the top left corner of the selection area stays within
* image boundaries (it might not if the image source was dynamically
* changed).
*/
x1 = min(x1, left + imgWidth);
y1 = min(y1, top + imgHeight);
if (abs(x2 - x1) < minWidth) {
/* Selection width is smaller than minWidth */
x2 = x1 - minWidth * (x2 < x1 || -1);
if (x2 < left)
x1 = left + minWidth;
else if (x2 > left + imgWidth)
x1 = left + imgWidth - minWidth;
}
if (abs(y2 - y1) < minHeight) {
/* Selection height is smaller than minHeight */
y2 = y1 - minHeight * (y2 < y1 || -1);
if (y2 < top)
y1 = top + minHeight;
else if (y2 > top + imgHeight)
y1 = top + imgHeight - minHeight;
}
x2 = max(left, min(x2, left + imgWidth));
y2 = max(top, min(y2, top + imgHeight));
fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio);
if (abs(x2 - x1) > maxWidth) {
/* Selection width is greater than maxWidth */
x2 = x1 - maxWidth * (x2 < x1 || -1);
fixAspectRatio();
}
if (abs(y2 - y1) > maxHeight) {
/* Selection height is greater than maxHeight */
y2 = y1 - maxHeight * (y2 < y1 || -1);
fixAspectRatio(true);
}
selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)),
y1: selY(min(y1, y2)), y2: selY(max(y1, y2)),
width: abs(x2 - x1), height: abs(y2 - y1) };
update();
options.onSelectChange(img, getSelection());
}
/**
* Mousemove event handler triggered when the user is selecting an area
*
* @param event
* The event object
* @return false
*/
function selectingMouseMove(event) {
x2 = /w|e|^$/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
y2 = /n|s|^$/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2);
doResize();
return false;
}
/**
* Move the selection area
*
* @param newX1
* New viewport X1
* @param newY1
* New viewport Y1
*/
function doMove(newX1, newY1) {
x2 = (x1 = newX1) + selection.width;
y2 = (y1 = newY1) + selection.height;
$.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2),
y2: selY(y2) });
update();
options.onSelectChange(img, getSelection());
}
/**
* Mousemove event handler triggered when the selection area is being moved
*
* @param event
* The event object
* @return false
*/
function movingMouseMove(event) {
x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width));
y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height));
doMove(x1, y1);
event.preventDefault();
return false;
}
/**
* Start selection
*/
function startSelection() {
$(document).unbind('mousemove', startSelection);
adjust();
x2 = x1;
y2 = y1;
doResize();
resize = '';
if (!$outer.is(':visible'))
/* Show the plugin elements */
$box.add($outer).hide().fadeIn(options.fadeSpeed||0);
shown = true;
$(document).unbind('mouseup', cancelSelection)
.mousemove(selectingMouseMove).one('mouseup', docMouseUp);
$box.unbind('mousemove', areaMouseMove);
options.onSelectStart(img, getSelection());
}
/**
* Cancel selection
*/
function cancelSelection() {
$(document).unbind('mousemove', startSelection)
.unbind('mouseup', cancelSelection);
hide($box.add($outer));
setSelection(selX(x1), selY(y1), selX(x1), selY(y1));
/* If this is an API call, callback functions should not be triggered */
if (!(this instanceof $.imgAreaSelect)) {
options.onSelectChange(img, getSelection());
options.onSelectEnd(img, getSelection());
}
}
/**
* Image mousedown event handler
*
* @param event
* The event object
* @return false
*/
function imgMouseDown(event) {
/* Ignore the event if animation is in progress */
if (event.which != 1 || $outer.is(':animated')) return false;
adjust();
startX = x1 = evX(event);
startY = y1 = evY(event);
/* Selection will start when the mouse is moved */
$(document).mousemove(startSelection).mouseup(cancelSelection);
return false;
}
/**
* Window resize event handler
*/
function windowResize() {
doUpdate(false);
}
/**
* Image load event handler. This is the final part of the initialization
* process.
*/
function imgLoad() {
imgLoaded = true;
/* Set options */
setOptions(options = $.extend({
classPrefix: 'imgareaselect',
movable: true,
parent: 'body',
resizable: true,
resizeMargin: 10,
onInit: function () {},
onSelectStart: function () {},
onSelectChange: function () {},
onSelectEnd: function () {}
}, options));
$box.add($outer).css({ visibility: '' });
if (options.show) {
shown = true;
adjust();
update();
$box.add($outer).hide().fadeIn(options.fadeSpeed||0);
}
/*
* Call the onInit callback. The setTimeout() call is used to ensure
* that the plugin has been fully initialized and the object instance is
* available (so that it can be obtained in the callback).
*/
setTimeout(function () { options.onInit(img, getSelection()); }, 0);
}
/**
* Document keypress event handler
*
* @param event
* The event object
* @return false
*/
var docKeyPress = function(event) {
var k = options.keys, d, t, key = event.keyCode;
d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
!isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
!isNaN(k.shift) && event.shiftKey ? k.shift :
!isNaN(k.arrows) ? k.arrows : 10;
if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
(k.ctrl == 'resize' && event.ctrlKey) ||
(k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
{
/* Resize selection */
switch (key) {
case 37:
/* Left */
d = -d;
case 39:
/* Right */
t = max(x1, x2);
x1 = min(x1, x2);
x2 = max(t + d, x1);
fixAspectRatio();
break;
case 38:
/* Up */
d = -d;
case 40:
/* Down */
t = max(y1, y2);
y1 = min(y1, y2);
y2 = max(t + d, y1);
fixAspectRatio(true);
break;
default:
return;
}
doResize();
}
else {
/* Move selection */
x1 = min(x1, x2);
y1 = min(y1, y2);
switch (key) {
case 37:
/* Left */
doMove(max(x1 - d, left), y1);
break;
case 38:
/* Up */
doMove(x1, max(y1 - d, top));
break;
case 39:
/* Right */
doMove(x1 + min(d, imgWidth - selX(x2)), y1);
break;
case 40:
/* Down */
doMove(x1, y1 + min(d, imgHeight - selY(y2)));
break;
default:
return;
}
}
return false;
};
/**
* Apply style options to plugin element (or multiple elements)
*
* @param $elem
* A jQuery object representing the element(s) to style
* @param props
* An object that maps option names to corresponding CSS
* properties
*/
function styleOptions($elem, props) {
for (var option in props)
if (options[option] !== undefined)
$elem.css(props[option], options[option]);
}
/**
* Set plugin options
*
* @param newOptions
* The new options object
*/
function setOptions(newOptions) {
if (newOptions.parent)
($parent = $(newOptions.parent)).append($box.add($outer));
/* Merge the new options with the existing ones */
$.extend(options, newOptions);
adjust();
if (newOptions.handles != null) {
/* Recreate selection area handles */
$handles.remove();
$handles = $([]);
i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
while (i--)
$handles = $handles.add(div());
/* Add a class to handles and set the CSS properties */
$handles.addClass(options.classPrefix + '-handle').css({
position: 'absolute',
/*
* The font-size property needs to be set to zero, otherwise
* Internet Explorer makes the handles too large
*/
fontSize: 0,
zIndex: zIndex + 1 || 1
});
/*
* If handle width/height has not been set with CSS rules, set the
* default 5px
*/
if (!parseInt($handles.css('width')) >= 0)
$handles.width(5).height(5);
/*
* If the borderWidth option is in use, add a solid border to
* handles
*/
if (o = options.borderWidth)
$handles.css({ borderWidth: o, borderStyle: 'solid' });
/* Apply other style options */
styleOptions($handles, { borderColor1: 'border-color',
borderColor2: 'background-color',
borderOpacity: 'opacity' });
}
/* Calculate scale factors */
scaleX = options.imageWidth / imgWidth || 1;
scaleY = options.imageHeight / imgHeight || 1;
/* Set selection */
if (newOptions.x1 != null) {
setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
newOptions.y2);
newOptions.show = !newOptions.hide;
}
if (newOptions.keys)
/* Enable keyboard support */
options.keys = $.extend({ shift: 1, ctrl: 'resize' },
newOptions.keys);
/* Add classes to plugin elements */
$outer.addClass(options.classPrefix + '-outer');
$area.addClass(options.classPrefix + '-selection');
for (i = 0; i++ < 4;)
$($border[i-1]).addClass(options.classPrefix + '-border' + i);
/* Apply style options */
styleOptions($area, { selectionColor: 'background-color',
selectionOpacity: 'opacity' });
styleOptions($border, { borderOpacity: 'opacity',
borderWidth: 'border-width' });
styleOptions($outer, { outerColor: 'background-color',
outerOpacity: 'opacity' });
if (o = options.borderColor1)
$($border[0]).css({ borderStyle: 'solid', borderColor: o });
if (o = options.borderColor2)
$($border[1]).css({ borderStyle: 'dashed', borderColor: o });
/* Append all the selection area elements to the container box */
$box.append($area.add($border).add($areaOpera)).append($handles);
if (msie) {
if (o = ($outer.css('filter')||'').match(/opacity=(\d+)/))
$outer.css('opacity', o[1]/100);
if (o = ($border.css('filter')||'').match(/opacity=(\d+)/))
$border.css('opacity', o[1]/100);
}
if (newOptions.hide)
hide($box.add($outer));
else if (newOptions.show && imgLoaded) {
shown = true;
$box.add($outer).fadeIn(options.fadeSpeed||0);
doUpdate();
}
/* Calculate the aspect ratio factor */
aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
$img.add($outer).unbind('mousedown', imgMouseDown);
if (options.disable || options.enable === false) {
/* Disable the plugin */
$box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown);
$(window).unbind('resize', windowResize);
}
else {
if (options.enable || options.disable === false) {
/* Enable the plugin */
if (options.resizable || options.movable)
$box.mousemove(areaMouseMove).mousedown(areaMouseDown);
$(window).resize(windowResize);
}
if (!options.persistent)
$img.add($outer).mousedown(imgMouseDown);
}
options.enable = options.disable = undefined;
}
/**
* Remove plugin completely
*/
this.remove = function () {
/*
* Call setOptions with { disable: true } to unbind the event handlers
*/
setOptions({ disable: true });
$box.add($outer).remove();
};
/*
* Public API
*/
/**
* Get current options
*
* @return An object containing the set of options currently in use
*/
this.getOptions = function () { return options; };
/**
* Set plugin options
*
* @param newOptions
* The new options object
*/
this.setOptions = setOptions;
/**
* Get the current selection
*
* @param noScale
* If set to <code>true</code>, scaling is not applied to the
* returned selection
* @return Selection object
*/
this.getSelection = getSelection;
/**
* Set the current selection
*
* @param x1
* X coordinate of the upper left corner of the selection area
* @param y1
* Y coordinate of the upper left corner of the selection area
* @param x2
* X coordinate of the lower right corner of the selection area
* @param y2
* Y coordinate of the lower right corner of the selection area
* @param noScale
* If set to <code>true</code>, scaling is not applied to the
* new selection
*/
this.setSelection = setSelection;
/**
* Cancel selection
*/
this.cancelSelection = cancelSelection;
/**
* Update plugin elements
*
* @param resetKeyPress
* If set to <code>false</code>, this instance's keypress
* event handler is not activated
*/
this.update = doUpdate;
/* Do the dreaded browser detection */
var msie = (/msie ([\w.]+)/i.exec(ua)||[])[1],
opera = /opera/i.test(ua),
safari = /webkit/i.test(ua) && !/chrome/i.test(ua);
/*
* Traverse the image's parent elements (up to <body>) and find the
* highest z-index
*/
$p = $img;
while ($p.length) {
zIndex = max(zIndex,
!isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex);
/* Also check if any of the ancestor elements has fixed position */
if ($p.css('position') == 'fixed')
position = 'fixed';
$p = $p.parent(':not(body)');
}
/*
* If z-index is given as an option, it overrides the one found by the
* above loop
*/
zIndex = options.zIndex || zIndex;
if (msie)
$img.attr('unselectable', 'on');
/*
* In MSIE and WebKit, we need to use the keydown event instead of keypress
*/
$.imgAreaSelect.keyPress = msie || safari ? 'keydown' : 'keypress';
/*
* There is a bug affecting the CSS cursor property in Opera (observed in
* versions up to 10.00) that prevents the cursor from being updated unless
* the mouse leaves and enters the element again. To trigger the mouseover
* event, we're adding an additional div to $box and we're going to toggle
* it when mouse moves inside the selection area.
*/
if (opera)
$areaOpera = div().css({ width: '100%', height: '100%',
position: 'absolute', zIndex: zIndex + 2 || 2 });
/*
* We initially set visibility to "hidden" as a workaround for a weird
* behaviour observed in Google Chrome 1.0.154.53 (on Windows XP). Normally
* we would just set display to "none", but, for some reason, if we do so
* then Chrome refuses to later display the element with .show() or
* .fadeIn().
*/
$box.add($outer).css({ visibility: 'hidden', position: position,
overflow: 'hidden', zIndex: zIndex || '0' });
$box.css({ zIndex: zIndex + 2 || 2 });
$area.add($border).css({ position: 'absolute', fontSize: 0 });
/*
* If the image has been fully loaded, or if it is not really an image (eg.
* a div), call imgLoad() immediately; otherwise, bind it to be called once
* on image load event.
*/
img.complete || img.readyState == 'complete' || !$img.is('img') ?
imgLoad() : $img.one('load', imgLoad);
/*
* MSIE 9.0 doesn't always fire the image load event -- resetting the src
* attribute seems to trigger it. The check is for version 7 and above to
* accommodate for MSIE 9 running in compatibility mode.
*/
if (!imgLoaded && msie && msie >= 7)
img.src = img.src;
};
/**
* Invoke imgAreaSelect on a jQuery object containing the image(s)
*
* @param options
* Options object
* @return The jQuery object or a reference to imgAreaSelect instance (if the
* <code>instance</code> option was specified)
*/
$.fn.imgAreaSelect = function (options) {
options = options || {};
this.each(function () {
/* Is there already an imgAreaSelect instance bound to this element? */
if ($(this).data('imgAreaSelect')) {
/* Yes there is -- is it supposed to be removed? */
if (options.remove) {
/* Remove the plugin */
$(this).data('imgAreaSelect').remove();
$(this).removeData('imgAreaSelect');
}
else
/* Reset options */
$(this).data('imgAreaSelect').setOptions(options);
}
else if (!options.remove) {
/* No exising instance -- create a new one */
/*
* If neither the "enable" nor the "disable" option is present, add
* "enable" as the default
*/
if (options.enable === undefined && options.disable === undefined)
options.enable = true;
$(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
}
});
if (options.instance)
/*
* Return the imgAreaSelect instance bound to the first element in the
* set
*/
return $(this).data('imgAreaSelect');
return this;
};
})(jQuery);
| JavaScript |
// Utility functions for parsing and handling shortcodes in Javascript.
// Ensure the global `wp` object exists.
window.wp = window.wp || {};
(function(){
wp.shortcode = {
// ### Find the next matching shortcode
//
// Given a shortcode `tag`, a block of `text`, and an optional starting
// `index`, returns the next matching shortcode or `undefined`.
//
// Shortcodes are formatted as an object that contains the match
// `content`, the matching `index`, and the parsed `shortcode` object.
next: function( tag, text, index ) {
var re = wp.shortcode.regexp( tag ),
match, result;
re.lastIndex = index || 0;
match = re.exec( text );
if ( ! match ) {
return;
}
// If we matched an escaped shortcode, try again.
if ( '[' === match[1] && ']' === match[7] ) {
return wp.shortcode.next( tag, text, re.lastIndex );
}
result = {
index: match.index,
content: match[0],
shortcode: wp.shortcode.fromMatch( match )
};
// If we matched a leading `[`, strip it from the match
// and increment the index accordingly.
if ( match[1] ) {
result.match = result.match.slice( 1 );
result.index++;
}
// If we matched a trailing `]`, strip it from the match.
if ( match[7] ) {
result.match = result.match.slice( 0, -1 );
}
return result;
},
// ### Replace matching shortcodes in a block of text
//
// Accepts a shortcode `tag`, content `text` to scan, and a `callback`
// to process the shortcode matches and return a replacement string.
// Returns the `text` with all shortcodes replaced.
//
// Shortcode matches are objects that contain the shortcode `tag`,
// a shortcode `attrs` object, the `content` between shortcode tags,
// and a boolean flag to indicate if the match was a `single` tag.
replace: function( tag, text, callback ) {
return text.replace( wp.shortcode.regexp( tag ), function( match, left, tag, attrs, slash, content, closing, right ) {
// If both extra brackets exist, the shortcode has been
// properly escaped.
if ( left === '[' && right === ']' ) {
return match;
}
// Create the match object and pass it through the callback.
var result = callback( wp.shortcode.fromMatch( arguments ) );
// Make sure to return any of the extra brackets if they
// weren't used to escape the shortcode.
return result ? left + result + right : match;
});
},
// ### Generate a string from shortcode parameters
//
// Creates a `wp.shortcode` instance and returns a string.
//
// Accepts the same `options` as the `wp.shortcode()` constructor,
// containing a `tag` string, a string or object of `attrs`, a boolean
// indicating whether to format the shortcode using a `single` tag, and a
// `content` string.
string: function( options ) {
return new wp.shortcode( options ).string();
},
// ### Generate a RegExp to identify a shortcode
//
// The base regex is functionally equivalent to the one found in
// `get_shortcode_regex()` in `wp-includes/shortcodes.php`.
//
// Capture groups:
//
// 1. An extra `[` to allow for escaping shortcodes with double `[[]]`
// 2. The shortcode name
// 3. The shortcode argument list
// 4. The self closing `/`
// 5. The content of a shortcode when it wraps some content.
// 6. The closing tag.
// 7. An extra `]` to allow for escaping shortcodes with double `[[]]`
regexp: _.memoize( function( tag ) {
return new RegExp( '\\[(\\[?)(' + tag + ')(?![\\w-])([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:\\[(?!\\/\\2\\])[^\\[]*)*)(\\[\\/\\2\\]))?)(\\]?)', 'g' );
}),
// ### Parse shortcode attributes
//
// Shortcodes accept many types of attributes. These can chiefly be
// divided into named and numeric attributes:
//
// Named attributes are assigned on a key/value basis, while numeric
// attributes are treated as an array.
//
// Named attributes can be formatted as either `name="value"`,
// `name='value'`, or `name=value`. Numeric attributes can be formatted
// as `"value"` or just `value`.
attrs: _.memoize( function( text ) {
var named = {},
numeric = [],
pattern, match;
// This regular expression is reused from `shortcode_parse_atts()`
// in `wp-includes/shortcodes.php`.
//
// Capture groups:
//
// 1. An attribute name, that corresponds to...
// 2. a value in double quotes.
// 3. An attribute name, that corresponds to...
// 4. a value in single quotes.
// 5. An attribute name, that corresponds to...
// 6. an unquoted value.
// 7. A numeric attribute in double quotes.
// 8. An unquoted numeric attribute.
pattern = /(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/g;
// Map zero-width spaces to actual spaces.
text = text.replace( /[\u00a0\u200b]/g, ' ' );
// Match and normalize attributes.
while ( (match = pattern.exec( text )) ) {
if ( match[1] ) {
named[ match[1].toLowerCase() ] = match[2];
} else if ( match[3] ) {
named[ match[3].toLowerCase() ] = match[4];
} else if ( match[5] ) {
named[ match[5].toLowerCase() ] = match[6];
} else if ( match[7] ) {
numeric.push( match[7] );
} else if ( match[8] ) {
numeric.push( match[8] );
}
}
return {
named: named,
numeric: numeric
};
}),
// ### Generate a Shortcode Object from a RegExp match
// Accepts a `match` object from calling `regexp.exec()` on a `RegExp`
// generated by `wp.shortcode.regexp()`. `match` can also be set to the
// `arguments` from a callback passed to `regexp.replace()`.
fromMatch: function( match ) {
var type;
if ( match[4] ) {
type = 'self-closing';
} else if ( match[6] ) {
type = 'closed';
} else {
type = 'single';
}
return new wp.shortcode({
tag: match[2],
attrs: match[3],
type: type,
content: match[5]
});
}
};
// Shortcode Objects
// -----------------
//
// Shortcode objects are generated automatically when using the main
// `wp.shortcode` methods: `next()`, `replace()`, and `string()`.
//
// To access a raw representation of a shortcode, pass an `options` object,
// containing a `tag` string, a string or object of `attrs`, a string
// indicating the `type` of the shortcode ('single', 'self-closing', or
// 'closed'), and a `content` string.
wp.shortcode = _.extend( function( options ) {
_.extend( this, _.pick( options || {}, 'tag', 'attrs', 'type', 'content' ) );
var attrs = this.attrs;
// Ensure we have a correctly formatted `attrs` object.
this.attrs = {
named: {},
numeric: []
};
if ( ! attrs ) {
return;
}
// Parse a string of attributes.
if ( _.isString( attrs ) ) {
this.attrs = wp.shortcode.attrs( attrs );
// Identify a correctly formatted `attrs` object.
} else if ( _.isEqual( _.keys( attrs ), [ 'named', 'numeric' ] ) ) {
this.attrs = attrs;
// Handle a flat object of attributes.
} else {
_.each( options.attrs, function( value, key ) {
this.set( key, value );
}, this );
}
}, wp.shortcode );
_.extend( wp.shortcode.prototype, {
// ### Get a shortcode attribute
//
// Automatically detects whether `attr` is named or numeric and routes
// it accordingly.
get: function( attr ) {
return this.attrs[ _.isNumber( attr ) ? 'numeric' : 'named' ][ attr ];
},
// ### Set a shortcode attribute
//
// Automatically detects whether `attr` is named or numeric and routes
// it accordingly.
set: function( attr, value ) {
this.attrs[ _.isNumber( attr ) ? 'numeric' : 'named' ][ attr ] = value;
return this;
},
// ### Transform the shortcode match into a string
string: function() {
var text = '[' + this.tag;
_.each( this.attrs.numeric, function( value ) {
if ( /\s/.test( value ) ) {
text += ' "' + value + '"';
} else {
text += ' ' + value;
}
});
_.each( this.attrs.named, function( value, name ) {
text += ' ' + name + '="' + value + '"';
});
// If the tag is marked as `single` or `self-closing`, close the
// tag and ignore any additional content.
if ( 'single' === this.type ) {
return text + ']';
} else if ( 'self-closing' === this.type ) {
return text + ' /]';
}
// Complete the opening tag.
text += ']';
if ( this.content ) {
text += this.content;
}
// Add the closing tag.
return text + '[/' + this.tag + ']';
}
});
}());
// HTML utility functions
// ----------------------
//
// Experimental. These functions may change or be removed in the future.
(function(){
wp.html = _.extend( wp.html || {}, {
// ### Parse HTML attributes.
//
// Converts `content` to a set of parsed HTML attributes.
// Utilizes `wp.shortcode.attrs( content )`, which is a valid superset of
// the HTML attribute specification. Reformats the attributes into an
// object that contains the `attrs` with `key:value` mapping, and a record
// of the attributes that were entered using `empty` attribute syntax (i.e.
// with no value).
attrs: function( content ) {
var result, attrs;
// If `content` ends in a slash, strip it.
if ( '/' === content[ content.length - 1 ] ) {
content = content.slice( 0, -1 );
}
result = wp.shortcode.attrs( content );
attrs = result.named;
_.each( result.numeric, function( key ) {
if ( /\s/.test( key ) ) {
return;
}
attrs[ key ] = '';
});
return attrs;
},
// ### Convert an HTML-representation of an object to a string.
string: function( options ) {
var text = '<' + options.tag,
content = options.content || '';
_.each( options.attrs, function( value, attr ) {
text += ' ' + attr;
// Use empty attribute notation where possible.
if ( '' === value ) {
return;
}
// Convert boolean values to strings.
if ( _.isBoolean( value ) ) {
value = value ? 'true' : 'false';
}
text += '="' + value + '"';
});
// Return the result if it is a self-closing tag.
if ( options.single ) {
return text + ' />';
}
// Complete the opening tag.
text += '>';
// If `content` is an object, recursively call this function.
text += _.isObject( content ) ? wp.html.string( content ) : content;
return text + '</' + options.tag + '>';
}
});
}()); | JavaScript |
/* global _zxcvbnSettings */
(function() {
var async_load = function() {
var first, s;
s = document.createElement('script');
s.src = _zxcvbnSettings.src;
s.type = 'text/javascript';
s.async = true;
first = document.getElementsByTagName('script')[0];
return first.parentNode.insertBefore(s, first);
};
if (window.attachEvent != null) {
window.attachEvent('onload', async_load);
} else {
window.addEventListener('load', async_load, false);
}
}).call(this);
| JavaScript |
(function( wp, $ ){
if ( ! wp || ! wp.customize ) { return; }
var api = wp.customize,
OldPreview;
/**
* wp.customize.WidgetCustomizerPreview
*
*/
api.WidgetCustomizerPreview = {
renderedSidebars: {}, // @todo Make rendered a property of the Backbone model
renderedWidgets: {}, // @todo Make rendered a property of the Backbone model
registeredSidebars: [], // @todo Make a Backbone collection
registeredWidgets: {}, // @todo Make array, Backbone collection
widgetSelectors: [],
preview: null,
l10n: {},
init: function () {
var self = this;
this.buildWidgetSelectors();
this.highlightControls();
this.preview.bind( 'active', function() {
self.preview.send( 'rendered-sidebars', self.renderedSidebars ); // @todo Only send array of IDs
self.preview.send( 'rendered-widgets', self.renderedWidgets ); // @todo Only send array of IDs
} );
this.preview.bind( 'highlight-widget', self.highlightWidget );
},
/**
* Calculate the selector for the sidebar's widgets based on the registered sidebar's info
*/
buildWidgetSelectors: function () {
var self = this;
$.each( this.registeredSidebars, function ( i, sidebar ) {
var widgetTpl = [
sidebar.before_widget.replace('%1$s', '').replace('%2$s', ''),
sidebar.before_title,
sidebar.after_title,
sidebar.after_widget
].join(''),
emptyWidget,
widgetSelector,
widgetClasses;
emptyWidget = $(widgetTpl);
widgetSelector = emptyWidget.prop('tagName');
widgetClasses = emptyWidget.prop('className');
// Prevent a rare case when before_widget, before_title, after_title and after_widget is empty.
if ( ! widgetClasses ) {
return;
}
widgetClasses = widgetClasses.replace(/^\s+|\s+$/g, '');
if ( widgetClasses ) {
widgetSelector += '.' + widgetClasses.split(/\s+/).join('.');
}
self.widgetSelectors.push(widgetSelector);
});
},
/**
* Highlight the widget on widget updates or widget control mouse overs.
*
* @param {string} widgetId ID of the widget.
*/
highlightWidget: function( widgetId ) {
var $body = $( document.body ),
$widget = $( '#' + widgetId );
$body.find( '.widget-customizer-highlighted-widget' ).removeClass( 'widget-customizer-highlighted-widget' );
$widget.addClass( 'widget-customizer-highlighted-widget' );
setTimeout( function () {
$widget.removeClass( 'widget-customizer-highlighted-widget' );
}, 500 );
},
/**
* Show a title and highlight widgets on hover. On shift+clicking
* focus the widget control.
*/
highlightControls: function() {
var self = this,
selector = this.widgetSelectors.join(',');
$(selector).attr( 'title', this.l10n.widgetTooltip );
$(document).on( 'mouseenter', selector, function () {
self.preview.send( 'highlight-widget-control', $( this ).prop( 'id' ) );
});
// Open expand the widget control when shift+clicking the widget element
$(document).on( 'click', selector, function ( e ) {
if ( ! e.shiftKey ) {
return;
}
e.preventDefault();
self.preview.send( 'focus-widget-control', $( this ).prop( 'id' ) );
});
}
};
/**
* Capture the instance of the Preview since it is private
*/
OldPreview = api.Preview;
api.Preview = OldPreview.extend( {
initialize: function( params, options ) {
api.WidgetCustomizerPreview.preview = this;
OldPreview.prototype.initialize.call( this, params, options );
}
} );
$(function () {
var settings = window._wpWidgetCustomizerPreviewSettings;
if ( ! settings ) {
return;
}
$.extend( api.WidgetCustomizerPreview, settings );
api.WidgetCustomizerPreview.init();
});
})( window.wp, jQuery );
| JavaScript |
(function( exports, $ ){
var api = wp.customize,
debounce;
debounce = function( fn, delay, context ) {
var timeout;
return function() {
var args = arguments;
context = context || this;
clearTimeout( timeout );
timeout = setTimeout( function() {
timeout = null;
fn.apply( context, args );
}, delay );
};
};
api.Preview = api.Messenger.extend({
/**
* Requires params:
* - url - the URL of preview frame
*/
initialize: function( params, options ) {
var self = this;
api.Messenger.prototype.initialize.call( this, params, options );
this.body = $( document.body );
this.body.on( 'click.preview', 'a', function( event ) {
event.preventDefault();
self.send( 'scroll', 0 );
self.send( 'url', $(this).prop('href') );
});
// You cannot submit forms.
// @todo: Allow form submissions by mixing $_POST data with the customize setting $_POST data.
this.body.on( 'submit.preview', 'form', function( event ) {
event.preventDefault();
});
this.window = $( window );
this.window.on( 'scroll.preview', debounce( function() {
self.send( 'scroll', self.window.scrollTop() );
}, 200 ));
this.bind( 'scroll', function( distance ) {
self.window.scrollTop( distance );
});
}
});
$( function() {
api.settings = window._wpCustomizeSettings;
if ( ! api.settings )
return;
var preview, bg;
preview = new api.Preview({
url: window.location.href,
channel: api.settings.channel
});
preview.bind( 'settings', function( values ) {
$.each( values, function( id, value ) {
if ( api.has( id ) )
api( id ).set( value );
else
api.create( id, value );
});
});
preview.trigger( 'settings', api.settings.values );
preview.bind( 'setting', function( args ) {
var value;
args = args.slice();
if ( value = api( args.shift() ) )
value.set.apply( value, args );
});
preview.bind( 'sync', function( events ) {
$.each( events, function( event, args ) {
preview.trigger( event, args );
});
preview.send( 'synced' );
});
preview.bind( 'active', function() {
if ( api.settings.nonce )
preview.send( 'nonce', api.settings.nonce );
});
preview.send( 'ready' );
/* Custom Backgrounds */
bg = $.map(['color', 'image', 'position_x', 'repeat', 'attachment'], function( prop ) {
return 'background_' + prop;
});
api.when.apply( api, bg ).done( function( color, image, position_x, repeat, attachment ) {
var body = $(document.body),
head = $('head'),
style = $('#custom-background-css'),
update;
update = function() {
var css = '';
// The body will support custom backgrounds if either
// the color or image are set.
//
// See get_body_class() in /wp-includes/post-template.php
body.toggleClass( 'custom-background', !! ( color() || image() ) );
if ( color() )
css += 'background-color: ' + color() + ';';
if ( image() ) {
css += 'background-image: url("' + image() + '");';
css += 'background-position: top ' + position_x() + ';';
css += 'background-repeat: ' + repeat() + ';';
css += 'background-attachment: ' + attachment() + ';';
}
// Refresh the stylesheet by removing and recreating it.
style.remove();
style = $('<style type="text/css" id="custom-background-css">body.custom-background { ' + css + ' }</style>').appendTo( head );
};
$.each( arguments, function() {
this.bind( update );
});
});
});
})( wp, jQuery );
| JavaScript |
/* global userSettings */
/* exported getUserSetting, setUserSetting, deleteUserSetting */
// utility functions
var wpCookies = {
// The following functions are from Cookie.js class in TinyMCE, Moxiecode, used under LGPL.
each : function(obj, cb, scope) {
var n, l;
if ( !obj )
return 0;
scope = scope || obj;
if ( typeof(obj.length) != 'undefined' ) {
for ( n = 0, l = obj.length; n < l; n++ ) {
if ( cb.call(scope, obj[n], n, obj) === false )
return 0;
}
} else {
for ( n in obj ) {
if ( obj.hasOwnProperty(n) ) {
if ( cb.call(scope, obj[n], n, obj) === false ) {
return 0;
}
}
}
}
return 1;
},
/**
* Get a multi-values cookie.
* Returns a JS object with the name: 'value' pairs.
*/
getHash : function(name) {
var all = this.get(name), ret;
if ( all ) {
this.each( all.split('&'), function(pair) {
pair = pair.split('=');
ret = ret || {};
ret[pair[0]] = pair[1];
});
}
return ret;
},
/**
* Set a multi-values cookie.
*
* 'values_obj' is the JS object that is stored. It is encoded as URI in wpCookies.set().
*/
setHash : function(name, values_obj, expires, path, domain, secure) {
var str = '';
this.each(values_obj, function(val, key) {
str += (!str ? '' : '&') + key + '=' + val;
});
this.set(name, str, expires, path, domain, secure);
},
/**
* Get a cookie.
*/
get : function(name) {
var e, b,
cookie = document.cookie,
p = name + '=';
if ( !cookie )
return;
b = cookie.indexOf('; ' + p);
if ( b == -1 ) {
b = cookie.indexOf(p);
if ( b !== 0 )
return null;
} else {
b += 2;
}
e = cookie.indexOf( ';', b );
if ( e == -1 )
e = cookie.length;
return decodeURIComponent( cookie.substring(b + p.length, e) );
},
/**
* Set a cookie.
*
* The 'expires' arg can be either a JS Date() object set to the expiration date (back-compat)
* or the number of seconds until expiration
*/
set : function(name, value, expires, path, domain, secure) {
var d = new Date();
if ( typeof(expires) == 'object' && expires.toGMTString ) {
expires = expires.toGMTString();
} else if ( parseInt(expires, 10) ) {
d.setTime( d.getTime() + ( parseInt(expires, 10) * 1000 ) ); // time must be in miliseconds
expires = d.toGMTString();
} else {
expires = '';
}
document.cookie = name + '=' + encodeURIComponent( value ) +
( expires ? '; expires=' + expires : '' ) +
( path ? '; path=' + path : '' ) +
( domain ? '; domain=' + domain : '' ) +
( secure ? '; secure' : '' );
},
/**
* Remove a cookie.
*
* This is done by setting it to an empty value and setting the expiration time in the past.
*/
remove : function(name, path) {
this.set(name, '', -1000, path);
}
};
// Returns the value as string. Second arg or empty string is returned when value is not set.
function getUserSetting( name, def ) {
var obj = getAllUserSettings();
if ( obj.hasOwnProperty(name) )
return obj[name];
if ( typeof def != 'undefined' )
return def;
return '';
}
// Both name and value must be only ASCII letters, numbers or underscore
// and the shorter, the better (cookies can store maximum 4KB). Not suitable to store text.
function setUserSetting( name, value, _del ) {
if ( 'object' !== typeof userSettings )
return false;
var cookie = 'wp-settings-' + userSettings.uid, all = wpCookies.getHash(cookie) || {}, path = userSettings.url,
n = name.toString().replace(/[^A-Za-z0-9_]/, ''), v = value.toString().replace(/[^A-Za-z0-9_]/, '');
if ( _del ) {
delete all[n];
} else {
all[n] = v;
}
wpCookies.setHash(cookie, all, 31536000, path);
wpCookies.set('wp-settings-time-'+userSettings.uid, userSettings.time, 31536000, path);
return name;
}
function deleteUserSetting( name ) {
return setUserSetting( name, '', 1 );
}
// Returns all settings as js object.
function getAllUserSettings() {
if ( 'object' !== typeof userSettings )
return {};
return wpCookies.getHash('wp-settings-' + userSettings.uid) || {};
}
| JavaScript |
/* global _wpMediaModelsL10n:false */
window.wp = window.wp || {};
(function($){
var Attachment, Attachments, Query, PostImage, compare, l10n, media;
/**
* wp.media( attributes )
*
* Handles the default media experience. Automatically creates
* and opens a media frame, and returns the result.
* Does nothing if the controllers do not exist.
*
* @param {object} attributes The properties passed to the main media controller.
* @return {wp.media.view.MediaFrame} A media workflow.
*/
media = wp.media = function( attributes ) {
var MediaFrame = media.view.MediaFrame,
frame;
if ( ! MediaFrame ) {
return;
}
attributes = _.defaults( attributes || {}, {
frame: 'select'
});
if ( 'select' === attributes.frame && MediaFrame.Select ) {
frame = new MediaFrame.Select( attributes );
} else if ( 'post' === attributes.frame && MediaFrame.Post ) {
frame = new MediaFrame.Post( attributes );
} else if ( 'image' === attributes.frame && MediaFrame.ImageDetails ) {
frame = new MediaFrame.ImageDetails( attributes );
} else if ( 'audio' === attributes.frame && MediaFrame.AudioDetails ) {
frame = new MediaFrame.AudioDetails( attributes );
} else if ( 'video' === attributes.frame && MediaFrame.VideoDetails ) {
frame = new MediaFrame.VideoDetails( attributes );
}
delete attributes.frame;
media.frame = frame;
return frame;
};
_.extend( media, { model: {}, view: {}, controller: {}, frames: {} });
// Link any localized strings.
l10n = media.model.l10n = typeof _wpMediaModelsL10n === 'undefined' ? {} : _wpMediaModelsL10n;
// Link any settings.
media.model.settings = l10n.settings || {};
delete l10n.settings;
/**
* ========================================================================
* UTILITIES
* ========================================================================
*/
/**
* A basic comparator.
*
* @param {mixed} a The primary parameter to compare.
* @param {mixed} b The primary parameter to compare.
* @param {string} ac The fallback parameter to compare, a's cid.
* @param {string} bc The fallback parameter to compare, b's cid.
* @return {number} -1: a should come before b.
* 0: a and b are of the same rank.
* 1: b should come before a.
*/
compare = function( a, b, ac, bc ) {
if ( _.isEqual( a, b ) ) {
return ac === bc ? 0 : (ac > bc ? -1 : 1);
} else {
return a > b ? -1 : 1;
}
};
_.extend( media, {
/**
* media.template( id )
*
* Fetches a template by id.
* See wp.template() in `wp-includes/js/wp-util.js`.
*
* @borrows wp.template as template
*/
template: wp.template,
/**
* media.post( [action], [data] )
*
* Sends a POST request to WordPress.
* See wp.ajax.post() in `wp-includes/js/wp-util.js`.
*
* @borrows wp.ajax.post as post
*/
post: wp.ajax.post,
/**
* media.ajax( [action], [options] )
*
* Sends an XHR request to WordPress.
* See wp.ajax.send() in `wp-includes/js/wp-util.js`.
*
* @borrows wp.ajax.send as ajax
*/
ajax: wp.ajax.send,
/**
* Scales a set of dimensions to fit within bounding dimensions.
*
* @param {Object} dimensions
* @returns {Object}
*/
fit: function( dimensions ) {
var width = dimensions.width,
height = dimensions.height,
maxWidth = dimensions.maxWidth,
maxHeight = dimensions.maxHeight,
constraint;
// Compare ratios between the two values to determine which
// max to constrain by. If a max value doesn't exist, then the
// opposite side is the constraint.
if ( ! _.isUndefined( maxWidth ) && ! _.isUndefined( maxHeight ) ) {
constraint = ( width / height > maxWidth / maxHeight ) ? 'width' : 'height';
} else if ( _.isUndefined( maxHeight ) ) {
constraint = 'width';
} else if ( _.isUndefined( maxWidth ) && height > maxHeight ) {
constraint = 'height';
}
// If the value of the constrained side is larger than the max,
// then scale the values. Otherwise return the originals; they fit.
if ( 'width' === constraint && width > maxWidth ) {
return {
width : maxWidth,
height: Math.round( maxWidth * height / width )
};
} else if ( 'height' === constraint && height > maxHeight ) {
return {
width : Math.round( maxHeight * width / height ),
height: maxHeight
};
} else {
return {
width : width,
height: height
};
}
},
/**
* Truncates a string by injecting an ellipsis into the middle.
* Useful for filenames.
*
* @param {String} string
* @param {Number} [length=30]
* @param {String} [replacement=…]
* @returns {String} The string, unless length is greater than string.length.
*/
truncate: function( string, length, replacement ) {
length = length || 30;
replacement = replacement || '…';
if ( string.length <= length ) {
return string;
}
return string.substr( 0, length / 2 ) + replacement + string.substr( -1 * length / 2 );
}
});
/**
* ========================================================================
* MODELS
* ========================================================================
*/
/**
* wp.media.attachment
*
* @static
* @param {String} id A string used to identify a model.
* @returns {wp.media.model.Attachment}
*/
media.attachment = function( id ) {
return Attachment.get( id );
};
/**
* wp.media.model.Attachment
*
* @constructor
* @augments Backbone.Model
*/
Attachment = media.model.Attachment = Backbone.Model.extend({
/**
* Triggered when attachment details change
* Overrides Backbone.Model.sync
*
* @param {string} method
* @param {wp.media.model.Attachment} model
* @param {Object} [options={}]
*
* @returns {Promise}
*/
sync: function( method, model, options ) {
// If the attachment does not yet have an `id`, return an instantly
// rejected promise. Otherwise, all of our requests will fail.
if ( _.isUndefined( this.id ) ) {
return $.Deferred().rejectWith( this ).promise();
}
// Overload the `read` request so Attachment.fetch() functions correctly.
if ( 'read' === method ) {
options = options || {};
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'get-attachment',
id: this.id
});
return media.ajax( options );
// Overload the `update` request so properties can be saved.
} else if ( 'update' === method ) {
// If we do not have the necessary nonce, fail immeditately.
if ( ! this.get('nonces') || ! this.get('nonces').update ) {
return $.Deferred().rejectWith( this ).promise();
}
options = options || {};
options.context = this;
// Set the action and ID.
options.data = _.extend( options.data || {}, {
action: 'save-attachment',
id: this.id,
nonce: this.get('nonces').update,
post_id: media.model.settings.post.id
});
// Record the values of the changed attributes.
if ( model.hasChanged() ) {
options.data.changes = {};
_.each( model.changed, function( value, key ) {
options.data.changes[ key ] = this.get( key );
}, this );
}
return media.ajax( options );
// Overload the `delete` request so attachments can be removed.
// This will permanently delete an attachment.
} else if ( 'delete' === method ) {
options = options || {};
if ( ! options.wait ) {
this.destroyed = true;
}
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'delete-post',
id: this.id,
_wpnonce: this.get('nonces')['delete']
});
return media.ajax( options ).done( function() {
this.destroyed = true;
}).fail( function() {
this.destroyed = false;
});
// Otherwise, fall back to `Backbone.sync()`.
} else {
/**
* Call `sync` directly on Backbone.Model
*/
return Backbone.Model.prototype.sync.apply( this, arguments );
}
},
/**
* Convert date strings into Date objects.
*
* @param {Object} resp The raw response object, typically returned by fetch()
* @returns {Object} The modified response object, which is the attributes hash
* to be set on the model.
*/
parse: function( resp ) {
if ( ! resp ) {
return resp;
}
resp.date = new Date( resp.date );
resp.modified = new Date( resp.modified );
return resp;
},
/**
* @param {Object} data The properties to be saved.
* @param {Object} options Sync options. e.g. patch, wait, success, error.
*
* @this Backbone.Model
*
* @returns {Promise}
*/
saveCompat: function( data, options ) {
var model = this;
// If we do not have the necessary nonce, fail immeditately.
if ( ! this.get('nonces') || ! this.get('nonces').update ) {
return $.Deferred().rejectWith( this ).promise();
}
return media.post( 'save-attachment-compat', _.defaults({
id: this.id,
nonce: this.get('nonces').update,
post_id: media.model.settings.post.id
}, data ) ).done( function( resp, status, xhr ) {
model.set( model.parse( resp, xhr ), options );
});
}
}, {
/**
* Add a model to the end of the static 'all' collection and return it.
*
* @static
* @param {Object} attrs
* @returns {wp.media.model.Attachment}
*/
create: function( attrs ) {
return Attachments.all.push( attrs );
},
/**
* Retrieve a model, or add it to the end of the static 'all' collection before returning it.
*
* @static
* @param {string} id A string used to identify a model.
* @param {Backbone.Model|undefined} attachment
* @returns {wp.media.model.Attachment}
*/
get: _.memoize( function( id, attachment ) {
return Attachments.all.push( attachment || { id: id } );
})
});
/**
* wp.media.model.PostImage
*
* @constructor
* @augments Backbone.Model
**/
PostImage = media.model.PostImage = Backbone.Model.extend({
initialize: function( attributes ) {
this.attachment = false;
if ( attributes.attachment_id ) {
this.attachment = Attachment.get( attributes.attachment_id );
if ( this.attachment.get( 'url' ) ) {
this.dfd = $.Deferred();
this.dfd.resolve();
} else {
this.dfd = this.attachment.fetch();
}
this.bindAttachmentListeners();
}
// keep url in sync with changes to the type of link
this.on( 'change:link', this.updateLinkUrl, this );
this.on( 'change:size', this.updateSize, this );
this.setLinkTypeFromUrl();
this.setAspectRatio();
this.set( 'originalUrl', attributes.url );
},
bindAttachmentListeners: function() {
this.listenTo( this.attachment, 'sync', this.setLinkTypeFromUrl );
this.listenTo( this.attachment, 'sync', this.setAspectRatio );
this.listenTo( this.attachment, 'change', this.updateSize );
},
changeAttachment: function( attachment, props ) {
this.stopListening( this.attachment );
this.attachment = attachment;
this.bindAttachmentListeners();
this.set( 'attachment_id', this.attachment.get( 'id' ) );
this.set( 'caption', this.attachment.get( 'caption' ) );
this.set( 'alt', this.attachment.get( 'alt' ) );
this.set( 'size', props.get( 'size' ) );
this.set( 'align', props.get( 'align' ) );
this.set( 'link', props.get( 'link' ) );
this.updateLinkUrl();
this.updateSize();
},
setLinkTypeFromUrl: function() {
var linkUrl = this.get( 'linkUrl' ),
type;
if ( ! linkUrl ) {
this.set( 'link', 'none' );
return;
}
// default to custom if there is a linkUrl
type = 'custom';
if ( this.attachment ) {
if ( this.attachment.get( 'url' ) === linkUrl ) {
type = 'file';
} else if ( this.attachment.get( 'link' ) === linkUrl ) {
type = 'post';
}
} else {
if ( this.get( 'url' ) === linkUrl ) {
type = 'file';
}
}
this.set( 'link', type );
},
updateLinkUrl: function() {
var link = this.get( 'link' ),
url;
switch( link ) {
case 'file':
if ( this.attachment ) {
url = this.attachment.get( 'url' );
} else {
url = this.get( 'url' );
}
this.set( 'linkUrl', url );
break;
case 'post':
this.set( 'linkUrl', this.attachment.get( 'link' ) );
break;
case 'none':
this.set( 'linkUrl', '' );
break;
}
},
updateSize: function() {
var size;
if ( ! this.attachment ) {
return;
}
if ( this.get( 'size' ) === 'custom' ) {
this.set( 'width', this.get( 'customWidth' ) );
this.set( 'height', this.get( 'customHeight' ) );
this.set( 'url', this.get( 'originalUrl' ) );
return;
}
size = this.attachment.get( 'sizes' )[ this.get( 'size' ) ];
if ( ! size ) {
return;
}
this.set( 'url', size.url );
this.set( 'width', size.width );
this.set( 'height', size.height );
},
setAspectRatio: function() {
var full;
if ( this.attachment && this.attachment.get( 'sizes' ) ) {
full = this.attachment.get( 'sizes' ).full;
if ( full ) {
this.set( 'aspectRatio', full.width / full.height );
return;
}
}
this.set( 'aspectRatio', this.get( 'customWidth' ) / this.get( 'customHeight' ) );
}
});
/**
* wp.media.model.Attachments
*
* @constructor
* @augments Backbone.Collection
*/
Attachments = media.model.Attachments = Backbone.Collection.extend({
/**
* @type {wp.media.model.Attachment}
*/
model: Attachment,
/**
* @param {Array} [models=[]] Array of models used to populate the collection.
* @param {Object} [options={}]
*/
initialize: function( models, options ) {
options = options || {};
this.props = new Backbone.Model();
this.filters = options.filters || {};
// Bind default `change` events to the `props` model.
this.props.on( 'change', this._changeFilteredProps, this );
this.props.on( 'change:order', this._changeOrder, this );
this.props.on( 'change:orderby', this._changeOrderby, this );
this.props.on( 'change:query', this._changeQuery, this );
// Set the `props` model and fill the default property values.
this.props.set( _.defaults( options.props || {} ) );
// Observe another `Attachments` collection if one is provided.
if ( options.observe ) {
this.observe( options.observe );
}
},
/**
* Automatically sort the collection when the order changes.
*
* @access private
*/
_changeOrder: function() {
if ( this.comparator ) {
this.sort();
}
},
/**
* Set the default comparator only when the `orderby` property is set.
*
* @access private
*
* @param {Backbone.Model} model
* @param {string} orderby
*/
_changeOrderby: function( model, orderby ) {
// If a different comparator is defined, bail.
if ( this.comparator && this.comparator !== Attachments.comparator ) {
return;
}
if ( orderby && 'post__in' !== orderby ) {
this.comparator = Attachments.comparator;
} else {
delete this.comparator;
}
},
/**
* If the `query` property is set to true, query the server using
* the `props` values, and sync the results to this collection.
*
* @access private
*
* @param {Backbone.Model} model
* @param {Boolean} query
*/
_changeQuery: function( model, query ) {
if ( query ) {
this.props.on( 'change', this._requery, this );
this._requery();
} else {
this.props.off( 'change', this._requery, this );
}
},
/**
* @access private
*
* @param {Backbone.Model} model
*/
_changeFilteredProps: function( model ) {
// If this is a query, updating the collection will be handled by
// `this._requery()`.
if ( this.props.get('query') ) {
return;
}
var changed = _.chain( model.changed ).map( function( t, prop ) {
var filter = Attachments.filters[ prop ],
term = model.get( prop );
if ( ! filter ) {
return;
}
if ( term && ! this.filters[ prop ] ) {
this.filters[ prop ] = filter;
} else if ( ! term && this.filters[ prop ] === filter ) {
delete this.filters[ prop ];
} else {
return;
}
// Record the change.
return true;
}, this ).any().value();
if ( ! changed ) {
return;
}
// If no `Attachments` model is provided to source the searches
// from, then automatically generate a source from the existing
// models.
if ( ! this._source ) {
this._source = new Attachments( this.models );
}
this.reset( this._source.filter( this.validator, this ) );
},
validateDestroyed: false,
/**
* @param {wp.media.model.Attachment} attachment
* @returns {Boolean}
*/
validator: function( attachment ) {
if ( ! this.validateDestroyed && attachment.destroyed ) {
return false;
}
return _.all( this.filters, function( filter ) {
return !! filter.call( this, attachment );
}, this );
},
/**
* @param {wp.media.model.Attachment} attachment
* @param {Object} options
* @returns {wp.media.model.Attachments} Returns itself to allow chaining
*/
validate: function( attachment, options ) {
var valid = this.validator( attachment ),
hasAttachment = !! this.get( attachment.cid );
if ( ! valid && hasAttachment ) {
this.remove( attachment, options );
} else if ( valid && ! hasAttachment ) {
this.add( attachment, options );
}
return this;
},
/**
* @param {wp.media.model.Attachments} attachments
* @param {object} [options={}]
*
* @fires wp.media.model.Attachments#reset
*
* @returns {wp.media.model.Attachments} Returns itself to allow chaining
*/
validateAll: function( attachments, options ) {
options = options || {};
_.each( attachments.models, function( attachment ) {
this.validate( attachment, { silent: true });
}, this );
if ( ! options.silent ) {
this.trigger( 'reset', this, options );
}
return this;
},
/**
* @param {wp.media.model.Attachments} attachments
* @returns {wp.media.model.Attachments} Returns itself to allow chaining
*/
observe: function( attachments ) {
this.observers = this.observers || [];
this.observers.push( attachments );
attachments.on( 'add change remove', this._validateHandler, this );
attachments.on( 'reset', this._validateAllHandler, this );
this.validateAll( attachments );
return this;
},
/**
* @param {wp.media.model.Attachments} attachments
* @returns {wp.media.model.Attachments} Returns itself to allow chaining
*/
unobserve: function( attachments ) {
if ( attachments ) {
attachments.off( null, null, this );
this.observers = _.without( this.observers, attachments );
} else {
_.each( this.observers, function( attachments ) {
attachments.off( null, null, this );
}, this );
delete this.observers;
}
return this;
},
/**
* @access private
*
* @param {wp.media.model.Attachments} attachment
* @param {wp.media.model.Attachments} attachments
* @param {Object} options
*
* @returns {wp.media.model.Attachments} Returns itself to allow chaining
*/
_validateHandler: function( attachment, attachments, options ) {
// If we're not mirroring this `attachments` collection,
// only retain the `silent` option.
options = attachments === this.mirroring ? options : {
silent: options && options.silent
};
return this.validate( attachment, options );
},
/**
* @access private
*
* @param {wp.media.model.Attachments} attachments
* @param {Object} options
* @returns {wp.media.model.Attachments} Returns itself to allow chaining
*/
_validateAllHandler: function( attachments, options ) {
return this.validateAll( attachments, options );
},
/**
* @param {wp.media.model.Attachments} attachments
* @returns {wp.media.model.Attachments} Returns itself to allow chaining
*/
mirror: function( attachments ) {
if ( this.mirroring && this.mirroring === attachments ) {
return this;
}
this.unmirror();
this.mirroring = attachments;
// Clear the collection silently. A `reset` event will be fired
// when `observe()` calls `validateAll()`.
this.reset( [], { silent: true } );
this.observe( attachments );
return this;
},
unmirror: function() {
if ( ! this.mirroring ) {
return;
}
this.unobserve( this.mirroring );
delete this.mirroring;
},
/**
* @param {Object} options
* @returns {Promise}
*/
more: function( options ) {
var deferred = $.Deferred(),
mirroring = this.mirroring,
attachments = this;
if ( ! mirroring || ! mirroring.more ) {
return deferred.resolveWith( this ).promise();
}
// If we're mirroring another collection, forward `more` to
// the mirrored collection. Account for a race condition by
// checking if we're still mirroring that collection when
// the request resolves.
mirroring.more( options ).done( function() {
if ( this === attachments.mirroring )
deferred.resolveWith( this );
});
return deferred.promise();
},
/**
* @returns {Boolean}
*/
hasMore: function() {
return this.mirroring ? this.mirroring.hasMore() : false;
},
/**
* Overrides Backbone.Collection.parse
*
* @param {Object|Array} resp The raw response Object/Array.
* @param {Object} xhr
* @returns {Array} The array of model attributes to be added to the collection
*/
parse: function( resp, xhr ) {
if ( ! _.isArray( resp ) ) {
resp = [resp];
}
return _.map( resp, function( attrs ) {
var id, attachment, newAttributes;
if ( attrs instanceof Backbone.Model ) {
id = attrs.get( 'id' );
attrs = attrs.attributes;
} else {
id = attrs.id;
}
attachment = Attachment.get( id );
newAttributes = attachment.parse( attrs, xhr );
if ( ! _.isEqual( attachment.attributes, newAttributes ) ) {
attachment.set( newAttributes );
}
return attachment;
});
},
/**
* @access private
*/
_requery: function() {
if ( this.props.get('query') ) {
this.mirror( Query.get( this.props.toJSON() ) );
}
},
/**
* If this collection is sorted by `menuOrder`, recalculates and saves
* the menu order to the database.
*
* @returns {undefined|Promise}
*/
saveMenuOrder: function() {
if ( 'menuOrder' !== this.props.get('orderby') ) {
return;
}
// Removes any uploading attachments, updates each attachment's
// menu order, and returns an object with an { id: menuOrder }
// mapping to pass to the request.
var attachments = this.chain().filter( function( attachment ) {
return ! _.isUndefined( attachment.id );
}).map( function( attachment, index ) {
// Indices start at 1.
index = index + 1;
attachment.set( 'menuOrder', index );
return [ attachment.id, index ];
}).object().value();
if ( _.isEmpty( attachments ) ) {
return;
}
return media.post( 'save-attachment-order', {
nonce: media.model.settings.post.nonce,
post_id: media.model.settings.post.id,
attachments: attachments
});
}
}, {
/**
* @static
* Overrides Backbone.Collection.comparator
*
* @param {Backbone.Model} a
* @param {Backbone.Model} b
* @param {Object} options
* @returns {Number} -1 if the first model should come before the second,
* 0 if they are of the same rank and
* 1 if the first model should come after.
*/
comparator: function( a, b, options ) {
var key = this.props.get('orderby'),
order = this.props.get('order') || 'DESC',
ac = a.cid,
bc = b.cid;
a = a.get( key );
b = b.get( key );
if ( 'date' === key || 'modified' === key ) {
a = a || new Date();
b = b || new Date();
}
// If `options.ties` is set, don't enforce the `cid` tiebreaker.
if ( options && options.ties ) {
ac = bc = null;
}
return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac );
},
/**
* @namespace
*/
filters: {
/**
* @static
* Note that this client-side searching is *not* equivalent
* to our server-side searching.
*
* @param {wp.media.model.Attachment} attachment
*
* @this wp.media.model.Attachments
*
* @returns {Boolean}
*/
search: function( attachment ) {
if ( ! this.props.get('search') ) {
return true;
}
return _.any(['title','filename','description','caption','name'], function( key ) {
var value = attachment.get( key );
return value && -1 !== value.search( this.props.get('search') );
}, this );
},
/**
* @static
* @param {wp.media.model.Attachment} attachment
*
* @this wp.media.model.Attachments
*
* @returns {Boolean}
*/
type: function( attachment ) {
var type = this.props.get('type');
return ! type || -1 !== type.indexOf( attachment.get('type') );
},
/**
* @static
* @param {wp.media.model.Attachment} attachment
*
* @this wp.media.model.Attachments
*
* @returns {Boolean}
*/
uploadedTo: function( attachment ) {
var uploadedTo = this.props.get('uploadedTo');
if ( _.isUndefined( uploadedTo ) ) {
return true;
}
return uploadedTo === attachment.get('uploadedTo');
}
}
});
/**
* @static
* @member {wp.media.model.Attachments}
*/
Attachments.all = new Attachments();
/**
* wp.media.query
*
* @static
* @returns {wp.media.model.Attachments}
*/
media.query = function( props ) {
return new Attachments( null, {
props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } )
});
};
/**
* wp.media.model.Query
*
* A set of attachments that corresponds to a set of consecutively paged
* queries on the server.
*
* Note: Do NOT change this.args after the query has been initialized.
* Things will break.
*
* @constructor
* @augments wp.media.model.Attachments
* @augments Backbone.Collection
*/
Query = media.model.Query = Attachments.extend({
/**
* @global wp.Uploader
*
* @param {Array} [models=[]] Array of models used to populate the collection.
* @param {Object} [options={}]
*/
initialize: function( models, options ) {
var allowed;
options = options || {};
Attachments.prototype.initialize.apply( this, arguments );
this.args = options.args;
this._hasMore = true;
this.created = new Date();
this.filters.order = function( attachment ) {
var orderby = this.props.get('orderby'),
order = this.props.get('order');
if ( ! this.comparator ) {
return true;
}
// We want any items that can be placed before the last
// item in the set. If we add any items after the last
// item, then we can't guarantee the set is complete.
if ( this.length ) {
return 1 !== this.comparator( attachment, this.last(), { ties: true });
// Handle the case where there are no items yet and
// we're sorting for recent items. In that case, we want
// changes that occurred after we created the query.
} else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) {
return attachment.get( orderby ) >= this.created;
// If we're sorting by menu order and we have no items,
// accept any items that have the default menu order (0).
} else if ( 'ASC' === order && 'menuOrder' === orderby ) {
return attachment.get( orderby ) === 0;
}
// Otherwise, we don't want any items yet.
return false;
};
// Observe the central `wp.Uploader.queue` collection to watch for
// new matches for the query.
//
// Only observe when a limited number of query args are set. There
// are no filters for other properties, so observing will result in
// false positives in those queries.
allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent' ];
if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() ) {
this.observe( wp.Uploader.queue );
}
},
/**
* @returns {Boolean}
*/
hasMore: function() {
return this._hasMore;
},
/**
* @param {Object} [options={}]
* @returns {Promise}
*/
more: function( options ) {
var query = this;
if ( this._more && 'pending' === this._more.state() ) {
return this._more;
}
if ( ! this.hasMore() ) {
return $.Deferred().resolveWith( this ).promise();
}
options = options || {};
options.remove = false;
return this._more = this.fetch( options ).done( function( resp ) {
if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page ) {
query._hasMore = false;
}
});
},
/**
* Overrides Backbone.Collection.sync
* Overrides wp.media.model.Attachments.sync
*
* @param {String} method
* @param {Backbone.Model} model
* @param {Object} [options={}]
* @returns {Promise}
*/
sync: function( method, model, options ) {
var args, fallback;
// Overload the read method so Attachment.fetch() functions correctly.
if ( 'read' === method ) {
options = options || {};
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'query-attachments',
post_id: media.model.settings.post.id
});
// Clone the args so manipulation is non-destructive.
args = _.clone( this.args );
// Determine which page to query.
if ( -1 !== args.posts_per_page ) {
args.paged = Math.floor( this.length / args.posts_per_page ) + 1;
}
options.data.query = args;
return media.ajax( options );
// Otherwise, fall back to Backbone.sync()
} else {
/**
* Call wp.media.model.Attachments.sync or Backbone.sync
*/
fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
return fallback.sync.apply( this, arguments );
}
}
}, {
/**
* @readonly
*/
defaultProps: {
orderby: 'date',
order: 'DESC'
},
/**
* @readonly
*/
defaultArgs: {
posts_per_page: 40
},
/**
* @readonly
*/
orderby: {
allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ],
valuemap: {
'id': 'ID',
'uploadedTo': 'parent',
'menuOrder': 'menu_order ID'
}
},
/**
* @readonly
*/
propmap: {
'search': 's',
'type': 'post_mime_type',
'perPage': 'posts_per_page',
'menuOrder': 'menu_order',
'uploadedTo': 'post_parent'
},
/**
* @static
* @method
*
* @returns {wp.media.model.Query} A new query.
*/
// Caches query objects so queries can be easily reused.
get: (function(){
/**
* @static
* @type Array
*/
var queries = [];
/**
* @param {Object} props
* @param {Object} options
* @returns {Query}
*/
return function( props, options ) {
var args = {},
orderby = Query.orderby,
defaults = Query.defaultProps,
query;
// Remove the `query` property. This isn't linked to a query,
// this *is* the query.
delete props.query;
// Fill default args.
_.defaults( props, defaults );
// Normalize the order.
props.order = props.order.toUpperCase();
if ( 'DESC' !== props.order && 'ASC' !== props.order ) {
props.order = defaults.order.toUpperCase();
}
// Ensure we have a valid orderby value.
if ( ! _.contains( orderby.allowed, props.orderby ) ) {
props.orderby = defaults.orderby;
}
// Generate the query `args` object.
// Correct any differing property names.
_.each( props, function( value, prop ) {
if ( _.isNull( value ) ) {
return;
}
args[ Query.propmap[ prop ] || prop ] = value;
});
// Fill any other default query args.
_.defaults( args, Query.defaultArgs );
// `props.orderby` does not always map directly to `args.orderby`.
// Substitute exceptions specified in orderby.keymap.
args.orderby = orderby.valuemap[ props.orderby ] || props.orderby;
// Search the query cache for matches.
query = _.find( queries, function( query ) {
return _.isEqual( query.args, args );
});
// Otherwise, create a new query and add it to the cache.
if ( ! query ) {
query = new Query( [], _.extend( options || {}, {
props: props,
args: args
} ) );
queries.push( query );
}
return query;
};
}())
});
/**
* wp.media.model.Selection
*
* Used to manage a selection of attachments in the views.
*
* @constructor
* @augments wp.media.model.Attachments
* @augments Backbone.Collection
*/
media.model.Selection = Attachments.extend({
/**
* Refresh the `single` model whenever the selection changes.
* Binds `single` instead of using the context argument to ensure
* it receives no parameters.
*
* @param {Array} [models=[]] Array of models used to populate the collection.
* @param {Object} [options={}]
*/
initialize: function( models, options ) {
/**
* call 'initialize' directly on the parent class
*/
Attachments.prototype.initialize.apply( this, arguments );
this.multiple = options && options.multiple;
this.on( 'add remove reset', _.bind( this.single, this, false ) );
},
/**
* Override the selection's add method.
* If the workflow does not support multiple
* selected attachments, reset the selection.
*
* Overrides Backbone.Collection.add
* Overrides wp.media.model.Attachments.add
*
* @param {Array} models
* @param {Object} options
* @returns {wp.media.model.Attachment[]}
*/
add: function( models, options ) {
if ( ! this.multiple ) {
this.remove( this.models );
}
/**
* call 'add' directly on the parent class
*/
return Attachments.prototype.add.call( this, models, options );
},
/**
* Triggered when toggling (clicking on) an attachment in the modal
*
* @param {undefined|boolean|wp.media.model.Attachment} model
*
* @fires wp.media.model.Selection#selection:single
* @fires wp.media.model.Selection#selection:unsingle
*
* @returns {Backbone.Model}
*/
single: function( model ) {
var previous = this._single;
// If a `model` is provided, use it as the single model.
if ( model ) {
this._single = model;
}
// If the single model isn't in the selection, remove it.
if ( this._single && ! this.get( this._single.cid ) ) {
delete this._single;
}
this._single = this._single || this.last();
// If single has changed, fire an event.
if ( this._single !== previous ) {
if ( previous ) {
previous.trigger( 'selection:unsingle', previous, this );
// If the model was already removed, trigger the collection
// event manually.
if ( ! this.get( previous.cid ) ) {
this.trigger( 'selection:unsingle', previous, this );
}
}
if ( this._single ) {
this._single.trigger( 'selection:single', this._single, this );
}
}
// Return the single model, or the last model as a fallback.
return this._single;
}
});
// Clean up. Prevents mobile browsers caching
$(window).on('unload', function(){
window.wp = null;
});
}(jQuery));
| JavaScript |
/* global _wpMediaViewsL10n, confirm, getUserSetting, setUserSetting */
(function($, _){
var media = wp.media, l10n;
// Link any localized strings.
l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n;
// Link any settings.
media.view.settings = l10n.settings || {};
delete l10n.settings;
// Copy the `post` setting over to the model settings.
media.model.settings.post = media.view.settings.post;
// Check if the browser supports CSS 3.0 transitions
$.support.transition = (function(){
var style = document.documentElement.style,
transitions = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
}, transition;
transition = _.find( _.keys( transitions ), function( transition ) {
return ! _.isUndefined( style[ transition ] );
});
return transition && {
end: transitions[ transition ]
};
}());
/**
* A shared event bus used to provide events into
* the media workflows that 3rd-party devs can use to hook
* in.
*/
media.events = _.extend( {}, Backbone.Events );
/**
* Makes it easier to bind events using transitions.
*
* @param {string} selector
* @param {Number} sensitivity
* @returns {Promise}
*/
media.transition = function( selector, sensitivity ) {
var deferred = $.Deferred();
sensitivity = sensitivity || 2000;
if ( $.support.transition ) {
if ( ! (selector instanceof $) ) {
selector = $( selector );
}
// Resolve the deferred when the first element finishes animating.
selector.first().one( $.support.transition.end, deferred.resolve );
// Just in case the event doesn't trigger, fire a callback.
_.delay( deferred.resolve, sensitivity );
// Otherwise, execute on the spot.
} else {
deferred.resolve();
}
return deferred.promise();
};
/**
* ========================================================================
* CONTROLLERS
* ========================================================================
*/
/**
* wp.media.controller.Region
*
* @constructor
* @augments Backbone.Model
*
* @param {Object} [options={}]
*/
media.controller.Region = function( options ) {
_.extend( this, _.pick( options || {}, 'id', 'view', 'selector' ) );
};
// Use Backbone's self-propagating `extend` inheritance method.
media.controller.Region.extend = Backbone.Model.extend;
_.extend( media.controller.Region.prototype, {
/**
* Switch modes
*
* @param {string} mode
*
* @fires wp.media.controller.Region#{id}:activate:{mode}
* @fires wp.media.controller.Region#{id}:deactivate:{mode}
*
* @returns {wp.media.controller.Region} Returns itself to allow chaining
*/
mode: function( mode ) {
if ( ! mode ) {
return this._mode;
}
// Bail if we're trying to change to the current mode.
if ( mode === this._mode ) {
return this;
}
this.trigger('deactivate');
this._mode = mode;
this.render( mode );
this.trigger('activate');
return this;
},
/**
* Render a new mode, the view is set in the `create` callback method
* of the extending class
*
* If no mode is provided, just re-render the current mode.
* If the provided mode isn't active, perform a full switch.
*
* @param {string} mode
*
* @fires wp.media.controller.Region#{id}:create:{mode}
* @fires wp.media.controller.Region#{id}:render:{mode}
*
* @returns {wp.media.controller.Region} Returns itself to allow chaining
*/
render: function( mode ) {
if ( mode && mode !== this._mode ) {
return this.mode( mode );
}
var set = { view: null },
view;
this.trigger( 'create', set );
view = set.view;
this.trigger( 'render', view );
if ( view ) {
this.set( view );
}
return this;
},
/**
* @returns {wp.media.View} Returns the selector's first subview
*/
get: function() {
return this.view.views.first( this.selector );
},
/**
* @param {Array|Object} views
* @param {Object} [options={}]
* @returns {wp.Backbone.Subviews} Subviews is returned to allow chaining
*/
set: function( views, options ) {
if ( options ) {
options.add = false;
}
return this.view.views.set( this.selector, views, options );
},
/**
* Helper function to trigger view events based on {id}:{event}:{mode}
*
* @param {string} event
* @returns {undefined|wp.media.controller.Region} Returns itself to allow chaining
*/
trigger: function( event ) {
var base, args;
if ( ! this._mode ) {
return;
}
args = _.toArray( arguments );
base = this.id + ':' + event;
// Trigger `region:action:mode` event.
args[0] = base + ':' + this._mode;
this.view.trigger.apply( this.view, args );
// Trigger `region:action` event.
args[0] = base;
this.view.trigger.apply( this.view, args );
return this;
}
});
/**
* wp.media.controller.StateMachine
*
* @constructor
* @augments Backbone.Model
* @mixin
* @mixes Backbone.Events
*
* @param {Array} states
*/
media.controller.StateMachine = function( states ) {
this.states = new Backbone.Collection( states );
};
// Use Backbone's self-propagating `extend` inheritance method.
media.controller.StateMachine.extend = Backbone.Model.extend;
// Add events to the `StateMachine`.
_.extend( media.controller.StateMachine.prototype, Backbone.Events, {
/**
* Fetch a state.
*
* If no `id` is provided, returns the active state.
*
* Implicitly creates states.
*
* Ensure that the `states` collection exists so the `StateMachine`
* can be used as a mixin.
*
* @param {string} id
* @returns {wp.media.controller.State} Returns a State model
* from the StateMachine collection
*/
state: function( id ) {
this.states = this.states || new Backbone.Collection();
// Default to the active state.
id = id || this._state;
if ( id && ! this.states.get( id ) ) {
this.states.add({ id: id });
}
return this.states.get( id );
},
/**
* Sets the active state.
*
* Bail if we're trying to select the current state, if we haven't
* created the `states` collection, or are trying to select a state
* that does not exist.
*
* @param {string} id
*
* @fires wp.media.controller.State#deactivate
* @fires wp.media.controller.State#activate
*
* @returns {wp.media.controller.StateMachine} Returns itself to allow chaining
*/
setState: function( id ) {
var previous = this.state();
if ( ( previous && id === previous.id ) || ! this.states || ! this.states.get( id ) ) {
return this;
}
if ( previous ) {
previous.trigger('deactivate');
this._lastState = previous.id;
}
this._state = id;
this.state().trigger('activate');
return this;
},
/**
* Returns the previous active state.
*
* Call the `state()` method with no parameters to retrieve the current
* active state.
*
* @returns {wp.media.controller.State} Returns a State model
* from the StateMachine collection
*/
lastState: function() {
if ( this._lastState ) {
return this.state( this._lastState );
}
}
});
// Map methods from the `states` collection to the `StateMachine` itself.
_.each([ 'on', 'off', 'trigger' ], function( method ) {
/**
* @returns {wp.media.controller.StateMachine} Returns itself to allow chaining
*/
media.controller.StateMachine.prototype[ method ] = function() {
// Ensure that the `states` collection exists so the `StateMachine`
// can be used as a mixin.
this.states = this.states || new Backbone.Collection();
// Forward the method to the `states` collection.
this.states[ method ].apply( this.states, arguments );
return this;
};
});
/**
* wp.media.controller.State
*
* A state is a step in a workflow that when set will trigger
* the controllers for the regions to be updated as specified. This
* class is the base class that the various states used in the media
* modals extend.
*
* @constructor
* @augments Backbone.Model
*/
media.controller.State = Backbone.Model.extend({
constructor: function() {
this.on( 'activate', this._preActivate, this );
this.on( 'activate', this.activate, this );
this.on( 'activate', this._postActivate, this );
this.on( 'deactivate', this._deactivate, this );
this.on( 'deactivate', this.deactivate, this );
this.on( 'reset', this.reset, this );
this.on( 'ready', this._ready, this );
this.on( 'ready', this.ready, this );
/**
* Call parent constructor with passed arguments
*/
Backbone.Model.apply( this, arguments );
this.on( 'change:menu', this._updateMenu, this );
},
/**
* @abstract
*/
ready: function() {},
/**
* @abstract
*/
activate: function() {},
/**
* @abstract
*/
deactivate: function() {},
/**
* @abstract
*/
reset: function() {},
/**
* @access private
*/
_ready: function() {
this._updateMenu();
},
/**
* @access private
*/
_preActivate: function() {
this.active = true;
},
/**
* @access private
*/
_postActivate: function() {
this.on( 'change:menu', this._menu, this );
this.on( 'change:titleMode', this._title, this );
this.on( 'change:content', this._content, this );
this.on( 'change:toolbar', this._toolbar, this );
this.frame.on( 'title:render:default', this._renderTitle, this );
this._title();
this._menu();
this._toolbar();
this._content();
this._router();
},
/**
* @access private
*/
_deactivate: function() {
this.active = false;
this.frame.off( 'title:render:default', this._renderTitle, this );
this.off( 'change:menu', this._menu, this );
this.off( 'change:titleMode', this._title, this );
this.off( 'change:content', this._content, this );
this.off( 'change:toolbar', this._toolbar, this );
},
/**
* @access private
*/
_title: function() {
this.frame.title.render( this.get('titleMode') || 'default' );
},
/**
* @access private
*/
_renderTitle: function( view ) {
view.$el.text( this.get('title') || '' );
},
/**
* @access private
*/
_router: function() {
var router = this.frame.router,
mode = this.get('router'),
view;
this.frame.$el.toggleClass( 'hide-router', ! mode );
if ( ! mode ) {
return;
}
this.frame.router.render( mode );
view = router.get();
if ( view && view.select ) {
view.select( this.frame.content.mode() );
}
},
/**
* @access private
*/
_menu: function() {
var menu = this.frame.menu,
mode = this.get('menu'),
view;
if ( ! mode ) {
return;
}
menu.mode( mode );
view = menu.get();
if ( view && view.select ) {
view.select( this.id );
}
},
/**
* @access private
*/
_updateMenu: function() {
var previous = this.previous('menu'),
menu = this.get('menu');
if ( previous ) {
this.frame.off( 'menu:render:' + previous, this._renderMenu, this );
}
if ( menu ) {
this.frame.on( 'menu:render:' + menu, this._renderMenu, this );
}
},
/**
* @access private
*/
_renderMenu: function( view ) {
var menuItem = this.get('menuItem'),
title = this.get('title'),
priority = this.get('priority');
if ( ! menuItem && title ) {
menuItem = { text: title };
if ( priority ) {
menuItem.priority = priority;
}
}
if ( ! menuItem ) {
return;
}
view.set( this.id, menuItem );
}
});
_.each(['toolbar','content'], function( region ) {
/**
* @access private
*/
media.controller.State.prototype[ '_' + region ] = function() {
var mode = this.get( region );
if ( mode ) {
this.frame[ region ].render( mode );
}
};
});
media.selectionSync = {
syncSelection: function() {
var selection = this.get('selection'),
manager = this.frame._selection;
if ( ! this.get('syncSelection') || ! manager || ! selection ) {
return;
}
// If the selection supports multiple items, validate the stored
// attachments based on the new selection's conditions. Record
// the attachments that are not included; we'll maintain a
// reference to those. Other attachments are considered in flux.
if ( selection.multiple ) {
selection.reset( [], { silent: true });
selection.validateAll( manager.attachments );
manager.difference = _.difference( manager.attachments.models, selection.models );
}
// Sync the selection's single item with the master.
selection.single( manager.single );
},
/**
* Record the currently active attachments, which is a combination
* of the selection's attachments and the set of selected
* attachments that this specific selection considered invalid.
* Reset the difference and record the single attachment.
*/
recordSelection: function() {
var selection = this.get('selection'),
manager = this.frame._selection;
if ( ! this.get('syncSelection') || ! manager || ! selection ) {
return;
}
if ( selection.multiple ) {
manager.attachments.reset( selection.toArray().concat( manager.difference ) );
manager.difference = [];
} else {
manager.attachments.add( selection.toArray() );
}
manager.single = selection._single;
}
};
/**
* wp.media.controller.Library
*
* @constructor
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.Library = media.controller.State.extend({
defaults: {
id: 'library',
multiple: false, // false, 'add', 'reset'
describe: false,
toolbar: 'select',
sidebar: 'settings',
content: 'upload',
router: 'browse',
menu: 'default',
searchable: true,
filterable: false,
sortable: true,
title: l10n.mediaLibraryTitle,
// Uses a user setting to override the content mode.
contentUserSetting: true,
// Sync the selection from the last state when 'multiple' matches.
syncSelection: true
},
/**
* If a library isn't provided, query all media items.
* If a selection instance isn't provided, create one.
*/
initialize: function() {
var selection = this.get('selection'),
props;
if ( ! this.get('library') ) {
this.set( 'library', media.query() );
}
if ( ! (selection instanceof media.model.Selection) ) {
props = selection;
if ( ! props ) {
props = this.get('library').props.toJSON();
props = _.omit( props, 'orderby', 'query' );
}
// If the `selection` attribute is set to an object,
// it will use those values as the selection instance's
// `props` model. Otherwise, it will copy the library's
// `props` model.
this.set( 'selection', new media.model.Selection( null, {
multiple: this.get('multiple'),
props: props
}) );
}
if ( ! this.get('edge') ) {
this.set( 'edge', 120 );
}
if ( ! this.get('gutter') ) {
this.set( 'gutter', 8 );
}
this.resetDisplays();
},
activate: function() {
this.syncSelection();
wp.Uploader.queue.on( 'add', this.uploading, this );
this.get('selection').on( 'add remove reset', this.refreshContent, this );
if ( this.get('contentUserSetting') ) {
this.frame.on( 'content:activate', this.saveContentMode, this );
this.set( 'content', getUserSetting( 'libraryContent', this.get('content') ) );
}
},
deactivate: function() {
this.recordSelection();
this.frame.off( 'content:activate', this.saveContentMode, this );
// Unbind all event handlers that use this state as the context
// from the selection.
this.get('selection').off( null, null, this );
wp.Uploader.queue.off( null, null, this );
},
reset: function() {
this.get('selection').reset();
this.resetDisplays();
this.refreshContent();
},
resetDisplays: function() {
var defaultProps = media.view.settings.defaultProps;
this._displays = [];
this._defaultDisplaySettings = {
align: defaultProps.align || getUserSetting( 'align', 'none' ),
size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ),
link: defaultProps.link || getUserSetting( 'urlbutton', 'file' )
};
},
/**
* @param {wp.media.model.Attachment} attachment
* @returns {Backbone.Model}
*/
display: function( attachment ) {
var displays = this._displays;
if ( ! displays[ attachment.cid ] ) {
displays[ attachment.cid ] = new Backbone.Model( this.defaultDisplaySettings( attachment ) );
}
return displays[ attachment.cid ];
},
/**
* @param {wp.media.model.Attachment} attachment
* @returns {Object}
*/
defaultDisplaySettings: function( attachment ) {
var settings = this._defaultDisplaySettings;
if ( settings.canEmbed = this.canEmbed( attachment ) ) {
settings.link = 'embed';
}
return settings;
},
/**
* @param {wp.media.model.Attachment} attachment
* @returns {Boolean}
*/
canEmbed: function( attachment ) {
// If uploading, we know the filename but not the mime type.
if ( ! attachment.get('uploading') ) {
var type = attachment.get('type');
if ( type !== 'audio' && type !== 'video' ) {
return false;
}
}
return _.contains( media.view.settings.embedExts, attachment.get('filename').split('.').pop() );
},
/**
* If the state is active, no items are selected, and the current
* content mode is not an option in the state's router (provided
* the state has a router), reset the content mode to the default.
*/
refreshContent: function() {
var selection = this.get('selection'),
frame = this.frame,
router = frame.router.get(),
mode = frame.content.mode();
if ( this.active && ! selection.length && router && ! router.get( mode ) ) {
this.frame.content.render( this.get('content') );
}
},
/**
* If the uploader was selected, navigate to the browser.
*
* Automatically select any uploading attachments.
*
* Selections that don't support multiple attachments automatically
* limit themselves to one attachment (in this case, the last
* attachment in the upload queue).
*
* @param {wp.media.model.Attachment} attachment
*/
uploading: function( attachment ) {
var content = this.frame.content;
if ( 'upload' === content.mode() ) {
this.frame.content.mode('browse');
}
this.get('selection').add( attachment );
},
/**
* Only track the browse router on library states.
*/
saveContentMode: function() {
if ( 'browse' !== this.get('router') ) {
return;
}
var mode = this.frame.content.mode(),
view = this.frame.router.get();
if ( view && view.get( mode ) ) {
setUserSetting( 'libraryContent', mode );
}
}
});
_.extend( media.controller.Library.prototype, media.selectionSync );
/**
* wp.media.controller.ImageDetails
*
* @constructor
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.ImageDetails = media.controller.State.extend({
defaults: _.defaults({
id: 'image-details',
toolbar: 'image-details',
title: l10n.imageDetailsTitle,
content: 'image-details',
menu: 'image-details',
router: false,
attachment: false,
priority: 60,
editing: false
}, media.controller.Library.prototype.defaults ),
initialize: function( options ) {
this.image = options.image;
media.controller.State.prototype.initialize.apply( this, arguments );
},
activate: function() {
this.frame.modal.$el.addClass('image-details');
}
});
/**
* wp.media.controller.GalleryEdit
*
* @constructor
* @augments wp.media.controller.Library
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.GalleryEdit = media.controller.Library.extend({
defaults: {
id: 'gallery-edit',
multiple: false,
describe: true,
edge: 199,
editing: false,
sortable: true,
searchable: false,
toolbar: 'gallery-edit',
content: 'browse',
title: l10n.editGalleryTitle,
priority: 60,
dragInfo: true,
// Don't sync the selection, as the Edit Gallery library
// *is* the selection.
syncSelection: false
},
initialize: function() {
// If we haven't been provided a `library`, create a `Selection`.
if ( ! this.get('library') )
this.set( 'library', new media.model.Selection() );
// The single `Attachment` view to be used in the `Attachments` view.
if ( ! this.get('AttachmentView') )
this.set( 'AttachmentView', media.view.Attachment.EditLibrary );
media.controller.Library.prototype.initialize.apply( this, arguments );
},
activate: function() {
var library = this.get('library');
// Limit the library to images only.
library.props.set( 'type', 'image' );
// Watch for uploaded attachments.
this.get('library').observe( wp.Uploader.queue );
this.frame.on( 'content:render:browse', this.gallerySettings, this );
media.controller.Library.prototype.activate.apply( this, arguments );
},
deactivate: function() {
// Stop watching for uploaded attachments.
this.get('library').unobserve( wp.Uploader.queue );
this.frame.off( 'content:render:browse', this.gallerySettings, this );
media.controller.Library.prototype.deactivate.apply( this, arguments );
},
gallerySettings: function( browser ) {
var library = this.get('library');
if ( ! library || ! browser )
return;
library.gallery = library.gallery || new Backbone.Model();
browser.sidebar.set({
gallery: new media.view.Settings.Gallery({
controller: this,
model: library.gallery,
priority: 40
})
});
browser.toolbar.set( 'reverse', {
text: l10n.reverseOrder,
priority: 80,
click: function() {
library.reset( library.toArray().reverse() );
}
});
}
});
/**
* wp.media.controller.GalleryAdd
*
* @constructor
* @augments wp.media.controller.Library
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.GalleryAdd = media.controller.Library.extend({
defaults: _.defaults({
id: 'gallery-library',
filterable: 'uploaded',
multiple: 'add',
menu: 'gallery',
toolbar: 'gallery-add',
title: l10n.addToGalleryTitle,
priority: 100,
// Don't sync the selection, as the Edit Gallery library
// *is* the selection.
syncSelection: false
}, media.controller.Library.prototype.defaults ),
initialize: function() {
// If we haven't been provided a `library`, create a `Selection`.
if ( ! this.get('library') )
this.set( 'library', media.query({ type: 'image' }) );
media.controller.Library.prototype.initialize.apply( this, arguments );
},
activate: function() {
var library = this.get('library'),
edit = this.frame.state('gallery-edit').get('library');
if ( this.editLibrary && this.editLibrary !== edit )
library.unobserve( this.editLibrary );
// Accepts attachments that exist in the original library and
// that do not exist in gallery's library.
library.validator = function( attachment ) {
return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments );
};
// Reset the library to ensure that all attachments are re-added
// to the collection. Do so silently, as calling `observe` will
// trigger the `reset` event.
library.reset( library.mirroring.models, { silent: true });
library.observe( edit );
this.editLibrary = edit;
media.controller.Library.prototype.activate.apply( this, arguments );
}
});
/**
* wp.media.controller.CollectionEdit
*
* @constructor
* @augments wp.media.controller.Library
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.CollectionEdit = media.controller.Library.extend({
defaults: {
multiple: false,
describe: true,
edge: 199,
editing: false,
sortable: true,
searchable: false,
content: 'browse',
priority: 60,
dragInfo: true,
SettingsView: false,
// Don't sync the selection, as the Edit {Collection} library
// *is* the selection.
syncSelection: false
},
initialize: function() {
var collectionType = this.get('collectionType');
if ( 'video' === this.get( 'type' ) ) {
collectionType = 'video-' + collectionType;
}
this.set( 'id', collectionType + '-edit' );
this.set( 'toolbar', collectionType + '-edit' );
// If we haven't been provided a `library`, create a `Selection`.
if ( ! this.get('library') ) {
this.set( 'library', new media.model.Selection() );
}
// The single `Attachment` view to be used in the `Attachments` view.
if ( ! this.get('AttachmentView') ) {
this.set( 'AttachmentView', media.view.Attachment.EditLibrary );
}
media.controller.Library.prototype.initialize.apply( this, arguments );
},
activate: function() {
var library = this.get('library');
// Limit the library to images only.
library.props.set( 'type', this.get( 'type' ) );
// Watch for uploaded attachments.
this.get('library').observe( wp.Uploader.queue );
this.frame.on( 'content:render:browse', this.renderSettings, this );
media.controller.Library.prototype.activate.apply( this, arguments );
},
deactivate: function() {
// Stop watching for uploaded attachments.
this.get('library').unobserve( wp.Uploader.queue );
this.frame.off( 'content:render:browse', this.renderSettings, this );
media.controller.Library.prototype.deactivate.apply( this, arguments );
},
renderSettings: function( browser ) {
var library = this.get('library'),
collectionType = this.get('collectionType'),
dragInfoText = this.get('dragInfoText'),
SettingsView = this.get('SettingsView'),
obj = {};
if ( ! library || ! browser ) {
return;
}
library[ collectionType ] = library[ collectionType ] || new Backbone.Model();
obj[ collectionType ] = new SettingsView({
controller: this,
model: library[ collectionType ],
priority: 40
});
browser.sidebar.set( obj );
if ( dragInfoText ) {
browser.toolbar.set( 'dragInfo', new media.View({
el: $( '<div class="instructions">' + dragInfoText + '</div>' )[0],
priority: -40
}) );
}
browser.toolbar.set( 'reverse', {
text: l10n.reverseOrder,
priority: 80,
click: function() {
library.reset( library.toArray().reverse() );
}
});
}
});
/**
* wp.media.controller.CollectionAdd
*
* @constructor
* @augments wp.media.controller.Library
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.CollectionAdd = media.controller.Library.extend({
defaults: _.defaults( {
filterable: 'uploaded',
multiple: 'add',
priority: 100,
syncSelection: false
}, media.controller.Library.prototype.defaults ),
initialize: function() {
var collectionType = this.get('collectionType');
if ( 'video' === this.get( 'type' ) ) {
collectionType = 'video-' + collectionType;
}
this.set( 'id', collectionType + '-library' );
this.set( 'toolbar', collectionType + '-add' );
this.set( 'menu', collectionType );
// If we haven't been provided a `library`, create a `Selection`.
if ( ! this.get('library') ) {
this.set( 'library', media.query({ type: this.get('type') }) );
}
media.controller.Library.prototype.initialize.apply( this, arguments );
},
activate: function() {
var library = this.get('library'),
editLibrary = this.get('editLibrary'),
edit = this.frame.state( this.get('collectionType') + '-edit' ).get('library');
if ( editLibrary && editLibrary !== edit ) {
library.unobserve( editLibrary );
}
// Accepts attachments that exist in the original library and
// that do not exist in gallery's library.
library.validator = function( attachment ) {
return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments );
};
// Reset the library to ensure that all attachments are re-added
// to the collection. Do so silently, as calling `observe` will
// trigger the `reset` event.
library.reset( library.mirroring.models, { silent: true });
library.observe( edit );
this.set('editLibrary', edit);
media.controller.Library.prototype.activate.apply( this, arguments );
}
});
/**
* wp.media.controller.FeaturedImage
*
* @constructor
* @augments wp.media.controller.Library
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.FeaturedImage = media.controller.Library.extend({
defaults: _.defaults({
id: 'featured-image',
filterable: 'uploaded',
multiple: false,
toolbar: 'featured-image',
title: l10n.setFeaturedImageTitle,
priority: 60,
syncSelection: true
}, media.controller.Library.prototype.defaults ),
initialize: function() {
var library, comparator;
// If we haven't been provided a `library`, create a `Selection`.
if ( ! this.get('library') ) {
this.set( 'library', media.query({ type: 'image' }) );
}
media.controller.Library.prototype.initialize.apply( this, arguments );
library = this.get('library');
comparator = library.comparator;
// Overload the library's comparator to push items that are not in
// the mirrored query to the front of the aggregate collection.
library.comparator = function( a, b ) {
var aInQuery = !! this.mirroring.get( a.cid ),
bInQuery = !! this.mirroring.get( b.cid );
if ( ! aInQuery && bInQuery ) {
return -1;
} else if ( aInQuery && ! bInQuery ) {
return 1;
} else {
return comparator.apply( this, arguments );
}
};
// Add all items in the selection to the library, so any featured
// images that are not initially loaded still appear.
library.observe( this.get('selection') );
},
activate: function() {
this.updateSelection();
this.frame.on( 'open', this.updateSelection, this );
media.controller.Library.prototype.activate.apply( this, arguments );
},
deactivate: function() {
this.frame.off( 'open', this.updateSelection, this );
media.controller.Library.prototype.deactivate.apply( this, arguments );
},
updateSelection: function() {
var selection = this.get('selection'),
id = media.view.settings.post.featuredImageId,
attachment;
if ( '' !== id && -1 !== id ) {
attachment = media.model.Attachment.get( id );
attachment.fetch();
}
selection.reset( attachment ? [ attachment ] : [] );
}
});
/**
* wp.media.controller.ReplaceImage
*
* Replace a selected single image
*
* @constructor
* @augments wp.media.controller.Library
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.ReplaceImage = media.controller.Library.extend({
defaults: _.defaults({
id: 'replace-image',
filterable: 'uploaded',
multiple: false,
toolbar: 'replace',
title: l10n.replaceImageTitle,
priority: 60,
syncSelection: true
}, media.controller.Library.prototype.defaults ),
initialize: function( options ) {
var library, comparator;
this.image = options.image;
// If we haven't been provided a `library`, create a `Selection`.
if ( ! this.get('library') ) {
this.set( 'library', media.query({ type: 'image' }) );
}
media.controller.Library.prototype.initialize.apply( this, arguments );
library = this.get('library');
comparator = library.comparator;
// Overload the library's comparator to push items that are not in
// the mirrored query to the front of the aggregate collection.
library.comparator = function( a, b ) {
var aInQuery = !! this.mirroring.get( a.cid ),
bInQuery = !! this.mirroring.get( b.cid );
if ( ! aInQuery && bInQuery ) {
return -1;
} else if ( aInQuery && ! bInQuery ) {
return 1;
} else {
return comparator.apply( this, arguments );
}
};
// Add all items in the selection to the library, so any featured
// images that are not initially loaded still appear.
library.observe( this.get('selection') );
},
activate: function() {
this.updateSelection();
media.controller.Library.prototype.activate.apply( this, arguments );
},
updateSelection: function() {
var selection = this.get('selection'),
attachment = this.image.attachment;
selection.reset( attachment ? [ attachment ] : [] );
}
});
/**
* wp.media.controller.EditImage
*
* @constructor
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.EditImage = media.controller.State.extend({
defaults: {
id: 'edit-image',
url: '',
menu: false,
toolbar: 'edit-image',
title: l10n.editImage,
content: 'edit-image'
},
activate: function() {
this.listenTo( this.frame, 'toolbar:render:edit-image', this.toolbar );
},
deactivate: function() {
this.stopListening( this.frame );
},
toolbar: function() {
var frame = this.frame,
lastState = frame.lastState(),
previous = lastState && lastState.id;
frame.toolbar.set( new media.view.Toolbar({
controller: frame,
items: {
back: {
style: 'primary',
text: l10n.back,
priority: 20,
click: function() {
if ( previous ) {
frame.setState( previous );
} else {
frame.close();
}
}
}
}
}) );
}
});
/**
* wp.media.controller.MediaLibrary
*
* @constructor
* @augments wp.media.controller.Library
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.MediaLibrary = media.controller.Library.extend({
defaults: _.defaults({
filterable: 'uploaded',
priority: 80,
syncSelection: false,
displaySettings: false
}, media.controller.Library.prototype.defaults ),
initialize: function( options ) {
this.media = options.media;
this.type = options.type;
this.set( 'library', media.query({ type: this.type }) );
media.controller.Library.prototype.initialize.apply( this, arguments );
},
activate: function() {
if ( media.frame.lastMime ) {
this.set( 'library', media.query({ type: media.frame.lastMime }) );
delete media.frame.lastMime;
}
media.controller.Library.prototype.activate.apply( this, arguments );
}
});
/**
* wp.media.controller.Embed
*
* @constructor
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.Embed = media.controller.State.extend({
defaults: {
id: 'embed',
url: '',
menu: 'default',
content: 'embed',
toolbar: 'main-embed',
type: 'link',
title: l10n.insertFromUrlTitle,
priority: 120
},
// The amount of time used when debouncing the scan.
sensitivity: 200,
initialize: function() {
this.debouncedScan = _.debounce( _.bind( this.scan, this ), this.sensitivity );
this.props = new Backbone.Model({ url: '' });
this.props.on( 'change:url', this.debouncedScan, this );
this.props.on( 'change:url', this.refresh, this );
this.on( 'scan', this.scanImage, this );
},
/**
* @fires wp.media.controller.Embed#scan
*/
scan: function() {
var scanners,
embed = this,
attributes = {
type: 'link',
scanners: []
};
// Scan is triggered with the list of `attributes` to set on the
// state, useful for the 'type' attribute and 'scanners' attribute,
// an array of promise objects for asynchronous scan operations.
if ( this.props.get('url') ) {
this.trigger( 'scan', attributes );
}
if ( attributes.scanners.length ) {
scanners = attributes.scanners = $.when.apply( $, attributes.scanners );
scanners.always( function() {
if ( embed.get('scanners') === scanners ) {
embed.set( 'loading', false );
}
});
} else {
attributes.scanners = null;
}
attributes.loading = !! attributes.scanners;
this.set( attributes );
},
/**
* @param {Object} attributes
*/
scanImage: function( attributes ) {
var frame = this.frame,
state = this,
url = this.props.get('url'),
image = new Image(),
deferred = $.Deferred();
attributes.scanners.push( deferred.promise() );
// Try to load the image and find its width/height.
image.onload = function() {
deferred.resolve();
if ( state !== frame.state() || url !== state.props.get('url') ) {
return;
}
state.set({
type: 'image'
});
state.props.set({
width: image.width,
height: image.height
});
};
image.onerror = deferred.reject;
image.src = url;
},
refresh: function() {
this.frame.toolbar.get().refresh();
},
reset: function() {
this.props.clear().set({ url: '' });
if ( this.active ) {
this.refresh();
}
}
});
/**
* wp.media.controller.Cropper
*
* Allows for a cropping step.
*
* @constructor
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.Cropper = media.controller.State.extend({
defaults: {
id: 'cropper',
title: l10n.cropImage,
toolbar: 'crop',
content: 'crop',
router: false,
canSkipCrop: false
},
activate: function() {
this.frame.on( 'content:create:crop', this.createCropContent, this );
this.frame.on( 'close', this.removeCropper, this );
this.set('selection', new Backbone.Collection(this.frame._selection.single));
},
deactivate: function() {
this.frame.toolbar.mode('browse');
},
createCropContent: function() {
this.cropperView = new wp.media.view.Cropper({controller: this,
attachment: this.get('selection').first() });
this.cropperView.on('image-loaded', this.createCropToolbar, this);
this.frame.content.set(this.cropperView);
},
removeCropper: function() {
this.imgSelect.cancelSelection();
this.imgSelect.setOptions({remove: true});
this.imgSelect.update();
this.cropperView.remove();
},
createCropToolbar: function() {
var canSkipCrop, toolbarOptions;
canSkipCrop = this.get('canSkipCrop') || false;
toolbarOptions = {
controller: this.frame,
items: {
insert: {
style: 'primary',
text: l10n.cropImage,
priority: 80,
requires: { library: false, selection: false },
click: function() {
var self = this,
selection = this.controller.state().get('selection').first();
selection.set({cropDetails: this.controller.state().imgSelect.getSelection()});
this.$el.text(l10n.cropping);
this.$el.attr('disabled', true);
this.controller.state().doCrop( selection ).done( function( croppedImage ) {
self.controller.trigger('cropped', croppedImage );
self.controller.close();
}).fail( function() {
self.controller.trigger('content:error:crop');
});
}
}
}
};
if ( canSkipCrop ) {
_.extend( toolbarOptions.items, {
skip: {
style: 'secondary',
text: l10n.skipCropping,
priority: 70,
requires: { library: false, selection: false },
click: function() {
var selection = this.controller.state().get('selection').first();
this.controller.state().cropperView.remove();
this.controller.trigger('skippedcrop', selection);
this.controller.close();
}
}
});
}
this.frame.toolbar.set( new wp.media.view.Toolbar(toolbarOptions) );
},
doCrop: function( attachment ) {
return wp.ajax.post( 'custom-header-crop', {
nonce: attachment.get('nonces').edit,
id: attachment.get('id'),
cropDetails: attachment.get('cropDetails')
} );
}
});
/**
* ========================================================================
* VIEWS
* ========================================================================
*/
/**
* wp.media.View
* -------------
*
* The base view class.
*
* Undelegating events, removing events from the model, and
* removing events from the controller mirror the code for
* `Backbone.View.dispose` in Backbone 0.9.8 development.
*
* This behavior has since been removed, and should not be used
* outside of the media manager.
*
* @constructor
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.View = wp.Backbone.View.extend({
constructor: function( options ) {
if ( options && options.controller ) {
this.controller = options.controller;
}
wp.Backbone.View.apply( this, arguments );
},
/**
* @returns {wp.media.View} Returns itself to allow chaining
*/
dispose: function() {
// Undelegating events, removing events from the model, and
// removing events from the controller mirror the code for
// `Backbone.View.dispose` in Backbone 0.9.8 development.
this.undelegateEvents();
if ( this.model && this.model.off ) {
this.model.off( null, null, this );
}
if ( this.collection && this.collection.off ) {
this.collection.off( null, null, this );
}
// Unbind controller events.
if ( this.controller && this.controller.off ) {
this.controller.off( null, null, this );
}
return this;
},
/**
* @returns {wp.media.View} Returns itself to allow chaining
*/
remove: function() {
this.dispose();
/**
* call 'remove' directly on the parent class
*/
return wp.Backbone.View.prototype.remove.apply( this, arguments );
}
});
/**
* wp.media.view.Frame
*
* A frame is a composite view consisting of one or more regions and one or more
* states. Only one state can be active at any given moment.
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
* @mixes wp.media.controller.StateMachine
*/
media.view.Frame = media.View.extend({
initialize: function() {
this._createRegions();
this._createStates();
},
_createRegions: function() {
// Clone the regions array.
this.regions = this.regions ? this.regions.slice() : [];
// Initialize regions.
_.each( this.regions, function( region ) {
this[ region ] = new media.controller.Region({
view: this,
id: region,
selector: '.media-frame-' + region
});
}, this );
},
/**
* @fires wp.media.controller.State#ready
*/
_createStates: function() {
// Create the default `states` collection.
this.states = new Backbone.Collection( null, {
model: media.controller.State
});
// Ensure states have a reference to the frame.
this.states.on( 'add', function( model ) {
model.frame = this;
model.trigger('ready');
}, this );
if ( this.options.states ) {
this.states.add( this.options.states );
}
},
/**
* @returns {wp.media.view.Frame} Returns itself to allow chaining
*/
reset: function() {
this.states.invoke( 'trigger', 'reset' );
return this;
}
});
// Make the `Frame` a `StateMachine`.
_.extend( media.view.Frame.prototype, media.controller.StateMachine.prototype );
/**
* wp.media.view.MediaFrame
*
* Type of frame used to create the media modal.
*
* @constructor
* @augments wp.media.view.Frame
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
* @mixes wp.media.controller.StateMachine
*/
media.view.MediaFrame = media.view.Frame.extend({
className: 'media-frame',
template: media.template('media-frame'),
regions: ['menu','title','content','toolbar','router'],
/**
* @global wp.Uploader
*/
initialize: function() {
media.view.Frame.prototype.initialize.apply( this, arguments );
_.defaults( this.options, {
title: '',
modal: true,
uploader: true
});
// Ensure core UI is enabled.
this.$el.addClass('wp-core-ui');
// Initialize modal container view.
if ( this.options.modal ) {
this.modal = new media.view.Modal({
controller: this,
title: this.options.title
});
this.modal.content( this );
}
// Force the uploader off if the upload limit has been exceeded or
// if the browser isn't supported.
if ( wp.Uploader.limitExceeded || ! wp.Uploader.browser.supported ) {
this.options.uploader = false;
}
// Initialize window-wide uploader.
if ( this.options.uploader ) {
this.uploader = new media.view.UploaderWindow({
controller: this,
uploader: {
dropzone: this.modal ? this.modal.$el : this.$el,
container: this.$el
}
});
this.views.set( '.media-frame-uploader', this.uploader );
}
this.on( 'attach', _.bind( this.views.ready, this.views ), this );
// Bind default title creation.
this.on( 'title:create:default', this.createTitle, this );
this.title.mode('default');
// Bind default menu.
this.on( 'menu:create:default', this.createMenu, this );
},
/**
* @returns {wp.media.view.MediaFrame} Returns itself to allow chaining
*/
render: function() {
// Activate the default state if no active state exists.
if ( ! this.state() && this.options.state ) {
this.setState( this.options.state );
}
/**
* call 'render' directly on the parent class
*/
return media.view.Frame.prototype.render.apply( this, arguments );
},
/**
* @param {Object} title
* @this wp.media.controller.Region
*/
createTitle: function( title ) {
title.view = new media.View({
controller: this,
tagName: 'h1'
});
},
/**
* @param {Object} menu
* @this wp.media.controller.Region
*/
createMenu: function( menu ) {
menu.view = new media.view.Menu({
controller: this
});
},
/**
* @param {Object} toolbar
* @this wp.media.controller.Region
*/
createToolbar: function( toolbar ) {
toolbar.view = new media.view.Toolbar({
controller: this
});
},
/**
* @param {Object} router
* @this wp.media.controller.Region
*/
createRouter: function( router ) {
router.view = new media.view.Router({
controller: this
});
},
/**
* @param {Object} options
*/
createIframeStates: function( options ) {
var settings = media.view.settings,
tabs = settings.tabs,
tabUrl = settings.tabUrl,
$postId;
if ( ! tabs || ! tabUrl ) {
return;
}
// Add the post ID to the tab URL if it exists.
$postId = $('#post_ID');
if ( $postId.length ) {
tabUrl += '&post_id=' + $postId.val();
}
// Generate the tab states.
_.each( tabs, function( title, id ) {
this.state( 'iframe:' + id ).set( _.defaults({
tab: id,
src: tabUrl + '&tab=' + id,
title: title,
content: 'iframe',
menu: 'default'
}, options ) );
}, this );
this.on( 'content:create:iframe', this.iframeContent, this );
this.on( 'menu:render:default', this.iframeMenu, this );
this.on( 'open', this.hijackThickbox, this );
this.on( 'close', this.restoreThickbox, this );
},
/**
* @param {Object} content
* @this wp.media.controller.Region
*/
iframeContent: function( content ) {
this.$el.addClass('hide-toolbar');
content.view = new media.view.Iframe({
controller: this
});
},
iframeMenu: function( view ) {
var views = {};
if ( ! view ) {
return;
}
_.each( media.view.settings.tabs, function( title, id ) {
views[ 'iframe:' + id ] = {
text: this.state( 'iframe:' + id ).get('title'),
priority: 200
};
}, this );
view.set( views );
},
hijackThickbox: function() {
var frame = this;
if ( ! window.tb_remove || this._tb_remove ) {
return;
}
this._tb_remove = window.tb_remove;
window.tb_remove = function() {
frame.close();
frame.reset();
frame.setState( frame.options.state );
frame._tb_remove.call( window );
};
},
restoreThickbox: function() {
if ( ! this._tb_remove ) {
return;
}
window.tb_remove = this._tb_remove;
delete this._tb_remove;
}
});
// Map some of the modal's methods to the frame.
_.each(['open','close','attach','detach','escape'], function( method ) {
/**
* @returns {wp.media.view.MediaFrame} Returns itself to allow chaining
*/
media.view.MediaFrame.prototype[ method ] = function() {
if ( this.modal ) {
this.modal[ method ].apply( this.modal, arguments );
}
return this;
};
});
/**
* wp.media.view.MediaFrame.Select
*
* Type of media frame that is used to select an item or items from the media library
*
* @constructor
* @augments wp.media.view.MediaFrame
* @augments wp.media.view.Frame
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
* @mixes wp.media.controller.StateMachine
*/
media.view.MediaFrame.Select = media.view.MediaFrame.extend({
initialize: function() {
/**
* call 'initialize' directly on the parent class
*/
media.view.MediaFrame.prototype.initialize.apply( this, arguments );
_.defaults( this.options, {
selection: [],
library: {},
multiple: false,
state: 'library'
});
this.createSelection();
this.createStates();
this.bindHandlers();
},
createSelection: function() {
var selection = this.options.selection;
if ( ! (selection instanceof media.model.Selection) ) {
this.options.selection = new media.model.Selection( selection, {
multiple: this.options.multiple
});
}
this._selection = {
attachments: new media.model.Attachments(),
difference: []
};
},
createStates: function() {
var options = this.options;
if ( this.options.states ) {
return;
}
// Add the default states.
this.states.add([
// Main states.
new media.controller.Library({
library: media.query( options.library ),
multiple: options.multiple,
title: options.title,
priority: 20
})
]);
},
bindHandlers: function() {
this.on( 'router:create:browse', this.createRouter, this );
this.on( 'router:render:browse', this.browseRouter, this );
this.on( 'content:create:browse', this.browseContent, this );
this.on( 'content:render:upload', this.uploadContent, this );
this.on( 'toolbar:create:select', this.createSelectToolbar, this );
},
// Routers
browseRouter: function( view ) {
view.set({
upload: {
text: l10n.uploadFilesTitle,
priority: 20
},
browse: {
text: l10n.mediaLibraryTitle,
priority: 40
}
});
},
/**
* Content
*
* @param {Object} content
* @this wp.media.controller.Region
*/
browseContent: function( content ) {
var state = this.state();
this.$el.removeClass('hide-toolbar');
// Browse our library of attachments.
content.view = new media.view.AttachmentsBrowser({
controller: this,
collection: state.get('library'),
selection: state.get('selection'),
model: state,
sortable: state.get('sortable'),
search: state.get('searchable'),
filters: state.get('filterable'),
display: state.get('displaySettings'),
dragInfo: state.get('dragInfo'),
suggestedWidth: state.get('suggestedWidth'),
suggestedHeight: state.get('suggestedHeight'),
AttachmentView: state.get('AttachmentView')
});
},
/**
*
* @this wp.media.controller.Region
*/
uploadContent: function() {
this.$el.removeClass('hide-toolbar');
this.content.set( new media.view.UploaderInline({
controller: this
}) );
},
/**
* Toolbars
*
* @param {Object} toolbar
* @param {Object} [options={}]
* @this wp.media.controller.Region
*/
createSelectToolbar: function( toolbar, options ) {
options = options || this.options.button || {};
options.controller = this;
toolbar.view = new media.view.Toolbar.Select( options );
}
});
/**
* wp.media.view.MediaFrame.Post
*
* @constructor
* @augments wp.media.view.MediaFrame.Select
* @augments wp.media.view.MediaFrame
* @augments wp.media.view.Frame
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
* @mixes wp.media.controller.StateMachine
*/
media.view.MediaFrame.Post = media.view.MediaFrame.Select.extend({
initialize: function() {
this.counts = {
audio: {
count: media.view.settings.attachmentCounts.audio,
state: 'playlist'
},
video: {
count: media.view.settings.attachmentCounts.video,
state: 'video-playlist'
}
};
_.defaults( this.options, {
multiple: true,
editing: false,
state: 'insert'
});
/**
* call 'initialize' directly on the parent class
*/
media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
this.createIframeStates();
},
createStates: function() {
var options = this.options;
// Add the default states.
this.states.add([
// Main states.
new media.controller.Library({
id: 'insert',
title: l10n.insertMediaTitle,
priority: 20,
toolbar: 'main-insert',
filterable: 'all',
library: media.query( options.library ),
multiple: options.multiple ? 'reset' : false,
editable: true,
// If the user isn't allowed to edit fields,
// can they still edit it locally?
allowLocalEdits: true,
// Show the attachment display settings.
displaySettings: true,
// Update user settings when users adjust the
// attachment display settings.
displayUserSettings: true
}),
new media.controller.Library({
id: 'gallery',
title: l10n.createGalleryTitle,
priority: 40,
toolbar: 'main-gallery',
filterable: 'uploaded',
multiple: 'add',
editable: false,
library: media.query( _.defaults({
type: 'image'
}, options.library ) )
}),
// Embed states.
new media.controller.Embed(),
new media.controller.EditImage( { model: options.editImage } ),
// Gallery states.
new media.controller.GalleryEdit({
library: options.selection,
editing: options.editing,
menu: 'gallery'
}),
new media.controller.GalleryAdd(),
new media.controller.Library({
id: 'playlist',
title: l10n.createPlaylistTitle,
priority: 60,
toolbar: 'main-playlist',
filterable: 'uploaded',
multiple: 'add',
editable: false,
library: media.query( _.defaults({
type: 'audio'
}, options.library ) )
}),
// Playlist states.
new media.controller.CollectionEdit({
type: 'audio',
collectionType: 'playlist',
title: l10n.editPlaylistTitle,
SettingsView: media.view.Settings.Playlist,
library: options.selection,
editing: options.editing,
menu: 'playlist',
dragInfoText: l10n.playlistDragInfo,
dragInfo: false
}),
new media.controller.CollectionAdd({
type: 'audio',
collectionType: 'playlist',
title: l10n.addToPlaylistTitle
}),
new media.controller.Library({
id: 'video-playlist',
title: l10n.createVideoPlaylistTitle,
priority: 60,
toolbar: 'main-video-playlist',
filterable: 'uploaded',
multiple: 'add',
editable: false,
library: media.query( _.defaults({
type: 'video'
}, options.library ) )
}),
new media.controller.CollectionEdit({
type: 'video',
collectionType: 'playlist',
title: l10n.editVideoPlaylistTitle,
SettingsView: media.view.Settings.Playlist,
library: options.selection,
editing: options.editing,
menu: 'video-playlist',
dragInfoText: l10n.playlistDragInfo,
dragInfo: false
}),
new media.controller.CollectionAdd({
type: 'video',
collectionType: 'playlist',
title: l10n.addToVideoPlaylistTitle
})
]);
if ( media.view.settings.post.featuredImageId ) {
this.states.add( new media.controller.FeaturedImage() );
}
},
bindHandlers: function() {
var handlers, checkCounts;
media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
this.on( 'activate', this.activate, this );
// Only bother checking media type counts if one of the counts is zero
checkCounts = _.find( this.counts, function( type ) {
return type.count === 0;
} );
if ( typeof checkCounts !== 'undefined' ) {
this.listenTo( media.model.Attachments.all, 'change:type', this.mediaTypeCounts );
}
this.on( 'menu:create:gallery', this.createMenu, this );
this.on( 'menu:create:playlist', this.createMenu, this );
this.on( 'menu:create:video-playlist', this.createMenu, this );
this.on( 'toolbar:create:main-insert', this.createToolbar, this );
this.on( 'toolbar:create:main-gallery', this.createToolbar, this );
this.on( 'toolbar:create:main-playlist', this.createToolbar, this );
this.on( 'toolbar:create:main-video-playlist', this.createToolbar, this );
this.on( 'toolbar:create:featured-image', this.featuredImageToolbar, this );
this.on( 'toolbar:create:main-embed', this.mainEmbedToolbar, this );
handlers = {
menu: {
'default': 'mainMenu',
'gallery': 'galleryMenu',
'playlist': 'playlistMenu',
'video-playlist': 'videoPlaylistMenu'
},
content: {
'embed': 'embedContent',
'edit-image': 'editImageContent',
'edit-selection': 'editSelectionContent'
},
toolbar: {
'main-insert': 'mainInsertToolbar',
'main-gallery': 'mainGalleryToolbar',
'gallery-edit': 'galleryEditToolbar',
'gallery-add': 'galleryAddToolbar',
'main-playlist': 'mainPlaylistToolbar',
'playlist-edit': 'playlistEditToolbar',
'playlist-add': 'playlistAddToolbar',
'main-video-playlist': 'mainVideoPlaylistToolbar',
'video-playlist-edit': 'videoPlaylistEditToolbar',
'video-playlist-add': 'videoPlaylistAddToolbar'
}
};
_.each( handlers, function( regionHandlers, region ) {
_.each( regionHandlers, function( callback, handler ) {
this.on( region + ':render:' + handler, this[ callback ], this );
}, this );
}, this );
},
activate: function() {
// Hide menu items for states tied to particular media types if there are no items
_.each( this.counts, function( type ) {
if ( type.count < 1 ) {
this.menuItemVisibility( type.state, 'hide' );
}
}, this );
},
mediaTypeCounts: function( model, attr ) {
if ( typeof this.counts[ attr ] !== 'undefined' && this.counts[ attr ].count < 1 ) {
this.counts[ attr ].count++;
this.menuItemVisibility( this.counts[ attr ].state, 'show' );
}
},
// Menus
/**
* @param {wp.Backbone.View} view
*/
mainMenu: function( view ) {
view.set({
'library-separator': new media.View({
className: 'separator',
priority: 100
})
});
},
menuItemVisibility: function( state, visibility ) {
var menu = this.menu.get();
if ( visibility === 'hide' ) {
menu.hide( state );
} else if ( visibility === 'show' ) {
menu.show( state );
}
},
/**
* @param {wp.Backbone.View} view
*/
galleryMenu: function( view ) {
var lastState = this.lastState(),
previous = lastState && lastState.id,
frame = this;
view.set({
cancel: {
text: l10n.cancelGalleryTitle,
priority: 20,
click: function() {
if ( previous ) {
frame.setState( previous );
} else {
frame.close();
}
}
},
separateCancel: new media.View({
className: 'separator',
priority: 40
})
});
},
playlistMenu: function( view ) {
var lastState = this.lastState(),
previous = lastState && lastState.id,
frame = this;
view.set({
cancel: {
text: l10n.cancelPlaylistTitle,
priority: 20,
click: function() {
if ( previous ) {
frame.setState( previous );
} else {
frame.close();
}
}
},
separateCancel: new media.View({
className: 'separator',
priority: 40
})
});
},
videoPlaylistMenu: function( view ) {
var lastState = this.lastState(),
previous = lastState && lastState.id,
frame = this;
view.set({
cancel: {
text: l10n.cancelVideoPlaylistTitle,
priority: 20,
click: function() {
if ( previous ) {
frame.setState( previous );
} else {
frame.close();
}
}
},
separateCancel: new media.View({
className: 'separator',
priority: 40
})
});
},
// Content
embedContent: function() {
var view = new media.view.Embed({
controller: this,
model: this.state()
}).render();
this.content.set( view );
view.url.focus();
},
editSelectionContent: function() {
var state = this.state(),
selection = state.get('selection'),
view;
view = new media.view.AttachmentsBrowser({
controller: this,
collection: selection,
selection: selection,
model: state,
sortable: true,
search: false,
dragInfo: true,
AttachmentView: media.view.Attachment.EditSelection
}).render();
view.toolbar.set( 'backToLibrary', {
text: l10n.returnToLibrary,
priority: -100,
click: function() {
this.controller.content.mode('browse');
}
});
// Browse our library of attachments.
this.content.set( view );
},
editImageContent: function() {
var image = this.state().get('image'),
view = new media.view.EditImage( { model: image, controller: this } ).render();
this.content.set( view );
// after creating the wrapper view, load the actual editor via an ajax call
view.loadEditor();
},
// Toolbars
/**
* @param {wp.Backbone.View} view
*/
selectionStatusToolbar: function( view ) {
var editable = this.state().get('editable');
view.set( 'selection', new media.view.Selection({
controller: this,
collection: this.state().get('selection'),
priority: -40,
// If the selection is editable, pass the callback to
// switch the content mode.
editable: editable && function() {
this.controller.content.mode('edit-selection');
}
}).render() );
},
/**
* @param {wp.Backbone.View} view
*/
mainInsertToolbar: function( view ) {
var controller = this;
this.selectionStatusToolbar( view );
view.set( 'insert', {
style: 'primary',
priority: 80,
text: l10n.insertIntoPost,
requires: { selection: true },
/**
* @fires wp.media.controller.State#insert
*/
click: function() {
var state = controller.state(),
selection = state.get('selection');
controller.close();
state.trigger( 'insert', selection ).reset();
}
});
},
/**
* @param {wp.Backbone.View} view
*/
mainGalleryToolbar: function( view ) {
var controller = this;
this.selectionStatusToolbar( view );
view.set( 'gallery', {
style: 'primary',
text: l10n.createNewGallery,
priority: 60,
requires: { selection: true },
click: function() {
var selection = controller.state().get('selection'),
edit = controller.state('gallery-edit'),
models = selection.where({ type: 'image' });
edit.set( 'library', new media.model.Selection( models, {
props: selection.props.toJSON(),
multiple: true
}) );
this.controller.setState('gallery-edit');
}
});
},
mainPlaylistToolbar: function( view ) {
var controller = this;
this.selectionStatusToolbar( view );
view.set( 'playlist', {
style: 'primary',
text: l10n.createNewPlaylist,
priority: 100,
requires: { selection: true },
click: function() {
var selection = controller.state().get('selection'),
edit = controller.state('playlist-edit'),
models = selection.where({ type: 'audio' });
edit.set( 'library', new media.model.Selection( models, {
props: selection.props.toJSON(),
multiple: true
}) );
this.controller.setState('playlist-edit');
}
});
},
mainVideoPlaylistToolbar: function( view ) {
var controller = this;
this.selectionStatusToolbar( view );
view.set( 'video-playlist', {
style: 'primary',
text: l10n.createNewVideoPlaylist,
priority: 100,
requires: { selection: true },
click: function() {
var selection = controller.state().get('selection'),
edit = controller.state('video-playlist-edit'),
models = selection.where({ type: 'video' });
edit.set( 'library', new media.model.Selection( models, {
props: selection.props.toJSON(),
multiple: true
}) );
this.controller.setState('video-playlist-edit');
}
});
},
featuredImageToolbar: function( toolbar ) {
this.createSelectToolbar( toolbar, {
text: l10n.setFeaturedImage,
state: this.options.state
});
},
mainEmbedToolbar: function( toolbar ) {
toolbar.view = new media.view.Toolbar.Embed({
controller: this
});
},
galleryEditToolbar: function() {
var editing = this.state().get('editing');
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
insert: {
style: 'primary',
text: editing ? l10n.updateGallery : l10n.insertGallery,
priority: 80,
requires: { library: true },
/**
* @fires wp.media.controller.State#update
*/
click: function() {
var controller = this.controller,
state = controller.state();
controller.close();
state.trigger( 'update', state.get('library') );
// Restore and reset the default state.
controller.setState( controller.options.state );
controller.reset();
}
}
}
}) );
},
galleryAddToolbar: function() {
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
insert: {
style: 'primary',
text: l10n.addToGallery,
priority: 80,
requires: { selection: true },
/**
* @fires wp.media.controller.State#reset
*/
click: function() {
var controller = this.controller,
state = controller.state(),
edit = controller.state('gallery-edit');
edit.get('library').add( state.get('selection').models );
state.trigger('reset');
controller.setState('gallery-edit');
}
}
}
}) );
},
playlistEditToolbar: function() {
var editing = this.state().get('editing');
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
insert: {
style: 'primary',
text: editing ? l10n.updatePlaylist : l10n.insertPlaylist,
priority: 80,
requires: { library: true },
/**
* @fires wp.media.controller.State#update
*/
click: function() {
var controller = this.controller,
state = controller.state();
controller.close();
state.trigger( 'update', state.get('library') );
// Restore and reset the default state.
controller.setState( controller.options.state );
controller.reset();
}
}
}
}) );
},
playlistAddToolbar: function() {
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
insert: {
style: 'primary',
text: l10n.addToPlaylist,
priority: 80,
requires: { selection: true },
/**
* @fires wp.media.controller.State#reset
*/
click: function() {
var controller = this.controller,
state = controller.state(),
edit = controller.state('playlist-edit');
edit.get('library').add( state.get('selection').models );
state.trigger('reset');
controller.setState('playlist-edit');
}
}
}
}) );
},
videoPlaylistEditToolbar: function() {
var editing = this.state().get('editing');
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
insert: {
style: 'primary',
text: editing ? l10n.updateVideoPlaylist : l10n.insertVideoPlaylist,
priority: 140,
requires: { library: true },
click: function() {
var controller = this.controller,
state = controller.state(),
library = state.get('library');
library.type = 'video';
controller.close();
state.trigger( 'update', library );
// Restore and reset the default state.
controller.setState( controller.options.state );
controller.reset();
}
}
}
}) );
},
videoPlaylistAddToolbar: function() {
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
insert: {
style: 'primary',
text: l10n.addToVideoPlaylist,
priority: 140,
requires: { selection: true },
click: function() {
var controller = this.controller,
state = controller.state(),
edit = controller.state('video-playlist-edit');
edit.get('library').add( state.get('selection').models );
state.trigger('reset');
controller.setState('video-playlist-edit');
}
}
}
}) );
}
});
/**
* wp.media.view.MediaFrame.ImageDetails
*
* @constructor
* @augments wp.media.view.MediaFrame.Select
* @augments wp.media.view.MediaFrame
* @augments wp.media.view.Frame
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
* @mixes wp.media.controller.StateMachine
*/
media.view.MediaFrame.ImageDetails = media.view.MediaFrame.Select.extend({
defaults: {
id: 'image',
url: '',
menu: 'image-details',
content: 'image-details',
toolbar: 'image-details',
type: 'link',
title: l10n.imageDetailsTitle,
priority: 120
},
initialize: function( options ) {
this.image = new media.model.PostImage( options.metadata );
this.options.selection = new media.model.Selection( this.image.attachment, { multiple: false } );
media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
},
bindHandlers: function() {
media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
this.on( 'menu:create:image-details', this.createMenu, this );
this.on( 'content:create:image-details', this.imageDetailsContent, this );
this.on( 'content:render:edit-image', this.editImageContent, this );
this.on( 'menu:render:image-details', this.renderMenu, this );
this.on( 'toolbar:render:image-details', this.renderImageDetailsToolbar, this );
// override the select toolbar
this.on( 'toolbar:render:replace', this.renderReplaceImageToolbar, this );
},
createStates: function() {
this.states.add([
new media.controller.ImageDetails({
image: this.image,
editable: false,
menu: 'image-details'
}),
new media.controller.ReplaceImage({
id: 'replace-image',
library: media.query( { type: 'image' } ),
image: this.image,
multiple: false,
title: l10n.imageReplaceTitle,
menu: 'image-details',
toolbar: 'replace',
priority: 80,
displaySettings: true
}),
new media.controller.EditImage( {
image: this.image,
selection: this.options.selection
} )
]);
},
imageDetailsContent: function( options ) {
options.view = new media.view.ImageDetails({
controller: this,
model: this.state().image,
attachment: this.state().image.attachment
});
},
editImageContent: function() {
var state = this.state(),
model = state.get('image'),
view;
if ( ! model ) {
return;
}
view = new media.view.EditImage( { model: model, controller: this } ).render();
this.content.set( view );
// after bringing in the frame, load the actual editor via an ajax call
view.loadEditor();
},
renderMenu: function( view ) {
var lastState = this.lastState(),
previous = lastState && lastState.id,
frame = this;
view.set({
cancel: {
text: l10n.imageDetailsCancel,
priority: 20,
click: function() {
if ( previous ) {
frame.setState( previous );
} else {
frame.close();
}
}
},
separateCancel: new media.View({
className: 'separator',
priority: 40
})
});
},
renderImageDetailsToolbar: function() {
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
select: {
style: 'primary',
text: l10n.update,
priority: 80,
click: function() {
var controller = this.controller,
state = controller.state();
controller.close();
// not sure if we want to use wp.media.string.image which will create a shortcode or
// perhaps wp.html.string to at least to build the <img />
state.trigger( 'update', controller.image.toJSON() );
// Restore and reset the default state.
controller.setState( controller.options.state );
controller.reset();
}
}
}
}) );
},
renderReplaceImageToolbar: function() {
var frame = this,
lastState = frame.lastState(),
previous = lastState && lastState.id;
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
back: {
text: l10n.back,
priority: 20,
click: function() {
if ( previous ) {
frame.setState( previous );
} else {
frame.close();
}
}
},
replace: {
style: 'primary',
text: l10n.replace,
priority: 80,
click: function() {
var controller = this.controller,
state = controller.state(),
selection = state.get( 'selection' ),
attachment = selection.single();
controller.close();
controller.image.changeAttachment( attachment, state.display( attachment ) );
// not sure if we want to use wp.media.string.image which will create a shortcode or
// perhaps wp.html.string to at least to build the <img />
state.trigger( 'replace', controller.image.toJSON() );
// Restore and reset the default state.
controller.setState( controller.options.state );
controller.reset();
}
}
}
}) );
}
});
/**
* wp.media.view.Modal
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Modal = media.View.extend({
tagName: 'div',
template: media.template('media-modal'),
attributes: {
tabindex: 0
},
events: {
'click .media-modal-backdrop, .media-modal-close': 'escapeHandler',
'keydown': 'keydown'
},
initialize: function() {
_.defaults( this.options, {
container: document.body,
title: '',
propagate: true,
freeze: true
});
},
/**
* @returns {Object}
*/
prepare: function() {
return {
title: this.options.title
};
},
/**
* @returns {wp.media.view.Modal} Returns itself to allow chaining
*/
attach: function() {
if ( this.views.attached ) {
return this;
}
if ( ! this.views.rendered ) {
this.render();
}
this.$el.appendTo( this.options.container );
// Manually mark the view as attached and trigger ready.
this.views.attached = true;
this.views.ready();
return this.propagate('attach');
},
/**
* @returns {wp.media.view.Modal} Returns itself to allow chaining
*/
detach: function() {
if ( this.$el.is(':visible') ) {
this.close();
}
this.$el.detach();
this.views.attached = false;
return this.propagate('detach');
},
/**
* @returns {wp.media.view.Modal} Returns itself to allow chaining
*/
open: function() {
var $el = this.$el,
options = this.options;
if ( $el.is(':visible') ) {
return this;
}
if ( ! this.views.attached ) {
this.attach();
}
// If the `freeze` option is set, record the window's scroll position.
if ( options.freeze ) {
this._freeze = {
scrollTop: $( window ).scrollTop()
};
}
$el.show().focus();
return this.propagate('open');
},
/**
* @param {Object} options
* @returns {wp.media.view.Modal} Returns itself to allow chaining
*/
close: function( options ) {
var freeze = this._freeze;
if ( ! this.views.attached || ! this.$el.is(':visible') ) {
return this;
}
this.$el.hide();
this.propagate('close');
// If the `freeze` option is set, restore the container's scroll position.
if ( freeze ) {
$( window ).scrollTop( freeze.scrollTop );
}
if ( options && options.escape ) {
this.propagate('escape');
}
return this;
},
/**
* @returns {wp.media.view.Modal} Returns itself to allow chaining
*/
escape: function() {
return this.close({ escape: true });
},
/**
* @param {Object} event
*/
escapeHandler: function( event ) {
event.preventDefault();
this.escape();
},
/**
* @param {Array|Object} content Views to register to '.media-modal-content'
* @returns {wp.media.view.Modal} Returns itself to allow chaining
*/
content: function( content ) {
this.views.set( '.media-modal-content', content );
return this;
},
/**
* Triggers a modal event and if the `propagate` option is set,
* forwards events to the modal's controller.
*
* @param {string} id
* @returns {wp.media.view.Modal} Returns itself to allow chaining
*/
propagate: function( id ) {
this.trigger( id );
if ( this.options.propagate ) {
this.controller.trigger( id );
}
return this;
},
/**
* @param {Object} event
*/
keydown: function( event ) {
// Close the modal when escape is pressed.
if ( 27 === event.which && this.$el.is(':visible') ) {
this.escape();
event.stopImmediatePropagation();
}
}
});
/**
* wp.media.view.FocusManager
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.FocusManager = media.View.extend({
events: {
keydown: 'recordTab',
focusin: 'updateIndex'
},
focus: function() {
if ( _.isUndefined( this.index ) ) {
return;
}
// Update our collection of `$tabbables`.
this.$tabbables = this.$(':tabbable');
// If tab is saved, focus it.
this.$tabbables.eq( this.index ).focus();
},
/**
* @param {Object} event
*/
recordTab: function( event ) {
// Look for the tab key.
if ( 9 !== event.keyCode ) {
return;
}
// First try to update the index.
if ( _.isUndefined( this.index ) ) {
this.updateIndex( event );
}
// If we still don't have an index, bail.
if ( _.isUndefined( this.index ) ) {
return;
}
var index = this.index + ( event.shiftKey ? -1 : 1 );
if ( index >= 0 && index < this.$tabbables.length ) {
this.index = index;
} else {
delete this.index;
}
},
/**
* @param {Object} event
*/
updateIndex: function( event ) {
this.$tabbables = this.$(':tabbable');
var index = this.$tabbables.index( event.target );
if ( -1 === index ) {
delete this.index;
} else {
this.index = index;
}
}
});
/**
* wp.media.view.UploaderWindow
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.UploaderWindow = media.View.extend({
tagName: 'div',
className: 'uploader-window',
template: media.template('uploader-window'),
initialize: function() {
var uploader;
this.$browser = $('<a href="#" class="browser" />').hide().appendTo('body');
uploader = this.options.uploader = _.defaults( this.options.uploader || {}, {
dropzone: this.$el,
browser: this.$browser,
params: {}
});
// Ensure the dropzone is a jQuery collection.
if ( uploader.dropzone && ! (uploader.dropzone instanceof $) ) {
uploader.dropzone = $( uploader.dropzone );
}
this.controller.on( 'activate', this.refresh, this );
this.controller.on( 'detach', function() {
this.$browser.remove();
}, this );
},
refresh: function() {
if ( this.uploader ) {
this.uploader.refresh();
}
},
ready: function() {
var postId = media.view.settings.post.id,
dropzone;
// If the uploader already exists, bail.
if ( this.uploader ) {
return;
}
if ( postId ) {
this.options.uploader.params.post_id = postId;
}
this.uploader = new wp.Uploader( this.options.uploader );
dropzone = this.uploader.dropzone;
dropzone.on( 'dropzone:enter', _.bind( this.show, this ) );
dropzone.on( 'dropzone:leave', _.bind( this.hide, this ) );
$( this.uploader ).on( 'uploader:ready', _.bind( this._ready, this ) );
},
_ready: function() {
this.controller.trigger( 'uploader:ready' );
},
show: function() {
var $el = this.$el.show();
// Ensure that the animation is triggered by waiting until
// the transparent element is painted into the DOM.
_.defer( function() {
$el.css({ opacity: 1 });
});
},
hide: function() {
var $el = this.$el.css({ opacity: 0 });
media.transition( $el ).done( function() {
// Transition end events are subject to race conditions.
// Make sure that the value is set as intended.
if ( '0' === $el.css('opacity') ) {
$el.hide();
}
});
}
});
/**
* wp.media.view.EditorUploader
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.EditorUploader = media.View.extend({
tagName: 'div',
className: 'uploader-editor',
template: media.template( 'uploader-editor' ),
localDrag: false,
overContainer: false,
overDropzone: false,
initialize: function() {
var self = this;
this.initialized = false;
// Bail if not enabled or UA does not support drag'n'drop or File API.
if ( ! window.tinyMCEPreInit || ! window.tinyMCEPreInit.dragDropUpload || ! this.browserSupport() ) {
return this;
}
this.$document = $(document);
this.dropzones = [];
this.files = [];
this.$document.on( 'drop', '.uploader-editor', _.bind( this.drop, this ) );
this.$document.on( 'dragover', '.uploader-editor', _.bind( this.dropzoneDragover, this ) );
this.$document.on( 'dragleave', '.uploader-editor', _.bind( this.dropzoneDragleave, this ) );
this.$document.on( 'click', '.uploader-editor', _.bind( this.click, this ) );
this.$document.on( 'dragover', _.bind( this.containerDragover, this ) );
this.$document.on( 'dragleave', _.bind( this.containerDragleave, this ) );
this.$document.on( 'dragstart dragend drop', function( event ) {
self.localDrag = event.type === 'dragstart';
});
this.initialized = true;
return this;
},
browserSupport: function() {
var supports = false, div = document.createElement('div');
supports = ( 'draggable' in div ) || ( 'ondragstart' in div && 'ondrop' in div );
supports = supports && !! ( window.File && window.FileList && window.FileReader );
return supports;
},
refresh: function( e ) {
var dropzone_id;
for ( dropzone_id in this.dropzones ) {
// Hide the dropzones only if dragging has left the screen.
this.dropzones[ dropzone_id ].toggle( this.overContainer || this.overDropzone );
}
if ( ! _.isUndefined( e ) ) {
$( e.target ).closest( '.uploader-editor' ).toggleClass( 'droppable', this.overDropzone );
}
return this;
},
render: function() {
if ( ! this.initialized ) {
return this;
}
media.View.prototype.render.apply( this, arguments );
$( '.wp-editor-wrap, #wp-fullscreen-body' ).each( _.bind( this.attach, this ) );
return this;
},
attach: function( index, editor ) {
// Attach a dropzone to an editor.
var dropzone = this.$el.clone();
this.dropzones.push( dropzone );
$( editor ).append( dropzone );
return this;
},
drop: function( event ) {
var $wrap = null;
this.containerDragleave( event );
this.dropzoneDragleave( event );
this.files = event.originalEvent.dataTransfer.files;
if ( this.files.length < 1 ) {
return;
}
// Set the active editor to the drop target.
$wrap = $( event.target ).parents( '.wp-editor-wrap' );
if ( $wrap.length > 0 && $wrap[0].id ) {
window.wpActiveEditor = $wrap[0].id.slice( 3, -5 );
}
if ( ! this.workflow ) {
this.workflow = wp.media.editor.open( 'content', {
frame: 'post',
state: 'insert',
title: wp.media.view.l10n.addMedia,
multiple: true
});
this.workflow.on( 'uploader:ready', this.addFiles, this );
} else {
this.workflow.state().reset();
this.addFiles.apply( this );
this.workflow.open();
}
return false;
},
addFiles: function() {
if ( this.files.length ) {
this.workflow.uploader.uploader.uploader.addFile( _.toArray( this.files ) );
this.files = [];
}
return this;
},
containerDragover: function() {
if ( this.localDrag ) {
return;
}
this.overContainer = true;
this.refresh();
},
containerDragleave: function() {
this.overContainer = false;
// Throttle dragleave because it's called when bouncing from some elements to others.
_.delay( _.bind( this.refresh, this ), 50 );
},
dropzoneDragover: function( e ) {
if ( this.localDrag ) {
return;
}
this.overDropzone = true;
this.refresh( e );
return false;
},
dropzoneDragleave: function( e ) {
this.overDropzone = false;
_.delay( _.bind( this.refresh, this, e ), 50 );
},
click: function( e ) {
// In the rare case where the dropzone gets stuck, hide it on click.
this.containerDragleave( e );
this.dropzoneDragleave( e );
this.localDrag = false;
}
});
/**
* wp.media.view.UploaderInline
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.UploaderInline = media.View.extend({
tagName: 'div',
className: 'uploader-inline',
template: media.template('uploader-inline'),
initialize: function() {
_.defaults( this.options, {
message: '',
status: true
});
if ( ! this.options.$browser && this.controller.uploader ) {
this.options.$browser = this.controller.uploader.$browser;
}
if ( _.isUndefined( this.options.postId ) ) {
this.options.postId = media.view.settings.post.id;
}
if ( this.options.status ) {
this.views.set( '.upload-inline-status', new media.view.UploaderStatus({
controller: this.controller
}) );
}
},
prepare: function() {
var suggestedWidth = this.controller.state().get('suggestedWidth'),
suggestedHeight = this.controller.state().get('suggestedHeight');
if ( suggestedWidth && suggestedHeight ) {
return {
suggestedWidth: suggestedWidth,
suggestedHeight: suggestedHeight
};
}
},
/**
* @returns {wp.media.view.UploaderInline} Returns itself to allow chaining
*/
dispose: function() {
if ( this.disposing ) {
/**
* call 'dispose' directly on the parent class
*/
return media.View.prototype.dispose.apply( this, arguments );
}
// Run remove on `dispose`, so we can be sure to refresh the
// uploader with a view-less DOM. Track whether we're disposing
// so we don't trigger an infinite loop.
this.disposing = true;
return this.remove();
},
/**
* @returns {wp.media.view.UploaderInline} Returns itself to allow chaining
*/
remove: function() {
/**
* call 'remove' directly on the parent class
*/
var result = media.View.prototype.remove.apply( this, arguments );
_.defer( _.bind( this.refresh, this ) );
return result;
},
refresh: function() {
var uploader = this.controller.uploader;
if ( uploader ) {
uploader.refresh();
}
},
/**
* @returns {wp.media.view.UploaderInline}
*/
ready: function() {
var $browser = this.options.$browser,
$placeholder;
if ( this.controller.uploader ) {
$placeholder = this.$('.browser');
// Check if we've already replaced the placeholder.
if ( $placeholder[0] === $browser[0] ) {
return;
}
$browser.detach().text( $placeholder.text() );
$browser[0].className = $placeholder[0].className;
$placeholder.replaceWith( $browser.show() );
}
this.refresh();
return this;
}
});
/**
* wp.media.view.UploaderStatus
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.UploaderStatus = media.View.extend({
className: 'media-uploader-status',
template: media.template('uploader-status'),
events: {
'click .upload-dismiss-errors': 'dismiss'
},
initialize: function() {
this.queue = wp.Uploader.queue;
this.queue.on( 'add remove reset', this.visibility, this );
this.queue.on( 'add remove reset change:percent', this.progress, this );
this.queue.on( 'add remove reset change:uploading', this.info, this );
this.errors = wp.Uploader.errors;
this.errors.reset();
this.errors.on( 'add remove reset', this.visibility, this );
this.errors.on( 'add', this.error, this );
},
/**
* @global wp.Uploader
* @returns {wp.media.view.UploaderStatus}
*/
dispose: function() {
wp.Uploader.queue.off( null, null, this );
/**
* call 'dispose' directly on the parent class
*/
media.View.prototype.dispose.apply( this, arguments );
return this;
},
visibility: function() {
this.$el.toggleClass( 'uploading', !! this.queue.length );
this.$el.toggleClass( 'errors', !! this.errors.length );
this.$el.toggle( !! this.queue.length || !! this.errors.length );
},
ready: function() {
_.each({
'$bar': '.media-progress-bar div',
'$index': '.upload-index',
'$total': '.upload-total',
'$filename': '.upload-filename'
}, function( selector, key ) {
this[ key ] = this.$( selector );
}, this );
this.visibility();
this.progress();
this.info();
},
progress: function() {
var queue = this.queue,
$bar = this.$bar;
if ( ! $bar || ! queue.length ) {
return;
}
$bar.width( ( queue.reduce( function( memo, attachment ) {
if ( ! attachment.get('uploading') ) {
return memo + 100;
}
var percent = attachment.get('percent');
return memo + ( _.isNumber( percent ) ? percent : 100 );
}, 0 ) / queue.length ) + '%' );
},
info: function() {
var queue = this.queue,
index = 0, active;
if ( ! queue.length ) {
return;
}
active = this.queue.find( function( attachment, i ) {
index = i;
return attachment.get('uploading');
});
this.$index.text( index + 1 );
this.$total.text( queue.length );
this.$filename.html( active ? this.filename( active.get('filename') ) : '' );
},
/**
* @param {string} filename
* @returns {string}
*/
filename: function( filename ) {
return media.truncate( _.escape( filename ), 24 );
},
/**
* @param {Backbone.Model} error
*/
error: function( error ) {
this.views.add( '.upload-errors', new media.view.UploaderStatusError({
filename: this.filename( error.get('file').name ),
message: error.get('message')
}), { at: 0 });
},
/**
* @global wp.Uploader
*
* @param {Object} event
*/
dismiss: function( event ) {
var errors = this.views.get('.upload-errors');
event.preventDefault();
if ( errors ) {
_.invoke( errors, 'remove' );
}
wp.Uploader.errors.reset();
}
});
/**
* wp.media.view.UploaderStatusError
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.UploaderStatusError = media.View.extend({
className: 'upload-error',
template: media.template('uploader-status-error')
});
/**
* wp.media.view.Toolbar
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Toolbar = media.View.extend({
tagName: 'div',
className: 'media-toolbar',
initialize: function() {
var state = this.controller.state(),
selection = this.selection = state.get('selection'),
library = this.library = state.get('library');
this._views = {};
// The toolbar is composed of two `PriorityList` views.
this.primary = new media.view.PriorityList();
this.secondary = new media.view.PriorityList();
this.primary.$el.addClass('media-toolbar-primary');
this.secondary.$el.addClass('media-toolbar-secondary');
this.views.set([ this.secondary, this.primary ]);
if ( this.options.items ) {
this.set( this.options.items, { silent: true });
}
if ( ! this.options.silent ) {
this.render();
}
if ( selection ) {
selection.on( 'add remove reset', this.refresh, this );
}
if ( library ) {
library.on( 'add remove reset', this.refresh, this );
}
},
/**
* @returns {wp.media.view.Toolbar} Returns itsef to allow chaining
*/
dispose: function() {
if ( this.selection ) {
this.selection.off( null, null, this );
}
if ( this.library ) {
this.library.off( null, null, this );
}
/**
* call 'dispose' directly on the parent class
*/
return media.View.prototype.dispose.apply( this, arguments );
},
ready: function() {
this.refresh();
},
/**
* @param {string} id
* @param {Backbone.View|Object} view
* @param {Object} [options={}]
* @returns {wp.media.view.Toolbar} Returns itself to allow chaining
*/
set: function( id, view, options ) {
var list;
options = options || {};
// Accept an object with an `id` : `view` mapping.
if ( _.isObject( id ) ) {
_.each( id, function( view, id ) {
this.set( id, view, { silent: true });
}, this );
} else {
if ( ! ( view instanceof Backbone.View ) ) {
view.classes = [ 'media-button-' + id ].concat( view.classes || [] );
view = new media.view.Button( view ).render();
}
view.controller = view.controller || this.controller;
this._views[ id ] = view;
list = view.options.priority < 0 ? 'secondary' : 'primary';
this[ list ].set( id, view, options );
}
if ( ! options.silent ) {
this.refresh();
}
return this;
},
/**
* @param {string} id
* @returns {wp.media.view.Button}
*/
get: function( id ) {
return this._views[ id ];
},
/**
* @param {string} id
* @param {Object} options
* @returns {wp.media.view.Toolbar} Returns itself to allow chaining
*/
unset: function( id, options ) {
delete this._views[ id ];
this.primary.unset( id, options );
this.secondary.unset( id, options );
if ( ! options || ! options.silent ) {
this.refresh();
}
return this;
},
refresh: function() {
var state = this.controller.state(),
library = state.get('library'),
selection = state.get('selection');
_.each( this._views, function( button ) {
if ( ! button.model || ! button.options || ! button.options.requires ) {
return;
}
var requires = button.options.requires,
disabled = false;
// Prevent insertion of attachments if any of them are still uploading
disabled = _.some( selection.models, function( attachment ) {
return attachment.get('uploading') === true;
});
if ( requires.selection && selection && ! selection.length ) {
disabled = true;
} else if ( requires.library && library && ! library.length ) {
disabled = true;
}
button.model.set( 'disabled', disabled );
});
}
});
/**
* wp.media.view.Toolbar.Select
*
* @constructor
* @augments wp.media.view.Toolbar
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Toolbar.Select = media.view.Toolbar.extend({
initialize: function() {
var options = this.options;
_.bindAll( this, 'clickSelect' );
_.defaults( options, {
event: 'select',
state: false,
reset: true,
close: true,
text: l10n.select,
// Does the button rely on the selection?
requires: {
selection: true
}
});
options.items = _.defaults( options.items || {}, {
select: {
style: 'primary',
text: options.text,
priority: 80,
click: this.clickSelect,
requires: options.requires
}
});
/**
* call 'initialize' directly on the parent class
*/
media.view.Toolbar.prototype.initialize.apply( this, arguments );
},
clickSelect: function() {
var options = this.options,
controller = this.controller;
if ( options.close ) {
controller.close();
}
if ( options.event ) {
controller.state().trigger( options.event );
}
if ( options.state ) {
controller.setState( options.state );
}
if ( options.reset ) {
controller.reset();
}
}
});
/**
* wp.media.view.Toolbar.Embed
*
* @constructor
* @augments wp.media.view.Toolbar.Select
* @augments wp.media.view.Toolbar
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Toolbar.Embed = media.view.Toolbar.Select.extend({
initialize: function() {
_.defaults( this.options, {
text: l10n.insertIntoPost,
requires: false
});
/**
* call 'initialize' directly on the parent class
*/
media.view.Toolbar.Select.prototype.initialize.apply( this, arguments );
},
refresh: function() {
var url = this.controller.state().props.get('url');
this.get('select').model.set( 'disabled', ! url || url === 'http://' );
/**
* call 'refresh' directly on the parent class
*/
media.view.Toolbar.Select.prototype.refresh.apply( this, arguments );
}
});
/**
* wp.media.view.Button
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Button = media.View.extend({
tagName: 'a',
className: 'media-button',
attributes: { href: '#' },
events: {
'click': 'click'
},
defaults: {
text: '',
style: '',
size: 'large',
disabled: false
},
initialize: function() {
/**
* Create a model with the provided `defaults`.
*
* @member {Backbone.Model}
*/
this.model = new Backbone.Model( this.defaults );
// If any of the `options` have a key from `defaults`, apply its
// value to the `model` and remove it from the `options object.
_.each( this.defaults, function( def, key ) {
var value = this.options[ key ];
if ( _.isUndefined( value ) ) {
return;
}
this.model.set( key, value );
delete this.options[ key ];
}, this );
this.model.on( 'change', this.render, this );
},
/**
* @returns {wp.media.view.Button} Returns itself to allow chaining
*/
render: function() {
var classes = [ 'button', this.className ],
model = this.model.toJSON();
if ( model.style ) {
classes.push( 'button-' + model.style );
}
if ( model.size ) {
classes.push( 'button-' + model.size );
}
classes = _.uniq( classes.concat( this.options.classes ) );
this.el.className = classes.join(' ');
this.$el.attr( 'disabled', model.disabled );
this.$el.text( this.model.get('text') );
return this;
},
/**
* @param {Object} event
*/
click: function( event ) {
if ( '#' === this.attributes.href ) {
event.preventDefault();
}
if ( this.options.click && ! this.model.get('disabled') ) {
this.options.click.apply( this, arguments );
}
}
});
/**
* wp.media.view.ButtonGroup
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.ButtonGroup = media.View.extend({
tagName: 'div',
className: 'button-group button-large media-button-group',
initialize: function() {
/**
* @member {wp.media.view.Button[]}
*/
this.buttons = _.map( this.options.buttons || [], function( button ) {
if ( button instanceof Backbone.View ) {
return button;
} else {
return new media.view.Button( button ).render();
}
});
delete this.options.buttons;
if ( this.options.classes ) {
this.$el.addClass( this.options.classes );
}
},
/**
* @returns {wp.media.view.ButtonGroup}
*/
render: function() {
this.$el.html( $( _.pluck( this.buttons, 'el' ) ).detach() );
return this;
}
});
/**
* wp.media.view.PriorityList
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.PriorityList = media.View.extend({
tagName: 'div',
initialize: function() {
this._views = {};
this.set( _.extend( {}, this._views, this.options.views ), { silent: true });
delete this.options.views;
if ( ! this.options.silent ) {
this.render();
}
},
/**
* @param {string} id
* @param {wp.media.View|Object} view
* @param {Object} options
* @returns {wp.media.view.PriorityList} Returns itself to allow chaining
*/
set: function( id, view, options ) {
var priority, views, index;
options = options || {};
// Accept an object with an `id` : `view` mapping.
if ( _.isObject( id ) ) {
_.each( id, function( view, id ) {
this.set( id, view );
}, this );
return this;
}
if ( ! (view instanceof Backbone.View) ) {
view = this.toView( view, id, options );
}
view.controller = view.controller || this.controller;
this.unset( id );
priority = view.options.priority || 10;
views = this.views.get() || [];
_.find( views, function( existing, i ) {
if ( existing.options.priority > priority ) {
index = i;
return true;
}
});
this._views[ id ] = view;
this.views.add( view, {
at: _.isNumber( index ) ? index : views.length || 0
});
return this;
},
/**
* @param {string} id
* @returns {wp.media.View}
*/
get: function( id ) {
return this._views[ id ];
},
/**
* @param {string} id
* @returns {wp.media.view.PriorityList}
*/
unset: function( id ) {
var view = this.get( id );
if ( view ) {
view.remove();
}
delete this._views[ id ];
return this;
},
/**
* @param {Object} options
* @returns {wp.media.View}
*/
toView: function( options ) {
return new media.View( options );
}
});
/**
* wp.media.view.MenuItem
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.MenuItem = media.View.extend({
tagName: 'a',
className: 'media-menu-item',
attributes: {
href: '#'
},
events: {
'click': '_click'
},
/**
* @param {Object} event
*/
_click: function( event ) {
var clickOverride = this.options.click;
if ( event ) {
event.preventDefault();
}
if ( clickOverride ) {
clickOverride.call( this );
} else {
this.click();
}
},
click: function() {
var state = this.options.state;
if ( state ) {
this.controller.setState( state );
}
},
/**
* @returns {wp.media.view.MenuItem} returns itself to allow chaining
*/
render: function() {
var options = this.options;
if ( options.text ) {
this.$el.text( options.text );
} else if ( options.html ) {
this.$el.html( options.html );
}
return this;
}
});
/**
* wp.media.view.Menu
*
* @constructor
* @augments wp.media.view.PriorityList
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Menu = media.view.PriorityList.extend({
tagName: 'div',
className: 'media-menu',
property: 'state',
ItemView: media.view.MenuItem,
region: 'menu',
/**
* @param {Object} options
* @param {string} id
* @returns {wp.media.View}
*/
toView: function( options, id ) {
options = options || {};
options[ this.property ] = options[ this.property ] || id;
return new this.ItemView( options ).render();
},
ready: function() {
/**
* call 'ready' directly on the parent class
*/
media.view.PriorityList.prototype.ready.apply( this, arguments );
this.visibility();
},
set: function() {
/**
* call 'set' directly on the parent class
*/
media.view.PriorityList.prototype.set.apply( this, arguments );
this.visibility();
},
unset: function() {
/**
* call 'unset' directly on the parent class
*/
media.view.PriorityList.prototype.unset.apply( this, arguments );
this.visibility();
},
visibility: function() {
var region = this.region,
view = this.controller[ region ].get(),
views = this.views.get(),
hide = ! views || views.length < 2;
if ( this === view ) {
this.controller.$el.toggleClass( 'hide-' + region, hide );
}
},
/**
* @param {string} id
*/
select: function( id ) {
var view = this.get( id );
if ( ! view ) {
return;
}
this.deselect();
view.$el.addClass('active');
},
deselect: function() {
this.$el.children().removeClass('active');
},
hide: function( id ) {
var view = this.get( id );
if ( ! view ) {
return;
}
view.$el.addClass('hidden');
},
show: function( id ) {
var view = this.get( id );
if ( ! view ) {
return;
}
view.$el.removeClass('hidden');
}
});
/**
* wp.media.view.RouterItem
*
* @constructor
* @augments wp.media.view.MenuItem
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.RouterItem = media.view.MenuItem.extend({
click: function() {
var contentMode = this.options.contentMode;
if ( contentMode ) {
this.controller.content.mode( contentMode );
}
}
});
/**
* wp.media.view.Router
*
* @constructor
* @augments wp.media.view.Menu
* @augments wp.media.view.PriorityList
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Router = media.view.Menu.extend({
tagName: 'div',
className: 'media-router',
property: 'contentMode',
ItemView: media.view.RouterItem,
region: 'router',
initialize: function() {
this.controller.on( 'content:render', this.update, this );
/**
* call 'initialize' directly on the parent class
*/
media.view.Menu.prototype.initialize.apply( this, arguments );
},
update: function() {
var mode = this.controller.content.mode();
if ( mode ) {
this.select( mode );
}
}
});
/**
* wp.media.view.Sidebar
*
* @constructor
* @augments wp.media.view.PriorityList
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Sidebar = media.view.PriorityList.extend({
className: 'media-sidebar'
});
/**
* wp.media.view.Attachment
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Attachment = media.View.extend({
tagName: 'li',
className: 'attachment',
template: media.template('attachment'),
events: {
'click .attachment-preview': 'toggleSelectionHandler',
'change [data-setting]': 'updateSetting',
'change [data-setting] input': 'updateSetting',
'change [data-setting] select': 'updateSetting',
'change [data-setting] textarea': 'updateSetting',
'click .close': 'removeFromLibrary',
'click .check': 'removeFromSelection',
'click a': 'preventDefault'
},
buttons: {},
initialize: function() {
var selection = this.options.selection;
this.model.on( 'change:sizes change:uploading', this.render, this );
this.model.on( 'change:title', this._syncTitle, this );
this.model.on( 'change:caption', this._syncCaption, this );
this.model.on( 'change:percent', this.progress, this );
// Update the selection.
this.model.on( 'add', this.select, this );
this.model.on( 'remove', this.deselect, this );
if ( selection ) {
selection.on( 'reset', this.updateSelect, this );
}
// Update the model's details view.
this.model.on( 'selection:single selection:unsingle', this.details, this );
this.details( this.model, this.controller.state().get('selection') );
},
/**
* @returns {wp.media.view.Attachment} Returns itself to allow chaining
*/
dispose: function() {
var selection = this.options.selection;
// Make sure all settings are saved before removing the view.
this.updateAll();
if ( selection ) {
selection.off( null, null, this );
}
/**
* call 'dispose' directly on the parent class
*/
media.View.prototype.dispose.apply( this, arguments );
return this;
},
/**
* @returns {wp.media.view.Attachment} Returns itself to allow chaining
*/
render: function() {
var options = _.defaults( this.model.toJSON(), {
orientation: 'landscape',
uploading: false,
type: '',
subtype: '',
icon: '',
filename: '',
caption: '',
title: '',
dateFormatted: '',
width: '',
height: '',
compat: false,
alt: '',
description: ''
});
options.buttons = this.buttons;
options.describe = this.controller.state().get('describe');
if ( 'image' === options.type ) {
options.size = this.imageSize();
}
options.can = {};
if ( options.nonces ) {
options.can.remove = !! options.nonces['delete'];
options.can.save = !! options.nonces.update;
}
if ( this.controller.state().get('allowLocalEdits') ) {
options.allowLocalEdits = true;
}
this.views.detach();
this.$el.html( this.template( options ) );
this.$el.toggleClass( 'uploading', options.uploading );
if ( options.uploading ) {
this.$bar = this.$('.media-progress-bar div');
} else {
delete this.$bar;
}
// Check if the model is selected.
this.updateSelect();
// Update the save status.
this.updateSave();
this.views.render();
return this;
},
progress: function() {
if ( this.$bar && this.$bar.length ) {
this.$bar.width( this.model.get('percent') + '%' );
}
},
/**
* @param {Object} event
*/
toggleSelectionHandler: function( event ) {
var method;
if ( event.shiftKey ) {
method = 'between';
} else if ( event.ctrlKey || event.metaKey ) {
method = 'toggle';
}
this.toggleSelection({
method: method
});
},
/**
* @param {Object} options
*/
toggleSelection: function( options ) {
var collection = this.collection,
selection = this.options.selection,
model = this.model,
method = options && options.method,
single, models, singleIndex, modelIndex;
if ( ! selection ) {
return;
}
single = selection.single();
method = _.isUndefined( method ) ? selection.multiple : method;
// If the `method` is set to `between`, select all models that
// exist between the current and the selected model.
if ( 'between' === method && single && selection.multiple ) {
// If the models are the same, short-circuit.
if ( single === model ) {
return;
}
singleIndex = collection.indexOf( single );
modelIndex = collection.indexOf( this.model );
if ( singleIndex < modelIndex ) {
models = collection.models.slice( singleIndex, modelIndex + 1 );
} else {
models = collection.models.slice( modelIndex, singleIndex + 1 );
}
selection.add( models );
selection.single( model );
return;
// If the `method` is set to `toggle`, just flip the selection
// status, regardless of whether the model is the single model.
} else if ( 'toggle' === method ) {
selection[ this.selected() ? 'remove' : 'add' ]( model );
selection.single( model );
return;
}
if ( method !== 'add' ) {
method = 'reset';
}
if ( this.selected() ) {
// If the model is the single model, remove it.
// If it is not the same as the single model,
// it now becomes the single model.
selection[ single === model ? 'remove' : 'single' ]( model );
} else {
// If the model is not selected, run the `method` on the
// selection. By default, we `reset` the selection, but the
// `method` can be set to `add` the model to the selection.
selection[ method ]( model );
selection.single( model );
}
},
updateSelect: function() {
this[ this.selected() ? 'select' : 'deselect' ]();
},
/**
* @returns {unresolved|Boolean}
*/
selected: function() {
var selection = this.options.selection;
if ( selection ) {
return !! selection.get( this.model.cid );
}
},
/**
* @param {Backbone.Model} model
* @param {Backbone.Collection} collection
*/
select: function( model, collection ) {
var selection = this.options.selection;
// Check if a selection exists and if it's the collection provided.
// If they're not the same collection, bail; we're in another
// selection's event loop.
if ( ! selection || ( collection && collection !== selection ) ) {
return;
}
this.$el.addClass('selected');
},
/**
* @param {Backbone.Model} model
* @param {Backbone.Collection} collection
*/
deselect: function( model, collection ) {
var selection = this.options.selection;
// Check if a selection exists and if it's the collection provided.
// If they're not the same collection, bail; we're in another
// selection's event loop.
if ( ! selection || ( collection && collection !== selection ) ) {
return;
}
this.$el.removeClass('selected');
},
/**
* @param {Backbone.Model} model
* @param {Backbone.Collection} collection
*/
details: function( model, collection ) {
var selection = this.options.selection,
details;
if ( selection !== collection ) {
return;
}
details = selection.single();
this.$el.toggleClass( 'details', details === this.model );
},
/**
* @param {Object} event
*/
preventDefault: function( event ) {
event.preventDefault();
},
/**
* @param {string} size
* @returns {Object}
*/
imageSize: function( size ) {
var sizes = this.model.get('sizes');
size = size || 'medium';
// Use the provided image size if possible.
if ( sizes && sizes[ size ] ) {
return _.clone( sizes[ size ] );
} else {
return {
url: this.model.get('url'),
width: this.model.get('width'),
height: this.model.get('height'),
orientation: this.model.get('orientation')
};
}
},
/**
* @param {Object} event
*/
updateSetting: function( event ) {
var $setting = $( event.target ).closest('[data-setting]'),
setting, value;
if ( ! $setting.length ) {
return;
}
setting = $setting.data('setting');
value = event.target.value;
if ( this.model.get( setting ) !== value ) {
this.save( setting, value );
}
},
/**
* Pass all the arguments to the model's save method.
*
* Records the aggregate status of all save requests and updates the
* view's classes accordingly.
*/
save: function() {
var view = this,
save = this._save = this._save || { status: 'ready' },
request = this.model.save.apply( this.model, arguments ),
requests = save.requests ? $.when( request, save.requests ) : request;
// If we're waiting to remove 'Saved.', stop.
if ( save.savedTimer ) {
clearTimeout( save.savedTimer );
}
this.updateSave('waiting');
save.requests = requests;
requests.always( function() {
// If we've performed another request since this one, bail.
if ( save.requests !== requests ) {
return;
}
view.updateSave( requests.state() === 'resolved' ? 'complete' : 'error' );
save.savedTimer = setTimeout( function() {
view.updateSave('ready');
delete save.savedTimer;
}, 2000 );
});
},
/**
* @param {string} status
* @returns {wp.media.view.Attachment} Returns itself to allow chaining
*/
updateSave: function( status ) {
var save = this._save = this._save || { status: 'ready' };
if ( status && status !== save.status ) {
this.$el.removeClass( 'save-' + save.status );
save.status = status;
}
this.$el.addClass( 'save-' + save.status );
return this;
},
updateAll: function() {
var $settings = this.$('[data-setting]'),
model = this.model,
changed;
changed = _.chain( $settings ).map( function( el ) {
var $input = $('input, textarea, select, [value]', el ),
setting, value;
if ( ! $input.length ) {
return;
}
setting = $(el).data('setting');
value = $input.val();
// Record the value if it changed.
if ( model.get( setting ) !== value ) {
return [ setting, value ];
}
}).compact().object().value();
if ( ! _.isEmpty( changed ) ) {
model.save( changed );
}
},
/**
* @param {Object} event
*/
removeFromLibrary: function( event ) {
// Stop propagation so the model isn't selected.
event.stopPropagation();
this.collection.remove( this.model );
},
/**
* @param {Object} event
*/
removeFromSelection: function( event ) {
var selection = this.options.selection;
if ( ! selection ) {
return;
}
// Stop propagation so the model isn't selected.
event.stopPropagation();
selection.remove( this.model );
}
});
// Ensure settings remain in sync between attachment views.
_.each({
caption: '_syncCaption',
title: '_syncTitle'
}, function( method, setting ) {
/**
* @param {Backbone.Model} model
* @param {string} value
* @returns {wp.media.view.Attachment} Returns itself to allow chaining
*/
media.view.Attachment.prototype[ method ] = function( model, value ) {
var $setting = this.$('[data-setting="' + setting + '"]');
if ( ! $setting.length ) {
return this;
}
// If the updated value is in sync with the value in the DOM, there
// is no need to re-render. If we're currently editing the value,
// it will automatically be in sync, suppressing the re-render for
// the view we're editing, while updating any others.
if ( value === $setting.find('input, textarea, select, [value]').val() ) {
return this;
}
return this.render();
};
});
/**
* wp.media.view.Attachment.Library
*
* @constructor
* @augments wp.media.view.Attachment
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Attachment.Library = media.view.Attachment.extend({
buttons: {
check: true
}
});
/**
* wp.media.view.Attachment.EditLibrary
*
* @constructor
* @augments wp.media.view.Attachment
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Attachment.EditLibrary = media.view.Attachment.extend({
buttons: {
close: true
}
});
/**
* wp.media.view.Attachments
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Attachments = media.View.extend({
tagName: 'ul',
className: 'attachments',
cssTemplate: media.template('attachments-css'),
events: {
'scroll': 'scroll'
},
initialize: function() {
this.el.id = _.uniqueId('__attachments-view-');
_.defaults( this.options, {
refreshSensitivity: 200,
refreshThreshold: 3,
AttachmentView: media.view.Attachment,
sortable: false,
resize: true
});
this._viewsByCid = {};
this.collection.on( 'add', function( attachment ) {
this.views.add( this.createAttachmentView( attachment ), {
at: this.collection.indexOf( attachment )
});
}, this );
this.collection.on( 'remove', function( attachment ) {
var view = this._viewsByCid[ attachment.cid ];
delete this._viewsByCid[ attachment.cid ];
if ( view ) {
view.remove();
}
}, this );
this.collection.on( 'reset', this.render, this );
// Throttle the scroll handler.
this.scroll = _.chain( this.scroll ).bind( this ).throttle( this.options.refreshSensitivity ).value();
this.initSortable();
_.bindAll( this, 'css' );
this.model.on( 'change:edge change:gutter', this.css, this );
this._resizeCss = _.debounce( _.bind( this.css, this ), this.refreshSensitivity );
if ( this.options.resize ) {
$(window).on( 'resize.attachments', this._resizeCss );
}
this.css();
},
dispose: function() {
this.collection.props.off( null, null, this );
$(window).off( 'resize.attachments', this._resizeCss );
/**
* call 'dispose' directly on the parent class
*/
media.View.prototype.dispose.apply( this, arguments );
},
css: function() {
var $css = $( '#' + this.el.id + '-css' );
if ( $css.length ) {
$css.remove();
}
media.view.Attachments.$head().append( this.cssTemplate({
id: this.el.id,
edge: this.edge(),
gutter: this.model.get('gutter')
}) );
},
/**
* @returns {Number}
*/
edge: function() {
var edge = this.model.get('edge'),
gutter, width, columns;
if ( ! this.$el.is(':visible') ) {
return edge;
}
gutter = this.model.get('gutter') * 2;
width = this.$el.width() - gutter;
columns = Math.ceil( width / ( edge + gutter ) );
edge = Math.floor( ( width - ( columns * gutter ) ) / columns );
return edge;
},
initSortable: function() {
var collection = this.collection;
if ( ! this.options.sortable || ! $.fn.sortable ) {
return;
}
this.$el.sortable( _.extend({
// If the `collection` has a `comparator`, disable sorting.
disabled: !! collection.comparator,
// Prevent attachments from being dragged outside the bounding
// box of the list.
containment: this.$el,
// Change the position of the attachment as soon as the
// mouse pointer overlaps a thumbnail.
tolerance: 'pointer',
// Record the initial `index` of the dragged model.
start: function( event, ui ) {
ui.item.data('sortableIndexStart', ui.item.index());
},
// Update the model's index in the collection.
// Do so silently, as the view is already accurate.
update: function( event, ui ) {
var model = collection.at( ui.item.data('sortableIndexStart') ),
comparator = collection.comparator;
// Temporarily disable the comparator to prevent `add`
// from re-sorting.
delete collection.comparator;
// Silently shift the model to its new index.
collection.remove( model, {
silent: true
});
collection.add( model, {
silent: true,
at: ui.item.index()
});
// Restore the comparator.
collection.comparator = comparator;
// Fire the `reset` event to ensure other collections sync.
collection.trigger( 'reset', collection );
// If the collection is sorted by menu order,
// update the menu order.
collection.saveMenuOrder();
}
}, this.options.sortable ) );
// If the `orderby` property is changed on the `collection`,
// check to see if we have a `comparator`. If so, disable sorting.
collection.props.on( 'change:orderby', function() {
this.$el.sortable( 'option', 'disabled', !! collection.comparator );
}, this );
this.collection.props.on( 'change:orderby', this.refreshSortable, this );
this.refreshSortable();
},
refreshSortable: function() {
if ( ! this.options.sortable || ! $.fn.sortable ) {
return;
}
// If the `collection` has a `comparator`, disable sorting.
var collection = this.collection,
orderby = collection.props.get('orderby'),
enabled = 'menuOrder' === orderby || ! collection.comparator;
this.$el.sortable( 'option', 'disabled', ! enabled );
},
/**
* @param {wp.media.model.Attachment} attachment
* @returns {wp.media.View}
*/
createAttachmentView: function( attachment ) {
var view = new this.options.AttachmentView({
controller: this.controller,
model: attachment,
collection: this.collection,
selection: this.options.selection
});
return this._viewsByCid[ attachment.cid ] = view;
},
prepare: function() {
// Create all of the Attachment views, and replace
// the list in a single DOM operation.
if ( this.collection.length ) {
this.views.set( this.collection.map( this.createAttachmentView, this ) );
// If there are no elements, clear the views and load some.
} else {
this.views.unset();
this.collection.more().done( this.scroll );
}
},
ready: function() {
// Trigger the scroll event to check if we're within the
// threshold to query for additional attachments.
this.scroll();
},
scroll: function() {
var view = this,
toolbar;
if ( ! this.$el.is(':visible') || ! this.collection.hasMore() ) {
return;
}
toolbar = this.views.parent.toolbar;
// Show the spinner only if we are close to the bottom.
if ( this.el.scrollHeight - ( this.el.scrollTop + this.el.clientHeight ) < this.el.clientHeight / 3 ) {
toolbar.get('spinner').show();
}
if ( this.el.scrollHeight < this.el.scrollTop + ( this.el.clientHeight * this.options.refreshThreshold ) ) {
this.collection.more().done(function() {
view.scroll();
toolbar.get('spinner').hide();
});
}
}
}, {
$head: (function() {
var $head;
return function() {
return $head = $head || $('head');
};
}())
});
/**
* wp.media.view.Search
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Search = media.View.extend({
tagName: 'input',
className: 'search',
attributes: {
type: 'search',
placeholder: l10n.search
},
events: {
'input': 'search',
'keyup': 'search',
'change': 'search',
'search': 'search'
},
/**
* @returns {wp.media.view.Search} Returns itself to allow chaining
*/
render: function() {
this.el.value = this.model.escape('search');
return this;
},
search: function( event ) {
if ( event.target.value ) {
this.model.set( 'search', event.target.value );
} else {
this.model.unset('search');
}
}
});
/**
* wp.media.view.AttachmentFilters
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.AttachmentFilters = media.View.extend({
tagName: 'select',
className: 'attachment-filters',
events: {
change: 'change'
},
keys: [],
initialize: function() {
this.createFilters();
_.extend( this.filters, this.options.filters );
// Build `<option>` elements.
this.$el.html( _.chain( this.filters ).map( function( filter, value ) {
return {
el: $( '<option></option>' ).val( value ).html( filter.text )[0],
priority: filter.priority || 50
};
}, this ).sortBy('priority').pluck('el').value() );
this.model.on( 'change', this.select, this );
this.select();
},
createFilters: function() {
this.filters = {};
},
change: function() {
var filter = this.filters[ this.el.value ];
if ( filter ) {
this.model.set( filter.props );
}
},
select: function() {
var model = this.model,
value = 'all',
props = model.toJSON();
_.find( this.filters, function( filter, id ) {
var equal = _.all( filter.props, function( prop, key ) {
return prop === ( _.isUndefined( props[ key ] ) ? null : props[ key ] );
});
if ( equal ) {
return value = id;
}
});
this.$el.val( value );
}
});
/**
* wp.media.view.AttachmentFilters.Uploaded
*
* @constructor
* @augments wp.media.view.AttachmentFilters
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.AttachmentFilters.Uploaded = media.view.AttachmentFilters.extend({
createFilters: function() {
var type = this.model.get('type'),
types = media.view.settings.mimeTypes,
text;
if ( types && type ) {
text = types[ type ];
}
this.filters = {
all: {
text: text || l10n.allMediaItems,
props: {
uploadedTo: null,
orderby: 'date',
order: 'DESC'
},
priority: 10
},
uploaded: {
text: l10n.uploadedToThisPost,
props: {
uploadedTo: media.view.settings.post.id,
orderby: 'menuOrder',
order: 'ASC'
},
priority: 20
}
};
}
});
/**
* wp.media.view.AttachmentFilters.All
*
* @constructor
* @augments wp.media.view.AttachmentFilters
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.AttachmentFilters.All = media.view.AttachmentFilters.extend({
createFilters: function() {
var filters = {};
_.each( media.view.settings.mimeTypes || {}, function( text, key ) {
filters[ key ] = {
text: text,
props: {
type: key,
uploadedTo: null,
orderby: 'date',
order: 'DESC'
}
};
});
filters.all = {
text: l10n.allMediaItems,
props: {
type: null,
uploadedTo: null,
orderby: 'date',
order: 'DESC'
},
priority: 10
};
filters.uploaded = {
text: l10n.uploadedToThisPost,
props: {
type: null,
uploadedTo: media.view.settings.post.id,
orderby: 'menuOrder',
order: 'ASC'
},
priority: 20
};
this.filters = filters;
}
});
/**
* wp.media.view.AttachmentsBrowser
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.AttachmentsBrowser = media.View.extend({
tagName: 'div',
className: 'attachments-browser',
initialize: function() {
_.defaults( this.options, {
filters: false,
search: true,
display: false,
AttachmentView: media.view.Attachment.Library
});
this.createToolbar();
this.updateContent();
this.createSidebar();
this.collection.on( 'add remove reset', this.updateContent, this );
},
/**
* @returns {wp.media.view.AttachmentsBrowser} Returns itself to allow chaining
*/
dispose: function() {
this.options.selection.off( null, null, this );
media.View.prototype.dispose.apply( this, arguments );
return this;
},
createToolbar: function() {
var filters, FiltersConstructor;
/**
* @member {wp.media.view.Toolbar}
*/
this.toolbar = new media.view.Toolbar({
controller: this.controller
});
this.views.add( this.toolbar );
filters = this.options.filters;
if ( 'uploaded' === filters ) {
FiltersConstructor = media.view.AttachmentFilters.Uploaded;
} else if ( 'all' === filters ) {
FiltersConstructor = media.view.AttachmentFilters.All;
}
if ( FiltersConstructor ) {
this.toolbar.set( 'filters', new FiltersConstructor({
controller: this.controller,
model: this.collection.props,
priority: -80
}).render() );
}
this.toolbar.set( 'spinner', new media.view.Spinner({
priority: -70
}) );
if ( this.options.search ) {
this.toolbar.set( 'search', new media.view.Search({
controller: this.controller,
model: this.collection.props,
priority: 60
}).render() );
}
if ( this.options.dragInfo ) {
this.toolbar.set( 'dragInfo', new media.View({
el: $( '<div class="instructions">' + l10n.dragInfo + '</div>' )[0],
priority: -40
}) );
}
if ( this.options.suggestedWidth && this.options.suggestedHeight ) {
this.toolbar.set( 'suggestedDimensions', new media.View({
el: $( '<div class="instructions">' + l10n.suggestedDimensions + ' ' + this.options.suggestedWidth + ' × ' + this.options.suggestedHeight + '</div>' )[0],
priority: -40
}) );
}
},
updateContent: function() {
var view = this;
if( ! this.attachments ) {
this.createAttachments();
}
if ( ! this.collection.length ) {
this.toolbar.get( 'spinner' ).show();
this.collection.more().done(function() {
if ( ! view.collection.length ) {
view.createUploader();
}
view.toolbar.get( 'spinner' ).hide();
});
} else {
view.toolbar.get( 'spinner' ).hide();
}
},
removeContent: function() {
_.each(['attachments','uploader'], function( key ) {
if ( this[ key ] ) {
this[ key ].remove();
delete this[ key ];
}
}, this );
},
createUploader: function() {
this.removeContent();
this.uploader = new media.view.UploaderInline({
controller: this.controller,
status: false,
message: l10n.noItemsFound
});
this.views.add( this.uploader );
},
createAttachments: function() {
this.removeContent();
this.attachments = new media.view.Attachments({
controller: this.controller,
collection: this.collection,
selection: this.options.selection,
model: this.model,
sortable: this.options.sortable,
// The single `Attachment` view to be used in the `Attachments` view.
AttachmentView: this.options.AttachmentView
});
this.views.add( this.attachments );
},
createSidebar: function() {
var options = this.options,
selection = options.selection,
sidebar = this.sidebar = new media.view.Sidebar({
controller: this.controller
});
this.views.add( sidebar );
if ( this.controller.uploader ) {
sidebar.set( 'uploads', new media.view.UploaderStatus({
controller: this.controller,
priority: 40
}) );
}
selection.on( 'selection:single', this.createSingle, this );
selection.on( 'selection:unsingle', this.disposeSingle, this );
if ( selection.single() ) {
this.createSingle();
}
},
createSingle: function() {
var sidebar = this.sidebar,
single = this.options.selection.single();
sidebar.set( 'details', new media.view.Attachment.Details({
controller: this.controller,
model: single,
priority: 80
}) );
sidebar.set( 'compat', new media.view.AttachmentCompat({
controller: this.controller,
model: single,
priority: 120
}) );
if ( this.options.display ) {
sidebar.set( 'display', new media.view.Settings.AttachmentDisplay({
controller: this.controller,
model: this.model.display( single ),
attachment: single,
priority: 160,
userSettings: this.model.get('displayUserSettings')
}) );
}
},
disposeSingle: function() {
var sidebar = this.sidebar;
sidebar.unset('details');
sidebar.unset('compat');
sidebar.unset('display');
}
});
/**
* wp.media.view.Selection
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Selection = media.View.extend({
tagName: 'div',
className: 'media-selection',
template: media.template('media-selection'),
events: {
'click .edit-selection': 'edit',
'click .clear-selection': 'clear'
},
initialize: function() {
_.defaults( this.options, {
editable: false,
clearable: true
});
/**
* @member {wp.media.view.Attachments.Selection}
*/
this.attachments = new media.view.Attachments.Selection({
controller: this.controller,
collection: this.collection,
selection: this.collection,
model: new Backbone.Model({
edge: 40,
gutter: 5
})
});
this.views.set( '.selection-view', this.attachments );
this.collection.on( 'add remove reset', this.refresh, this );
this.controller.on( 'content:activate', this.refresh, this );
},
ready: function() {
this.refresh();
},
refresh: function() {
// If the selection hasn't been rendered, bail.
if ( ! this.$el.children().length ) {
return;
}
var collection = this.collection,
editing = 'edit-selection' === this.controller.content.mode();
// If nothing is selected, display nothing.
this.$el.toggleClass( 'empty', ! collection.length );
this.$el.toggleClass( 'one', 1 === collection.length );
this.$el.toggleClass( 'editing', editing );
this.$('.count').text( l10n.selected.replace('%d', collection.length) );
},
edit: function( event ) {
event.preventDefault();
if ( this.options.editable ) {
this.options.editable.call( this, this.collection );
}
},
clear: function( event ) {
event.preventDefault();
this.collection.reset();
}
});
/**
* wp.media.view.Attachment.Selection
*
* @constructor
* @augments wp.media.view.Attachment
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Attachment.Selection = media.view.Attachment.extend({
className: 'attachment selection',
// On click, just select the model, instead of removing the model from
// the selection.
toggleSelection: function() {
this.options.selection.single( this.model );
}
});
/**
* wp.media.view.Attachments.Selection
*
* @constructor
* @augments wp.media.view.Attachments
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Attachments.Selection = media.view.Attachments.extend({
events: {},
initialize: function() {
_.defaults( this.options, {
sortable: true,
resize: false,
// The single `Attachment` view to be used in the `Attachments` view.
AttachmentView: media.view.Attachment.Selection
});
/**
* call 'initialize' directly on the parent class
*/
return media.view.Attachments.prototype.initialize.apply( this, arguments );
}
});
/**
* wp.media.view.Attachments.EditSelection
*
* @constructor
* @augments wp.media.view.Attachment.Selection
* @augments wp.media.view.Attachment
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Attachment.EditSelection = media.view.Attachment.Selection.extend({
buttons: {
close: true
}
});
/**
* wp.media.view.Settings
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Settings = media.View.extend({
events: {
'click button': 'updateHandler',
'change input': 'updateHandler',
'change select': 'updateHandler',
'change textarea': 'updateHandler'
},
initialize: function() {
this.model = this.model || new Backbone.Model();
this.model.on( 'change', this.updateChanges, this );
},
prepare: function() {
return _.defaults({
model: this.model.toJSON()
}, this.options );
},
/**
* @returns {wp.media.view.Settings} Returns itself to allow chaining
*/
render: function() {
media.View.prototype.render.apply( this, arguments );
// Select the correct values.
_( this.model.attributes ).chain().keys().each( this.update, this );
return this;
},
/**
* @param {string} key
*/
update: function( key ) {
var value = this.model.get( key ),
$setting = this.$('[data-setting="' + key + '"]'),
$buttons, $value;
// Bail if we didn't find a matching setting.
if ( ! $setting.length ) {
return;
}
// Attempt to determine how the setting is rendered and update
// the selected value.
// Handle dropdowns.
if ( $setting.is('select') ) {
$value = $setting.find('[value="' + value + '"]');
if ( $value.length ) {
$setting.find('option').prop( 'selected', false );
$value.prop( 'selected', true );
} else {
// If we can't find the desired value, record what *is* selected.
this.model.set( key, $setting.find(':selected').val() );
}
// Handle button groups.
} else if ( $setting.hasClass('button-group') ) {
$buttons = $setting.find('button').removeClass('active');
$buttons.filter( '[value="' + value + '"]' ).addClass('active');
// Handle text inputs and textareas.
} else if ( $setting.is('input[type="text"], textarea') ) {
if ( ! $setting.is(':focus') ) {
$setting.val( value );
}
// Handle checkboxes.
} else if ( $setting.is('input[type="checkbox"]') ) {
$setting.prop( 'checked', !! value );
}
},
/**
* @param {Object} event
*/
updateHandler: function( event ) {
var $setting = $( event.target ).closest('[data-setting]'),
value = event.target.value,
userSetting;
event.preventDefault();
if ( ! $setting.length ) {
return;
}
// Use the correct value for checkboxes.
if ( $setting.is('input[type="checkbox"]') ) {
value = $setting[0].checked;
}
// Update the corresponding setting.
this.model.set( $setting.data('setting'), value );
// If the setting has a corresponding user setting,
// update that as well.
if ( userSetting = $setting.data('userSetting') ) {
setUserSetting( userSetting, value );
}
},
updateChanges: function( model ) {
if ( model.hasChanged() ) {
_( model.changed ).chain().keys().each( this.update, this );
}
}
});
/**
* wp.media.view.Settings.AttachmentDisplay
*
* @constructor
* @augments wp.media.view.Settings
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Settings.AttachmentDisplay = media.view.Settings.extend({
className: 'attachment-display-settings',
template: media.template('attachment-display-settings'),
initialize: function() {
var attachment = this.options.attachment;
_.defaults( this.options, {
userSettings: false
});
/**
* call 'initialize' directly on the parent class
*/
media.view.Settings.prototype.initialize.apply( this, arguments );
this.model.on( 'change:link', this.updateLinkTo, this );
if ( attachment ) {
attachment.on( 'change:uploading', this.render, this );
}
},
dispose: function() {
var attachment = this.options.attachment;
if ( attachment ) {
attachment.off( null, null, this );
}
/**
* call 'dispose' directly on the parent class
*/
media.view.Settings.prototype.dispose.apply( this, arguments );
},
/**
* @returns {wp.media.view.AttachmentDisplay} Returns itself to allow chaining
*/
render: function() {
var attachment = this.options.attachment;
if ( attachment ) {
_.extend( this.options, {
sizes: attachment.get('sizes'),
type: attachment.get('type')
});
}
/**
* call 'render' directly on the parent class
*/
media.view.Settings.prototype.render.call( this );
this.updateLinkTo();
return this;
},
updateLinkTo: function() {
var linkTo = this.model.get('link'),
$input = this.$('.link-to-custom'),
attachment = this.options.attachment;
if ( 'none' === linkTo || 'embed' === linkTo || ( ! attachment && 'custom' !== linkTo ) ) {
$input.addClass( 'hidden' );
return;
}
if ( attachment ) {
if ( 'post' === linkTo ) {
$input.val( attachment.get('link') );
} else if ( 'file' === linkTo ) {
$input.val( attachment.get('url') );
} else if ( ! this.model.get('linkUrl') ) {
$input.val('http://');
}
$input.prop( 'readonly', 'custom' !== linkTo );
}
$input.removeClass( 'hidden' );
// If the input is visible, focus and select its contents.
if ( $input.is(':visible') ) {
$input.focus()[0].select();
}
}
});
/**
* wp.media.view.Settings.Gallery
*
* @constructor
* @augments wp.media.view.Settings
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Settings.Gallery = media.view.Settings.extend({
className: 'collection-settings gallery-settings',
template: media.template('gallery-settings')
});
/**
* wp.media.view.Settings.Playlist
*
* @constructor
* @augments wp.media.view.Settings
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Settings.Playlist = media.view.Settings.extend({
className: 'collection-settings playlist-settings',
template: media.template('playlist-settings')
});
/**
* wp.media.view.Attachment.Details
*
* @constructor
* @augments wp.media.view.Attachment
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Attachment.Details = media.view.Attachment.extend({
tagName: 'div',
className: 'attachment-details',
template: media.template('attachment-details'),
events: {
'change [data-setting]': 'updateSetting',
'change [data-setting] input': 'updateSetting',
'change [data-setting] select': 'updateSetting',
'change [data-setting] textarea': 'updateSetting',
'click .delete-attachment': 'deleteAttachment',
'click .trash-attachment': 'trashAttachment',
'click .edit-attachment': 'editAttachment',
'click .refresh-attachment': 'refreshAttachment'
},
initialize: function() {
/**
* @member {wp.media.view.FocusManager}
*/
this.focusManager = new media.view.FocusManager({
el: this.el
});
/**
* call 'initialize' directly on the parent class
*/
media.view.Attachment.prototype.initialize.apply( this, arguments );
},
/**
* @returns {wp.media.view..Attachment.Details} Returns itself to allow chaining
*/
render: function() {
/**
* call 'render' directly on the parent class
*/
media.view.Attachment.prototype.render.apply( this, arguments );
this.focusManager.focus();
return this;
},
/**
* @param {Object} event
*/
deleteAttachment: function( event ) {
event.preventDefault();
if ( confirm( l10n.warnDelete ) ) {
this.model.destroy();
}
},
/**
* @param {Object} event
*/
trashAttachment: function( event ) {
event.preventDefault();
this.model.destroy();
},
/**
* @param {Object} event
*/
editAttachment: function( event ) {
var editState = this.controller.states.get( 'edit-image' );
if ( window.imageEdit && editState ) {
event.preventDefault();
editState.set( 'image', this.model );
this.controller.setState( 'edit-image' );
} else {
this.$el.addClass('needs-refresh');
}
},
/**
* @param {Object} event
*/
refreshAttachment: function( event ) {
this.$el.removeClass('needs-refresh');
event.preventDefault();
this.model.fetch();
}
});
/**
* wp.media.view.AttachmentCompat
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.AttachmentCompat = media.View.extend({
tagName: 'form',
className: 'compat-item',
events: {
'submit': 'preventDefault',
'change input': 'save',
'change select': 'save',
'change textarea': 'save'
},
initialize: function() {
/**
* @member {wp.media.view.FocusManager}
*/
this.focusManager = new media.view.FocusManager({
el: this.el
});
this.model.on( 'change:compat', this.render, this );
},
/**
* @returns {wp.media.view.AttachmentCompat} Returns itself to allow chaining
*/
dispose: function() {
if ( this.$(':focus').length ) {
this.save();
}
/**
* call 'dispose' directly on the parent class
*/
return media.View.prototype.dispose.apply( this, arguments );
},
/**
* @returns {wp.media.view.AttachmentCompat} Returns itself to allow chaining
*/
render: function() {
var compat = this.model.get('compat');
if ( ! compat || ! compat.item ) {
return;
}
this.views.detach();
this.$el.html( compat.item );
this.views.render();
this.focusManager.focus();
return this;
},
/**
* @param {Object} event
*/
preventDefault: function( event ) {
event.preventDefault();
},
/**
* @param {Object} event
*/
save: function( event ) {
var data = {};
if ( event ) {
event.preventDefault();
}
_.each( this.$el.serializeArray(), function( pair ) {
data[ pair.name ] = pair.value;
});
this.model.saveCompat( data );
}
});
/**
* wp.media.view.Iframe
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Iframe = media.View.extend({
className: 'media-iframe',
/**
* @returns {wp.media.view.Iframe} Returns itself to allow chaining
*/
render: function() {
this.views.detach();
this.$el.html( '<iframe src="' + this.controller.state().get('src') + '" />' );
this.views.render();
return this;
}
});
/**
* wp.media.view.Embed
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Embed = media.View.extend({
className: 'media-embed',
initialize: function() {
/**
* @member {wp.media.view.EmbedUrl}
*/
this.url = new media.view.EmbedUrl({
controller: this.controller,
model: this.model.props
}).render();
this.views.set([ this.url ]);
this.refresh();
this.model.on( 'change:type', this.refresh, this );
this.model.on( 'change:loading', this.loading, this );
},
/**
* @param {Object} view
*/
settings: function( view ) {
if ( this._settings ) {
this._settings.remove();
}
this._settings = view;
this.views.add( view );
},
refresh: function() {
var type = this.model.get('type'),
constructor;
if ( 'image' === type ) {
constructor = media.view.EmbedImage;
} else if ( 'link' === type ) {
constructor = media.view.EmbedLink;
} else {
return;
}
this.settings( new constructor({
controller: this.controller,
model: this.model.props,
priority: 40
}) );
},
loading: function() {
this.$el.toggleClass( 'embed-loading', this.model.get('loading') );
}
});
/**
* wp.media.view.EmbedUrl
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.EmbedUrl = media.View.extend({
tagName: 'label',
className: 'embed-url',
events: {
'input': 'url',
'keyup': 'url',
'change': 'url'
},
initialize: function() {
this.$input = $('<input/>').attr( 'type', 'text' ).val( this.model.get('url') );
this.input = this.$input[0];
this.spinner = $('<span class="spinner" />')[0];
this.$el.append([ this.input, this.spinner ]);
this.model.on( 'change:url', this.render, this );
},
/**
* @returns {wp.media.view.EmbedUrl} Returns itself to allow chaining
*/
render: function() {
var $input = this.$input;
if ( $input.is(':focus') ) {
return;
}
this.input.value = this.model.get('url') || 'http://';
/**
* Call `render` directly on parent class with passed arguments
*/
media.View.prototype.render.apply( this, arguments );
return this;
},
ready: function() {
this.focus();
},
url: function( event ) {
this.model.set( 'url', event.target.value );
},
/**
* If the input is visible, focus and select its contents.
*/
focus: function() {
var $input = this.$input;
if ( $input.is(':visible') ) {
$input.focus()[0].select();
}
}
});
/**
* wp.media.view.EmbedLink
*
* @constructor
* @augments wp.media.view.Settings
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.EmbedLink = media.view.Settings.extend({
className: 'embed-link-settings',
template: media.template('embed-link-settings')
});
/**
* wp.media.view.EmbedImage
*
* @contructor
* @augments wp.media.view.Settings.AttachmentDisplay
* @augments wp.media.view.Settings
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.EmbedImage = media.view.Settings.AttachmentDisplay.extend({
className: 'embed-media-settings',
template: media.template('embed-image-settings'),
initialize: function() {
/**
* Call `initialize` directly on parent class with passed arguments
*/
media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
this.model.on( 'change:url', this.updateImage, this );
},
updateImage: function() {
this.$('img').attr( 'src', this.model.get('url') );
}
});
/**
* wp.media.view.ImageDetails
*
* @contructor
* @augments wp.media.view.Settings.AttachmentDisplay
* @augments wp.media.view.Settings
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.ImageDetails = media.view.Settings.AttachmentDisplay.extend({
className: 'image-details',
template: media.template('image-details'),
events: _.defaults( media.view.Settings.AttachmentDisplay.prototype.events, {
'click .edit-attachment': 'editAttachment',
'click .replace-attachment': 'replaceAttachment',
'click .advanced-toggle': 'onToggleAdvanced',
'change [data-setting="customWidth"]': 'onCustomSize',
'change [data-setting="customHeight"]': 'onCustomSize',
'keyup [data-setting="customWidth"]': 'onCustomSize',
'keyup [data-setting="customHeight"]': 'onCustomSize'
} ),
initialize: function() {
// used in AttachmentDisplay.prototype.updateLinkTo
this.options.attachment = this.model.attachment;
this.listenTo( this.model, 'change:url', this.updateUrl );
this.listenTo( this.model, 'change:link', this.toggleLinkSettings );
this.listenTo( this.model, 'change:size', this.toggleCustomSize );
media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
},
prepare: function() {
var attachment = false;
if ( this.model.attachment ) {
attachment = this.model.attachment.toJSON();
}
return _.defaults({
model: this.model.toJSON(),
attachment: attachment
}, this.options );
},
render: function() {
var self = this,
args = arguments;
if ( this.model.attachment && 'pending' === this.model.dfd.state() ) {
this.model.dfd.done( function() {
media.view.Settings.AttachmentDisplay.prototype.render.apply( self, args );
self.postRender();
} ).fail( function() {
self.model.attachment = false;
media.view.Settings.AttachmentDisplay.prototype.render.apply( self, args );
self.postRender();
} );
} else {
media.view.Settings.AttachmentDisplay.prototype.render.apply( this, arguments );
this.postRender();
}
return this;
},
postRender: function() {
setTimeout( _.bind( this.resetFocus, this ), 10 );
this.toggleLinkSettings();
if ( getUserSetting( 'advImgDetails' ) === 'show' ) {
this.toggleAdvanced( true );
}
this.trigger( 'post-render' );
},
resetFocus: function() {
this.$( '.link-to-custom' ).blur();
this.$( '.embed-media-settings' ).scrollTop( 0 );
},
updateUrl: function() {
this.$( '.image img' ).attr( 'src', this.model.get( 'url' ) );
this.$( '.url' ).val( this.model.get( 'url' ) );
},
toggleLinkSettings: function() {
if ( this.model.get( 'link' ) === 'none' ) {
this.$( '.link-settings' ).addClass('hidden');
} else {
this.$( '.link-settings' ).removeClass('hidden');
}
},
toggleCustomSize: function() {
if ( this.model.get( 'size' ) !== 'custom' ) {
this.$( '.custom-size' ).addClass('hidden');
} else {
this.$( '.custom-size' ).removeClass('hidden');
}
},
onCustomSize: function( event ) {
var dimension = $( event.target ).data('setting'),
num = $( event.target ).val(),
value;
// Ignore bogus input
if ( ! /^\d+/.test( num ) || parseInt( num, 10 ) < 1 ) {
event.preventDefault();
return;
}
if ( dimension === 'customWidth' ) {
value = Math.round( 1 / this.model.get( 'aspectRatio' ) * num );
this.model.set( 'customHeight', value, { silent: true } );
this.$( '[data-setting="customHeight"]' ).val( value );
} else {
value = Math.round( this.model.get( 'aspectRatio' ) * num );
this.model.set( 'customWidth', value, { silent: true } );
this.$( '[data-setting="customWidth"]' ).val( value );
}
},
onToggleAdvanced: function( event ) {
event.preventDefault();
this.toggleAdvanced();
},
toggleAdvanced: function( show ) {
var $advanced = this.$el.find( '.advanced-section' ),
mode;
if ( $advanced.hasClass('advanced-visible') || show === false ) {
$advanced.removeClass('advanced-visible');
$advanced.find('.advanced-settings').addClass('hidden');
mode = 'hide';
} else {
$advanced.addClass('advanced-visible');
$advanced.find('.advanced-settings').removeClass('hidden');
mode = 'show';
}
setUserSetting( 'advImgDetails', mode );
},
editAttachment: function( event ) {
var editState = this.controller.states.get( 'edit-image' );
if ( window.imageEdit && editState ) {
event.preventDefault();
editState.set( 'image', this.model.attachment );
this.controller.setState( 'edit-image' );
}
},
replaceAttachment: function( event ) {
event.preventDefault();
this.controller.setState( 'replace-image' );
}
});
/**
* wp.media.view.Cropper
*
* Uses the imgAreaSelect plugin to allow a user to crop an image.
*
* Takes imgAreaSelect options from
* wp.customize.HeaderControl.calculateImageSelectOptions via
* wp.customize.HeaderControl.openMM.
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Cropper = media.View.extend({
className: 'crop-content',
template: media.template('crop-content'),
initialize: function() {
_.bindAll(this, 'onImageLoad');
},
ready: function() {
this.controller.frame.on('content:error:crop', this.onError, this);
this.$image = this.$el.find('.crop-image');
this.$image.on('load', this.onImageLoad);
$(window).on('resize.cropper', _.debounce(this.onImageLoad, 250));
},
remove: function() {
$(window).off('resize.cropper');
this.$el.remove();
this.$el.off();
wp.media.View.prototype.remove.apply(this, arguments);
},
prepare: function() {
return {
title: l10n.cropYourImage,
url: this.options.attachment.get('url')
};
},
onImageLoad: function() {
var imgOptions = this.controller.get('imgSelectOptions');
if (typeof imgOptions === 'function') {
imgOptions = imgOptions(this.options.attachment, this.controller);
}
imgOptions = _.extend(imgOptions, {parent: this.$el});
this.trigger('image-loaded');
this.controller.imgSelect = this.$image.imgAreaSelect(imgOptions);
},
onError: function() {
var filename = this.options.attachment.get('filename');
this.views.add( '.upload-errors', new media.view.UploaderStatusError({
filename: media.view.UploaderStatus.prototype.filename(filename),
message: _wpMediaViewsL10n.cropError
}), { at: 0 });
}
});
media.view.EditImage = media.View.extend({
className: 'image-editor',
template: media.template('image-editor'),
initialize: function( options ) {
this.editor = window.imageEdit;
this.controller = options.controller;
media.View.prototype.initialize.apply( this, arguments );
},
prepare: function() {
return this.model.toJSON();
},
render: function() {
media.View.prototype.render.apply( this, arguments );
return this;
},
loadEditor: function() {
this.editor.open( this.model.get('id'), this.model.get('nonces').edit, this );
},
back: function() {
var lastState = this.controller.lastState();
this.controller.setState( lastState );
},
refresh: function() {
this.model.fetch();
},
save: function() {
var self = this,
lastState = this.controller.lastState();
this.model.fetch().done( function() {
self.controller.setState( lastState );
});
}
});
/**
* wp.media.view.Spinner
*
* @constructor
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.Spinner = media.View.extend({
tagName: 'span',
className: 'spinner',
spinnerTimeout: false,
delay: 400,
show: function() {
if ( ! this.spinnerTimeout ) {
this.spinnerTimeout = _.delay(function( $el ) {
$el.show();
}, this.delay, this.$el );
}
return this;
},
hide: function() {
this.$el.hide();
this.spinnerTimeout = clearTimeout( this.spinnerTimeout );
return this;
}
});
}(jQuery, _));
| JavaScript |
/**
* Heartbeat API
*
* Heartbeat is a simple server polling API that sends XHR requests to
* the server every 15 - 60 seconds and triggers events (or callbacks) upon
* receiving data. Currently these 'ticks' handle transports for post locking,
* login-expiration warnings, autosave, and related tasks while a user is logged in.
*
* Available PHP filters (in ajax-actions.php):
* - heartbeat_received
* - heartbeat_send
* - heartbeat_tick
* - heartbeat_nopriv_received
* - heartbeat_nopriv_send
* - heartbeat_nopriv_tick
* @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat()
*
* Custom jQuery events:
* - heartbeat-send
* - heartbeat-tick
* - heartbeat-error
* - heartbeat-connection-lost
* - heartbeat-connection-restored
* - heartbeat-nonces-expired
*
* @since 3.6.0
*/
( function( $, window, undefined ) {
var Heartbeat = function() {
var $document = $(document),
settings = {
// Suspend/resume
suspend: false,
// Whether suspending is enabled
suspendEnabled: true,
// Current screen id, defaults to the JS global 'pagenow' when present (in the admin) or 'front'
screenId: '',
// XHR request URL, defaults to the JS global 'ajaxurl' when present
url: '',
// Timestamp, start of the last connection request
lastTick: 0,
// Container for the enqueued items
queue: {},
// Connect interval (in seconds)
mainInterval: 60,
// Used when the interval is set to 5 sec. temporarily
tempInterval: 0,
// Used when the interval is reset
originalInterval: 0,
// Used together with tempInterval
countdown: 0,
// Whether a connection is currently in progress
connecting: false,
// Whether a connection error occured
connectionError: false,
// Used to track non-critical errors
errorcount: 0,
// Whether at least one connection has completed successfully
hasConnected: false,
// Whether the current browser window is in focus and the user is active
hasFocus: true,
// Timestamp, last time the user was active. Checked every 30 sec.
userActivity: 0,
// Flags whether events tracking user activity were set
userActivityEvents: false,
// References to various timeouts
beatTimer: 0,
winBlurTimer: 0,
frameBlurTimer: 0
};
/**
* Set local vars and events, then start
*
* @access private
*
* @return void
*/
function initialize() {
if ( typeof window.pagenow === 'string' ) {
settings.screenId = window.pagenow;
}
if ( typeof window.ajaxurl === 'string' ) {
settings.url = window.ajaxurl;
}
// Pull in options passed from PHP
if ( typeof window.heartbeatSettings === 'object' ) {
var options = window.heartbeatSettings;
// The XHR URL can be passed as option when window.ajaxurl is not set
if ( ! settings.url && options.ajaxurl ) {
settings.url = options.ajaxurl;
}
// The interval can be from 15 to 60 sec. and can be set temporarily to 5 sec.
if ( options.interval ) {
settings.mainInterval = options.interval;
if ( settings.mainInterval < 15 ) {
settings.mainInterval = 15;
} else if ( settings.mainInterval > 60 ) {
settings.mainInterval = 60;
}
}
// 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set
if ( ! settings.screenId ) {
settings.screenId = options.screenId || 'front';
}
if ( options.suspension === 'disable' ) {
settings.suspendEnabled = false;
}
}
// Convert to milliseconds
settings.mainInterval = settings.mainInterval * 1000;
settings.originalInterval = settings.mainInterval;
// Set focus/blur events on the window
$(window).on( 'blur.wp-heartbeat-focus', function() {
setFrameFocusEvents();
// We don't know why the 'blur' was fired. Either the user clicked in an iframe or outside the browser.
// Running blurred() after some timeout lets us cancel it if the user clicked in an iframe.
settings.winBlurTimer = window.setTimeout( function(){ blurred(); }, 500 );
}).on( 'focus.wp-heartbeat-focus', function() {
removeFrameFocusEvents();
focused();
}).on( 'unload.wp-heartbeat', function() {
// Don't connect any more
settings.suspend = true;
// Abort the last request if not completed
if ( settings.xhr && settings.xhr.readyState !== 4 ) {
settings.xhr.abort();
}
});
// Check for user activity every 30 seconds.
window.setInterval( function(){ checkUserActivity(); }, 30000 );
// Start one tick after DOM ready
$document.ready( function() {
settings.lastTick = time();
scheduleNextTick();
});
}
/**
* Return the current time according to the browser
*
* @access private
*
* @return int
*/
function time() {
return (new Date()).getTime();
}
/**
* Check if the iframe is from the same origin
*
* @access private
*
* @return bool
*/
function isLocalFrame( frame ) {
var origin, src = frame.src;
// Need to compare strings as WebKit doesn't throw JS errors when iframes have different origin.
// It throws uncatchable exceptions.
if ( src && /^https?:\/\//.test( src ) ) {
origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
if ( src.indexOf( origin ) !== 0 ) {
return false;
}
}
try {
if ( frame.contentWindow.document ) {
return true;
}
} catch(e) {}
return false;
}
/**
* Set error state and fire an event on XHR errors or timeout
*
* @access private
*
* @param string error The error type passed from the XHR
* @param int status The HTTP status code passed from jqXHR (200, 404, 500, etc.)
* @return void
*/
function setErrorState( error, status ) {
var trigger;
if ( error ) {
switch ( error ) {
case 'abort':
// do nothing
break;
case 'timeout':
// no response for 30 sec.
trigger = true;
break;
case 'error':
if ( 503 === status && settings.hasConnected ) {
trigger = true;
break;
}
/* falls through */
case 'parsererror':
case 'empty':
case 'unknown':
settings.errorcount++;
if ( settings.errorcount > 2 && settings.hasConnected ) {
trigger = true;
}
break;
}
if ( trigger && ! hasConnectionError() ) {
settings.connectionError = true;
$document.trigger( 'heartbeat-connection-lost', [error, status] );
}
}
}
/**
* Clear the error state and fire an event
*
* @access private
*
* @return void
*/
function clearErrorState() {
// Has connected successfully
settings.hasConnected = true;
if ( hasConnectionError() ) {
settings.errorcount = 0;
settings.connectionError = false;
$document.trigger( 'heartbeat-connection-restored' );
}
}
/**
* Gather the data and connect to the server
*
* @access private
*
* @return void
*/
function connect() {
var ajaxData, heartbeatData;
// If the connection to the server is slower than the interval,
// heartbeat connects as soon as the previous connection's response is received.
if ( settings.connecting || settings.suspend ) {
return;
}
settings.lastTick = time();
heartbeatData = $.extend( {}, settings.queue );
// Clear the data queue, anything added after this point will be send on the next tick
settings.queue = {};
$document.trigger( 'heartbeat-send', [ heartbeatData ] );
ajaxData = {
data: heartbeatData,
interval: settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000,
_nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.nonce : '',
action: 'heartbeat',
screen_id: settings.screenId,
has_focus: settings.hasFocus
};
settings.connecting = true;
settings.xhr = $.ajax({
url: settings.url,
type: 'post',
timeout: 30000, // throw an error if not completed after 30 sec.
data: ajaxData,
dataType: 'json'
}).always( function() {
settings.connecting = false;
scheduleNextTick();
}).done( function( response, textStatus, jqXHR ) {
var newInterval;
if ( ! response ) {
setErrorState( 'empty' );
return;
}
clearErrorState();
if ( response.nonces_expired ) {
$document.trigger( 'heartbeat-nonces-expired' );
return;
}
// Change the interval from PHP
if ( response.heartbeat_interval ) {
newInterval = response.heartbeat_interval;
delete response.heartbeat_interval;
}
$document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
// Do this last, can trigger the next XHR if connection time > 5 sec. and newInterval == 'fast'
if ( newInterval ) {
interval( newInterval );
}
}).fail( function( jqXHR, textStatus, error ) {
setErrorState( textStatus || 'unknown', jqXHR.status );
$document.trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
});
}
/**
* Schedule the next connection
*
* Fires immediately if the connection time is longer than the interval.
*
* @access private
*
* @return void
*/
function scheduleNextTick() {
var delta = time() - settings.lastTick,
interval = settings.mainInterval;
if ( settings.suspend ) {
return;
}
if ( ! settings.hasFocus ) {
interval = 120000; // 120 sec. Post locks expire after 150 sec.
} else if ( settings.countdown > 0 && settings.tempInterval ) {
interval = settings.tempInterval;
settings.countdown--;
if ( settings.countdown < 1 ) {
settings.tempInterval = 0;
}
}
window.clearTimeout( settings.beatTimer );
if ( delta < interval ) {
settings.beatTimer = window.setTimeout(
function() {
connect();
},
interval - delta
);
} else {
connect();
}
}
/**
* Set the internal state when the browser window looses focus
*
* @access private
*
* @return void
*/
function blurred() {
clearFocusTimers();
settings.hasFocus = false;
}
/**
* Set the internal state when the browser window is focused
*
* @access private
*
* @return void
*/
function focused() {
clearFocusTimers();
settings.userActivity = time();
// Resume if suspended
settings.suspend = false;
if ( ! settings.hasFocus ) {
settings.hasFocus = true;
scheduleNextTick();
}
}
/**
* Add focus/blur events to all local iframes
*
* Used to detect when focus is moved from the main window to an iframe
*
* @access private
*
* @return void
*/
function setFrameFocusEvents() {
$('iframe').each( function( i, frame ) {
if ( ! isLocalFrame( frame ) ) {
return;
}
if ( $.data( frame, 'wp-heartbeat-focus' ) ) {
return;
}
$.data( frame, 'wp-heartbeat-focus', 1 );
$( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function() {
focused();
}).on('blur.wp-heartbeat-focus', function() {
setFrameFocusEvents();
// We don't know why 'blur' was fired. Either the user clicked in the main window or outside the browser.
// Running blurred() after some timeout lets us cancel it if the user clicked in the main window.
settings.frameBlurTimer = window.setTimeout( function(){ blurred(); }, 500 );
});
});
}
/**
* Remove the focus/blur events to all local iframes
*
* @access private
*
* @return void
*/
function removeFrameFocusEvents() {
$('iframe').each( function( i, frame ) {
if ( ! isLocalFrame( frame ) ) {
return;
}
$.removeData( frame, 'wp-heartbeat-focus' );
$( frame.contentWindow ).off( '.wp-heartbeat-focus' );
});
}
/**
* Clear the reset timers for focus/blur events on the window and iframes
*
* @access private
*
* @return void
*/
function clearFocusTimers() {
window.clearTimeout( settings.winBlurTimer );
window.clearTimeout( settings.frameBlurTimer );
}
/**
* Runs when the user becomes active after a period of inactivity
*
* @access private
*
* @return void
*/
function userIsActive() {
settings.userActivityEvents = false;
$document.off( '.wp-heartbeat-active' );
$('iframe').each( function( i, frame ) {
if ( ! isLocalFrame( frame ) ) {
return;
}
$( frame.contentWindow ).off( '.wp-heartbeat-active' );
});
focused();
}
/**
* Check for user activity
*
* Runs every 30 sec.
* Sets 'hasFocus = true' if user is active and the window is in the background.
* Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity)
* for 5 min. even when the window has focus.
*
* @access private
*
* @return void
*/
function checkUserActivity() {
var lastActive = settings.userActivity ? time() - settings.userActivity : 0;
if ( lastActive > 300000 && settings.hasFocus ) {
// Throttle down when no mouse or keyboard activity for 5 min
blurred();
}
if ( settings.suspendEnabled && lastActive > 1200000 ) {
// Suspend after 20 min. of inactivity
settings.suspend = true;
}
if ( ! settings.userActivityEvents ) {
$document.on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
$('iframe').each( function( i, frame ) {
if ( ! isLocalFrame( frame ) ) {
return;
}
$( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
});
settings.userActivityEvents = true;
}
}
// Public methods
/**
* Whether the window (or any local iframe in it) has focus, or the user is active
*
* @return bool
*/
function hasFocus() {
return settings.hasFocus;
}
/**
* Whether there is a connection error
*
* @return bool
*/
function hasConnectionError() {
return settings.connectionError;
}
/**
* Connect asap regardless of 'hasFocus'
*
* Will not open two concurrent connections. If a connection is in progress,
* will connect again immediately after the current connection completes.
*
* @return void
*/
function connectNow() {
settings.lastTick = 0;
scheduleNextTick();
}
/**
* Disable suspending
*
* Should be used only when Heartbeat is performing critical tasks like autosave, post-locking, etc.
* Using this on many screens may overload the user's hosting account if several
* browser windows/tabs are left open for a long time.
*
* @return void
*/
function disableSuspend() {
settings.suspendEnabled = false;
}
/**
* Get/Set the interval
*
* When setting to 'fast' or 5, by default interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
* In this case the number of 'ticks' can be passed as second argument.
* If the window doesn't have focus, the interval slows down to 2 min.
*
* @param mixed speed Interval: 'fast' or 5, 15, 30, 60
* @param string ticks Used with speed = 'fast' or 5, how many ticks before the interval reverts back
* @return int Current interval in seconds
*/
function interval( speed, ticks ) {
var newInterval,
oldInterval = settings.tempInterval ? settings.tempInterval : settings.mainInterval;
if ( speed ) {
switch ( speed ) {
case 'fast':
case 5:
newInterval = 5000;
break;
case 15:
newInterval = 15000;
break;
case 30:
newInterval = 30000;
break;
case 60:
newInterval = 60000;
break;
case 'long-polling':
// Allow long polling, (experimental)
settings.mainInterval = 0;
return 0;
default:
newInterval = settings.originalInterval;
}
if ( 5000 === newInterval ) {
ticks = parseInt( ticks, 10 ) || 30;
ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
settings.countdown = ticks;
settings.tempInterval = newInterval;
} else {
settings.countdown = 0;
settings.tempInterval = 0;
settings.mainInterval = newInterval;
}
// Change the next connection time if new interval has been set.
// Will connect immediately if the time since the last connection
// is greater than the new interval.
if ( newInterval !== oldInterval ) {
scheduleNextTick();
}
}
return settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000;
}
/**
* Enqueue data to send with the next XHR
*
* As the data is send asynchronously, this function doesn't return the XHR response.
* To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
* $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
* // code
* });
* If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'.
* Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
*
* $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
* $param mixed data The data to send.
* $param bool noOverwrite Whether to overwrite existing data in the queue.
* $return bool Whether the data was queued or not.
*/
function enqueue( handle, data, noOverwrite ) {
if ( handle ) {
if ( noOverwrite && this.isQueued( handle ) ) {
return false;
}
settings.queue[handle] = data;
return true;
}
return false;
}
/**
* Check if data with a particular handle is queued
*
* $param string handle The handle for the data
* $return bool Whether some data is queued with this handle
*/
function isQueued( handle ) {
if ( handle ) {
return settings.queue.hasOwnProperty( handle );
}
}
/**
* Remove data with a particular handle from the queue
*
* $param string handle The handle for the data
* $return void
*/
function dequeue( handle ) {
if ( handle ) {
delete settings.queue[handle];
}
}
/**
* Get data that was enqueued with a particular handle
*
* $param string handle The handle for the data
* $return mixed The data or undefined
*/
function getQueuedItem( handle ) {
if ( handle ) {
return this.isQueued( handle ) ? settings.queue[handle] : undefined;
}
}
initialize();
// Expose public methods
return {
hasFocus: hasFocus,
connectNow: connectNow,
disableSuspend: disableSuspend,
interval: interval,
hasConnectionError: hasConnectionError,
enqueue: enqueue,
dequeue: dequeue,
isQueued: isQueued,
getQueuedItem: getQueuedItem
};
};
// Ensure the global `wp` object exists.
window.wp = window.wp || {};
window.wp.heartbeat = new Heartbeat();
}( jQuery, window ));
| JavaScript |
/* global getUserSetting, tinymce, QTags, wpActiveEditor */
// WordPress, TinyMCE, and Media
// -----------------------------
(function($, _){
/**
* Stores the editors' `wp.media.controller.Frame` instances.
*
* @static
*/
var workflows = {};
/**
* A helper mixin function to avoid truthy and falsey values being
* passed as an input that expects booleans. If key is undefined in the map,
* but has a default value, set it.
*
* @param {object} attrs Map of props from a shortcode or settings.
* @param {string} key The key within the passed map to check for a value.
* @returns {mixed|undefined} The original or coerced value of key within attrs
*/
wp.media.coerce = function ( attrs, key ) {
if ( _.isUndefined( attrs[ key ] ) && ! _.isUndefined( this.defaults[ key ] ) ) {
attrs[ key ] = this.defaults[ key ];
} else if ( 'true' === attrs[ key ] ) {
attrs[ key ] = true;
} else if ( 'false' === attrs[ key ] ) {
attrs[ key ] = false;
}
return attrs[ key ];
};
/**
* wp.media.string
* @namespace
*/
wp.media.string = {
/**
* Joins the `props` and `attachment` objects,
* outputting the proper object format based on the
* attachment's type.
*
* @global wp.media.view.settings
* @global getUserSetting()
*
* @param {Object} [props={}] Attachment details (align, link, size, etc).
* @param {Object} attachment The attachment object, media version of Post.
* @returns {Object} Joined props
*/
props: function( props, attachment ) {
var link, linkUrl, size, sizes, fallbacks,
defaultProps = wp.media.view.settings.defaultProps;
// Final fallbacks run after all processing has been completed.
fallbacks = function( props ) {
// Generate alt fallbacks and strip tags.
if ( 'image' === props.type && ! props.alt ) {
props.alt = props.caption || props.title || '';
props.alt = props.alt.replace( /<\/?[^>]+>/g, '' );
props.alt = props.alt.replace( /[\r\n]+/g, ' ' );
}
return props;
};
props = props ? _.clone( props ) : {};
if ( attachment && attachment.type ) {
props.type = attachment.type;
}
if ( 'image' === props.type ) {
props = _.defaults( props || {}, {
align: defaultProps.align || getUserSetting( 'align', 'none' ),
size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ),
url: '',
classes: []
});
}
// All attachment-specific settings follow.
if ( ! attachment ) {
return fallbacks( props );
}
props.title = props.title || attachment.title;
link = props.link || defaultProps.link || getUserSetting( 'urlbutton', 'file' );
if ( 'file' === link || 'embed' === link ) {
linkUrl = attachment.url;
} else if ( 'post' === link ) {
linkUrl = attachment.link;
} else if ( 'custom' === link ) {
linkUrl = props.linkUrl;
}
props.linkUrl = linkUrl || '';
// Format properties for images.
if ( 'image' === attachment.type ) {
props.classes.push( 'wp-image-' + attachment.id );
sizes = attachment.sizes;
size = sizes && sizes[ props.size ] ? sizes[ props.size ] : attachment;
_.extend( props, _.pick( attachment, 'align', 'caption', 'alt' ), {
width: size.width,
height: size.height,
src: size.url,
captionId: 'attachment_' + attachment.id
});
} else if ( 'video' === attachment.type || 'audio' === attachment.type ) {
_.extend( props, _.pick( attachment, 'title', 'type', 'icon', 'mime' ) );
// Format properties for non-images.
} else {
props.title = props.title || attachment.filename;
props.rel = props.rel || 'attachment wp-att-' + attachment.id;
}
return fallbacks( props );
},
/**
* Create link markup that is suitable for passing to the editor
*
* @global wp.html.string
*
* @param {Object} props Attachment details (align, link, size, etc).
* @param {Object} attachment The attachment object, media version of Post.
* @returns {string} The link markup
*/
link: function( props, attachment ) {
var options;
props = wp.media.string.props( props, attachment );
options = {
tag: 'a',
content: props.title,
attrs: {
href: props.linkUrl
}
};
if ( props.rel ) {
options.attrs.rel = props.rel;
}
return wp.html.string( options );
},
/**
* Create an Audio shortcode string that is suitable for passing to the editor
*
* @param {Object} props Attachment details (align, link, size, etc).
* @param {Object} attachment The attachment object, media version of Post.
* @returns {string} The audio shortcode
*/
audio: function( props, attachment ) {
return wp.media.string._audioVideo( 'audio', props, attachment );
},
/**
* Create a Video shortcode string that is suitable for passing to the editor
*
* @param {Object} props Attachment details (align, link, size, etc).
* @param {Object} attachment The attachment object, media version of Post.
* @returns {string} The video shortcode
*/
video: function( props, attachment ) {
return wp.media.string._audioVideo( 'video', props, attachment );
},
/**
* Helper function to create a media shortcode string
*
* @access private
*
* @global wp.shortcode
* @global wp.media.view.settings
*
* @param {string} type The shortcode tag name: 'audio' or 'video'.
* @param {Object} props Attachment details (align, link, size, etc).
* @param {Object} attachment The attachment object, media version of Post.
* @returns {string} The media shortcode
*/
_audioVideo: function( type, props, attachment ) {
var shortcode, html, extension;
props = wp.media.string.props( props, attachment );
if ( props.link !== 'embed' )
return wp.media.string.link( props );
shortcode = {};
if ( 'video' === type ) {
if ( attachment.image && -1 === attachment.image.src.indexOf( attachment.icon ) ) {
shortcode.poster = attachment.image.src;
}
if ( attachment.width ) {
shortcode.width = attachment.width;
}
if ( attachment.height ) {
shortcode.height = attachment.height;
}
}
extension = attachment.filename.split('.').pop();
if ( _.contains( wp.media.view.settings.embedExts, extension ) ) {
shortcode[extension] = attachment.url;
} else {
// Render unsupported audio and video files as links.
return wp.media.string.link( props );
}
html = wp.shortcode.string({
tag: type,
attrs: shortcode
});
return html;
},
/**
* Create image markup, optionally with a link and/or wrapped in a caption shortcode,
* that is suitable for passing to the editor
*
* @global wp.html
* @global wp.shortcode
*
* @param {Object} props Attachment details (align, link, size, etc).
* @param {Object} attachment The attachment object, media version of Post.
* @returns {string}
*/
image: function( props, attachment ) {
var img = {},
options, classes, shortcode, html;
props = wp.media.string.props( props, attachment );
classes = props.classes || [];
img.src = ! _.isUndefined( attachment ) ? attachment.url : props.url;
_.extend( img, _.pick( props, 'width', 'height', 'alt' ) );
// Only assign the align class to the image if we're not printing
// a caption, since the alignment is sent to the shortcode.
if ( props.align && ! props.caption ) {
classes.push( 'align' + props.align );
}
if ( props.size ) {
classes.push( 'size-' + props.size );
}
img['class'] = _.compact( classes ).join(' ');
// Generate `img` tag options.
options = {
tag: 'img',
attrs: img,
single: true
};
// Generate the `a` element options, if they exist.
if ( props.linkUrl ) {
options = {
tag: 'a',
attrs: {
href: props.linkUrl
},
content: options
};
}
html = wp.html.string( options );
// Generate the caption shortcode.
if ( props.caption ) {
shortcode = {};
if ( img.width ) {
shortcode.width = img.width;
}
if ( props.captionId ) {
shortcode.id = props.captionId;
}
if ( props.align ) {
shortcode.align = 'align' + props.align;
}
html = wp.shortcode.string({
tag: 'caption',
attrs: shortcode,
content: html + ' ' + props.caption
});
}
return html;
}
};
wp.media.collection = function(attributes) {
var collections = {};
return _.extend( attributes, {
coerce : wp.media.coerce,
/**
* Retrieve attachments based on the properties of the passed shortcode
*
* @global wp.media.query
*
* @param {wp.shortcode} shortcode An instance of wp.shortcode().
* @returns {wp.media.model.Attachments} A Backbone.Collection containing
* the media items belonging to a collection.
* The query[ this.tag ] property is a Backbone.Model
* containing the 'props' for the collection.
*/
attachments: function( shortcode ) {
var shortcodeString = shortcode.string(),
result = collections[ shortcodeString ],
attrs, args, query, others, self = this;
delete collections[ shortcodeString ];
if ( result ) {
return result;
}
// Fill the default shortcode attributes.
attrs = _.defaults( shortcode.attrs.named, this.defaults );
args = _.pick( attrs, 'orderby', 'order' );
args.type = this.type;
args.perPage = -1;
// Mark the `orderby` override attribute.
if ( undefined !== attrs.orderby ) {
attrs._orderByField = attrs.orderby;
}
if ( 'rand' === attrs.orderby ) {
attrs._orderbyRandom = true;
}
// Map the `orderby` attribute to the corresponding model property.
if ( ! attrs.orderby || /^menu_order(?: ID)?$/i.test( attrs.orderby ) ) {
args.orderby = 'menuOrder';
}
// Map the `ids` param to the correct query args.
if ( attrs.ids ) {
args.post__in = attrs.ids.split(',');
args.orderby = 'post__in';
} else if ( attrs.include ) {
args.post__in = attrs.include.split(',');
}
if ( attrs.exclude ) {
args.post__not_in = attrs.exclude.split(',');
}
if ( ! args.post__in ) {
args.uploadedTo = attrs.id;
}
// Collect the attributes that were not included in `args`.
others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' );
_.each( this.defaults, function( value, key ) {
others[ key ] = self.coerce( others, key );
});
query = wp.media.query( args );
query[ this.tag ] = new Backbone.Model( others );
return query;
},
/**
* Triggered when clicking 'Insert {label}' or 'Update {label}'
*
* @global wp.shortcode
* @global wp.media.model.Attachments
*
* @param {wp.media.model.Attachments} attachments A Backbone.Collection containing
* the media items belonging to a collection.
* The query[ this.tag ] property is a Backbone.Model
* containing the 'props' for the collection.
* @returns {wp.shortcode}
*/
shortcode: function( attachments ) {
var props = attachments.props.toJSON(),
attrs = _.pick( props, 'orderby', 'order' ),
shortcode, clone, self = this;
if ( attachments.type ) {
attrs.type = attachments.type;
delete attachments.type;
}
if ( attachments[this.tag] ) {
_.extend( attrs, attachments[this.tag].toJSON() );
}
// Convert all gallery shortcodes to use the `ids` property.
// Ignore `post__in` and `post__not_in`; the attachments in
// the collection will already reflect those properties.
attrs.ids = attachments.pluck('id');
// Copy the `uploadedTo` post ID.
if ( props.uploadedTo ) {
attrs.id = props.uploadedTo;
}
// Check if the gallery is randomly ordered.
delete attrs.orderby;
if ( attrs._orderbyRandom ) {
attrs.orderby = 'rand';
} else if ( attrs._orderByField && attrs._orderByField != 'rand' ) {
attrs.orderby = attrs._orderByField;
}
delete attrs._orderbyRandom;
delete attrs._orderByField;
// If the `ids` attribute is set and `orderby` attribute
// is the default value, clear it for cleaner output.
if ( attrs.ids && 'post__in' === attrs.orderby ) {
delete attrs.orderby;
}
// Remove default attributes from the shortcode.
_.each( this.defaults, function( value, key ) {
attrs[ key ] = self.coerce( attrs, key );
if ( value === attrs[ key ] ) {
delete attrs[ key ];
}
});
shortcode = new wp.shortcode({
tag: this.tag,
attrs: attrs,
type: 'single'
});
// Use a cloned version of the gallery.
clone = new wp.media.model.Attachments( attachments.models, {
props: props
});
clone[ this.tag ] = attachments[ this.tag ];
collections[ shortcode.string() ] = clone;
return shortcode;
},
/**
* Triggered when double-clicking a collection shortcode placeholder
* in the editor
*
* @global wp.shortcode
* @global wp.media.model.Selection
* @global wp.media.view.l10n
*
* @param {string} content Content that is searched for possible
* shortcode markup matching the passed tag name,
*
* @this wp.media.{prop}
*
* @returns {wp.media.view.MediaFrame.Select} A media workflow.
*/
edit: function( content ) {
var shortcode = wp.shortcode.next( this.tag, content ),
defaultPostId = this.defaults.id,
attachments, selection, state;
// Bail if we didn't match the shortcode or all of the content.
if ( ! shortcode || shortcode.content !== content ) {
return;
}
// Ignore the rest of the match object.
shortcode = shortcode.shortcode;
if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) ) {
shortcode.set( 'id', defaultPostId );
}
attachments = this.attachments( shortcode );
selection = new wp.media.model.Selection( attachments.models, {
props: attachments.props.toJSON(),
multiple: true
});
selection[ this.tag ] = attachments[ this.tag ];
// Fetch the query's attachments, and then break ties from the
// query to allow for sorting.
selection.more().done( function() {
// Break ties with the query.
selection.props.set({ query: false });
selection.unmirror();
selection.props.unset('orderby');
});
// Destroy the previous gallery frame.
if ( this.frame ) {
this.frame.dispose();
}
if ( shortcode.attrs.named.type && 'video' === shortcode.attrs.named.type ) {
state = 'video-' + this.tag + '-edit';
} else {
state = this.tag + '-edit';
}
// Store the current frame.
this.frame = wp.media({
frame: 'post',
state: state,
title: this.editTitle,
editing: true,
multiple: true,
selection: selection
}).open();
return this.frame;
}
});
};
wp.media.gallery = new wp.media.collection({
tag: 'gallery',
type : 'image',
editTitle : wp.media.view.l10n.editGalleryTitle,
defaults : {
itemtag: 'dl',
icontag: 'dt',
captiontag: 'dd',
columns: '3',
link: 'post',
size: 'thumbnail',
order: 'ASC',
id: wp.media.view.settings.post && wp.media.view.settings.post.id,
orderby : 'menu_order ID'
}
});
/**
* wp.media.featuredImage
* @namespace
*/
wp.media.featuredImage = {
/**
* Get the featured image post ID
*
* @global wp.media.view.settings
*
* @returns {wp.media.view.settings.post.featuredImageId|number}
*/
get: function() {
return wp.media.view.settings.post.featuredImageId;
},
/**
* Set the featured image id, save the post thumbnail data and
* set the HTML in the post meta box to the new featured image.
*
* @global wp.media.view.settings
* @global wp.media.post
*
* @param {number} id The post ID of the featured image, or -1 to unset it.
*/
set: function( id ) {
var settings = wp.media.view.settings;
settings.post.featuredImageId = id;
wp.media.post( 'set-post-thumbnail', {
json: true,
post_id: settings.post.id,
thumbnail_id: settings.post.featuredImageId,
_wpnonce: settings.post.nonce
}).done( function( html ) {
$( '.inside', '#postimagediv' ).html( html );
});
},
/**
* The Featured Image workflow
*
* @global wp.media.controller.FeaturedImage
* @global wp.media.view.l10n
*
* @this wp.media.featuredImage
*
* @returns {wp.media.view.MediaFrame.Select} A media workflow.
*/
frame: function() {
if ( this._frame ) {
return this._frame;
}
this._frame = wp.media({
state: 'featured-image',
states: [ new wp.media.controller.FeaturedImage() , new wp.media.controller.EditImage() ]
});
this._frame.on( 'toolbar:create:featured-image', function( toolbar ) {
/**
* @this wp.media.view.MediaFrame.Select
*/
this.createSelectToolbar( toolbar, {
text: wp.media.view.l10n.setFeaturedImage
});
}, this._frame );
this._frame.on( 'content:render:edit-image', function() {
var selection = this.state('featured-image').get('selection'),
view = new wp.media.view.EditImage( { model: selection.single(), controller: this } ).render();
this.content.set( view );
// after bringing in the frame, load the actual editor via an ajax call
view.loadEditor();
}, this._frame );
this._frame.state('featured-image').on( 'select', this.select );
return this._frame;
},
/**
* 'select' callback for Featured Image workflow, triggered when
* the 'Set Featured Image' button is clicked in the media modal.
*
* @global wp.media.view.settings
*
* @this wp.media.controller.FeaturedImage
*/
select: function() {
var selection = this.get('selection').single();
if ( ! wp.media.view.settings.post.featuredImageId ) {
return;
}
wp.media.featuredImage.set( selection ? selection.id : -1 );
},
/**
* Open the content media manager to the 'featured image' tab when
* the post thumbnail is clicked.
*
* Update the featured image id when the 'remove' link is clicked.
*
* @global wp.media.view.settings
*/
init: function() {
$('#postimagediv').on( 'click', '#set-post-thumbnail', function( event ) {
event.preventDefault();
// Stop propagation to prevent thickbox from activating.
event.stopPropagation();
wp.media.featuredImage.frame().open();
}).on( 'click', '#remove-post-thumbnail', function() {
wp.media.view.settings.post.featuredImageId = -1;
});
}
};
$( wp.media.featuredImage.init );
/**
* wp.media.editor
* @namespace
*/
wp.media.editor = {
/**
* Send content to the editor
*
* @global tinymce
* @global QTags
* @global wpActiveEditor
* @global tb_remove() - Possibly overloaded by legacy plugins
*
* @param {string} html Content to send to the editor
*/
insert: function( html ) {
var editor,
hasTinymce = ! _.isUndefined( window.tinymce ),
hasQuicktags = ! _.isUndefined( window.QTags ),
wpActiveEditor = window.wpActiveEditor;
// Delegate to the global `send_to_editor` if it exists.
// This attempts to play nice with any themes/plugins that have
// overridden the insert functionality.
if ( window.send_to_editor ) {
return window.send_to_editor.apply( this, arguments );
}
if ( ! wpActiveEditor ) {
if ( hasTinymce && tinymce.activeEditor ) {
editor = tinymce.activeEditor;
wpActiveEditor = window.wpActiveEditor = editor.id;
} else if ( ! hasQuicktags ) {
return false;
}
} else if ( hasTinymce ) {
editor = tinymce.get( wpActiveEditor );
}
if ( editor && ! editor.isHidden() ) {
editor.execCommand( 'mceInsertContent', false, html );
} else if ( hasQuicktags ) {
QTags.insertContent( html );
} else {
document.getElementById( wpActiveEditor ).value += html;
}
// If the old thickbox remove function exists, call it in case
// a theme/plugin overloaded it.
if ( window.tb_remove ) {
try { window.tb_remove(); } catch( e ) {}
}
},
/**
* Setup 'workflow' and add to the 'workflows' cache. 'open' can
* subsequently be called upon it.
*
* @global wp.media.view.l10n
*
* @param {string} id A slug used to identify the workflow.
* @param {Object} [options={}]
*
* @this wp.media.editor
*
* @returns {wp.media.view.MediaFrame.Select} A media workflow.
*/
add: function( id, options ) {
var workflow = this.get( id );
// only add once: if exists return existing
if ( workflow ) {
return workflow;
}
workflow = workflows[ id ] = wp.media( _.defaults( options || {}, {
frame: 'post',
state: 'insert',
title: wp.media.view.l10n.addMedia,
multiple: true
} ) );
workflow.on( 'insert', function( selection ) {
var state = workflow.state();
selection = selection || state.get('selection');
if ( ! selection )
return;
$.when.apply( $, selection.map( function( attachment ) {
var display = state.display( attachment ).toJSON();
/**
* @this wp.media.editor
*/
return this.send.attachment( display, attachment.toJSON() );
}, this ) ).done( function() {
wp.media.editor.insert( _.toArray( arguments ).join('\n\n') );
});
}, this );
workflow.state('gallery-edit').on( 'update', function( selection ) {
/**
* @this wp.media.editor
*/
this.insert( wp.media.gallery.shortcode( selection ).string() );
}, this );
workflow.state('playlist-edit').on( 'update', function( selection ) {
/**
* @this wp.media.editor
*/
this.insert( wp.media.playlist.shortcode( selection ).string() );
}, this );
workflow.state('video-playlist-edit').on( 'update', function( selection ) {
/**
* @this wp.media.editor
*/
this.insert( wp.media.playlist.shortcode( selection ).string() );
}, this );
workflow.state('embed').on( 'select', function() {
/**
* @this wp.media.editor
*/
var state = workflow.state(),
type = state.get('type'),
embed = state.props.toJSON();
embed.url = embed.url || '';
if ( 'link' === type ) {
_.defaults( embed, {
title: embed.url,
linkUrl: embed.url
});
this.send.link( embed ).done( function( resp ) {
wp.media.editor.insert( resp );
});
} else if ( 'image' === type ) {
_.defaults( embed, {
title: embed.url,
linkUrl: '',
align: 'none',
link: 'none'
});
if ( 'none' === embed.link ) {
embed.linkUrl = '';
} else if ( 'file' === embed.link ) {
embed.linkUrl = embed.url;
}
this.insert( wp.media.string.image( embed ) );
}
}, this );
workflow.state('featured-image').on( 'select', wp.media.featuredImage.select );
workflow.setState( workflow.options.state );
return workflow;
},
/**
* Determines the proper current workflow id
*
* @global wpActiveEditor
* @global tinymce
*
* @param {string} [id=''] A slug used to identify the workflow.
*
* @returns {wpActiveEditor|string|tinymce.activeEditor.id}
*/
id: function( id ) {
if ( id ) {
return id;
}
// If an empty `id` is provided, default to `wpActiveEditor`.
id = wpActiveEditor;
// If that doesn't work, fall back to `tinymce.activeEditor.id`.
if ( ! id && ! _.isUndefined( window.tinymce ) && tinymce.activeEditor ) {
id = tinymce.activeEditor.id;
}
// Last but not least, fall back to the empty string.
id = id || '';
return id;
},
/**
* Return the workflow specified by id
*
* @param {string} id A slug used to identify the workflow.
*
* @this wp.media.editor
*
* @returns {wp.media.view.MediaFrame} A media workflow.
*/
get: function( id ) {
id = this.id( id );
return workflows[ id ];
},
/**
* Remove the workflow represented by id from the workflow cache
*
* @param {string} id A slug used to identify the workflow.
*
* @this wp.media.editor
*/
remove: function( id ) {
id = this.id( id );
delete workflows[ id ];
},
/**
* @namespace
*/
send: {
/**
* Called when sending an attachment to the editor
* from the medial modal.
*
* @global wp.media.view.settings
* @global wp.media.post
*
* @param {Object} props Attachment details (align, link, size, etc).
* @param {Object} attachment The attachment object, media version of Post.
* @returns {Promise}
*/
attachment: function( props, attachment ) {
var caption = attachment.caption,
options, html;
// If captions are disabled, clear the caption.
if ( ! wp.media.view.settings.captions ) {
delete attachment.caption;
}
props = wp.media.string.props( props, attachment );
options = {
id: attachment.id,
post_content: attachment.description,
post_excerpt: caption
};
if ( props.linkUrl ) {
options.url = props.linkUrl;
}
if ( 'image' === attachment.type ) {
html = wp.media.string.image( props );
_.each({
align: 'align',
size: 'image-size',
alt: 'image_alt'
}, function( option, prop ) {
if ( props[ prop ] )
options[ option ] = props[ prop ];
});
} else if ( 'video' === attachment.type ) {
html = wp.media.string.video( props, attachment );
} else if ( 'audio' === attachment.type ) {
html = wp.media.string.audio( props, attachment );
} else {
html = wp.media.string.link( props );
options.post_title = props.title;
}
return wp.media.post( 'send-attachment-to-editor', {
nonce: wp.media.view.settings.nonce.sendToEditor,
attachment: options,
html: html,
post_id: wp.media.view.settings.post.id
});
},
/**
* Called when 'Insert From URL' source is not an image. Example: YouTube url.
*
* @global wp.media.view.settings
*
* @param {Object} embed
* @returns {Promise}
*/
link: function( embed ) {
return wp.media.post( 'send-link-to-editor', {
nonce: wp.media.view.settings.nonce.sendToEditor,
src: embed.linkUrl,
title: embed.title,
html: wp.media.string.link( embed ),
post_id: wp.media.view.settings.post.id
});
}
},
/**
* Open a workflow
*
* @param {string} [id=undefined] Optional. A slug used to identify the workflow.
* @param {Object} [options={}]
*
* @this wp.media.editor
*
* @returns {wp.media.view.MediaFrame}
*/
open: function( id, options ) {
var workflow;
options = options || {};
id = this.id( id );
/*
// Save a bookmark of the caret position in IE.
if ( ! _.isUndefined( window.tinymce ) ) {
editor = tinymce.get( id );
if ( tinymce.isIE && editor && ! editor.isHidden() ) {
editor.focus();
editor.windowManager.insertimagebookmark = editor.selection.getBookmark();
}
}
*/
workflow = this.get( id );
// Redo workflow if state has changed
if ( ! workflow || ( workflow.options && options.state !== workflow.options.state ) ) {
workflow = this.add( id, options );
}
return workflow.open();
},
/**
* Bind click event for .insert-media using event delegation
*
* @global wp.media.view.l10n
*/
init: function() {
$(document.body)
.on( 'click', '.insert-media', function( event ) {
var elem = $( event.currentTarget ),
editor = elem.data('editor'),
options = {
frame: 'post',
state: 'insert',
title: wp.media.view.l10n.addMedia,
multiple: true
};
event.preventDefault();
// Remove focus from the `.insert-media` button.
// Prevents Opera from showing the outline of the button
// above the modal.
//
// See: http://core.trac.wordpress.org/ticket/22445
elem.blur();
if ( elem.hasClass( 'gallery' ) ) {
options.state = 'gallery';
options.title = wp.media.view.l10n.createGalleryTitle;
}
wp.media.editor.open( editor, options );
});
// Initialize and render the Editor drag-and-drop uploader.
new wp.media.view.EditorUploader().render();
}
};
_.bindAll( wp.media.editor, 'open' );
$( wp.media.editor.init );
}(jQuery, _));
| JavaScript |
var addComment = {
moveForm : function(commId, parentId, respondId, postId) {
var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID');
if ( ! comm || ! respond || ! cancel || ! parent )
return;
t.respondId = respondId;
postId = postId || false;
if ( ! t.I('wp-temp-form-div') ) {
div = document.createElement('div');
div.id = 'wp-temp-form-div';
div.style.display = 'none';
respond.parentNode.insertBefore(div, respond);
}
comm.parentNode.insertBefore(respond, comm.nextSibling);
if ( post && postId )
post.value = postId;
parent.value = parentId;
cancel.style.display = '';
cancel.onclick = function() {
var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId);
if ( ! temp || ! respond )
return;
t.I('comment_parent').value = '0';
temp.parentNode.insertBefore(respond, temp);
temp.parentNode.removeChild(temp);
this.style.display = 'none';
this.onclick = null;
return false;
};
try { t.I('comment').focus(); }
catch(e) {}
return false;
},
I : function(e) {
return document.getElementById(e);
}
};
| JavaScript |
/*
http://www.JSON.org/json2.js
2011-02-23
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, strict: false, regexp: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
var JSON;
if (!JSON) {
JSON = {};
}
(function () {
"use strict";
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
| JavaScript |
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================
/* SOURCE FILE: AnchorPosition.js */
/*
AnchorPosition.js
Author: Matt Kruse
Last modified: 10/11/02
DESCRIPTION: These functions find the position of an <A> tag in a document,
so other elements can be positioned relative to it.
COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the
Macintosh platform.
FUNCTIONS:
getAnchorPosition(anchorname)
Returns an Object() having .x and .y properties of the pixel coordinates
of the upper-left corner of the anchor. Position is relative to the PAGE.
getAnchorWindowPosition(anchorname)
Returns an Object() having .x and .y properties of the pixel coordinates
of the upper-left corner of the anchor, relative to the WHOLE SCREEN.
NOTES:
1) For popping up separate browser windows, use getAnchorWindowPosition.
Otherwise, use getAnchorPosition
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
*/
// getAnchorPosition(anchorname)
// This function returns an object having .x and .y properties which are the coordinates
// of the named anchor, relative to the page.
function getAnchorPosition(anchorname) {
// This function will return an Object with x and y properties
var useWindow=false;
var coordinates=new Object();
var x=0,y=0;
// Browser capability sniffing
var use_gebi=false, use_css=false, use_layers=false;
if (document.getElementById) { use_gebi=true; }
else if (document.all) { use_css=true; }
else if (document.layers) { use_layers=true; }
// Logic to find position
if (use_gebi && document.all) {
x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
}
else if (use_gebi) {
var o=document.getElementById(anchorname);
x=AnchorPosition_getPageOffsetLeft(o);
y=AnchorPosition_getPageOffsetTop(o);
}
else if (use_css) {
x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
}
else if (use_layers) {
var found=0;
for (var i=0; i<document.anchors.length; i++) {
if (document.anchors[i].name==anchorname) { found=1; break; }
}
if (found==0) {
coordinates.x=0; coordinates.y=0; return coordinates;
}
x=document.anchors[i].x;
y=document.anchors[i].y;
}
else {
coordinates.x=0; coordinates.y=0; return coordinates;
}
coordinates.x=x;
coordinates.y=y;
return coordinates;
}
// getAnchorWindowPosition(anchorname)
// This function returns an object having .x and .y properties which are the coordinates
// of the named anchor, relative to the window
function getAnchorWindowPosition(anchorname) {
var coordinates=getAnchorPosition(anchorname);
var x=0;
var y=0;
if (document.getElementById) {
if (isNaN(window.screenX)) {
x=coordinates.x-document.body.scrollLeft+window.screenLeft;
y=coordinates.y-document.body.scrollTop+window.screenTop;
}
else {
x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
}
}
else if (document.all) {
x=coordinates.x-document.body.scrollLeft+window.screenLeft;
y=coordinates.y-document.body.scrollTop+window.screenTop;
}
else if (document.layers) {
x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
}
coordinates.x=x;
coordinates.y=y;
return coordinates;
}
// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft (el) {
var ol=el.offsetLeft;
while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
return ol;
}
function AnchorPosition_getWindowOffsetLeft (el) {
return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft;
}
function AnchorPosition_getPageOffsetTop (el) {
var ot=el.offsetTop;
while((el=el.offsetParent) != null) { ot += el.offsetTop; }
return ot;
}
function AnchorPosition_getWindowOffsetTop (el) {
return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop;
}
/* SOURCE FILE: PopupWindow.js */
/*
PopupWindow.js
Author: Matt Kruse
Last modified: 02/16/04
DESCRIPTION: This object allows you to easily and quickly popup a window
in a certain place. The window can either be a DIV or a separate browser
window.
COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the
Macintosh platform. Due to bugs in Netscape 4.x, populating the popup
window with <STYLE> tags may cause errors.
USAGE:
// Create an object for a WINDOW popup
var win = new PopupWindow();
// Create an object for a DIV window using the DIV named 'mydiv'
var win = new PopupWindow('mydiv');
// Set the window to automatically hide itself when the user clicks
// anywhere else on the page except the popup
win.autoHide();
// Show the window relative to the anchor name passed in
win.showPopup(anchorname);
// Hide the popup
win.hidePopup();
// Set the size of the popup window (only applies to WINDOW popups
win.setSize(width,height);
// Populate the contents of the popup window that will be shown. If you
// change the contents while it is displayed, you will need to refresh()
win.populate(string);
// set the URL of the window, rather than populating its contents
// manually
win.setUrl("http://www.site.com/");
// Refresh the contents of the popup
win.refresh();
// Specify how many pixels to the right of the anchor the popup will appear
win.offsetX = 50;
// Specify how many pixels below the anchor the popup will appear
win.offsetY = 100;
NOTES:
1) Requires the functions in AnchorPosition.js
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
4) When a PopupWindow object is created, a handler for 'onmouseup' is
attached to any event handler you may have already defined. Do NOT define
an event handler for 'onmouseup' after you define a PopupWindow object or
the autoHide() will not work correctly.
*/
// Set the position of the popup window based on the anchor
function PopupWindow_getXYPosition(anchorname) {
var coordinates;
if (this.type == "WINDOW") {
coordinates = getAnchorWindowPosition(anchorname);
}
else {
coordinates = getAnchorPosition(anchorname);
}
this.x = coordinates.x;
this.y = coordinates.y;
}
// Set width/height of DIV/popup window
function PopupWindow_setSize(width,height) {
this.width = width;
this.height = height;
}
// Fill the window with contents
function PopupWindow_populate(contents) {
this.contents = contents;
this.populated = false;
}
// Set the URL to go to
function PopupWindow_setUrl(url) {
this.url = url;
}
// Set the window popup properties
function PopupWindow_setWindowProperties(props) {
this.windowProperties = props;
}
// Refresh the displayed contents of the popup
function PopupWindow_refresh() {
if (this.divName != null) {
// refresh the DIV object
if (this.use_gebi) {
document.getElementById(this.divName).innerHTML = this.contents;
}
else if (this.use_css) {
document.all[this.divName].innerHTML = this.contents;
}
else if (this.use_layers) {
var d = document.layers[this.divName];
d.document.open();
d.document.writeln(this.contents);
d.document.close();
}
}
else {
if (this.popupWindow != null && !this.popupWindow.closed) {
if (this.url!="") {
this.popupWindow.location.href=this.url;
}
else {
this.popupWindow.document.open();
this.popupWindow.document.writeln(this.contents);
this.popupWindow.document.close();
}
this.popupWindow.focus();
}
}
}
// Position and show the popup, relative to an anchor object
function PopupWindow_showPopup(anchorname) {
this.getXYPosition(anchorname);
this.x += this.offsetX;
this.y += this.offsetY;
if (!this.populated && (this.contents != "")) {
this.populated = true;
this.refresh();
}
if (this.divName != null) {
// Show the DIV object
if (this.use_gebi) {
document.getElementById(this.divName).style.left = this.x + "px";
document.getElementById(this.divName).style.top = this.y;
document.getElementById(this.divName).style.visibility = "visible";
}
else if (this.use_css) {
document.all[this.divName].style.left = this.x;
document.all[this.divName].style.top = this.y;
document.all[this.divName].style.visibility = "visible";
}
else if (this.use_layers) {
document.layers[this.divName].left = this.x;
document.layers[this.divName].top = this.y;
document.layers[this.divName].visibility = "visible";
}
}
else {
if (this.popupWindow == null || this.popupWindow.closed) {
// If the popup window will go off-screen, move it so it doesn't
if (this.x<0) { this.x=0; }
if (this.y<0) { this.y=0; }
if (screen && screen.availHeight) {
if ((this.y + this.height) > screen.availHeight) {
this.y = screen.availHeight - this.height;
}
}
if (screen && screen.availWidth) {
if ((this.x + this.width) > screen.availWidth) {
this.x = screen.availWidth - this.width;
}
}
var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled );
this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+"");
}
this.refresh();
}
}
// Hide the popup
function PopupWindow_hidePopup() {
if (this.divName != null) {
if (this.use_gebi) {
document.getElementById(this.divName).style.visibility = "hidden";
}
else if (this.use_css) {
document.all[this.divName].style.visibility = "hidden";
}
else if (this.use_layers) {
document.layers[this.divName].visibility = "hidden";
}
}
else {
if (this.popupWindow && !this.popupWindow.closed) {
this.popupWindow.close();
this.popupWindow = null;
}
}
}
// Pass an event and return whether or not it was the popup DIV that was clicked
function PopupWindow_isClicked(e) {
if (this.divName != null) {
if (this.use_layers) {
var clickX = e.pageX;
var clickY = e.pageY;
var t = document.layers[this.divName];
if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) {
return true;
}
else { return false; }
}
else if (document.all) { // Need to hard-code this to trap IE for error-handling
var t = window.event.srcElement;
while (t.parentElement != null) {
if (t.id==this.divName) {
return true;
}
t = t.parentElement;
}
return false;
}
else if (this.use_gebi && e) {
var t = e.originalTarget;
while (t.parentNode != null) {
if (t.id==this.divName) {
return true;
}
t = t.parentNode;
}
return false;
}
return false;
}
return false;
}
// Check an onMouseDown event to see if we should hide
function PopupWindow_hideIfNotClicked(e) {
if (this.autoHideEnabled && !this.isClicked(e)) {
this.hidePopup();
}
}
// Call this to make the DIV disable automatically when mouse is clicked outside it
function PopupWindow_autoHide() {
this.autoHideEnabled = true;
}
// This global function checks all PopupWindow objects onmouseup to see if they should be hidden
function PopupWindow_hidePopupWindows(e) {
for (var i=0; i<popupWindowObjects.length; i++) {
if (popupWindowObjects[i] != null) {
var p = popupWindowObjects[i];
p.hideIfNotClicked(e);
}
}
}
// Run this immediately to attach the event listener
function PopupWindow_attachListener() {
if (document.layers) {
document.captureEvents(Event.MOUSEUP);
}
window.popupWindowOldEventListener = document.onmouseup;
if (window.popupWindowOldEventListener != null) {
document.onmouseup = new Function("window.popupWindowOldEventListener(); PopupWindow_hidePopupWindows();");
}
else {
document.onmouseup = PopupWindow_hidePopupWindows;
}
}
// CONSTRUCTOR for the PopupWindow object
// Pass it a DIV name to use a DHTML popup, otherwise will default to window popup
function PopupWindow() {
if (!window.popupWindowIndex) { window.popupWindowIndex = 0; }
if (!window.popupWindowObjects) { window.popupWindowObjects = new Array(); }
if (!window.listenerAttached) {
window.listenerAttached = true;
PopupWindow_attachListener();
}
this.index = popupWindowIndex++;
popupWindowObjects[this.index] = this;
this.divName = null;
this.popupWindow = null;
this.width=0;
this.height=0;
this.populated = false;
this.visible = false;
this.autoHideEnabled = false;
this.contents = "";
this.url="";
this.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no";
if (arguments.length>0) {
this.type="DIV";
this.divName = arguments[0];
}
else {
this.type="WINDOW";
}
this.use_gebi = false;
this.use_css = false;
this.use_layers = false;
if (document.getElementById) { this.use_gebi = true; }
else if (document.all) { this.use_css = true; }
else if (document.layers) { this.use_layers = true; }
else { this.type = "WINDOW"; }
this.offsetX = 0;
this.offsetY = 0;
// Method mappings
this.getXYPosition = PopupWindow_getXYPosition;
this.populate = PopupWindow_populate;
this.setUrl = PopupWindow_setUrl;
this.setWindowProperties = PopupWindow_setWindowProperties;
this.refresh = PopupWindow_refresh;
this.showPopup = PopupWindow_showPopup;
this.hidePopup = PopupWindow_hidePopup;
this.setSize = PopupWindow_setSize;
this.isClicked = PopupWindow_isClicked;
this.autoHide = PopupWindow_autoHide;
this.hideIfNotClicked = PopupWindow_hideIfNotClicked;
}
/* SOURCE FILE: ColorPicker2.js */
/*
Last modified: 02/24/2003
DESCRIPTION: This widget is used to select a color, in hexadecimal #RRGGBB
form. It uses a color "swatch" to display the standard 216-color web-safe
palette. The user can then click on a color to select it.
COMPATABILITY: See notes in AnchorPosition.js and PopupWindow.js.
Only the latest DHTML-capable browsers will show the color and hex values
at the bottom as your mouse goes over them.
USAGE:
// Create a new ColorPicker object using DHTML popup
var cp = new ColorPicker();
// Create a new ColorPicker object using Window Popup
var cp = new ColorPicker('window');
// Add a link in your page to trigger the popup. For example:
<A HREF="#" onClick="cp.show('pick');return false;" NAME="pick" ID="pick">Pick</A>
// Or use the built-in "select" function to do the dirty work for you:
<A HREF="#" onClick="cp.select(document.forms[0].color,'pick');return false;" NAME="pick" ID="pick">Pick</A>
// If using DHTML popup, write out the required DIV tag near the bottom
// of your page.
<SCRIPT LANGUAGE="JavaScript">cp.writeDiv()</SCRIPT>
// Write the 'pickColor' function that will be called when the user clicks
// a color and do something with the value. This is only required if you
// want to do something other than simply populate a form field, which is
// what the 'select' function will give you.
function pickColor(color) {
field.value = color;
}
NOTES:
1) Requires the functions in AnchorPosition.js and PopupWindow.js
2) Your anchor tag MUST contain both NAME and ID attributes which are the
same. For example:
<A NAME="test" ID="test"> </A>
3) There must be at least a space between <A> </A> for IE5.5 to see the
anchor tag correctly. Do not do <A></A> with no space.
4) When a ColorPicker object is created, a handler for 'onmouseup' is
attached to any event handler you may have already defined. Do NOT define
an event handler for 'onmouseup' after you define a ColorPicker object or
the color picker will not hide itself correctly.
*/
ColorPicker_targetInput = null;
function ColorPicker_writeDiv() {
document.writeln("<DIV ID=\"colorPickerDiv\" STYLE=\"position:absolute;visibility:hidden;\"> </DIV>");
}
function ColorPicker_show(anchorname) {
this.showPopup(anchorname);
}
function ColorPicker_pickColor(color,obj) {
obj.hidePopup();
pickColor(color);
}
// A Default "pickColor" function to accept the color passed back from popup.
// User can over-ride this with their own function.
function pickColor(color) {
if (ColorPicker_targetInput==null) {
alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!");
return;
}
ColorPicker_targetInput.value = color;
}
// This function is the easiest way to popup the window, select a color, and
// have the value populate a form field, which is what most people want to do.
function ColorPicker_select(inputobj,linkname) {
if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") {
alert("colorpicker.select: Input object passed is not a valid form input object");
window.ColorPicker_targetInput=null;
return;
}
window.ColorPicker_targetInput = inputobj;
this.show(linkname);
}
// This function runs when you move your mouse over a color block, if you have a newer browser
function ColorPicker_highlightColor(c) {
var thedoc = (arguments.length>1)?arguments[1]:window.document;
var d = thedoc.getElementById("colorPickerSelectedColor");
d.style.backgroundColor = c;
d = thedoc.getElementById("colorPickerSelectedColorValue");
d.innerHTML = c;
}
function ColorPicker() {
var windowMode = false;
// Create a new PopupWindow object
if (arguments.length==0) {
var divname = "colorPickerDiv";
}
else if (arguments[0] == "window") {
var divname = '';
windowMode = true;
}
else {
var divname = arguments[0];
}
if (divname != "") {
var cp = new PopupWindow(divname);
}
else {
var cp = new PopupWindow();
cp.setSize(225,250);
}
// Object variables
cp.currentValue = "#FFFFFF";
// Method Mappings
cp.writeDiv = ColorPicker_writeDiv;
cp.highlightColor = ColorPicker_highlightColor;
cp.show = ColorPicker_show;
cp.select = ColorPicker_select;
// Code to populate color picker window
var colors = new Array( "#4180B6","#69AEE7","#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099",
"#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099",
"#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099",
"#FF00CC","#FF00FF","#7FFFFF","#7FFFFF","#7FF7F7","#7FEFEF","#7FE7E7","#7FDFDF","#7FD7D7","#7FCFCF","#7FC7C7","#7FBFBF",
"#7FB7B7","#7FAFAF","#7FA7A7","#7F9F9F","#7F9797","#7F8F8F","#7F8787","#7F7F7F","#7F7777","#7F6F6F","#7F6767","#7F5F5F",
"#7F5757","#7F4F4F","#7F4747","#7F3F3F","#7F3737","#7F2F2F","#7F2727","#7F1F1F","#7F1717","#7F0F0F","#7F0707","#7F0000",
"#4180B6","#69AEE7","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399",
"#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399",
"#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399",
"#FF33CC","#FF33FF","#FF7FFF","#FF7FFF","#F77FF7","#EF7FEF","#E77FE7","#DF7FDF","#D77FD7","#CF7FCF","#C77FC7","#BF7FBF",
"#B77FB7","#AF7FAF","#A77FA7","#9F7F9F","#977F97","#8F7F8F","#877F87","#7F7F7F","#777F77","#6F7F6F","#677F67","#5F7F5F",
"#577F57","#4F7F4F","#477F47","#3F7F3F","#377F37","#2F7F2F","#277F27","#1F7F1F","#177F17","#0F7F0F","#077F07","#007F00",
"#4180B6","#69AEE7","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699",
"#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699",
"#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699",
"#FF66CC","#FF66FF","#FFFF7F","#FFFF7F","#F7F77F","#EFEF7F","#E7E77F","#DFDF7F","#D7D77F","#CFCF7F","#C7C77F","#BFBF7F",
"#B7B77F","#AFAF7F","#A7A77F","#9F9F7F","#97977F","#8F8F7F","#87877F","#7F7F7F","#77777F","#6F6F7F","#67677F","#5F5F7F",
"#57577F","#4F4F7F","#47477F","#3F3F7F","#37377F","#2F2F7F","#27277F","#1F1F7F","#17177F","#0F0F7F","#07077F","#00007F",
"#4180B6","#69AEE7","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999",
"#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999",
"#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999",
"#FF99CC","#FF99FF","#3FFFFF","#3FFFFF","#3FF7F7","#3FEFEF","#3FE7E7","#3FDFDF","#3FD7D7","#3FCFCF","#3FC7C7","#3FBFBF",
"#3FB7B7","#3FAFAF","#3FA7A7","#3F9F9F","#3F9797","#3F8F8F","#3F8787","#3F7F7F","#3F7777","#3F6F6F","#3F6767","#3F5F5F",
"#3F5757","#3F4F4F","#3F4747","#3F3F3F","#3F3737","#3F2F2F","#3F2727","#3F1F1F","#3F1717","#3F0F0F","#3F0707","#3F0000",
"#4180B6","#69AEE7","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99",
"#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99",
"#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99",
"#FFCCCC","#FFCCFF","#FF3FFF","#FF3FFF","#F73FF7","#EF3FEF","#E73FE7","#DF3FDF","#D73FD7","#CF3FCF","#C73FC7","#BF3FBF",
"#B73FB7","#AF3FAF","#A73FA7","#9F3F9F","#973F97","#8F3F8F","#873F87","#7F3F7F","#773F77","#6F3F6F","#673F67","#5F3F5F",
"#573F57","#4F3F4F","#473F47","#3F3F3F","#373F37","#2F3F2F","#273F27","#1F3F1F","#173F17","#0F3F0F","#073F07","#003F00",
"#4180B6","#69AEE7","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99",
"#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99",
"#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99",
"#FFFFCC","#FFFFFF","#FFFF3F","#FFFF3F","#F7F73F","#EFEF3F","#E7E73F","#DFDF3F","#D7D73F","#CFCF3F","#C7C73F","#BFBF3F",
"#B7B73F","#AFAF3F","#A7A73F","#9F9F3F","#97973F","#8F8F3F","#87873F","#7F7F3F","#77773F","#6F6F3F","#67673F","#5F5F3F",
"#57573F","#4F4F3F","#47473F","#3F3F3F","#37373F","#2F2F3F","#27273F","#1F1F3F","#17173F","#0F0F3F","#07073F","#00003F",
"#4180B6","#69AEE7","#FFFFFF","#FFEEEE","#FFDDDD","#FFCCCC","#FFBBBB","#FFAAAA","#FF9999","#FF8888","#FF7777","#FF6666",
"#FF5555","#FF4444","#FF3333","#FF2222","#FF1111","#FF0000","#FF0000","#FF0000","#FF0000","#EE0000","#DD0000","#CC0000",
"#BB0000","#AA0000","#990000","#880000","#770000","#660000","#550000","#440000","#330000","#220000","#110000","#000000",
"#000000","#000000","#000000","#001111","#002222","#003333","#004444","#005555","#006666","#007777","#008888","#009999",
"#00AAAA","#00BBBB","#00CCCC","#00DDDD","#00EEEE","#00FFFF","#00FFFF","#00FFFF","#00FFFF","#11FFFF","#22FFFF","#33FFFF",
"#44FFFF","#55FFFF","#66FFFF","#77FFFF","#88FFFF","#99FFFF","#AAFFFF","#BBFFFF","#CCFFFF","#DDFFFF","#EEFFFF","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#EEFFEE","#DDFFDD","#CCFFCC","#BBFFBB","#AAFFAA","#99FF99","#88FF88","#77FF77","#66FF66",
"#55FF55","#44FF44","#33FF33","#22FF22","#11FF11","#00FF00","#00FF00","#00FF00","#00FF00","#00EE00","#00DD00","#00CC00",
"#00BB00","#00AA00","#009900","#008800","#007700","#006600","#005500","#004400","#003300","#002200","#001100","#000000",
"#000000","#000000","#000000","#110011","#220022","#330033","#440044","#550055","#660066","#770077","#880088","#990099",
"#AA00AA","#BB00BB","#CC00CC","#DD00DD","#EE00EE","#FF00FF","#FF00FF","#FF00FF","#FF00FF","#FF11FF","#FF22FF","#FF33FF",
"#FF44FF","#FF55FF","#FF66FF","#FF77FF","#FF88FF","#FF99FF","#FFAAFF","#FFBBFF","#FFCCFF","#FFDDFF","#FFEEFF","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#EEEEFF","#DDDDFF","#CCCCFF","#BBBBFF","#AAAAFF","#9999FF","#8888FF","#7777FF","#6666FF",
"#5555FF","#4444FF","#3333FF","#2222FF","#1111FF","#0000FF","#0000FF","#0000FF","#0000FF","#0000EE","#0000DD","#0000CC",
"#0000BB","#0000AA","#000099","#000088","#000077","#000066","#000055","#000044","#000033","#000022","#000011","#000000",
"#000000","#000000","#000000","#111100","#222200","#333300","#444400","#555500","#666600","#777700","#888800","#999900",
"#AAAA00","#BBBB00","#CCCC00","#DDDD00","#EEEE00","#FFFF00","#FFFF00","#FFFF00","#FFFF00","#FFFF11","#FFFF22","#FFFF33",
"#FFFF44","#FFFF55","#FFFF66","#FFFF77","#FFFF88","#FFFF99","#FFFFAA","#FFFFBB","#FFFFCC","#FFFFDD","#FFFFEE","#FFFFFF",
"#4180B6","#69AEE7","#FFFFFF","#FFFFFF","#FBFBFB","#F7F7F7","#F3F3F3","#EFEFEF","#EBEBEB","#E7E7E7","#E3E3E3","#DFDFDF",
"#DBDBDB","#D7D7D7","#D3D3D3","#CFCFCF","#CBCBCB","#C7C7C7","#C3C3C3","#BFBFBF","#BBBBBB","#B7B7B7","#B3B3B3","#AFAFAF",
"#ABABAB","#A7A7A7","#A3A3A3","#9F9F9F","#9B9B9B","#979797","#939393","#8F8F8F","#8B8B8B","#878787","#838383","#7F7F7F",
"#7B7B7B","#777777","#737373","#6F6F6F","#6B6B6B","#676767","#636363","#5F5F5F","#5B5B5B","#575757","#535353","#4F4F4F",
"#4B4B4B","#474747","#434343","#3F3F3F","#3B3B3B","#373737","#333333","#2F2F2F","#2B2B2B","#272727","#232323","#1F1F1F",
"#1B1B1B","#171717","#131313","#0F0F0F","#0B0B0B","#070707","#030303","#000000","#000000","#000000","#000000","#000000");
var total = colors.length;
var width = 72;
var cp_contents = "";
var windowRef = (windowMode)?"window.opener.":"";
if (windowMode) {
cp_contents += "<html><head><title>Select Color</title></head>";
cp_contents += "<body marginwidth=0 marginheight=0 leftmargin=0 topmargin=0><span style='text-align: center;'>";
}
cp_contents += "<table style='border: none;' cellspacing=0 cellpadding=0>";
var use_highlight = (document.getElementById || document.all)?true:false;
for (var i=0; i<total; i++) {
if ((i % width) == 0) { cp_contents += "<tr>"; }
if (use_highlight) { var mo = 'onMouseOver="'+windowRef+'ColorPicker_highlightColor(\''+colors[i]+'\',window.document)"'; }
else { mo = ""; }
cp_contents += '<td style="background-color: '+colors[i]+';"><a href="javascript:void()" onclick="'+windowRef+'ColorPicker_pickColor(\''+colors[i]+'\','+windowRef+'window.popupWindowObjects['+cp.index+']);return false;" '+mo+'> </a></td>';
if ( ((i+1)>=total) || (((i+1) % width) == 0)) {
cp_contents += "</tr>";
}
}
// If the browser supports dynamically changing TD cells, add the fancy stuff
if (document.getElementById) {
var width1 = Math.floor(width/2);
var width2 = width = width1;
cp_contents += "<tr><td colspan='"+width1+"' style='background-color: #FFF;' ID='colorPickerSelectedColor'> </td><td colspan='"+width2+"' style='text-align: center;' id='colorPickerSelectedColorValue'>#FFFFFF</td></tr>";
}
cp_contents += "</table>";
if (windowMode) {
cp_contents += "</span></body></html>";
}
// end populate code
// Write the contents to the popup object
cp.populate(cp_contents+"\n");
// Move the table down a bit so you can see it
cp.offsetY = 25;
cp.autoHide();
return cp;
}
| JavaScript |
/* global _wpCustomizeLoaderSettings */
window.wp = window.wp || {};
(function( exports, $ ){
var api = wp.customize,
Loader;
$.extend( $.support, {
history: !! ( window.history && history.pushState ),
hashchange: ('onhashchange' in window) && (document.documentMode === undefined || document.documentMode > 7)
});
Loader = $.extend( {}, api.Events, {
initialize: function() {
this.body = $( document.body );
// Ensure the loader is supported.
// Check for settings, postMessage support, and whether we require CORS support.
if ( ! Loader.settings || ! $.support.postMessage || ( ! $.support.cors && Loader.settings.isCrossDomain ) ) {
return;
}
this.window = $( window );
this.element = $( '<div id="customize-container" />' ).appendTo( this.body );
this.bind( 'open', this.overlay.show );
this.bind( 'close', this.overlay.hide );
$('#wpbody').on( 'click', '.load-customize', function( event ) {
event.preventDefault();
// Store a reference to the link that opened the customizer.
Loader.link = $(this);
// Load the theme.
Loader.open( Loader.link.attr('href') );
});
// Add navigation listeners.
if ( $.support.history )
this.window.on( 'popstate', Loader.popstate );
if ( $.support.hashchange ) {
this.window.on( 'hashchange', Loader.hashchange );
this.window.triggerHandler( 'hashchange' );
}
},
popstate: function( e ) {
var state = e.originalEvent.state;
if ( state && state.customize )
Loader.open( state.customize );
else if ( Loader.active )
Loader.close();
},
hashchange: function() {
var hash = window.location.toString().split('#')[1];
if ( hash && 0 === hash.indexOf( 'wp_customize=on' ) )
Loader.open( Loader.settings.url + '?' + hash );
if ( ! hash && ! $.support.history )
Loader.close();
},
open: function( src ) {
var hash;
if ( this.active )
return;
// Load the full page on mobile devices.
if ( Loader.settings.browser.mobile )
return window.location = src;
this.active = true;
this.body.addClass('customize-loading');
this.iframe = $( '<iframe />', { src: src }).appendTo( this.element );
this.iframe.one( 'load', this.loaded );
// Create a postMessage connection with the iframe.
this.messenger = new api.Messenger({
url: src,
channel: 'loader',
targetWindow: this.iframe[0].contentWindow
});
// Wait for the connection from the iframe before sending any postMessage events.
this.messenger.bind( 'ready', function() {
Loader.messenger.send( 'back' );
});
this.messenger.bind( 'close', function() {
if ( $.support.history )
history.back();
else if ( $.support.hashchange )
window.location.hash = '';
else
Loader.close();
});
this.messenger.bind( 'activated', function( location ) {
if ( location )
window.location = location;
});
hash = src.split('?')[1];
// Ensure we don't call pushState if the user hit the forward button.
if ( $.support.history && window.location.href !== src )
history.pushState( { customize: src }, '', src );
else if ( ! $.support.history && $.support.hashchange && hash )
window.location.hash = 'wp_customize=on&' + hash;
this.trigger( 'open' );
},
opened: function() {
Loader.body.addClass( 'customize-active full-overlay-active' );
},
close: function() {
if ( ! this.active )
return;
this.active = false;
this.trigger( 'close' );
// Return focus to link that was originally clicked.
if ( this.link )
this.link.focus();
},
closed: function() {
Loader.iframe.remove();
Loader.messenger.destroy();
Loader.iframe = null;
Loader.messenger = null;
Loader.body.removeClass( 'customize-active full-overlay-active' ).removeClass( 'customize-loading' );
},
loaded: function() {
Loader.body.removeClass('customize-loading');
},
overlay: {
show: function() {
this.element.fadeIn( 200, Loader.opened );
},
hide: function() {
this.element.fadeOut( 200, Loader.closed );
}
}
});
$( function() {
Loader.settings = _wpCustomizeLoaderSettings;
Loader.initialize();
});
// Expose the API to the world.
api.Loader = Loader;
})( wp, jQuery );
| JavaScript |
window.wp = window.wp || {};
(function ($) {
// Create the WordPress Backbone namespace.
wp.Backbone = {};
// wp.Backbone.Subviews
// --------------------
//
// A subview manager.
wp.Backbone.Subviews = function( view, views ) {
this.view = view;
this._views = _.isArray( views ) ? { '': views } : views || {};
};
wp.Backbone.Subviews.extend = Backbone.Model.extend;
_.extend( wp.Backbone.Subviews.prototype, {
// ### Fetch all of the subviews
//
// Returns an array of all subviews.
all: function() {
return _.flatten( this._views );
},
// ### Get a selector's subviews
//
// Fetches all subviews that match a given `selector`.
//
// If no `selector` is provided, it will grab all subviews attached
// to the view's root.
get: function( selector ) {
selector = selector || '';
return this._views[ selector ];
},
// ### Get a selector's first subview
//
// Fetches the first subview that matches a given `selector`.
//
// If no `selector` is provided, it will grab the first subview
// attached to the view's root.
//
// Useful when a selector only has one subview at a time.
first: function( selector ) {
var views = this.get( selector );
return views && views.length ? views[0] : null;
},
// ### Register subview(s)
//
// Registers any number of `views` to a `selector`.
//
// When no `selector` is provided, the root selector (the empty string)
// is used. `views` accepts a `Backbone.View` instance or an array of
// `Backbone.View` instances.
//
// ---
//
// Accepts an `options` object, which has a significant effect on the
// resulting behavior.
//
// `options.silent` – *boolean, `false`*
// > If `options.silent` is true, no DOM modifications will be made.
//
// `options.add` – *boolean, `false`*
// > Use `Views.add()` as a shortcut for setting `options.add` to true.
//
// > By default, the provided `views` will replace
// any existing views associated with the selector. If `options.add`
// is true, the provided `views` will be added to the existing views.
//
// `options.at` – *integer, `undefined`*
// > When adding, to insert `views` at a specific index, use
// `options.at`. By default, `views` are added to the end of the array.
set: function( selector, views, options ) {
var existing, next;
if ( ! _.isString( selector ) ) {
options = views;
views = selector;
selector = '';
}
options = options || {};
views = _.isArray( views ) ? views : [ views ];
existing = this.get( selector );
next = views;
if ( existing ) {
if ( options.add ) {
if ( _.isUndefined( options.at ) ) {
next = existing.concat( views );
} else {
next = existing;
next.splice.apply( next, [ options.at, 0 ].concat( views ) );
}
} else {
_.each( next, function( view ) {
view.__detach = true;
});
_.each( existing, function( view ) {
if ( view.__detach )
view.$el.detach();
else
view.remove();
});
_.each( next, function( view ) {
delete view.__detach;
});
}
}
this._views[ selector ] = next;
_.each( views, function( subview ) {
var constructor = subview.Views || wp.Backbone.Subviews,
subviews = subview.views = subview.views || new constructor( subview );
subviews.parent = this.view;
subviews.selector = selector;
}, this );
if ( ! options.silent )
this._attach( selector, views, _.extend({ ready: this._isReady() }, options ) );
return this;
},
// ### Add subview(s) to existing subviews
//
// An alias to `Views.set()`, which defaults `options.add` to true.
//
// Adds any number of `views` to a `selector`.
//
// When no `selector` is provided, the root selector (the empty string)
// is used. `views` accepts a `Backbone.View` instance or an array of
// `Backbone.View` instances.
//
// Use `Views.set()` when setting `options.add` to `false`.
//
// Accepts an `options` object. By default, provided `views` will be
// inserted at the end of the array of existing views. To insert
// `views` at a specific index, use `options.at`. If `options.silent`
// is true, no DOM modifications will be made.
//
// For more information on the `options` object, see `Views.set()`.
add: function( selector, views, options ) {
if ( ! _.isString( selector ) ) {
options = views;
views = selector;
selector = '';
}
return this.set( selector, views, _.extend({ add: true }, options ) );
},
// ### Stop tracking subviews
//
// Stops tracking `views` registered to a `selector`. If no `views` are
// set, then all of the `selector`'s subviews will be unregistered and
// removed.
//
// Accepts an `options` object. If `options.silent` is set, `remove`
// will *not* be triggered on the unregistered views.
unset: function( selector, views, options ) {
var existing;
if ( ! _.isString( selector ) ) {
options = views;
views = selector;
selector = '';
}
views = views || [];
if ( existing = this.get( selector ) ) {
views = _.isArray( views ) ? views : [ views ];
this._views[ selector ] = views.length ? _.difference( existing, views ) : [];
}
if ( ! options || ! options.silent )
_.invoke( views, 'remove' );
return this;
},
// ### Detach all subviews
//
// Detaches all subviews from the DOM.
//
// Helps to preserve all subview events when re-rendering the master
// view. Used in conjunction with `Views.render()`.
detach: function() {
$( _.pluck( this.all(), 'el' ) ).detach();
return this;
},
// ### Render all subviews
//
// Renders all subviews. Used in conjunction with `Views.detach()`.
render: function() {
var options = {
ready: this._isReady()
};
_.each( this._views, function( views, selector ) {
this._attach( selector, views, options );
}, this );
this.rendered = true;
return this;
},
// ### Remove all subviews
//
// Triggers the `remove()` method on all subviews. Detaches the master
// view from its parent. Resets the internals of the views manager.
//
// Accepts an `options` object. If `options.silent` is set, `unset`
// will *not* be triggered on the master view's parent.
remove: function( options ) {
if ( ! options || ! options.silent ) {
if ( this.parent && this.parent.views )
this.parent.views.unset( this.selector, this.view, { silent: true });
delete this.parent;
delete this.selector;
}
_.invoke( this.all(), 'remove' );
this._views = [];
return this;
},
// ### Replace a selector's subviews
//
// By default, sets the `$target` selector's html to the subview `els`.
//
// Can be overridden in subclasses.
replace: function( $target, els ) {
$target.html( els );
return this;
},
// ### Insert subviews into a selector
//
// By default, appends the subview `els` to the end of the `$target`
// selector. If `options.at` is set, inserts the subview `els` at the
// provided index.
//
// Can be overridden in subclasses.
insert: function( $target, els, options ) {
var at = options && options.at,
$children;
if ( _.isNumber( at ) && ($children = $target.children()).length > at )
$children.eq( at ).before( els );
else
$target.append( els );
return this;
},
// ### Trigger the ready event
//
// **Only use this method if you know what you're doing.**
// For performance reasons, this method does not check if the view is
// actually attached to the DOM. It's taking your word for it.
//
// Fires the ready event on the current view and all attached subviews.
ready: function() {
this.view.trigger('ready');
// Find all attached subviews, and call ready on them.
_.chain( this.all() ).map( function( view ) {
return view.views;
}).flatten().where({ attached: true }).invoke('ready');
},
// #### Internal. Attaches a series of views to a selector.
//
// Checks to see if a matching selector exists, renders the views,
// performs the proper DOM operation, and then checks if the view is
// attached to the document.
_attach: function( selector, views, options ) {
var $selector = selector ? this.view.$( selector ) : this.view.$el,
managers;
// Check if we found a location to attach the views.
if ( ! $selector.length )
return this;
managers = _.chain( views ).pluck('views').flatten().value();
// Render the views if necessary.
_.each( managers, function( manager ) {
if ( manager.rendered )
return;
manager.view.render();
manager.rendered = true;
}, this );
// Insert or replace the views.
this[ options.add ? 'insert' : 'replace' ]( $selector, _.pluck( views, 'el' ), options );
// Set attached and trigger ready if the current view is already
// attached to the DOM.
_.each( managers, function( manager ) {
manager.attached = true;
if ( options.ready )
manager.ready();
}, this );
return this;
},
// #### Internal. Checks if the current view is in the DOM.
_isReady: function() {
var node = this.view.el;
while ( node ) {
if ( node === document.body )
return true;
node = node.parentNode;
}
return false;
}
});
// wp.Backbone.View
// ----------------
//
// The base view class.
wp.Backbone.View = Backbone.View.extend({
// The constructor for the `Views` manager.
Subviews: wp.Backbone.Subviews,
constructor: function( options ) {
this.views = new this.Subviews( this, this.views );
this.on( 'ready', this.ready, this );
this.options = options || {};
Backbone.View.apply( this, arguments );
},
remove: function() {
var result = Backbone.View.prototype.remove.apply( this, arguments );
// Recursively remove child views.
if ( this.views )
this.views.remove();
return result;
},
render: function() {
var options;
if ( this.prepare )
options = this.prepare();
this.views.detach();
if ( this.template ) {
options = options || {};
this.trigger( 'prepare', options );
this.$el.html( this.template( options ) );
}
this.views.render();
return this;
},
prepare: function() {
return this.options;
},
ready: function() {}
});
}(jQuery));
| JavaScript |
/* global wpPointerL10n */
/**
* Pointer jQuery widget.
*/
(function($){
var identifier = 0,
zindex = 9999;
$.widget('wp.pointer', {
options: {
pointerClass: 'wp-pointer',
pointerWidth: 320,
content: function() {
return $(this).text();
},
buttons: function( event, t ) {
var close = ( wpPointerL10n ) ? wpPointerL10n.dismiss : 'Dismiss',
button = $('<a class="close" href="#">' + close + '</a>');
return button.bind( 'click.pointer', function(e) {
e.preventDefault();
t.element.pointer('close');
});
},
position: 'top',
show: function( event, t ) {
t.pointer.show();
t.opened();
},
hide: function( event, t ) {
t.pointer.hide();
t.closed();
},
document: document
},
_create: function() {
var positioning,
family;
this.content = $('<div class="wp-pointer-content"></div>');
this.arrow = $('<div class="wp-pointer-arrow"><div class="wp-pointer-arrow-inner"></div></div>');
family = this.element.parents().add( this.element );
positioning = 'absolute';
if ( family.filter(function(){ return 'fixed' === $(this).css('position'); }).length )
positioning = 'fixed';
this.pointer = $('<div />')
.append( this.content )
.append( this.arrow )
.attr('id', 'wp-pointer-' + identifier++)
.addClass( this.options.pointerClass )
.css({'position': positioning, 'width': this.options.pointerWidth+'px', 'display': 'none'})
.appendTo( this.options.document.body );
},
_setOption: function( key, value ) {
var o = this.options,
tip = this.pointer;
// Handle document transfer
if ( key === 'document' && value !== o.document ) {
tip.detach().appendTo( value.body );
// Handle class change
} else if ( key === 'pointerClass' ) {
tip.removeClass( o.pointerClass ).addClass( value );
}
// Call super method.
$.Widget.prototype._setOption.apply( this, arguments );
// Reposition automatically
if ( key === 'position' ) {
this.reposition();
// Update content automatically if pointer is open
} else if ( key === 'content' && this.active ) {
this.update();
}
},
destroy: function() {
this.pointer.remove();
$.Widget.prototype.destroy.call( this );
},
widget: function() {
return this.pointer;
},
update: function( event ) {
var self = this,
o = this.options,
dfd = $.Deferred(),
content;
if ( o.disabled )
return;
dfd.done( function( content ) {
self._update( event, content );
});
// Either o.content is a string...
if ( typeof o.content === 'string' ) {
content = o.content;
// ...or o.content is a callback.
} else {
content = o.content.call( this.element[0], dfd.resolve, event, this._handoff() );
}
// If content is set, then complete the update.
if ( content )
dfd.resolve( content );
return dfd.promise();
},
/**
* Update is separated into two functions to allow events to defer
* updating the pointer (e.g. fetch content with ajax, etc).
*/
_update: function( event, content ) {
var buttons,
o = this.options;
if ( ! content )
return;
this.pointer.stop(); // Kill any animations on the pointer.
this.content.html( content );
buttons = o.buttons.call( this.element[0], event, this._handoff() );
if ( buttons ) {
buttons.wrap('<div class="wp-pointer-buttons" />').parent().appendTo( this.content );
}
this.reposition();
},
reposition: function() {
var position;
if ( this.options.disabled )
return;
position = this._processPosition( this.options.position );
// Reposition pointer.
this.pointer.css({
top: 0,
left: 0,
zIndex: zindex++ // Increment the z-index so that it shows above other opened pointers.
}).show().position($.extend({
of: this.element,
collision: 'fit none'
}, position )); // the object comes before this.options.position so the user can override position.of.
this.repoint();
},
repoint: function() {
var o = this.options,
edge;
if ( o.disabled )
return;
edge = ( typeof o.position == 'string' ) ? o.position : o.position.edge;
// Remove arrow classes.
this.pointer[0].className = this.pointer[0].className.replace( /wp-pointer-[^\s'"]*/, '' );
// Add arrow class.
this.pointer.addClass( 'wp-pointer-' + edge );
},
_processPosition: function( position ) {
var opposite = {
top: 'bottom',
bottom: 'top',
left: 'right',
right: 'left'
},
result;
// If the position object is a string, it is shorthand for position.edge.
if ( typeof position == 'string' ) {
result = {
edge: position + ''
};
} else {
result = $.extend( {}, position );
}
if ( ! result.edge )
return result;
if ( result.edge == 'top' || result.edge == 'bottom' ) {
result.align = result.align || 'left';
result.at = result.at || result.align + ' ' + opposite[ result.edge ];
result.my = result.my || result.align + ' ' + result.edge;
} else {
result.align = result.align || 'top';
result.at = result.at || opposite[ result.edge ] + ' ' + result.align;
result.my = result.my || result.edge + ' ' + result.align;
}
return result;
},
open: function( event ) {
var self = this,
o = this.options;
if ( this.active || o.disabled || this.element.is(':hidden') )
return;
this.update().done( function() {
self._open( event );
});
},
_open: function( event ) {
var self = this,
o = this.options;
if ( this.active || o.disabled || this.element.is(':hidden') )
return;
this.active = true;
this._trigger( 'open', event, this._handoff() );
this._trigger( 'show', event, this._handoff({
opened: function() {
self._trigger( 'opened', event, self._handoff() );
}
}));
},
close: function( event ) {
if ( !this.active || this.options.disabled )
return;
var self = this;
this.active = false;
this._trigger( 'close', event, this._handoff() );
this._trigger( 'hide', event, this._handoff({
closed: function() {
self._trigger( 'closed', event, self._handoff() );
}
}));
},
sendToTop: function() {
if ( this.active )
this.pointer.css( 'z-index', zindex++ );
},
toggle: function( event ) {
if ( this.pointer.is(':hidden') )
this.open( event );
else
this.close( event );
},
_handoff: function( extend ) {
return $.extend({
pointer: this.pointer,
element: this.element
}, extend);
}
});
})(jQuery);
| JavaScript |
/* global ajaxurl, tinymce, wpLinkL10n, setUserSetting, wpActiveEditor */
var wpLink;
( function( $ ) {
var inputs = {}, rivers = {}, editor, searchTimer, River, Query;
wpLink = {
timeToTriggerRiver: 150,
minRiverAJAXDuration: 200,
riverBottomThreshold: 5,
keySensitivity: 100,
lastSearch: '',
textarea: '',
init: function() {
inputs.wrap = $('#wp-link-wrap');
inputs.dialog = $( '#wp-link' );
inputs.backdrop = $( '#wp-link-backdrop' );
inputs.submit = $( '#wp-link-submit' );
inputs.close = $( '#wp-link-close' );
// URL
inputs.url = $( '#url-field' );
inputs.nonce = $( '#_ajax_linking_nonce' );
// Secondary options
inputs.title = $( '#link-title-field' );
// Advanced Options
inputs.openInNewTab = $( '#link-target-checkbox' );
inputs.search = $( '#search-field' );
// Build Rivers
rivers.search = new River( $( '#search-results' ) );
rivers.recent = new River( $( '#most-recent-results' ) );
rivers.elements = inputs.dialog.find( '.query-results' );
// Bind event handlers
inputs.dialog.keydown( wpLink.keydown );
inputs.dialog.keyup( wpLink.keyup );
inputs.submit.click( function( event ) {
event.preventDefault();
wpLink.update();
});
inputs.close.add( inputs.backdrop ).add( '#wp-link-cancel a' ).click( function( event ) {
event.preventDefault();
wpLink.close();
});
$( '#wp-link-search-toggle' ).click( wpLink.toggleInternalLinking );
rivers.elements.on( 'river-select', wpLink.updateFields );
inputs.search.keyup( function() {
var self = this;
window.clearTimeout( searchTimer );
searchTimer = window.setTimeout( function() {
wpLink.searchInternalLinks.call( self );
}, 500 );
});
},
open: function( editorId ) {
var ed;
wpLink.range = null;
if ( editorId ) {
window.wpActiveEditor = editorId;
}
if ( ! window.wpActiveEditor ) {
return;
}
this.textarea = $( '#' + window.wpActiveEditor ).get( 0 );
if ( typeof tinymce !== 'undefined' ) {
ed = tinymce.get( wpActiveEditor );
if ( ed && ! ed.isHidden() ) {
editor = ed;
} else {
editor = null;
}
if ( editor && tinymce.isIE ) {
editor.windowManager.bookmark = editor.selection.getBookmark();
}
}
if ( ! wpLink.isMCE() && document.selection ) {
this.textarea.focus();
this.range = document.selection.createRange();
}
inputs.wrap.show();
inputs.backdrop.show();
wpLink.refresh();
},
isMCE: function() {
return editor && ! editor.isHidden();
},
refresh: function() {
// Refresh rivers (clear links, check visibility)
rivers.search.refresh();
rivers.recent.refresh();
if ( wpLink.isMCE() )
wpLink.mceRefresh();
else
wpLink.setDefaultValues();
// Focus the URL field and highlight its contents.
// If this is moved above the selection changes,
// IE will show a flashing cursor over the dialog.
inputs.url.focus()[0].select();
// Load the most recent results if this is the first time opening the panel.
if ( ! rivers.recent.ul.children().length )
rivers.recent.ajax();
},
mceRefresh: function() {
var e;
// If link exists, select proper values.
if ( e = editor.dom.getParent( editor.selection.getNode(), 'A' ) ) {
// Set URL and description.
inputs.url.val( editor.dom.getAttrib( e, 'href' ) );
inputs.title.val( editor.dom.getAttrib( e, 'title' ) );
// Set open in new tab.
inputs.openInNewTab.prop( 'checked', ( '_blank' === editor.dom.getAttrib( e, 'target' ) ) );
// Update save prompt.
inputs.submit.val( wpLinkL10n.update );
// If there's no link, set the default values.
} else {
wpLink.setDefaultValues();
}
},
close: function() {
if ( ! wpLink.isMCE() ) {
wpLink.textarea.focus();
if ( wpLink.range ) {
wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
wpLink.range.select();
}
} else {
editor.focus();
}
inputs.backdrop.hide();
inputs.wrap.hide();
},
getAttrs: function() {
return {
href: inputs.url.val(),
title: inputs.title.val(),
target: inputs.openInNewTab.prop( 'checked' ) ? '_blank' : ''
};
},
update: function() {
if ( wpLink.isMCE() )
wpLink.mceUpdate();
else
wpLink.htmlUpdate();
},
htmlUpdate: function() {
var attrs, html, begin, end, cursor, title, selection,
textarea = wpLink.textarea;
if ( ! textarea )
return;
attrs = wpLink.getAttrs();
// If there's no href, return.
if ( ! attrs.href || attrs.href == 'http://' )
return;
// Build HTML
html = '<a href="' + attrs.href + '"';
if ( attrs.title ) {
title = attrs.title.replace( /</g, '<' ).replace( />/g, '>' ).replace( /"/g, '"' );
html += ' title="' + title + '"';
}
if ( attrs.target ) {
html += ' target="' + attrs.target + '"';
}
html += '>';
// Insert HTML
if ( document.selection && wpLink.range ) {
// IE
// Note: If no text is selected, IE will not place the cursor
// inside the closing tag.
textarea.focus();
wpLink.range.text = html + wpLink.range.text + '</a>';
wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
wpLink.range.select();
wpLink.range = null;
} else if ( typeof textarea.selectionStart !== 'undefined' ) {
// W3C
begin = textarea.selectionStart;
end = textarea.selectionEnd;
selection = textarea.value.substring( begin, end );
html = html + selection + '</a>';
cursor = begin + html.length;
// If no text is selected, place the cursor inside the closing tag.
if ( begin == end )
cursor -= '</a>'.length;
textarea.value = textarea.value.substring( 0, begin ) + html +
textarea.value.substring( end, textarea.value.length );
// Update cursor position
textarea.selectionStart = textarea.selectionEnd = cursor;
}
wpLink.close();
textarea.focus();
},
mceUpdate: function() {
var link,
attrs = wpLink.getAttrs();
wpLink.close();
editor.focus();
if ( tinymce.isIE ) {
editor.selection.moveToBookmark( editor.windowManager.bookmark );
}
link = editor.dom.getParent( editor.selection.getNode(), 'a[href]' );
// If the values are empty, unlink and return
if ( ! attrs.href || attrs.href == 'http://' ) {
editor.execCommand( 'unlink' );
return;
}
if ( link ) {
editor.dom.setAttribs( link, attrs );
} else {
editor.execCommand( 'mceInsertLink', false, attrs );
}
// Move the cursor to the end of the selection
editor.selection.collapse();
},
updateFields: function( e, li, originalEvent ) {
inputs.url.val( li.children( '.item-permalink' ).val() );
inputs.title.val( li.hasClass( 'no-title' ) ? '' : li.children( '.item-title' ).text() );
if ( originalEvent && originalEvent.type == 'click' )
inputs.url.focus();
},
setDefaultValues: function() {
// Set URL and description to defaults.
// Leave the new tab setting as-is.
inputs.url.val( 'http://' );
inputs.title.val( '' );
// Update save prompt.
inputs.submit.val( wpLinkL10n.save );
},
searchInternalLinks: function() {
var t = $( this ), waiting,
search = t.val();
if ( search.length > 2 ) {
rivers.recent.hide();
rivers.search.show();
// Don't search if the keypress didn't change the title.
if ( wpLink.lastSearch == search )
return;
wpLink.lastSearch = search;
waiting = t.parent().find('.spinner').show();
rivers.search.change( search );
rivers.search.ajax( function() {
waiting.hide();
});
} else {
rivers.search.hide();
rivers.recent.show();
}
},
next: function() {
rivers.search.next();
rivers.recent.next();
},
prev: function() {
rivers.search.prev();
rivers.recent.prev();
},
keydown: function( event ) {
var fn, id,
key = $.ui.keyCode;
if ( key.ESCAPE === event.keyCode ) {
wpLink.close();
event.stopImmediatePropagation();
} else if ( key.TAB === event.keyCode ) {
id = event.target.id;
if ( id === 'wp-link-submit' && ! event.shiftKey ) {
inputs.close.focus();
event.preventDefault();
} else if ( id === 'wp-link-close' && event.shiftKey ) {
inputs.submit.focus();
event.preventDefault();
}
}
if ( event.keyCode !== key.UP && event.keyCode !== key.DOWN ) {
return;
}
fn = event.keyCode === key.UP ? 'prev' : 'next';
clearInterval( wpLink.keyInterval );
wpLink[ fn ]();
wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
event.preventDefault();
},
keyup: function( event ) {
var key = $.ui.keyCode;
if ( event.which === key.UP || event.which === key.DOWN ) {
clearInterval( wpLink.keyInterval );
event.preventDefault();
}
},
delayedCallback: function( func, delay ) {
var timeoutTriggered, funcTriggered, funcArgs, funcContext;
if ( ! delay )
return func;
setTimeout( function() {
if ( funcTriggered )
return func.apply( funcContext, funcArgs );
// Otherwise, wait.
timeoutTriggered = true;
}, delay );
return function() {
if ( timeoutTriggered )
return func.apply( this, arguments );
// Otherwise, wait.
funcArgs = arguments;
funcContext = this;
funcTriggered = true;
};
},
toggleInternalLinking: function() {
var visible = inputs.wrap.hasClass( 'search-panel-visible' );
inputs.wrap.toggleClass( 'search-panel-visible', ! visible );
setUserSetting( 'wplink', visible ? '0' : '1' );
inputs[ ! visible ? 'search' : 'url' ].focus();
}
};
River = function( element, search ) {
var self = this;
this.element = element;
this.ul = element.children( 'ul' );
this.contentHeight = element.children( '#link-selector-height' );
this.waiting = element.find('.river-waiting');
this.change( search );
this.refresh();
$( '#wp-link .query-results, #wp-link #link-selector' ).scroll( function() {
self.maybeLoad();
});
element.on( 'click', 'li', function( event ) {
self.select( $( this ), event );
});
};
$.extend( River.prototype, {
refresh: function() {
this.deselect();
this.visible = this.element.is( ':visible' );
},
show: function() {
if ( ! this.visible ) {
this.deselect();
this.element.show();
this.visible = true;
}
},
hide: function() {
this.element.hide();
this.visible = false;
},
// Selects a list item and triggers the river-select event.
select: function( li, event ) {
var liHeight, elHeight, liTop, elTop;
if ( li.hasClass( 'unselectable' ) || li == this.selected )
return;
this.deselect();
this.selected = li.addClass( 'selected' );
// Make sure the element is visible
liHeight = li.outerHeight();
elHeight = this.element.height();
liTop = li.position().top;
elTop = this.element.scrollTop();
if ( liTop < 0 ) // Make first visible element
this.element.scrollTop( elTop + liTop );
else if ( liTop + liHeight > elHeight ) // Make last visible element
this.element.scrollTop( elTop + liTop - elHeight + liHeight );
// Trigger the river-select event
this.element.trigger( 'river-select', [ li, event, this ] );
},
deselect: function() {
if ( this.selected )
this.selected.removeClass( 'selected' );
this.selected = false;
},
prev: function() {
if ( ! this.visible )
return;
var to;
if ( this.selected ) {
to = this.selected.prev( 'li' );
if ( to.length )
this.select( to );
}
},
next: function() {
if ( ! this.visible )
return;
var to = this.selected ? this.selected.next( 'li' ) : $( 'li:not(.unselectable):first', this.element );
if ( to.length )
this.select( to );
},
ajax: function( callback ) {
var self = this,
delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration,
response = wpLink.delayedCallback( function( results, params ) {
self.process( results, params );
if ( callback )
callback( results, params );
}, delay );
this.query.ajax( response );
},
change: function( search ) {
if ( this.query && this._search == search )
return;
this._search = search;
this.query = new Query( search );
this.element.scrollTop( 0 );
},
process: function( results, params ) {
var list = '', alt = true, classes = '',
firstPage = params.page == 1;
if ( ! results ) {
if ( firstPage ) {
list += '<li class="unselectable"><span class="item-title"><em>' +
wpLinkL10n.noMatchesFound + '</em></span></li>';
}
} else {
$.each( results, function() {
classes = alt ? 'alternate' : '';
classes += this.title ? '' : ' no-title';
list += classes ? '<li class="' + classes + '">' : '<li>';
list += '<input type="hidden" class="item-permalink" value="' + this.permalink + '" />';
list += '<span class="item-title">';
list += this.title ? this.title : wpLinkL10n.noTitle;
list += '</span><span class="item-info">' + this.info + '</span></li>';
alt = ! alt;
});
}
this.ul[ firstPage ? 'html' : 'append' ]( list );
},
maybeLoad: function() {
var self = this,
el = this.element,
bottom = el.scrollTop() + el.height();
if ( ! this.query.ready() || bottom < this.contentHeight.height() - wpLink.riverBottomThreshold )
return;
setTimeout(function() {
var newTop = el.scrollTop(),
newBottom = newTop + el.height();
if ( ! self.query.ready() || newBottom < self.contentHeight.height() - wpLink.riverBottomThreshold )
return;
self.waiting.show();
el.scrollTop( newTop + self.waiting.outerHeight() );
self.ajax( function() {
self.waiting.hide();
});
}, wpLink.timeToTriggerRiver );
}
});
Query = function( search ) {
this.page = 1;
this.allLoaded = false;
this.querying = false;
this.search = search;
};
$.extend( Query.prototype, {
ready: function() {
return ! ( this.querying || this.allLoaded );
},
ajax: function( callback ) {
var self = this,
query = {
action : 'wp-link-ajax',
page : this.page,
'_ajax_linking_nonce' : inputs.nonce.val()
};
if ( this.search )
query.search = this.search;
this.querying = true;
$.post( ajaxurl, query, function( r ) {
self.page++;
self.querying = false;
self.allLoaded = ! r;
callback( r, query );
}, 'json' );
}
});
$( document ).ready( wpLink.init );
})( jQuery );
| JavaScript |
/* global plupload, pluploadL10n, ajaxurl, post_id, wpUploaderInit, deleteUserSetting, setUserSetting, getUserSetting, shortform */
var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init;
// progress and success handlers for media multi uploads
function fileQueued(fileObj) {
// Get rid of unused form
jQuery('.media-blank').remove();
var items = jQuery('#media-items').children(), postid = post_id || 0;
// Collapse a single item
if ( items.length == 1 ) {
items.removeClass('open').find('.slidetoggle').slideUp(200);
}
// Create a progress bar containing the filename
jQuery('<div class="media-item">')
.attr( 'id', 'media-item-' + fileObj.id )
.addClass('child-of-' + postid)
.append('<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>',
jQuery('<div class="filename original">').text( ' ' + fileObj.name ))
.appendTo( jQuery('#media-items' ) );
// Disable submit
jQuery('#insert-gallery').prop('disabled', true);
}
function uploadStart() {
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
} catch(e){}
return true;
}
function uploadProgress(up, file) {
var item = jQuery('#media-item-' + file.id);
jQuery('.bar', item).width( (200 * file.loaded) / file.size );
jQuery('.percent', item).html( file.percent + '%' );
}
// check to see if a large file failed to upload
function fileUploading( up, file ) {
var hundredmb = 100 * 1024 * 1024,
max = parseInt( up.settings.max_file_size, 10 );
if ( max > hundredmb && file.size > hundredmb ) {
setTimeout( function() {
if ( file.status < 3 && file.loaded === 0 ) { // not uploading
wpFileError( file, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) );
up.stop(); // stops the whole queue
up.removeFile( file );
up.start(); // restart the queue
}
}, 10000 ); // wait for 10 sec. for the file to start uploading
}
}
function updateMediaForm() {
var items = jQuery('#media-items').children();
// Just one file, no need for collapsible part
if ( items.length == 1 ) {
items.addClass('open').find('.slidetoggle').show();
jQuery('.insert-gallery').hide();
} else if ( items.length > 1 ) {
items.removeClass('open');
// Only show Gallery/Playlist buttons when there are at least two files.
jQuery('.insert-gallery').show();
}
// Only show Save buttons when there is at least one file.
if ( items.not('.media-blank').length > 0 )
jQuery('.savebutton').show();
else
jQuery('.savebutton').hide();
}
function uploadSuccess(fileObj, serverData) {
var item = jQuery('#media-item-' + fileObj.id);
// on success serverData should be numeric, fix bug in html4 runtime returning the serverData wrapped in a <pre> tag
serverData = serverData.replace(/^<pre>(\d+)<\/pre>$/, '$1');
// if async-upload returned an error message, place it in the media item div and return
if ( serverData.match(/media-upload-error|error-div/) ) {
item.html(serverData);
return;
} else {
jQuery('.percent', item).html( pluploadL10n.crunching );
}
prepareMediaItem(fileObj, serverData);
updateMediaForm();
// Increment the counter.
if ( post_id && item.hasClass('child-of-' + post_id) )
jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}
function setResize( arg ) {
if ( arg ) {
if ( window.resize_width && window.resize_height ) {
uploader.settings.resize = {
enabled: true,
width: window.resize_width,
height: window.resize_height,
quality: 100
};
} else {
uploader.settings.multipart_params.image_resize = true;
}
} else {
delete( uploader.settings.multipart_params.image_resize );
}
}
function prepareMediaItem(fileObj, serverData) {
var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
if ( f == 2 && shortform > 2 )
f = shortform;
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
} catch(e){}
if ( isNaN(serverData) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs
item.append(serverData);
prepareMediaItemInit(fileObj);
} else { // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm();});
}
}
function prepareMediaItemInit(fileObj) {
var item = jQuery('#media-item-' + fileObj.id);
// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
// Replace the original filename with the new (unique) one assigned during upload
jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
// Bind AJAX to the new Delete button
jQuery('a.delete', item).click(function(){
// Tell the server to delete it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
success: deleteSuccess,
error: deleteError,
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g, ''),
action : 'trash-post',
_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
}
});
return false;
});
// Bind AJAX to the new Undo button
jQuery('a.undo', item).click(function(){
// Tell the server to untrash it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g,''),
action: 'untrash-post',
_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
},
success: function( ){
var type,
item = jQuery('#media-item-' + fileObj.id);
if ( type = jQuery('#type-of-' + fileObj.id).val() )
jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
jQuery('.filename .trashnotice', item).remove();
jQuery('.filename .title', item).css('font-weight','normal');
jQuery('a.undo', item).addClass('hidden');
jQuery('.menu_order_input', item).show();
item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
}
});
return false;
});
// Open this item if it says to start open (e.g. to display an error)
jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').addClass('open').find('slidetoggle').fadeIn();
}
// generic error message
function wpQueueError(message) {
jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' );
}
// file-specific error messages
function wpFileError(fileObj, message) {
itemAjaxError(fileObj.id, message);
}
function itemAjaxError(id, message) {
var item = jQuery('#media-item-' + id), filename = item.find('.filename').text(), last_err = item.data('last-err');
if ( last_err == id ) // prevent firing an error for the same file twice
return;
item.html('<div class="error-div">' +
'<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>' +
'<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> ' +
message +
'</div>').data('last-err', id);
}
function deleteSuccess(data) {
var type, id, item;
if ( data == '-1' )
return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
if ( data == '0' )
return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
id = this.id;
item = jQuery('#media-item-' + id);
// Decrement the counters.
if ( type = jQuery('#type-of-' + id).val() )
jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.toggle').toggle();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Vanish it.
jQuery('.toggle', item).toggle();
jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
jQuery('.filename:empty', item).remove();
jQuery('.filename .title', item).css('font-weight','bold');
jQuery('.filename', item).append('<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
jQuery('.menu_order_input', item).hide();
return;
}
function deleteError() {
// TODO
}
function uploadComplete() {
jQuery('#insert-gallery').prop('disabled', false);
}
function switchUploader(s) {
if ( s ) {
deleteUserSetting('uploader');
jQuery('.media-upload-form').removeClass('html-uploader');
if ( typeof(uploader) == 'object' )
uploader.refresh();
} else {
setUserSetting('uploader', '1'); // 1 == html uploader
jQuery('.media-upload-form').addClass('html-uploader');
}
}
function uploadError(fileObj, errorCode, message, uploader) {
var hundredmb = 100 * 1024 * 1024, max;
switch (errorCode) {
case plupload.FAILED:
wpFileError(fileObj, pluploadL10n.upload_failed);
break;
case plupload.FILE_EXTENSION_ERROR:
wpFileError(fileObj, pluploadL10n.invalid_filetype);
break;
case plupload.FILE_SIZE_ERROR:
uploadSizeError(uploader, fileObj);
break;
case plupload.IMAGE_FORMAT_ERROR:
wpFileError(fileObj, pluploadL10n.not_an_image);
break;
case plupload.IMAGE_MEMORY_ERROR:
wpFileError(fileObj, pluploadL10n.image_memory_exceeded);
break;
case plupload.IMAGE_DIMENSIONS_ERROR:
wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded);
break;
case plupload.GENERIC_ERROR:
wpQueueError(pluploadL10n.upload_failed);
break;
case plupload.IO_ERROR:
max = parseInt( uploader.settings.filters.max_file_size, 10 );
if ( max > hundredmb && fileObj.size > hundredmb )
wpFileError( fileObj, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>') );
else
wpQueueError(pluploadL10n.io_error);
break;
case plupload.HTTP_ERROR:
wpQueueError(pluploadL10n.http_error);
break;
case plupload.INIT_ERROR:
jQuery('.media-upload-form').addClass('html-uploader');
break;
case plupload.SECURITY_ERROR:
wpQueueError(pluploadL10n.security_error);
break;
/* case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
case plupload.UPLOAD_ERROR.FILE_CANCELLED:
jQuery('#media-item-' + fileObj.id).remove();
break;*/
default:
wpFileError(fileObj, pluploadL10n.default_error);
}
}
function uploadSizeError( up, file, over100mb ) {
var message;
if ( over100mb )
message = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>');
else
message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>');
up.removeFile(file);
}
jQuery(document).ready(function($){
$('.media-upload-form').bind('click.uploader', function(e) {
var target = $(e.target), tr, c;
if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment
tr = target.closest('tr');
if ( tr.hasClass('align') )
setUserSetting('align', target.val());
else if ( tr.hasClass('image-size') )
setUserSetting('imgsize', target.val());
} else if ( target.is('button.button') ) { // remember the last used image link url
c = e.target.className || '';
c = c.match(/url([^ '"]+)/);
if ( c && c[1] ) {
setUserSetting('urlbutton', c[1]);
target.siblings('.urlfield').val( target.data('link-url') );
}
} else if ( target.is('a.dismiss') ) {
target.parents('.media-item').fadeOut(200, function(){
$(this).remove();
});
} else if ( target.is('.upload-flash-bypass a') || target.is('a.uploader-html') ) { // switch uploader to html4
$('#media-items, p.submit, span.big-file-warning').css('display', 'none');
switchUploader(0);
e.preventDefault();
} else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file
$('#media-items, p.submit, span.big-file-warning').css('display', '');
switchUploader(1);
e.preventDefault();
} else if ( target.is('a.describe-toggle-on') ) { // Show
target.parent().addClass('open');
target.siblings('.slidetoggle').fadeIn(250, function(){
var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B;
if ( H && top && h ) {
b = top + h;
B = S + H;
if ( b > B ) {
if ( b - B < top - S )
window.scrollBy(0, (b - B) + 10);
else
window.scrollBy(0, top - S - 40);
}
}
});
e.preventDefault();
} else if ( target.is('a.describe-toggle-off') ) { // Hide
target.siblings('.slidetoggle').fadeOut(250, function(){
target.parent().removeClass('open');
});
e.preventDefault();
}
});
// init and set the uploader
uploader_init = function() {
var isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1;
// Make sure flash sends cookies (seems in IE it does whitout switching to urlstream mode)
if ( ! isIE && 'flash' === plupload.predictRuntime( wpUploaderInit ) &&
( ! wpUploaderInit.required_features || ! wpUploaderInit.required_features.hasOwnProperty( 'send_binary_string' ) ) ) {
wpUploaderInit.required_features = wpUploaderInit.required_features || {};
wpUploaderInit.required_features.send_binary_string = true;
}
uploader = new plupload.Uploader(wpUploaderInit);
$('#image_resize').bind('change', function() {
var arg = $(this).prop('checked');
setResize( arg );
if ( arg )
setUserSetting('upload_resize', '1');
else
deleteUserSetting('upload_resize');
});
uploader.bind('Init', function(up) {
var uploaddiv = $('#plupload-upload-ui');
setResize( getUserSetting('upload_resize', false) );
if ( up.features.dragdrop && ! $(document.body).hasClass('mobile') ) {
uploaddiv.addClass('drag-drop');
$('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
uploaddiv.addClass('drag-over');
}).bind('dragleave.wp-uploader, drop.wp-uploader', function(){
uploaddiv.removeClass('drag-over');
});
} else {
uploaddiv.removeClass('drag-drop');
$('#drag-drop-area').unbind('.wp-uploader');
}
if ( up.runtime === 'html4' ) {
$('.upload-flash-bypass').hide();
}
});
uploader.init();
uploader.bind('FilesAdded', function( up, files ) {
$('#media-upload-error').html('');
uploadStart();
plupload.each( files, function( file ) {
fileQueued( file );
});
up.refresh();
up.start();
});
uploader.bind('UploadFile', function(up, file) {
fileUploading(up, file);
});
uploader.bind('UploadProgress', function(up, file) {
uploadProgress(up, file);
});
uploader.bind('Error', function(up, err) {
uploadError(err.file, err.code, err.message, up);
up.refresh();
});
uploader.bind('FileUploaded', function(up, file, response) {
uploadSuccess(file, response.response);
});
uploader.bind('UploadComplete', function() {
uploadComplete();
});
};
if ( typeof(wpUploaderInit) == 'object' ) {
uploader_init();
}
});
| JavaScript |
/* global pluploadL10n, plupload, _wpPluploadSettings */
window.wp = window.wp || {};
( function( exports, $ ) {
var Uploader;
if ( typeof _wpPluploadSettings === 'undefined' ) {
return;
}
/**
* An object that helps create a WordPress uploader using plupload.
*
* @param options - object - The options passed to the new plupload instance.
* Accepts the following parameters:
* - container - The id of uploader container.
* - browser - The id of button to trigger the file select.
* - dropzone - The id of file drop target.
* - plupload - An object of parameters to pass to the plupload instance.
* - params - An object of parameters to pass to $_POST when uploading the file.
* Extends this.plupload.multipart_params under the hood.
*
* @param attributes - object - Attributes and methods for this specific instance.
*/
Uploader = function( options ) {
var self = this,
isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1,
elements = {
container: 'container',
browser: 'browse_button',
dropzone: 'drop_element'
},
key, error;
this.supports = {
upload: Uploader.browser.supported
};
this.supported = this.supports.upload;
if ( ! this.supported ) {
return;
}
// Use deep extend to ensure that multipart_params and other objects are cloned.
this.plupload = $.extend( true, { multipart_params: {} }, Uploader.defaults );
this.container = document.body; // Set default container.
// Extend the instance with options
//
// Use deep extend to allow options.plupload to override individual
// default plupload keys.
$.extend( true, this, options );
// Proxy all methods so this always refers to the current instance.
for ( key in this ) {
if ( $.isFunction( this[ key ] ) ) {
this[ key ] = $.proxy( this[ key ], this );
}
}
// Ensure all elements are jQuery elements and have id attributes
// Then set the proper plupload arguments to the ids.
for ( key in elements ) {
if ( ! this[ key ] ) {
continue;
}
this[ key ] = $( this[ key ] ).first();
if ( ! this[ key ].length ) {
delete this[ key ];
continue;
}
if ( ! this[ key ].prop('id') ) {
this[ key ].prop( 'id', '__wp-uploader-id-' + Uploader.uuid++ );
}
this.plupload[ elements[ key ] ] = this[ key ].prop('id');
}
// If the uploader has neither a browse button nor a dropzone, bail.
if ( ! ( this.browser && this.browser.length ) && ! ( this.dropzone && this.dropzone.length ) ) {
return;
}
// Make sure flash sends cookies (seems in IE it does without switching to urlstream mode)
if ( ! isIE && 'flash' === plupload.predictRuntime( this.plupload ) &&
( ! this.plupload.required_features || ! this.plupload.required_features.hasOwnProperty( 'send_binary_string' ) ) ) {
this.plupload.required_features = this.plupload.required_features || {};
this.plupload.required_features.send_binary_string = true;
}
this.uploader = new plupload.Uploader( this.plupload );
delete this.plupload;
// Set default params and remove this.params alias.
this.param( this.params || {} );
delete this.params;
error = function( message, data, file ) {
if ( file.attachment ) {
file.attachment.destroy();
}
Uploader.errors.unshift({
message: message || pluploadL10n.default_error,
data: data,
file: file
});
self.error( message, data, file );
};
this.uploader.bind( 'init', function( uploader ) {
var timer, active, dragdrop,
dropzone = self.dropzone;
dragdrop = self.supports.dragdrop = uploader.features.dragdrop && ! Uploader.browser.mobile;
// Generate drag/drop helper classes.
if ( ! dropzone ) {
return;
}
dropzone.toggleClass( 'supports-drag-drop', !! dragdrop );
if ( ! dragdrop ) {
return dropzone.unbind('.wp-uploader');
}
// 'dragenter' doesn't fire correctly,
// simulate it with a limited 'dragover'
dropzone.bind( 'dragover.wp-uploader', function() {
if ( timer ) {
clearTimeout( timer );
}
if ( active ) {
return;
}
dropzone.trigger('dropzone:enter').addClass('drag-over');
active = true;
});
dropzone.bind('dragleave.wp-uploader, drop.wp-uploader', function() {
// Using an instant timer prevents the drag-over class from
// being quickly removed and re-added when elements inside the
// dropzone are repositioned.
//
// See http://core.trac.wordpress.org/ticket/21705
timer = setTimeout( function() {
active = false;
dropzone.trigger('dropzone:leave').removeClass('drag-over');
}, 0 );
});
$(self).trigger( 'uploader:ready' );
});
this.uploader.init();
if ( this.browser ) {
this.browser.on( 'mouseenter', this.refresh );
} else {
this.uploader.disableBrowse( true );
// If HTML5 mode, hide the auto-created file container.
$('#' + this.uploader.id + '_html5_container').hide();
}
this.uploader.bind( 'FilesAdded', function( up, files ) {
_.each( files, function( file ) {
var attributes, image;
// Ignore failed uploads.
if ( plupload.FAILED === file.status ) {
return;
}
// Generate attributes for a new `Attachment` model.
attributes = _.extend({
file: file,
uploading: true,
date: new Date(),
filename: file.name,
menuOrder: 0,
uploadedTo: wp.media.model.settings.post.id
}, _.pick( file, 'loaded', 'size', 'percent' ) );
// Handle early mime type scanning for images.
image = /(?:jpe?g|png|gif)$/i.exec( file.name );
// Did we find an image?
if ( image ) {
attributes.type = 'image';
// `jpeg`, `png` and `gif` are valid subtypes.
// `jpg` is not, so map it to `jpeg`.
attributes.subtype = ( 'jpg' === image[0] ) ? 'jpeg' : image[0];
}
// Create the `Attachment`.
file.attachment = wp.media.model.Attachment.create( attributes );
Uploader.queue.add( file.attachment );
self.added( file.attachment );
});
up.refresh();
up.start();
});
this.uploader.bind( 'UploadProgress', function( up, file ) {
file.attachment.set( _.pick( file, 'loaded', 'percent' ) );
self.progress( file.attachment );
});
this.uploader.bind( 'FileUploaded', function( up, file, response ) {
var complete;
try {
response = JSON.parse( response.response );
} catch ( e ) {
return error( pluploadL10n.default_error, e, file );
}
if ( ! _.isObject( response ) || _.isUndefined( response.success ) )
return error( pluploadL10n.default_error, null, file );
else if ( ! response.success )
return error( response.data && response.data.message, response.data, file );
_.each(['file','loaded','size','percent'], function( key ) {
file.attachment.unset( key );
});
file.attachment.set( _.extend( response.data, { uploading: false }) );
wp.media.model.Attachment.get( response.data.id, file.attachment );
complete = Uploader.queue.all( function( attachment ) {
return ! attachment.get('uploading');
});
if ( complete )
Uploader.queue.reset();
self.success( file.attachment );
});
this.uploader.bind( 'Error', function( up, pluploadError ) {
var message = pluploadL10n.default_error,
key;
// Check for plupload errors.
for ( key in Uploader.errorMap ) {
if ( pluploadError.code === plupload[ key ] ) {
message = Uploader.errorMap[ key ];
if ( _.isFunction( message ) ) {
message = message( pluploadError.file, pluploadError );
}
break;
}
}
error( message, pluploadError, pluploadError.file );
up.refresh();
});
this.uploader.bind( 'PostInit', function() {
self.init();
});
};
// Adds the 'defaults' and 'browser' properties.
$.extend( Uploader, _wpPluploadSettings );
Uploader.uuid = 0;
Uploader.errorMap = {
'FAILED': pluploadL10n.upload_failed,
'FILE_EXTENSION_ERROR': pluploadL10n.invalid_filetype,
'IMAGE_FORMAT_ERROR': pluploadL10n.not_an_image,
'IMAGE_MEMORY_ERROR': pluploadL10n.image_memory_exceeded,
'IMAGE_DIMENSIONS_ERROR': pluploadL10n.image_dimensions_exceeded,
'GENERIC_ERROR': pluploadL10n.upload_failed,
'IO_ERROR': pluploadL10n.io_error,
'HTTP_ERROR': pluploadL10n.http_error,
'SECURITY_ERROR': pluploadL10n.security_error,
'FILE_SIZE_ERROR': function( file ) {
return pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
}
};
$.extend( Uploader.prototype, {
/**
* Acts as a shortcut to extending the uploader's multipart_params object.
*
* param( key )
* Returns the value of the key.
*
* param( key, value )
* Sets the value of a key.
*
* param( map )
* Sets values for a map of data.
*/
param: function( key, value ) {
if ( arguments.length === 1 && typeof key === 'string' ) {
return this.uploader.settings.multipart_params[ key ];
}
if ( arguments.length > 1 ) {
this.uploader.settings.multipart_params[ key ] = value;
} else {
$.extend( this.uploader.settings.multipart_params, key );
}
},
init: function() {},
error: function() {},
success: function() {},
added: function() {},
progress: function() {},
complete: function() {},
refresh: function() {
var node, attached, container, id;
if ( this.browser ) {
node = this.browser[0];
// Check if the browser node is in the DOM.
while ( node ) {
if ( node === document.body ) {
attached = true;
break;
}
node = node.parentNode;
}
// If the browser node is not attached to the DOM, use a
// temporary container to house it, as the browser button
// shims require the button to exist in the DOM at all times.
if ( ! attached ) {
id = 'wp-uploader-browser-' + this.uploader.id;
container = $( '#' + id );
if ( ! container.length ) {
container = $('<div class="wp-uploader-browser" />').css({
position: 'fixed',
top: '-1000px',
left: '-1000px',
height: 0,
width: 0
}).attr( 'id', 'wp-uploader-browser-' + this.uploader.id ).appendTo('body');
}
container.append( this.browser );
}
}
this.uploader.refresh();
}
});
Uploader.queue = new wp.media.model.Attachments( [], { query: false });
Uploader.errors = new Backbone.Collection();
exports.Uploader = Uploader;
})( wp, jQuery );
| JavaScript |
/* globals _wpCustomizeHeader, _ */
(function( $, wp ) {
var api = wp.customize;
api.HeaderTool = {};
/**
* wp.customize.HeaderTool.ImageModel
*
* A header image. This is where saves via the Customizer API are
* abstracted away, plus our own AJAX calls to add images to and remove
* images from the user's recently uploaded images setting on the server.
* These calls are made regardless of whether the user actually saves new
* Customizer settings.
*
* @constructor
* @augments Backbone.Model
*/
api.HeaderTool.ImageModel = Backbone.Model.extend({
defaults: function() {
return {
header: {
attachment_id: 0,
url: '',
timestamp: _.now(),
thumbnail_url: ''
},
choice: '',
selected: false,
random: false
};
},
initialize: function() {
this.on('hide', this.hide, this);
},
hide: function() {
this.set('choice', '');
api('header_image').set('remove-header');
api('header_image_data').set('remove-header');
},
destroy: function() {
var data = this.get('header'),
curr = api.HeaderTool.currentHeader.get('header').attachment_id;
// If the image we're removing is also the current header, unset
// the latter
if (curr && data.attachment_id === curr) {
api.HeaderTool.currentHeader.trigger('hide');
}
wp.ajax.post( 'custom-header-remove', {
nonce: _wpCustomizeHeader.nonces.remove,
wp_customize: 'on',
theme: api.settings.theme.stylesheet,
attachment_id: data.attachment_id
});
this.trigger('destroy', this, this.collection);
},
save: function() {
if (this.get('random')) {
api('header_image').set(this.get('header').random);
api('header_image_data').set(this.get('header').random);
} else {
if (this.get('header').defaultName) {
api('header_image').set(this.get('header').url);
api('header_image_data').set(this.get('header').defaultName);
} else {
api('header_image').set(this.get('header').url);
api('header_image_data').set(this.get('header'));
}
}
api.HeaderTool.combinedList.trigger('control:setImage', this);
},
importImage: function() {
var data = this.get('header');
if (data.attachment_id === undefined) {
return;
}
wp.ajax.post( 'custom-header-add', {
nonce: _wpCustomizeHeader.nonces.add,
wp_customize: 'on',
theme: api.settings.theme.stylesheet,
attachment_id: data.attachment_id
} );
},
shouldBeCropped: function() {
if (this.get('themeFlexWidth') === true &&
this.get('themeFlexHeight') === true) {
return false;
}
if (this.get('themeFlexWidth') === true &&
this.get('themeHeight') === this.get('imageHeight')) {
return false;
}
if (this.get('themeFlexHeight') === true &&
this.get('themeWidth') === this.get('imageWidth')) {
return false;
}
if (this.get('themeWidth') === this.get('imageWidth') &&
this.get('themeHeight') === this.get('imageHeight')) {
return false;
}
return true;
}
});
/**
* wp.customize.HeaderTool.ChoiceList
*
* @constructor
* @augments Backbone.Collection
*/
api.HeaderTool.ChoiceList = Backbone.Collection.extend({
model: api.HeaderTool.ImageModel,
// Ordered from most recently used to least
comparator: function(model) {
return -model.get('header').timestamp;
},
initialize: function() {
var current = api.HeaderTool.currentHeader.get('choice').replace(/^https?:\/\//, ''),
isRandom = this.isRandomChoice(api.get().header_image);
// Overridable by an extending class
if (!this.type) {
this.type = 'uploaded';
}
// Overridable by an extending class
if (typeof this.data === 'undefined') {
this.data = _wpCustomizeHeader.uploads;
}
if (isRandom) {
// So that when adding data we don't hide regular images
current = api.get().header_image;
}
this.on('control:setImage', this.setImage, this);
this.on('control:removeImage', this.removeImage, this);
this.on('add', this.maybeAddRandomChoice, this);
_.each(this.data, function(elt, index) {
if (!elt.attachment_id) {
elt.defaultName = index;
}
if (typeof elt.timestamp === 'undefined') {
elt.timestamp = 0;
}
this.add({
header: elt,
choice: elt.url.split('/').pop(),
selected: current === elt.url.replace(/^https?:\/\//, '')
}, { silent: true });
}, this);
if (this.size() > 0) {
this.addRandomChoice(current);
}
},
maybeAddRandomChoice: function() {
if (this.size() === 1) {
this.addRandomChoice();
}
},
addRandomChoice: function(initialChoice) {
var isRandomSameType = RegExp(this.type).test(initialChoice),
randomChoice = 'random-' + this.type + '-image';
this.add({
header: {
timestamp: 0,
random: randomChoice,
width: 245,
height: 41
},
choice: randomChoice,
random: true,
selected: isRandomSameType
});
},
isRandomChoice: function(choice) {
return (/^random-(uploaded|default)-image$/).test(choice);
},
shouldHideTitle: function() {
return this.size() < 2;
},
setImage: function(model) {
this.each(function(m) {
m.set('selected', false);
});
if (model) {
model.set('selected', true);
}
},
removeImage: function() {
this.each(function(m) {
m.set('selected', false);
});
}
});
/**
* wp.customize.HeaderTool.DefaultsList
*
* @constructor
* @augments wp.customize.HeaderTool.ChoiceList
* @augments Backbone.Collection
*/
api.HeaderTool.DefaultsList = api.HeaderTool.ChoiceList.extend({
initialize: function() {
this.type = 'default';
this.data = _wpCustomizeHeader.defaults;
api.HeaderTool.ChoiceList.prototype.initialize.apply(this);
}
});
})( jQuery, window.wp );
| JavaScript |
(function($){
$.fn.filter_visible = function(depth) {
depth = depth || 3;
var is_visible = function() {
var p = $(this), i;
for(i=0; i<depth-1; ++i) {
if (!p.is(':visible')) return false;
p = p.parent();
}
return true;
};
return this.filter(is_visible);
};
$.table_hotkeys = function(table, keys, opts) {
opts = $.extend($.table_hotkeys.defaults, opts);
var selected_class, destructive_class, set_current_row, adjacent_row_callback, get_adjacent_row, adjacent_row, prev_row, next_row, check, get_first_row, get_last_row, make_key_callback, first_row;
selected_class = opts.class_prefix + opts.selected_suffix;
destructive_class = opts.class_prefix + opts.destructive_suffix;
set_current_row = function (tr) {
if ($.table_hotkeys.current_row) $.table_hotkeys.current_row.removeClass(selected_class);
tr.addClass(selected_class);
tr[0].scrollIntoView(false);
$.table_hotkeys.current_row = tr;
};
adjacent_row_callback = function(which) {
if (!adjacent_row(which) && $.isFunction(opts[which+'_page_link_cb'])) {
opts[which+'_page_link_cb']();
}
};
get_adjacent_row = function(which) {
var first_row, method;
if (!$.table_hotkeys.current_row) {
first_row = get_first_row();
$.table_hotkeys.current_row = first_row;
return first_row[0];
}
method = 'prev' == which? $.fn.prevAll : $.fn.nextAll;
return method.call($.table_hotkeys.current_row, opts.cycle_expr).filter_visible()[0];
};
adjacent_row = function(which) {
var adj = get_adjacent_row(which);
if (!adj) return false;
set_current_row($(adj));
return true;
};
prev_row = function() { return adjacent_row('prev'); };
next_row = function() { return adjacent_row('next'); };
check = function() {
$(opts.checkbox_expr, $.table_hotkeys.current_row).each(function() {
this.checked = !this.checked;
});
};
get_first_row = function() {
return $(opts.cycle_expr, table).filter_visible().eq(opts.start_row_index);
};
get_last_row = function() {
var rows = $(opts.cycle_expr, table).filter_visible();
return rows.eq(rows.length-1);
};
make_key_callback = function(expr) {
return function() {
if ( null == $.table_hotkeys.current_row ) return false;
var clickable = $(expr, $.table_hotkeys.current_row);
if (!clickable.length) return false;
if (clickable.is('.'+destructive_class)) next_row() || prev_row();
clickable.click();
};
};
first_row = get_first_row();
if (!first_row.length) return;
if (opts.highlight_first)
set_current_row(first_row);
else if (opts.highlight_last)
set_current_row(get_last_row());
$.hotkeys.add(opts.prev_key, opts.hotkeys_opts, function() {return adjacent_row_callback('prev');});
$.hotkeys.add(opts.next_key, opts.hotkeys_opts, function() {return adjacent_row_callback('next');});
$.hotkeys.add(opts.mark_key, opts.hotkeys_opts, check);
$.each(keys, function() {
var callback, key;
if ($.isFunction(this[1])) {
callback = this[1];
key = this[0];
$.hotkeys.add(key, opts.hotkeys_opts, function(event) { return callback(event, $.table_hotkeys.current_row); });
} else {
key = this;
$.hotkeys.add(key, opts.hotkeys_opts, make_key_callback('.'+opts.class_prefix+key));
}
});
};
$.table_hotkeys.current_row = null;
$.table_hotkeys.defaults = {cycle_expr: 'tr', class_prefix: 'vim-', selected_suffix: 'current',
destructive_suffix: 'destructive', hotkeys_opts: {disableInInput: true, type: 'keypress'},
checkbox_expr: ':checkbox', next_key: 'j', prev_key: 'k', mark_key: 'x',
start_row_index: 2, highlight_first: false, highlight_last: false, next_page_link_cb: false, prev_page_link_cb: false};
})(jQuery);
| JavaScript |
(function($){$.scheduler=function(){this.bucket={};return;};$.scheduler.prototype={schedule:function(){var ctx={"id":null,"time":1000,"repeat":false,"protect":false,"obj":null,"func":function(){},"args":[]};function _isfn(fn){return(!!fn&&typeof fn!="string"&&typeof fn[0]=="undefined"&&RegExp("function","i").test(fn+""));};var i=0;var override=false;if(typeof arguments[i]=="object"&&arguments.length>1){override=true;i++;}
if(typeof arguments[i]=="object"){for(var option in arguments[i])
if(typeof ctx[option]!="undefined")
ctx[option]=arguments[i][option];i++;}
if(typeof arguments[i]=="number"||(typeof arguments[i]=="string"&&arguments[i].match(RegExp("^[0-9]+[smhdw]$"))))
ctx["time"]=arguments[i++];if(typeof arguments[i]=="boolean")
ctx["repeat"]=arguments[i++];if(typeof arguments[i]=="boolean")
ctx["protect"]=arguments[i++];if(typeof arguments[i]=="object"&&typeof arguments[i+1]=="string"&&_isfn(arguments[i][arguments[i+1]])){ctx["obj"]=arguments[i++];ctx["func"]=arguments[i++];}
else if(typeof arguments[i]!="undefined"&&(_isfn(arguments[i])||typeof arguments[i]=="string"))
ctx["func"]=arguments[i++];while(typeof arguments[i]!="undefined")
ctx["args"].push(arguments[i++]);if(override){if(typeof arguments[1]=="object"){for(var option in arguments[0])
if(typeof ctx[option]!="undefined"&&typeof arguments[1][option]=="undefined")
ctx[option]=arguments[0][option];}
else{for(var option in arguments[0])
if(typeof ctx[option]!="undefined")
ctx[option]=arguments[0][option];}
i++;}
ctx["_scheduler"]=this;ctx["_handle"]=null;var match=String(ctx["time"]).match(RegExp("^([0-9]+)([smhdw])$"));if(match&&match[0]!="undefined"&&match[1]!="undefined")
ctx["time"]=String(parseInt(match[1])*{s:1000,m:1000*60,h:1000*60*60,d:1000*60*60*24,w:1000*60*60*24*7}[match[2]]);if(ctx["id"]==null)
ctx["id"]=(String(ctx["repeat"])+":"
+String(ctx["protect"])+":"
+String(ctx["time"])+":"
+String(ctx["obj"])+":"
+String(ctx["func"])+":"
+String(ctx["args"]));if(ctx["protect"])
if(typeof this.bucket[ctx["id"]]!="undefined")
return this.bucket[ctx["id"]];if(!_isfn(ctx["func"])){if(ctx["obj"]!=null&&typeof ctx["obj"]=="object"&&typeof ctx["func"]=="string"&&_isfn(ctx["obj"][ctx["func"]]))
ctx["func"]=ctx["obj"][ctx["func"]];else
ctx["func"]=eval("function () { "+ctx["func"]+" }");}
ctx["_handle"]=this._schedule(ctx);this.bucket[ctx["id"]]=ctx;return ctx;},reschedule:function(ctx){if(typeof ctx=="string")
ctx=this.bucket[ctx];ctx["_handle"]=this._schedule(ctx);return ctx;},_schedule:function(ctx){var trampoline=function(){var obj=(ctx["obj"]!=null?ctx["obj"]:ctx);(ctx["func"]).apply(obj,ctx["args"]);if(typeof(ctx["_scheduler"]).bucket[ctx["id"]]!="undefined"&&ctx["repeat"])
(ctx["_scheduler"])._schedule(ctx);else
delete(ctx["_scheduler"]).bucket[ctx["id"]];};return setTimeout(trampoline,ctx["time"]);},cancel:function(ctx){if(typeof ctx=="string")
ctx=this.bucket[ctx];if(typeof ctx=="object"){clearTimeout(ctx["_handle"]);delete this.bucket[ctx["id"]];}}};$.extend({scheduler$:new $.scheduler(),schedule:function(){return $.scheduler$.schedule.apply($.scheduler$,arguments)},reschedule:function(){return $.scheduler$.reschedule.apply($.scheduler$,arguments)},cancel:function(){return $.scheduler$.cancel.apply($.scheduler$,arguments)}});$.fn.extend({schedule:function(){var a=[{}];for(var i=0;i<arguments.length;i++)
a.push(arguments[i]);return this.each(function(){a[0]={"id":this,"obj":this};return $.schedule.apply($,a);});}});})(jQuery); | JavaScript |
/*!
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.
(function($,undefined){
'$:nomunge'; // Used by YUI compressor.
$.fn.serializeObject = function(){
var obj = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name,
v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
})(jQuery);
| JavaScript |
/*!
* jQuery Form Plugin
* version: 3.37.0-2013.07.11
* @requires jQuery v1.5 or later
* Copyright (c) 2013 M. Alsup
* Examples and documentation at: http://malsup.com/jquery/form/
* Project repository: https://github.com/malsup/form
* Dual licensed under the MIT and GPL licenses.
* https://github.com/malsup/form#copyright-and-license
*/
/*global ActiveXObject */
;(function($) {
"use strict";
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are mutually exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
form does not have to exist when you invoke ajaxForm:
$('#myForm').ajaxForm({
delegation: true,
target: '#output'
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* Feature detection
*/
var feature = {};
feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
feature.formdata = window.FormData !== undefined;
var hasProp = !!$.fn.prop;
// attr2 uses prop when it can but checks the return type for
// an expected string. this accounts for the case where a form
// contains inputs with names like "action" or "method"; in those
// cases "prop" returns the element
$.fn.attr2 = function() {
if ( ! hasProp )
return this.attr.apply(this, arguments);
var val = this.prop.apply(this, arguments);
if ( ( val && val.jquery ) || typeof val === 'string' )
return val;
return this.attr.apply(this, arguments);
};
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
/*jshint scripturl:true */
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
var method, action, url, $form = this;
if (typeof options == 'function') {
options = { success: options };
}
else if ( options === undefined ) {
options = {};
}
method = options.type || this.attr2('method');
action = options.url || this.attr2('action');
url = (typeof action === 'string') ? $.trim(action) : '';
url = url || window.location.href || '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/)||[])[1];
}
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: method || 'GET',
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var traditional = options.traditional;
if ( traditional === undefined ) {
traditional = $.ajaxSettings.traditional;
}
var elements = [];
var qx, a = this.formToArray(options.semantic, elements);
if (options.data) {
options.extraData = options.data;
qx = $.param(options.data, traditional);
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a, traditional);
if (qx) {
q = ( q ? (q + '&' + qx) : qx );
}
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}
var callbacks = [];
if (options.resetForm) {
callbacks.push(function() { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function() { $form.clearForm(options.includeHidden); });
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || this ; // jQuery 1.4+ supports scope context
for (var i=0, max=callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
if (options.error) {
var oldError = options.error;
options.error = function(xhr, status, error) {
var context = options.context || this;
oldError.apply(context, [xhr, status, error, $form]);
};
}
if (options.complete) {
var oldComplete = options.complete;
options.complete = function(xhr, status) {
var context = options.context || this;
oldComplete.apply(context, [xhr, status, $form]);
};
}
// are there files to upload?
// [value] (issue #113), also see comment:
// https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
var fileInputs = $('input[type=file]:enabled[value!=""]', this);
var hasFileInputs = fileInputs.length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
var fileAPI = feature.fileapi && feature.formdata;
log("fileAPI :" + fileAPI);
var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
var jqxhr;
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, function() {
jqxhr = fileUploadIframe(a);
});
}
else {
jqxhr = fileUploadIframe(a);
}
}
else if ((hasFileInputs || multipart) && fileAPI) {
jqxhr = fileUploadXhr(a);
}
else {
jqxhr = $.ajax(options);
}
$form.removeData('jqxhr').data('jqxhr', jqxhr);
// clear element array
for (var k=0; k < elements.length; k++)
elements[k] = null;
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// utility fn for deep serialization
function deepSerialize(extraData){
var serialized = $.param(extraData, options.traditional).split('&');
var len = serialized.length;
var result = [];
var i, part;
for (i=0; i < len; i++) {
// #252; undo param space replacement
serialized[i] = serialized[i].replace(/\+/g,' ');
part = serialized[i].split('=');
// #278; use array instead of object storage, favoring array serializations
result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
}
return result;
}
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i=0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}
if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (i=0; i < serializedData.length; i++)
if (serializedData[i])
formdata.append(serializedData[i][0], serializedData[i][1]);
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});
if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function() {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
}
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
o.data = formdata;
if(beforeSend)
beforeSend.call(this, xhr, o);
};
return $.ajax(s);
}
// private function for handling file uploads (hat tip to YAHOO!)
function fileUploadIframe(a) {
var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
var deferred = $.Deferred();
if (a) {
// ensure that every serialized input is still enabled
for (i=0; i < elements.length; i++) {
el = $(elements[i]);
if ( hasProp )
el.prop('disabled', false);
else
el.removeAttr('disabled');
}
}
s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
id = 'jqFormIO' + (new Date().getTime());
if (s.iframeTarget) {
$io = $(s.iframeTarget);
n = $io.attr2('name');
if (!n)
$io.attr2('name', id);
else
id = n;
}
else {
$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
}
io = $io[0];
xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function(status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
try { // #214, #257
if (io.contentWindow.document.execCommand) {
io.contentWindow.document.execCommand('Stop');
}
}
catch(ignore) {}
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
if (s.error)
s.error.call(s.context, xhr, e, status);
if (g)
$.event.trigger("ajaxError", [xhr, s, e]);
if (s.complete)
s.complete.call(s.context, xhr, e);
}
};
g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && 0 === $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
deferred.reject();
return deferred;
}
if (xhr.aborted) {
deferred.reject();
return deferred;
}
// add submitting element to data if we know it
sub = form.clk;
if (sub) {
n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n+'.x'] = form.clk_x;
s.extraData[n+'.y'] = form.clk_y;
}
}
}
var CLIENT_TIMEOUT_ABORT = 1;
var SERVER_ABORT = 2;
function getDoc(frame) {
/* it looks like contentWindow or contentDocument do not
* carry the protocol property in ie8, when running under ssl
* frame.document is the only valid response document, since
* the protocol is know but not on the other two objects. strange?
* "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
*/
var doc = null;
// IE8 cascading access check
try {
if (frame.contentWindow) {
doc = frame.contentWindow.document;
}
} catch(err) {
// IE8 access denied under ssl & missing protocol
log('cannot get iframe.contentWindow document: ' + err);
}
if (doc) { // successful getting content
return doc;
}
try { // simply checking may throw in ie8 under ssl or mismatched protocol
doc = frame.contentDocument ? frame.contentDocument : frame.document;
} catch(err) {
// last attempt
log('cannot get iframe.contentDocument: ' + err);
doc = frame.document;
}
return doc;
}
// Rails CSRF hack (thanks to Yvan Barthelemy)
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
if (csrf_param && csrf_token) {
s.extraData = s.extraData || {};
s.extraData[csrf_param] = csrf_token;
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr2('target'), a = $form.attr2('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
// if using the $.param format that allows for multiple values with the same name
if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
extraInputs.push(
$('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
.appendTo(form)[0]);
} else {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').val(s.extraData[n])
.appendTo(form)[0]);
}
}
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
if (io.attachEvent)
io.attachEvent('onload', cb);
else
io.addEventListener('load', cb, false);
}
setTimeout(checkState,15);
try {
form.submit();
} catch(err) {
// just in case form has element with name/id of 'submit'
var submitFn = document.createElement('form').submit;
submitFn.apply(form);
}
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
doc = getDoc(io);
if(!doc) {
log('cannot access response document');
e = SERVER_ABORT;
}
if (e === CLIENT_TIMEOUT_ABORT && xhr) {
xhr.abort('timeout');
deferred.reject(xhr, 'timeout');
return;
}
else if (e == SERVER_ABORT && xhr) {
xhr.abort('server abort');
deferred.reject(xhr, 'error', 'server abort');
return;
}
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut)
return;
}
if (io.detachEvent)
io.detachEvent('onload', cb);
else
io.removeEventListener('load', cb, false);
var status = 'success', errMsg;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
var docRoot = doc.body ? doc.body : doc.documentElement;
xhr.responseText = docRoot ? docRoot.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml)
s.dataType = 'xml';
xhr.getResponseHeader = function(header){
var headers = {'content-type': s.dataType};
return headers[header];
};
// support for XHR 'status' & 'statusText' emulation :
if (docRoot) {
xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
}
var dt = (s.dataType || '').toLowerCase();
var scr = /(json|script|text)/.test(dt);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
// support for XHR 'status' & 'statusText' emulation :
xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
}
else if (b) {
xhr.responseText = b.textContent ? b.textContent : b.innerText;
}
}
}
else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
xhr.responseXML = toXml(xhr.responseText);
}
try {
data = httpData(xhr, dt, s);
}
catch (err) {
status = 'parsererror';
xhr.error = errMsg = (err || status);
}
}
catch (err) {
log('error caught: ',err);
status = 'error';
xhr.error = errMsg = (err || status);
}
if (xhr.aborted) {
log('upload aborted');
status = null;
}
if (xhr.status) { // we've set xhr.status
status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (status === 'success') {
if (s.success)
s.success.call(s.context, data, 'success', xhr);
deferred.resolve(xhr.responseText, 'success', xhr);
if (g)
$.event.trigger("ajaxSuccess", [xhr, s]);
}
else if (status) {
if (errMsg === undefined)
errMsg = xhr.statusText;
if (s.error)
s.error.call(s.context, xhr, status, errMsg);
deferred.reject(xhr, 'error', errMsg);
if (g)
$.event.trigger("ajaxError", [xhr, s, errMsg]);
}
if (g)
$.event.trigger("ajaxComplete", [xhr, s]);
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
if (s.complete)
s.complete.call(s.context, xhr, status);
callbackProcessed = true;
if (s.timeout)
clearTimeout(timeoutHandle);
// clean up
setTimeout(function() {
if (!s.iframeTarget)
$io.remove();
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function(s) {
/*jslint evil:true */
return window['eval']('(' + s + ')');
};
var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
if ($.error)
$.error('parsererror');
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
return deferred;
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
options = options || {};
options.delegation = options.delegation && $.isFunction($.fn.on);
// in jQuery 1.3+ we can fix mistakes with the ready state
if (!options.delegation && this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s,o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
if ( options.delegation ) {
$(document)
.off('submit.form-plugin', this.selector, doAjaxSubmit)
.off('click.form-plugin', this.selector, captureSubmittingElement)
.on('submit.form-plugin', this.selector, options, doAjaxSubmit)
.on('click.form-plugin', this.selector, options, captureSubmittingElement);
return this;
}
return this.ajaxFormUnbind()
.bind('submit.form-plugin', options, doAjaxSubmit)
.bind('click.form-plugin', options, captureSubmittingElement);
};
// private event handlers
function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}
function captureSubmittingElement(e) {
/*jshint validthis:true */
var target = e.target;
var $el = $(target);
if (!($el.is("[type=submit],[type=image]"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest('[type=submit]');
if (t.length === 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX !== undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') {
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
}
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic, elements) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i,j,n,v,el,max,jmax;
for(i=0, max=els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n || el.disabled) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(form.clk == el) {
a.push({name: n, value: $(el).val(), type: el.type });
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
if (elements)
elements.push(el);
for(j=0, jmax=v.length; j < jmax; j++) {
a.push({name: n, value: v[j]});
}
}
else if (feature.fileapi && el.type == 'file') {
if (elements)
elements.push(el);
var files = el.files;
if (files.length) {
for (j=0; j < files.length; j++) {
a.push({name: n, value: files[j], type: el.type});
}
}
else {
// #180
a.push({ name: n, value: '', type: el.type });
}
}
else if (v !== null && typeof v != 'undefined') {
if (elements)
elements.push(el);
a.push({name: n, value: v, type: el.type, required: el.required});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++) {
a.push({name: n, value: v[i]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: this.name, value: v});
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $('input[type=text]').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $('input[type=checkbox]').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $('input[type=radio]').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
if (v.constructor == Array)
$.merge(val, v);
else
val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
$('input,select,textarea', this).clearFields(includeHidden);
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
else if (t == "file") {
if (/MSIE/.test(navigator.userAgent)) {
$(this).replaceWith($(this).clone(true));
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden can be the value true, or it can be a selector string
// indicating a special test; for example:
// $('#myForm').clearForm('.special:hidden')
// the above would clean hidden inputs that have the class of 'special'
if ( (includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden)) )
this.value = '';
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// expose debug var
$.fn.ajaxSubmit.debug = false;
// helper fn for console logging
function log() {
if (!$.fn.ajaxSubmit.debug)
return;
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
})(jQuery);
| JavaScript |
/******************************************************************************************************************************
* @ Original idea by by Binny V A, Original version: 2.00.A
* @ http://www.openjs.com/scripts/events/keyboard_shortcuts/
* @ Original License : BSD
* @ jQuery Plugin by Tzury Bar Yochay
mail: tzury.by@gmail.com
blog: evalinux.wordpress.com
face: facebook.com/profile.php?id=513676303
(c) Copyrights 2007
* @ jQuery Plugin version Beta (0.0.2)
* @ License: jQuery-License.
TODO:
add queue support (as in gmail) e.g. 'x' then 'y', etc.
add mouse + mouse wheel events.
USAGE:
$.hotkeys.add('Ctrl+c', function(){ alert('copy anyone?');});
$.hotkeys.add('Ctrl+c', {target:'div#editor', type:'keyup', propagate: true},function(){ alert('copy anyone?');});>
$.hotkeys.remove('Ctrl+c');
$.hotkeys.remove('Ctrl+c', {target:'div#editor', type:'keypress'});
******************************************************************************************************************************/
(function (jQuery){
this.version = '(beta)(0.0.3)';
this.all = {};
this.special_keys = {
27: 'esc', 9: 'tab', 32:'space', 13: 'return', 8:'backspace', 145: 'scroll', 20: 'capslock',
144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',35:'end', 33: 'pageup',
34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down', 112:'f1',113:'f2', 114:'f3',
115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12'};
this.shift_nums = { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&",
"8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<",
".":">", "/":"?", "\\":"|" };
this.add = function(combi, options, callback) {
if (jQuery.isFunction(options)){
callback = options;
options = {};
}
var opt = {},
defaults = {type: 'keydown', propagate: false, disableInInput: false, target: jQuery('html')[0]},
that = this;
opt = jQuery.extend( opt , defaults, options || {} );
combi = combi.toLowerCase();
// inspect if keystroke matches
var inspector = function(event) {
// WP: not needed with newer jQuery
// event = jQuery.event.fix(event); // jQuery event normalization.
var element = event.target;
// @ TextNode -> nodeType == 3
// WP: not needed with newer jQuery
// element = (element.nodeType==3) ? element.parentNode : element;
if ( opt['disableInInput'] ) { // Disable shortcut keys in Input, Textarea fields
var target = jQuery(element);
if ( ( target.is('input') || target.is('textarea') ) &&
( ! opt.noDisable || ! target.is( opt.noDisable ) ) ) {
return;
}
}
var code = event.which,
type = event.type,
character = String.fromCharCode(code).toLowerCase(),
special = that.special_keys[code],
shift = event.shiftKey,
ctrl = event.ctrlKey,
alt= event.altKey,
meta = event.metaKey,
propagate = true, // default behaivour
mapPoint = null;
// in opera + safari, the event.target is unpredictable.
// for example: 'keydown' might be associated with HtmlBodyElement
// or the element where you last clicked with your mouse.
// WP: needed for all browsers
// if (jQuery.browser.opera || jQuery.browser.safari){
while (!that.all[element] && element.parentNode){
element = element.parentNode;
}
// }
var cbMap = that.all[element].events[type].callbackMap;
if(!shift && !ctrl && !alt && !meta) { // No Modifiers
mapPoint = cbMap[special] || cbMap[character]
}
// deals with combinaitons (alt|ctrl|shift+anything)
else{
var modif = '';
if(alt) modif +='alt+';
if(ctrl) modif+= 'ctrl+';
if(shift) modif += 'shift+';
if(meta) modif += 'meta+';
// modifiers + special keys or modifiers + characters or modifiers + shift characters
mapPoint = cbMap[modif+special] || cbMap[modif+character] || cbMap[modif+that.shift_nums[character]]
}
if (mapPoint){
mapPoint.cb(event);
if(!mapPoint.propagate) {
event.stopPropagation();
event.preventDefault();
return false;
}
}
};
// first hook for this element
if (!this.all[opt.target]){
this.all[opt.target] = {events:{}};
}
if (!this.all[opt.target].events[opt.type]){
this.all[opt.target].events[opt.type] = {callbackMap: {}}
jQuery.event.add(opt.target, opt.type, inspector);
}
this.all[opt.target].events[opt.type].callbackMap[combi] = {cb: callback, propagate:opt.propagate};
return jQuery;
};
this.remove = function(exp, opt) {
opt = opt || {};
target = opt.target || jQuery('html')[0];
type = opt.type || 'keydown';
exp = exp.toLowerCase();
delete this.all[target].events[type].callbackMap[exp]
return jQuery;
};
jQuery.hotkeys = this;
return jQuery;
})(jQuery);
| JavaScript |
/* global _wpMediaViewsL10n, _wpmejsSettings, MediaElementPlayer */
(function($, _, Backbone) {
var media = wp.media,
baseSettings = {},
l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n;
if ( ! _.isUndefined( window._wpmejsSettings ) ) {
baseSettings.pluginPath = _wpmejsSettings.pluginPath;
}
/**
* @mixin
*/
wp.media.mixin = {
mejsSettings: baseSettings,
/**
* Pauses every instance of MediaElementPlayer
*/
pauseAllPlayers: function() {
var p;
if ( window.mejs && window.mejs.players ) {
for ( p in window.mejs.players ) {
window.mejs.players[p].pause();
}
}
},
/**
* Utility to identify the user's browser
*/
ua: {
is : function( browser ) {
var passes = false, ua = window.navigator.userAgent;
switch ( browser ) {
case 'oldie':
passes = ua.match(/MSIE [6-8]/gi) !== null;
break;
case 'ie':
passes = ua.match(/MSIE/gi) !== null;
break;
case 'ff':
passes = ua.match(/firefox/gi) !== null;
break;
case 'opera':
passes = ua.match(/OPR/) !== null;
break;
case 'safari':
passes = ua.match(/safari/gi) !== null && ua.match(/chrome/gi) === null;
break;
case 'chrome':
passes = ua.match(/safari/gi) !== null && ua.match(/chrome/gi) !== null;
break;
}
return passes;
}
},
/**
* Specify compatibility for native playback by browser
*/
compat :{
'opera' : {
audio: ['ogg', 'wav'],
video: ['ogg', 'webm']
},
'chrome' : {
audio: ['ogg', 'mpeg'],
video: ['ogg', 'webm', 'mp4', 'm4v', 'mpeg']
},
'ff' : {
audio: ['ogg', 'mpeg'],
video: ['ogg', 'webm']
},
'safari' : {
audio: ['mpeg', 'wav'],
video: ['mp4', 'm4v', 'mpeg', 'x-ms-wmv', 'quicktime']
},
'ie' : {
audio: ['mpeg'],
video: ['mp4', 'm4v', 'mpeg']
}
},
/**
* Determine if the passed media contains a <source> that provides
* native playback in the user's browser
*
* @param {jQuery} media
* @returns {Boolean}
*/
isCompatible: function( media ) {
if ( ! media.find( 'source' ).length ) {
return false;
}
var ua = this.ua, test = false, found = false, sources;
if ( ua.is( 'oldIE' ) ) {
return false;
}
sources = media.find( 'source' );
_.find( this.compat, function( supports, browser ) {
if ( ua.is( browser ) ) {
found = true;
_.each( sources, function( elem ) {
var audio = new RegExp( 'audio\/(' + supports.audio.join('|') + ')', 'gi' ),
video = new RegExp( 'video\/(' + supports.video.join('|') + ')', 'gi' );
if ( elem.type.match( video ) !== null || elem.type.match( audio ) !== null ) {
test = true;
}
} );
}
return test || found;
} );
return test;
},
/**
* Override the MediaElement method for removing a player.
* MediaElement tries to pull the audio/video tag out of
* its container and re-add it to the DOM.
*/
removePlayer: function(t) {
var featureIndex, feature;
// invoke features cleanup
for ( featureIndex in t.options.features ) {
feature = t.options.features[featureIndex];
if ( t['clean' + feature] ) {
try {
t['clean' + feature](t);
} catch (e) {}
}
}
if ( ! t.isDynamic ) {
t.$node.remove();
}
if ( 'native' !== t.media.pluginType ) {
t.media.remove();
}
delete window.mejs.players[t.id];
t.container.remove();
t.globalUnbind();
delete t.node.player;
},
/**
* Allows any class that has set 'player' to a MediaElementPlayer
* instance to remove the player when listening to events.
*
* Examples: modal closes, shortcode properties are removed, etc.
*/
unsetPlayer : function() {
if ( this.player ) {
wp.media.mixin.pauseAllPlayers();
wp.media.mixin.removePlayer( this.player );
this.player = false;
}
}
};
/**
* Autowire "collection"-type shortcodes
*/
wp.media.playlist = new wp.media.collection({
tag: 'playlist',
editTitle : l10n.editPlaylistTitle,
defaults : {
id: wp.media.view.settings.post.id,
style: 'light',
tracklist: true,
tracknumbers: true,
images: true,
artists: true,
type: 'audio'
}
});
/**
* Shortcode modeling for audio
* `edit()` prepares the shortcode for the media modal
* `shortcode()` builds the new shortcode after update
*
* @namespace
*/
wp.media.audio = {
coerce : wp.media.coerce,
defaults : {
id : wp.media.view.settings.post.id,
src : '',
loop : false,
autoplay : false,
preload : 'none',
width : 400
},
edit : function( data ) {
var frame, shortcode = wp.shortcode.next( 'audio', data ).shortcode;
frame = wp.media({
frame: 'audio',
state: 'audio-details',
metadata: _.defaults( shortcode.attrs.named, this.defaults )
});
return frame;
},
shortcode : function( model ) {
var self = this, content;
_.each( this.defaults, function( value, key ) {
model[ key ] = self.coerce( model, key );
if ( value === model[ key ] ) {
delete model[ key ];
}
});
content = model.content;
delete model.content;
return new wp.shortcode({
tag: 'audio',
attrs: model,
content: content
});
}
};
/**
* Shortcode modeling for video
* `edit()` prepares the shortcode for the media modal
* `shortcode()` builds the new shortcode after update
*
* @namespace
*/
wp.media.video = {
coerce : wp.media.coerce,
defaults : {
id : wp.media.view.settings.post.id,
src : '',
poster : '',
loop : false,
autoplay : false,
preload : 'metadata',
content : '',
width : 640,
height : 360
},
edit : function( data ) {
var frame,
shortcode = wp.shortcode.next( 'video', data ).shortcode,
attrs;
attrs = shortcode.attrs.named;
attrs.content = shortcode.content;
frame = wp.media({
frame: 'video',
state: 'video-details',
metadata: _.defaults( attrs, this.defaults )
});
return frame;
},
shortcode : function( model ) {
var self = this, content;
_.each( this.defaults, function( value, key ) {
model[ key ] = self.coerce( model, key );
if ( value === model[ key ] ) {
delete model[ key ];
}
});
content = model.content;
delete model.content;
return new wp.shortcode({
tag: 'video',
attrs: model,
content: content
});
}
};
/**
* Shared model class for audio and video. Updates the model after
* "Add Audio|Video Source" and "Replace Audio|Video" states return
*
* @constructor
* @augments Backbone.Model
*/
media.model.PostMedia = Backbone.Model.extend({
initialize: function() {
this.attachment = false;
},
setSource: function( attachment ) {
this.attachment = attachment;
this.extension = attachment.get( 'filename' ).split('.').pop();
if ( this.get( 'src' ) && this.extension === this.get( 'src' ).split('.').pop() ) {
this.unset( 'src' );
}
if ( _.contains( wp.media.view.settings.embedExts, this.extension ) ) {
this.set( this.extension, this.attachment.get( 'url' ) );
} else {
this.unset( this.extension );
}
},
changeAttachment: function( attachment ) {
var self = this;
this.setSource( attachment );
this.unset( 'src' );
_.each( _.without( wp.media.view.settings.embedExts, this.extension ), function( ext ) {
self.unset( ext );
} );
}
});
/**
* The controller for the Audio Details state
*
* @constructor
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.AudioDetails = media.controller.State.extend({
defaults: {
id: 'audio-details',
toolbar: 'audio-details',
title: l10n.audioDetailsTitle,
content: 'audio-details',
menu: 'audio-details',
router: false,
priority: 60
},
initialize: function( options ) {
this.media = options.media;
media.controller.State.prototype.initialize.apply( this, arguments );
}
});
/**
* The controller for the Video Details state
*
* @constructor
* @augments wp.media.controller.State
* @augments Backbone.Model
*/
media.controller.VideoDetails = media.controller.State.extend({
defaults: {
id: 'video-details',
toolbar: 'video-details',
title: l10n.videoDetailsTitle,
content: 'video-details',
menu: 'video-details',
router: false,
priority: 60
},
initialize: function( options ) {
this.media = options.media;
media.controller.State.prototype.initialize.apply( this, arguments );
}
});
/**
* wp.media.view.MediaFrame.MediaDetails
*
* @constructor
* @augments wp.media.view.MediaFrame.Select
* @augments wp.media.view.MediaFrame
* @augments wp.media.view.Frame
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
* @mixes wp.media.controller.StateMachine
*/
media.view.MediaFrame.MediaDetails = media.view.MediaFrame.Select.extend({
defaults: {
id: 'media',
url: '',
menu: 'media-details',
content: 'media-details',
toolbar: 'media-details',
type: 'link',
priority: 120
},
initialize: function( options ) {
this.DetailsView = options.DetailsView;
this.cancelText = options.cancelText;
this.addText = options.addText;
this.media = new media.model.PostMedia( options.metadata );
this.options.selection = new media.model.Selection( this.media.attachment, { multiple: false } );
media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
},
bindHandlers: function() {
var menu = this.defaults.menu;
media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
this.on( 'menu:create:' + menu, this.createMenu, this );
this.on( 'content:render:' + menu, this.renderDetailsContent, this );
this.on( 'menu:render:' + menu, this.renderMenu, this );
this.on( 'toolbar:render:' + menu, this.renderDetailsToolbar, this );
},
renderDetailsContent: function() {
var view = new this.DetailsView({
controller: this,
model: this.state().media,
attachment: this.state().media.attachment
}).render();
this.content.set( view );
},
renderMenu: function( view ) {
var lastState = this.lastState(),
previous = lastState && lastState.id,
frame = this;
view.set({
cancel: {
text: this.cancelText,
priority: 20,
click: function() {
if ( previous ) {
frame.setState( previous );
} else {
frame.close();
}
}
},
separateCancel: new media.View({
className: 'separator',
priority: 40
})
});
},
setPrimaryButton: function(text, handler) {
this.toolbar.set( new media.view.Toolbar({
controller: this,
items: {
button: {
style: 'primary',
text: text,
priority: 80,
click: function() {
var controller = this.controller;
handler.call( this, controller, controller.state() );
// Restore and reset the default state.
controller.setState( controller.options.state );
controller.reset();
}
}
}
}) );
},
renderDetailsToolbar: function() {
this.setPrimaryButton( l10n.update, function( controller, state ) {
controller.close();
state.trigger( 'update', controller.media.toJSON() );
} );
},
renderReplaceToolbar: function() {
this.setPrimaryButton( l10n.replace, function( controller, state ) {
var attachment = state.get( 'selection' ).single();
controller.media.changeAttachment( attachment );
state.trigger( 'replace', controller.media.toJSON() );
} );
},
renderAddSourceToolbar: function() {
this.setPrimaryButton( this.addText, function( controller, state ) {
var attachment = state.get( 'selection' ).single();
controller.media.setSource( attachment );
state.trigger( 'add-source', controller.media.toJSON() );
} );
}
});
/**
* wp.media.view.MediaFrame.AudioDetails
*
* @constructor
* @augments wp.media.view.MediaFrame.MediaDetails
* @augments wp.media.view.MediaFrame.Select
* @augments wp.media.view.MediaFrame
* @augments wp.media.view.Frame
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
* @mixes wp.media.controller.StateMachine
*/
media.view.MediaFrame.AudioDetails = media.view.MediaFrame.MediaDetails.extend({
defaults: {
id: 'audio',
url: '',
menu: 'audio-details',
content: 'audio-details',
toolbar: 'audio-details',
type: 'link',
title: l10n.audioDetailsTitle,
priority: 120
},
initialize: function( options ) {
options.DetailsView = media.view.AudioDetails;
options.cancelText = l10n.audioDetailsCancel;
options.addText = l10n.audioAddSourceTitle;
media.view.MediaFrame.MediaDetails.prototype.initialize.call( this, options );
},
bindHandlers: function() {
media.view.MediaFrame.MediaDetails.prototype.bindHandlers.apply( this, arguments );
this.on( 'toolbar:render:replace-audio', this.renderReplaceToolbar, this );
this.on( 'toolbar:render:add-audio-source', this.renderAddSourceToolbar, this );
},
createStates: function() {
this.states.add([
new media.controller.AudioDetails( {
media: this.media
} ),
new media.controller.MediaLibrary( {
type: 'audio',
id: 'replace-audio',
title: l10n.audioReplaceTitle,
toolbar: 'replace-audio',
media: this.media,
menu: 'audio-details'
} ),
new media.controller.MediaLibrary( {
type: 'audio',
id: 'add-audio-source',
title: l10n.audioAddSourceTitle,
toolbar: 'add-audio-source',
media: this.media,
menu: false
} )
]);
}
});
/**
* wp.media.view.MediaFrame.VideoDetails
*
* @constructor
* @augments wp.media.view.MediaFrame.MediaDetails
* @augments wp.media.view.MediaFrame.Select
* @augments wp.media.view.MediaFrame
* @augments wp.media.view.Frame
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
* @mixes wp.media.controller.StateMachine
*/
media.view.MediaFrame.VideoDetails = media.view.MediaFrame.MediaDetails.extend({
defaults: {
id: 'video',
url: '',
menu: 'video-details',
content: 'video-details',
toolbar: 'video-details',
type: 'link',
title: l10n.videoDetailsTitle,
priority: 120
},
initialize: function( options ) {
options.DetailsView = media.view.VideoDetails;
options.cancelText = l10n.videoDetailsCancel;
options.addText = l10n.videoAddSourceTitle;
media.view.MediaFrame.MediaDetails.prototype.initialize.call( this, options );
},
bindHandlers: function() {
media.view.MediaFrame.MediaDetails.prototype.bindHandlers.apply( this, arguments );
this.on( 'toolbar:render:replace-video', this.renderReplaceToolbar, this );
this.on( 'toolbar:render:add-video-source', this.renderAddSourceToolbar, this );
this.on( 'toolbar:render:select-poster-image', this.renderSelectPosterImageToolbar, this );
this.on( 'toolbar:render:add-track', this.renderAddTrackToolbar, this );
},
createStates: function() {
this.states.add([
new media.controller.VideoDetails({
media: this.media
}),
new media.controller.MediaLibrary( {
type: 'video',
id: 'replace-video',
title: l10n.videoReplaceTitle,
toolbar: 'replace-video',
media: this.media,
menu: 'video-details'
} ),
new media.controller.MediaLibrary( {
type: 'video',
id: 'add-video-source',
title: l10n.videoAddSourceTitle,
toolbar: 'add-video-source',
media: this.media,
menu: false
} ),
new media.controller.MediaLibrary( {
type: 'image',
id: 'select-poster-image',
title: l10n.videoSelectPosterImageTitle,
toolbar: 'select-poster-image',
media: this.media,
menu: 'video-details'
} ),
new media.controller.MediaLibrary( {
type: 'text',
id: 'add-track',
title: l10n.videoAddTrackTitle,
toolbar: 'add-track',
media: this.media,
menu: 'video-details'
} )
]);
},
renderSelectPosterImageToolbar: function() {
this.setPrimaryButton( l10n.videoSelectPosterImageTitle, function( controller, state ) {
var attachment = state.get( 'selection' ).single();
controller.media.set( 'poster', attachment.get( 'url' ) );
state.trigger( 'set-poster-image', controller.media.toJSON() );
} );
},
renderAddTrackToolbar: function() {
this.setPrimaryButton( l10n.videoAddTrackTitle, function( controller, state ) {
var attachment = state.get( 'selection' ).single(),
content = controller.media.get( 'content' );
if ( -1 === content.indexOf( attachment.get( 'url' ) ) ) {
content += [
'<track srclang="en" label="English"kind="subtitles" src="',
attachment.get( 'url' ),
'" />'
].join('');
controller.media.set( 'content', content );
}
state.trigger( 'add-track', controller.media.toJSON() );
} );
}
});
/**
* wp.media.view.MediaDetails
*
* @contructor
* @augments wp.media.view.Settings.AttachmentDisplay
* @augments wp.media.view.Settings
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.MediaDetails = media.view.Settings.AttachmentDisplay.extend({
initialize: function() {
_.bindAll(this, 'success');
this.listenTo( this.controller, 'close', media.mixin.unsetPlayer );
this.on( 'ready', this.setPlayer );
this.on( 'media:setting:remove', media.mixin.unsetPlayer, this );
this.on( 'media:setting:remove', this.render );
this.on( 'media:setting:remove', this.setPlayer );
this.events = _.extend( this.events, {
'click .remove-setting' : 'removeSetting',
'change .content-track' : 'setTracks',
'click .remove-track' : 'setTracks'
} );
media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
},
prepare: function() {
return _.defaults({
model: this.model.toJSON()
}, this.options );
},
/**
* Remove a setting's UI when the model unsets it
*
* @fires wp.media.view.MediaDetails#media:setting:remove
*
* @param {Event} e
*/
removeSetting : function(e) {
var wrap = $( e.currentTarget ).parent(), setting;
setting = wrap.find( 'input' ).data( 'setting' );
if ( setting ) {
this.model.unset( setting );
this.trigger( 'media:setting:remove', this );
}
wrap.remove();
},
/**
*
* @fires wp.media.view.MediaDetails#media:setting:remove
*/
setTracks : function() {
var tracks = '';
_.each( this.$('.content-track'), function(track) {
tracks += $( track ).val();
} );
this.model.set( 'content', tracks );
this.trigger( 'media:setting:remove', this );
},
/**
* @global MediaElementPlayer
*/
setPlayer : function() {
if ( ! this.player && this.media ) {
this.player = new MediaElementPlayer( this.media, this.settings );
}
},
/**
* @abstract
*/
setMedia : function() {
return this;
},
success : function(mejs) {
var autoplay = mejs.attributes.autoplay && 'false' !== mejs.attributes.autoplay;
if ( 'flash' === mejs.pluginType && autoplay ) {
mejs.addEventListener( 'canplay', function() {
mejs.play();
}, false );
}
this.mejs = mejs;
},
/**
* @returns {media.view.MediaDetails} Returns itself to allow chaining
*/
render: function() {
var self = this;
media.view.Settings.AttachmentDisplay.prototype.render.apply( this, arguments );
setTimeout( function() { self.resetFocus(); }, 10 );
this.settings = _.defaults( {
success : this.success
}, baseSettings );
return this.setMedia();
},
resetFocus: function() {
this.$( '.embed-media-settings' ).scrollTop( 0 );
}
}, {
instances : 0,
/**
* When multiple players in the DOM contain the same src, things get weird.
*
* @param {HTMLElement} elem
* @returns {HTMLElement}
*/
prepareSrc : function( elem ) {
var i = media.view.MediaDetails.instances++;
_.each( $( elem ).find( 'source' ), function( source ) {
source.src = [
source.src,
source.src.indexOf('?') > -1 ? '&' : '?',
'_=',
i
].join('');
} );
return elem;
}
});
/**
* wp.media.view.AudioDetails
*
* @contructor
* @augments wp.media.view.MediaDetails
* @augments wp.media.view.Settings.AttachmentDisplay
* @augments wp.media.view.Settings
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.AudioDetails = media.view.MediaDetails.extend({
className: 'audio-details',
template: media.template('audio-details'),
setMedia: function() {
var audio = this.$('.wp-audio-shortcode');
if ( audio.find( 'source' ).length ) {
if ( audio.is(':hidden') ) {
audio.show();
}
this.media = media.view.MediaDetails.prepareSrc( audio.get(0) );
} else {
audio.hide();
this.media = false;
}
return this;
}
});
/**
* wp.media.view.VideoDetails
*
* @contructor
* @augments wp.media.view.MediaDetails
* @augments wp.media.view.Settings.AttachmentDisplay
* @augments wp.media.view.Settings
* @augments wp.media.View
* @augments wp.Backbone.View
* @augments Backbone.View
*/
media.view.VideoDetails = media.view.MediaDetails.extend({
className: 'video-details',
template: media.template('video-details'),
setMedia: function() {
var video = this.$('.wp-video-shortcode');
if ( video.find( 'source' ).length ) {
if ( video.is(':hidden') ) {
video.show();
}
if ( ! video.hasClass('youtube-video') ) {
this.media = media.view.MediaDetails.prepareSrc( video.get(0) );
} else {
this.media = video.get(0);
}
} else {
video.hide();
this.media = false;
}
return this;
}
});
/**
* Event binding
*/
function init() {
$(document.body)
.on( 'click', '.wp-switch-editor', wp.media.mixin.pauseAllPlayers )
.on( 'click', '.add-media-source', function( e ) {
media.frame.lastMime = $( e.currentTarget ).data( 'mime' );
media.frame.setState( 'add-' + media.frame.defaults.id + '-source' );
} );
}
$( init );
}(jQuery, _, Backbone));
| JavaScript |
/**
* mctabs.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*jshint globals: tinyMCEPopup */
function MCTabs() {
this.settings = [];
this.onChange = tinyMCEPopup.editor.windowManager.createInstance('tinymce.util.Dispatcher');
};
MCTabs.prototype.init = function(settings) {
this.settings = settings;
};
MCTabs.prototype.getParam = function(name, default_value) {
var value = null;
value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name];
// Fix bool values
if (value == "true" || value == "false")
return (value == "true");
return value;
};
MCTabs.prototype.showTab =function(tab){
tab.className = 'current';
tab.setAttribute("aria-selected", true);
tab.setAttribute("aria-expanded", true);
tab.tabIndex = 0;
};
MCTabs.prototype.hideTab =function(tab){
var t=this;
tab.className = '';
tab.setAttribute("aria-selected", false);
tab.setAttribute("aria-expanded", false);
tab.tabIndex = -1;
};
MCTabs.prototype.showPanel = function(panel) {
panel.className = 'current';
panel.setAttribute("aria-hidden", false);
};
MCTabs.prototype.hidePanel = function(panel) {
panel.className = 'panel';
panel.setAttribute("aria-hidden", true);
};
MCTabs.prototype.getPanelForTab = function(tabElm) {
return tinyMCEPopup.dom.getAttrib(tabElm, "aria-controls");
};
MCTabs.prototype.displayTab = function(tab_id, panel_id, avoid_focus) {
var panelElm, panelContainerElm, tabElm, tabContainerElm, selectionClass, nodes, i, t = this;
tabElm = document.getElementById(tab_id);
if (panel_id === undefined) {
panel_id = t.getPanelForTab(tabElm);
}
panelElm= document.getElementById(panel_id);
panelContainerElm = panelElm ? panelElm.parentNode : null;
tabContainerElm = tabElm ? tabElm.parentNode : null;
selectionClass = t.getParam('selection_class', 'current');
if (tabElm && tabContainerElm) {
nodes = tabContainerElm.childNodes;
// Hide all other tabs
for (i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "LI") {
t.hideTab(nodes[i]);
}
}
// Show selected tab
t.showTab(tabElm);
}
if (panelElm && panelContainerElm) {
nodes = panelContainerElm.childNodes;
// Hide all other panels
for (i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "DIV")
t.hidePanel(nodes[i]);
}
if (!avoid_focus) {
tabElm.focus();
}
// Show selected panel
t.showPanel(panelElm);
}
};
MCTabs.prototype.getAnchor = function() {
var pos, url = document.location.href;
if ((pos = url.lastIndexOf('#')) != -1)
return url.substring(pos + 1);
return "";
};
//Global instance
var mcTabs = new MCTabs();
tinyMCEPopup.onInit.add(function() {
var tinymce = tinyMCEPopup.getWin().tinymce, dom = tinyMCEPopup.dom, each = tinymce.each;
each(dom.select('div.tabs'), function(tabContainerElm) {
//var keyNav;
dom.setAttrib(tabContainerElm, "role", "tablist");
var items = tinyMCEPopup.dom.select('li', tabContainerElm);
var action = function(id) {
mcTabs.displayTab(id, mcTabs.getPanelForTab(id));
mcTabs.onChange.dispatch(id);
};
each(items, function(item) {
dom.setAttrib(item, 'role', 'tab');
dom.bind(item, 'click', function(evt) {
action(item.id);
});
});
dom.bind(dom.getRoot(), 'keydown', function(evt) {
if (evt.keyCode === 9 && evt.ctrlKey && !evt.altKey) { // Tab
//keyNav.moveFocus(evt.shiftKey ? -1 : 1);
tinymce.dom.Event.cancel(evt);
}
});
each(dom.select('a', tabContainerElm), function(a) {
dom.setAttrib(a, 'tabindex', '-1');
});
/*keyNav = tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', {
root: tabContainerElm,
items: items,
onAction: action,
actOnFocus: true,
enableLeftRight: true,
enableUpDown: true
}, tinyMCEPopup.dom);*/
});
}); | JavaScript |
/**
* validate.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
// String validation:
if (!Validator.isEmail('myemail'))
alert('Invalid email.');
// Form validation:
var f = document.forms['myform'];
if (!Validator.isEmail(f.myemail))
alert('Invalid email.');
*/
var Validator = {
isEmail : function(s) {
return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$');
},
isAbsUrl : function(s) {
return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$');
},
isSize : function(s) {
return this.test(s, '^[0-9.]+(%|in|cm|mm|em|ex|pt|pc|px)?$');
},
isId : function(s) {
return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$');
},
isEmpty : function(s) {
var nl, i;
if (s.nodeName == 'SELECT' && s.selectedIndex < 1)
return true;
if (s.type == 'checkbox' && !s.checked)
return true;
if (s.type == 'radio') {
for (i=0, nl = s.form.elements; i<nl.length; i++) {
if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked)
return false;
}
return true;
}
return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s);
},
isNumber : function(s, d) {
return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$'));
},
test : function(s, p) {
s = s.nodeType == 1 ? s.value : s;
return s == '' || new RegExp(p).test(s);
}
};
var AutoValidator = {
settings : {
id_cls : 'id',
int_cls : 'int',
url_cls : 'url',
number_cls : 'number',
email_cls : 'email',
size_cls : 'size',
required_cls : 'required',
invalid_cls : 'invalid',
min_cls : 'min',
max_cls : 'max'
},
init : function(s) {
var n;
for (n in s)
this.settings[n] = s[n];
},
validate : function(f) {
var i, nl, s = this.settings, c = 0;
nl = this.tags(f, 'label');
for (i=0; i<nl.length; i++) {
this.removeClass(nl[i], s.invalid_cls);
nl[i].setAttribute('aria-invalid', false);
}
c += this.validateElms(f, 'input');
c += this.validateElms(f, 'select');
c += this.validateElms(f, 'textarea');
return c == 3;
},
invalidate : function(n) {
this.mark(n.form, n);
},
getErrorMessages : function(f) {
var nl, i, s = this.settings, field, msg, values, messages = [], ed = tinyMCEPopup.editor;
nl = this.tags(f, "label");
for (i=0; i<nl.length; i++) {
if (this.hasClass(nl[i], s.invalid_cls)) {
field = document.getElementById(nl[i].getAttribute("for"));
values = { field: nl[i].textContent };
if (this.hasClass(field, s.min_cls, true)) {
message = ed.getLang('invalid_data_min');
values.min = this.getNum(field, s.min_cls);
} else if (this.hasClass(field, s.number_cls)) {
message = ed.getLang('invalid_data_number');
} else if (this.hasClass(field, s.size_cls)) {
message = ed.getLang('invalid_data_size');
} else {
message = ed.getLang('invalid_data');
}
message = message.replace(/{\#([^}]+)\}/g, function(a, b) {
return values[b] || '{#' + b + '}';
});
messages.push(message);
}
}
return messages;
},
reset : function(e) {
var t = ['label', 'input', 'select', 'textarea'];
var i, j, nl, s = this.settings;
if (e == null)
return;
for (i=0; i<t.length; i++) {
nl = this.tags(e.form ? e.form : e, t[i]);
for (j=0; j<nl.length; j++) {
this.removeClass(nl[j], s.invalid_cls);
nl[j].setAttribute('aria-invalid', false);
}
}
},
validateElms : function(f, e) {
var nl, i, n, s = this.settings, st = true, va = Validator, v;
nl = this.tags(f, e);
for (i=0; i<nl.length; i++) {
n = nl[i];
this.removeClass(n, s.invalid_cls);
if (this.hasClass(n, s.required_cls) && va.isEmpty(n))
st = this.mark(f, n);
if (this.hasClass(n, s.number_cls) && !va.isNumber(n))
st = this.mark(f, n);
if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true))
st = this.mark(f, n);
if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n))
st = this.mark(f, n);
if (this.hasClass(n, s.email_cls) && !va.isEmail(n))
st = this.mark(f, n);
if (this.hasClass(n, s.size_cls) && !va.isSize(n))
st = this.mark(f, n);
if (this.hasClass(n, s.id_cls) && !va.isId(n))
st = this.mark(f, n);
if (this.hasClass(n, s.min_cls, true)) {
v = this.getNum(n, s.min_cls);
if (isNaN(v) || parseInt(n.value) < parseInt(v))
st = this.mark(f, n);
}
if (this.hasClass(n, s.max_cls, true)) {
v = this.getNum(n, s.max_cls);
if (isNaN(v) || parseInt(n.value) > parseInt(v))
st = this.mark(f, n);
}
}
return st;
},
hasClass : function(n, c, d) {
return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className);
},
getNum : function(n, c) {
c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0];
c = c.replace(/[^0-9]/g, '');
return c;
},
addClass : function(n, c, b) {
var o = this.removeClass(n, c);
n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c;
},
removeClass : function(n, c) {
c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' ');
return n.className = c != ' ' ? c : '';
},
tags : function(f, s) {
return f.getElementsByTagName(s);
},
mark : function(f, n) {
var s = this.settings;
this.addClass(n, s.invalid_cls);
n.setAttribute('aria-invalid', 'true');
this.markLabels(f, n, s.invalid_cls);
return false;
},
markLabels : function(f, n, ic) {
var nl, i;
nl = this.tags(f, "label");
for (i=0; i<nl.length; i++) {
if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id)
this.addClass(nl[i], ic);
}
return null;
}
};
| JavaScript |
/**
* form_utils.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
var themeBaseURL = tinyMCEPopup.editor.baseURI.toAbsolute('themes/' + tinyMCEPopup.getParam("theme"));
function getColorPickerHTML(id, target_form_element) {
var h = "", dom = tinyMCEPopup.dom;
if (label = dom.select('label[for=' + target_form_element + ']')[0]) {
label.id = label.id || dom.uniqueId();
}
h += '<a role="button" aria-labelledby="' + id + '_label" id="' + id + '_link" href="javascript:;" onclick="tinyMCEPopup.pickColor(event,\'' + target_form_element +'\');" onmousedown="return false;" class="pickcolor">';
h += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '"> <span id="' + id + '_label" class="mceVoiceLabel mceIconOnly" style="display:none;">' + tinyMCEPopup.getLang('browse') + '</span></span></a>';
return h;
}
function updateColor(img_id, form_element_id) {
document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value;
}
function setBrowserDisabled(id, state) {
var img = document.getElementById(id);
var lnk = document.getElementById(id + "_link");
if (lnk) {
if (state) {
lnk.setAttribute("realhref", lnk.getAttribute("href"));
lnk.removeAttribute("href");
tinyMCEPopup.dom.addClass(img, 'disabled');
} else {
if (lnk.getAttribute("realhref"))
lnk.setAttribute("href", lnk.getAttribute("realhref"));
tinyMCEPopup.dom.removeClass(img, 'disabled');
}
}
}
function getBrowserHTML(id, target_form_element, type, prefix) {
var option = prefix + "_" + type + "_browser_callback", cb, html;
cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback"));
if (!cb)
return "";
html = "";
html += '<a id="' + id + '_link" href="javascript:openBrowser(\'' + id + '\',\'' + target_form_element + '\', \'' + type + '\',\'' + option + '\');" onmousedown="return false;" class="browse">';
html += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '"> </span></a>';
return html;
}
function openBrowser(img_id, target_form_element, type, option) {
var img = document.getElementById(img_id);
if (img.className != "mceButtonDisabled")
tinyMCEPopup.openBrowser(target_form_element, type, option);
}
function selectByValue(form_obj, field_name, value, add_custom, ignore_case) {
if (!form_obj || !form_obj.elements[field_name])
return;
if (!value)
value = "";
var sel = form_obj.elements[field_name];
var found = false;
for (var i=0; i<sel.options.length; i++) {
var option = sel.options[i];
if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) {
option.selected = true;
found = true;
} else
option.selected = false;
}
if (!found && add_custom && value != '') {
var option = new Option(value, value);
option.selected = true;
sel.options[sel.options.length] = option;
sel.selectedIndex = sel.options.length - 1;
}
return found;
}
function getSelectValue(form_obj, field_name) {
var elm = form_obj.elements[field_name];
if (elm == null || elm.options == null || elm.selectedIndex === -1)
return "";
return elm.options[elm.selectedIndex].value;
}
function addSelectValue(form_obj, field_name, name, value) {
var s = form_obj.elements[field_name];
var o = new Option(name, value);
s.options[s.options.length] = o;
}
function addClassesToList(list_id, specific_option) {
// Setup class droplist
var styleSelectElm = document.getElementById(list_id);
var styles = tinyMCEPopup.getParam('theme_advanced_styles', false);
styles = tinyMCEPopup.getParam(specific_option, styles);
if (styles) {
var stylesAr = styles.split(';');
for (var i=0; i<stylesAr.length; i++) {
if (stylesAr != "") {
var key, value;
key = stylesAr[i].split('=')[0];
value = stylesAr[i].split('=')[1];
styleSelectElm.options[styleSelectElm.length] = new Option(key, value);
}
}
} else {
/*tinymce.each(tinyMCEPopup.editor.dom.getClasses(), function(o) {
styleSelectElm.options[styleSelectElm.length] = new Option(o.title || o['class'], o['class']);
});*/
}
}
function isVisible(element_id) {
var elm = document.getElementById(element_id);
return elm && elm.style.display != "none";
}
function convertRGBToHex(col) {
var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
var rgb = col.replace(re, "$1,$2,$3").split(',');
if (rgb.length == 3) {
r = parseInt(rgb[0]).toString(16);
g = parseInt(rgb[1]).toString(16);
b = parseInt(rgb[2]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
return "#" + r + g + b;
}
return col;
}
function convertHexToRGB(col) {
if (col.indexOf('#') != -1) {
col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');
r = parseInt(col.substring(0, 2), 16);
g = parseInt(col.substring(2, 4), 16);
b = parseInt(col.substring(4, 6), 16);
return "rgb(" + r + "," + g + "," + b + ")";
}
return col;
}
function trimSize(size) {
return size.replace(/([0-9\.]+)(px|%|in|cm|mm|em|ex|pt|pc)/i, '$1$2');
}
function getCSSSize(size) {
size = trimSize(size);
if (size == "")
return "";
// Add px
if (/^[0-9]+$/.test(size))
size += 'px';
// Sanity check, IE doesn't like broken values
else if (!(/^[0-9\.]+(px|%|in|cm|mm|em|ex|pt|pc)$/i.test(size)))
return "";
return size;
}
function getStyle(elm, attrib, style) {
var val = tinyMCEPopup.dom.getAttrib(elm, attrib);
if (val != '')
return '' + val;
if (typeof(style) == 'undefined')
style = attrib;
return tinyMCEPopup.dom.getStyle(elm, style);
}
| JavaScript |
/**
* editable_selects.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
var TinyMCE_EditableSelects = {
editSelectElm : null,
init : function() {
var nl = document.getElementsByTagName("select"), i, d = document, o;
for (i=0; i<nl.length; i++) {
if (nl[i].className.indexOf('mceEditableSelect') != -1) {
o = new Option(tinyMCEPopup.editor.translate('value'), '__mce_add_custom__');
o.className = 'mceAddSelectValue';
nl[i].options[nl[i].options.length] = o;
nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect;
}
}
},
onChangeEditableSelect : function(e) {
var d = document, ne, se = window.event ? window.event.srcElement : e.target;
if (se.options[se.selectedIndex].value == '__mce_add_custom__') {
ne = d.createElement("input");
ne.id = se.id + "_custom";
ne.name = se.name + "_custom";
ne.type = "text";
ne.style.width = se.offsetWidth + 'px';
se.parentNode.insertBefore(ne, se);
se.style.display = 'none';
ne.focus();
ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput;
ne.onkeydown = TinyMCE_EditableSelects.onKeyDown;
TinyMCE_EditableSelects.editSelectElm = se;
}
},
onBlurEditableSelectInput : function() {
var se = TinyMCE_EditableSelects.editSelectElm;
if (se) {
if (se.previousSibling.value != '') {
addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value);
selectByValue(document.forms[0], se.id, se.previousSibling.value);
} else
selectByValue(document.forms[0], se.id, '');
se.style.display = 'inline';
se.parentNode.removeChild(se.previousSibling);
TinyMCE_EditableSelects.editSelectElm = null;
}
},
onKeyDown : function(e) {
e = e || window.event;
if (e.keyCode == 13)
TinyMCE_EditableSelects.onBlurEditableSelectInput();
}
};
| JavaScript |
/**
* theme.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.ThemeManager.add('modern', function(editor) {
var self = this, settings = editor.settings, Factory = tinymce.ui.Factory, each = tinymce.each, DOM = tinymce.DOM;
// Default menus
var defaultMenus = {
file: {title: 'File', items: 'newdocument'},
edit: {title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall'},
insert: {title: 'Insert', items: '|'},
view: {title: 'View', items: 'visualaid |'},
format: {title: 'Format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat'},
table: {title: 'Table'},
tools: {title: 'Tools'}
};
var defaultToolbar = "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | " +
"bullist numlist outdent indent | link image";
/**
* Creates the toolbars from config and returns a toolbar array.
*
* @return {Array} Array with toolbars.
*/
function createToolbars() {
var toolbars = [];
function addToolbar(items) {
var toolbarItems = [], buttonGroup;
if (!items) {
return;
}
each(items.split(/[ ,]/), function(item) {
var itemName;
function bindSelectorChanged() {
var selection = editor.selection;
if (itemName == "bullist") {
selection.selectorChanged('ul > li', function(state, args) {
var nodeName, i = args.parents.length;
while (i--) {
nodeName = args.parents[i].nodeName;
if (nodeName == "OL" || nodeName == "UL") {
break;
}
}
item.active(state && nodeName == "UL");
});
}
if (itemName == "numlist") {
selection.selectorChanged('ol > li', function(state, args) {
var nodeName, i = args.parents.length;
while (i--) {
nodeName = args.parents[i].nodeName;
if (nodeName == "OL" || nodeName == "UL") {
break;
}
}
item.active(state && nodeName == "OL");
});
}
if (item.settings.stateSelector) {
selection.selectorChanged(item.settings.stateSelector, function(state) {
item.active(state);
}, true);
}
if (item.settings.disabledStateSelector) {
selection.selectorChanged(item.settings.disabledStateSelector, function(state) {
item.disabled(state);
});
}
}
if (item == "|") {
buttonGroup = null;
} else {
if (Factory.has(item)) {
item = {type: item};
if (settings.toolbar_items_size) {
item.size = settings.toolbar_items_size;
}
toolbarItems.push(item);
buttonGroup = null;
} else {
if (!buttonGroup) {
buttonGroup = {type: 'buttongroup', items: []};
toolbarItems.push(buttonGroup);
}
if (editor.buttons[item]) {
// TODO: Move control creation to some UI class
itemName = item;
item = editor.buttons[itemName];
if (typeof(item) == "function") {
item = item();
}
item.type = item.type || 'button';
if (settings.toolbar_items_size) {
item.size = settings.toolbar_items_size;
}
item = Factory.create(item);
buttonGroup.items.push(item);
if (editor.initialized) {
bindSelectorChanged();
} else {
editor.on('init', bindSelectorChanged);
}
}
}
}
});
toolbars.push({type: 'toolbar', layout: 'flow', items: toolbarItems});
return true;
}
// Convert toolbar array to multiple options
if (tinymce.isArray(settings.toolbar)) {
// Empty toolbar array is the same as a disabled toolbar
if (settings.toolbar.length === 0) {
return;
}
tinymce.each(settings.toolbar, function(toolbar, i) {
settings["toolbar" + (i + 1)] = toolbar;
});
delete settings.toolbar;
}
// Generate toolbar<n>
for (var i = 1; i < 10; i++) {
if (!addToolbar(settings["toolbar" + i])) {
break;
}
}
// Generate toolbar or default toolbar unless it's disabled
if (!toolbars.length && settings.toolbar !== false) {
addToolbar(settings.toolbar || defaultToolbar);
}
if (toolbars.length) {
return {
type: 'panel',
layout: 'stack',
classes: "toolbar-grp",
ariaRoot: true,
ariaRemember: true,
items: toolbars
};
}
}
/**
* Creates the menu buttons based on config.
*
* @return {Array} Menu buttons array.
*/
function createMenuButtons() {
var name, menuButtons = [];
function createMenuItem(name) {
var menuItem;
if (name == '|') {
return {text: '|'};
}
menuItem = editor.menuItems[name];
return menuItem;
}
function createMenu(context) {
var menuButton, menu, menuItems, isUserDefined, removedMenuItems;
removedMenuItems = tinymce.makeMap((settings.removed_menuitems || '').split(/[ ,]/));
// User defined menu
if (settings.menu) {
menu = settings.menu[context];
isUserDefined = true;
} else {
menu = defaultMenus[context];
}
if (menu) {
menuButton = {text: menu.title};
menuItems = [];
// Default/user defined items
each((menu.items || '').split(/[ ,]/), function(item) {
var menuItem = createMenuItem(item);
if (menuItem && !removedMenuItems[item]) {
menuItems.push(createMenuItem(item));
}
});
// Added though context
if (!isUserDefined) {
each(editor.menuItems, function(menuItem) {
if (menuItem.context == context) {
if (menuItem.separator == 'before') {
menuItems.push({text: '|'});
}
if (menuItem.prependToContext) {
menuItems.unshift(menuItem);
} else {
menuItems.push(menuItem);
}
if (menuItem.separator == 'after') {
menuItems.push({text: '|'});
}
}
});
}
for (var i = 0; i < menuItems.length; i++) {
if (menuItems[i].text == '|') {
if (i === 0 || i == menuItems.length - 1) {
menuItems.splice(i, 1);
}
}
}
menuButton.menu = menuItems;
if (!menuButton.menu.length) {
return null;
}
}
return menuButton;
}
var defaultMenuBar = [];
if (settings.menu) {
for (name in settings.menu) {
defaultMenuBar.push(name);
}
} else {
for (name in defaultMenus) {
defaultMenuBar.push(name);
}
}
var enabledMenuNames = typeof(settings.menubar) == "string" ? settings.menubar.split(/[ ,]/) : defaultMenuBar;
for (var i = 0; i < enabledMenuNames.length; i++) {
var menu = enabledMenuNames[i];
menu = createMenu(menu);
if (menu) {
menuButtons.push(menu);
}
}
return menuButtons;
}
/**
* Adds accessibility shortcut keys to panel.
*
* @param {tinymce.ui.Panel} panel Panel to add focus to.
*/
function addAccessibilityKeys(panel) {
function focus(type) {
var item = panel.find(type)[0];
if (item) {
item.focus(true);
}
}
editor.shortcuts.add('Alt+F9', '', function() {
focus('menubar');
});
editor.shortcuts.add('Alt+F10', '', function() {
focus('toolbar');
});
editor.shortcuts.add('Alt+F11', '', function() {
focus('elementpath');
});
panel.on('cancel', function() {
editor.focus();
});
}
/**
* Resizes the editor to the specified width, height.
*/
function resizeTo(width, height) {
var containerElm, iframeElm, containerSize, iframeSize;
function getSize(elm) {
return {
width: elm.clientWidth,
height: elm.clientHeight
};
}
containerElm = editor.getContainer();
iframeElm = editor.getContentAreaContainer().firstChild;
containerSize = getSize(containerElm);
iframeSize = getSize(iframeElm);
if (width !== null) {
width = Math.max(settings.min_width || 100, width);
width = Math.min(settings.max_width || 0xFFFF, width);
DOM.css(containerElm, 'width', width + (containerSize.width - iframeSize.width));
DOM.css(iframeElm, 'width', width);
}
height = Math.max(settings.min_height || 100, height);
height = Math.min(settings.max_height || 0xFFFF, height);
DOM.css(iframeElm, 'height', height);
editor.fire('ResizeEditor');
}
function resizeBy(dw, dh) {
var elm = editor.getContentAreaContainer();
self.resizeTo(elm.clientWidth + dw, elm.clientHeight + dh);
}
/**
* Renders the inline editor UI.
*
* @return {Object} Name/value object with theme data.
*/
function renderInlineUI(args) {
var panel, inlineToolbarContainer;
if (settings.fixed_toolbar_container) {
inlineToolbarContainer = DOM.select(settings.fixed_toolbar_container)[0];
}
function reposition() {
if (panel && panel.moveRel && panel.visible() && !panel._fixed) {
// TODO: This is kind of ugly and doesn't handle multiple scrollable elements
var scrollContainer = editor.selection.getScrollContainer(), body = editor.getBody();
var deltaX = 0, deltaY = 0;
if (scrollContainer) {
var bodyPos = DOM.getPos(body), scrollContainerPos = DOM.getPos(scrollContainer);
deltaX = Math.max(0, scrollContainerPos.x - bodyPos.x);
deltaY = Math.max(0, scrollContainerPos.y - bodyPos.y);
}
panel.fixed(false).moveRel(body, editor.rtl ? ['tr-br', 'br-tr'] : ['tl-bl', 'bl-tl']).moveBy(deltaX, deltaY);
}
}
function show() {
if (panel) {
panel.show();
reposition();
DOM.addClass(editor.getBody(), 'mce-edit-focus');
}
}
function hide() {
if (panel) {
panel.hide();
DOM.removeClass(editor.getBody(), 'mce-edit-focus');
}
}
function render() {
if (panel) {
if (!panel.visible()) {
show();
}
return;
}
// Render a plain panel inside the inlineToolbarContainer if it's defined
panel = self.panel = Factory.create({
type: inlineToolbarContainer ? 'panel' : 'floatpanel',
role: 'application',
classes: 'tinymce tinymce-inline',
layout: 'flex',
direction: 'column',
align: 'stretch',
autohide: false,
autofix: true,
fixed: !!inlineToolbarContainer,
border: 1,
items: [
settings.menubar === false ? null : {type: 'menubar', border: '0 0 1 0', items: createMenuButtons()},
createToolbars()
]
});
// Add statusbar
/*if (settings.statusbar !== false) {
panel.add({type: 'panel', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', items: [
{type: 'elementpath'}
]});
}*/
editor.fire('BeforeRenderUI');
panel.renderTo(inlineToolbarContainer || document.body).reflow();
addAccessibilityKeys(panel);
show();
editor.on('nodeChange', reposition);
editor.on('activate', show);
editor.on('deactivate', hide);
editor.nodeChanged();
}
settings.content_editable = true;
editor.on('focus', function() {
// Render only when the CSS file has been loaded
if (args.skinUiCss) {
tinymce.DOM.styleSheetLoader.load(args.skinUiCss, render, render);
} else {
render();
}
});
editor.on('blur', hide);
// Remove the panel when the editor is removed
editor.on('remove', function() {
if (panel) {
panel.remove();
panel = null;
}
});
// Preload skin css
if (args.skinUiCss) {
tinymce.DOM.styleSheetLoader.load(args.skinUiCss);
}
return {};
}
/**
* Renders the iframe editor UI.
*
* @param {Object} args Details about target element etc.
* @return {Object} Name/value object with theme data.
*/
function renderIframeUI(args) {
var panel, resizeHandleCtrl, startSize;
if (args.skinUiCss) {
tinymce.DOM.loadCSS(args.skinUiCss);
}
// Basic UI layout
panel = self.panel = Factory.create({
type: 'panel',
role: 'application',
classes: 'tinymce',
style: 'visibility: hidden',
layout: 'stack',
border: 1,
items: [
settings.menubar === false ? null : {type: 'menubar', border: '0 0 1 0', items: createMenuButtons()},
createToolbars(),
{type: 'panel', name: 'iframe', layout: 'stack', classes: 'edit-area', html: '', border: '1 0 0 0'}
]
});
if (settings.resize !== false) {
resizeHandleCtrl = {
type: 'resizehandle',
direction: settings.resize,
onResizeStart: function() {
var elm = editor.getContentAreaContainer().firstChild;
startSize = {
width: elm.clientWidth,
height: elm.clientHeight
};
},
onResize: function(e) {
if (settings.resize == 'both') {
resizeTo(startSize.width + e.deltaX, startSize.height + e.deltaY);
} else {
resizeTo(null, startSize.height + e.deltaY);
}
}
};
}
// Add statusbar if needed
if (settings.statusbar !== false) {
panel.add({type: 'panel', name: 'statusbar', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', ariaRoot: true, items: [
{type: 'elementpath'},
resizeHandleCtrl
]});
}
if (settings.readonly) {
panel.find('*').disabled(true);
}
editor.fire('BeforeRenderUI');
panel.renderBefore(args.targetNode).reflow();
if (settings.width) {
tinymce.DOM.setStyle(panel.getEl(), 'width', settings.width);
}
// Remove the panel when the editor is removed
editor.on('remove', function() {
panel.remove();
panel = null;
});
// Add accesibility shortkuts
addAccessibilityKeys(panel);
return {
iframeContainer: panel.find('#iframe')[0].getEl(),
editorContainer: panel.getEl()
};
}
/**
* Renders the UI for the theme. This gets called by the editor.
*
* @param {Object} args Details about target element etc.
* @return {Object} Theme UI data items.
*/
self.renderUI = function(args) {
var skin = settings.skin !== false ? settings.skin || 'lightgray' : false;
if (skin) {
var skinUrl = settings.skin_url;
if (skinUrl) {
skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
} else {
skinUrl = tinymce.baseURL + '/skins/' + skin;
}
// Load special skin for IE7
// TODO: Remove this when we drop IE7 support
if (tinymce.Env.documentMode <= 7) {
args.skinUiCss = skinUrl + '/skin.ie7.min.css';
} else {
args.skinUiCss = skinUrl + '/skin.min.css';
}
// Load content.min.css or content.inline.min.css
editor.contentCSS.push(skinUrl + '/content' + (editor.inline ? '.inline' : '') + '.min.css');
}
// Handle editor setProgressState change
editor.on('ProgressState', function(e) {
self.throbber = self.throbber || new tinymce.ui.Throbber(self.panel.getEl('body'));
if (e.state) {
self.throbber.show(e.time);
} else {
self.throbber.hide();
}
});
if (settings.inline) {
return renderInlineUI(args);
}
return renderIframeUI(args);
};
self.resizeTo = resizeTo;
self.resizeBy = resizeBy;
});
| JavaScript |
/* global tinymce */
tinymce.PluginManager.add( 'wpeditimage', function( editor ) {
var toolbarActive = false;
function parseShortcode( content ) {
return content.replace( /(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?/g, function( a, b, c ) {
var id, cls, w, cap, img, width,
trim = tinymce.trim;
id = b.match( /id=['"]([^'"]*)['"] ?/ );
if ( id ) {
b = b.replace( id[0], '' );
}
cls = b.match( /align=['"]([^'"]*)['"] ?/ );
if ( cls ) {
b = b.replace( cls[0], '' );
}
w = b.match( /width=['"]([0-9]*)['"] ?/ );
if ( w ) {
b = b.replace( w[0], '' );
}
c = trim( c );
img = c.match( /((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)([\s\S]*)/i );
if ( img && img[2] ) {
cap = trim( img[2] );
img = trim( img[1] );
} else {
// old captions shortcode style
cap = trim( b ).replace( /caption=['"]/, '' ).replace( /['"]$/, '' );
img = c;
}
id = ( id && id[1] ) ? id[1] : '';
cls = ( cls && cls[1] ) ? cls[1] : 'alignnone';
if ( ! w && img ) {
w = img.match( /width=['"]([0-9]*)['"]/ );
}
if ( w && w[1] ) {
w = w[1];
}
if ( ! w || ! cap ) {
return c;
}
width = parseInt( w, 10 );
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
width += 10;
}
return '<div class="mceTemp"><dl id="'+ id +'" class="wp-caption '+ cls +'" style="width: '+ width +'px">' +
'<dt class="wp-caption-dt">'+ img +'</dt><dd class="wp-caption-dd">'+ cap +'</dd></dl></div>';
});
}
function getShortcode( content ) {
return content.replace( /<div (?:id="attachment_|class="mceTemp)[^>]*>([\s\S]+?)<\/div>/g, function( a, b ) {
var out = '';
if ( b.indexOf('<img ') === -1 ) {
// Broken caption. The user managed to drag the image out?
// Try to return the caption text as a paragraph.
out = b.match( /<dd [^>]+>([\s\S]+?)<\/dd>/i );
if ( out && out[1] ) {
return '<p>' + out[1] + '</p>';
}
return '';
}
out = b.replace( /<dl ([^>]+)>\s*<dt [^>]+>([\s\S]+?)<\/dt>\s*<dd [^>]+>([\s\S]*?)<\/dd>\s*<\/dl>/gi, function( a, b, c, cap ) {
var id, cls, w;
w = c.match( /width="([0-9]*)"/ );
w = ( w && w[1] ) ? w[1] : '';
if ( ! w || ! cap ) {
return c;
}
id = b.match( /id="([^"]*)"/ );
id = ( id && id[1] ) ? id[1] : '';
cls = b.match( /class="([^"]*)"/ );
cls = ( cls && cls[1] ) ? cls[1] : '';
cls = cls.match( /align[a-z]+/ ) || 'alignnone';
cap = cap.replace( /\r\n|\r/g, '\n' ).replace( /<[a-zA-Z0-9]+( [^<>]+)?>/g, function( a ) {
// no line breaks inside HTML tags
return a.replace( /[\r\n\t]+/, ' ' );
});
// convert remaining line breaks to <br>
cap = cap.replace( /\s*\n\s*/g, '<br />' );
return '[caption id="'+ id +'" align="'+ cls +'" width="'+ w +'"]'+ c +' '+ cap +'[/caption]';
});
if ( out.indexOf('[caption') !== 0 ) {
// the caption html seems broken, try to find the image that may be wrapped in a link
// and may be followed by <p> with the caption text.
out = b.replace( /[\s\S]*?((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)(<p>[\s\S]*<\/p>)?[\s\S]*/gi, '<p>$1</p>$2' );
}
return out;
});
}
function extractImageData( imageNode ) {
var classes, extraClasses, metadata, captionBlock, caption, link, width, height,
dom = editor.dom,
isIntRegExp = /^\d+$/;
// default attributes
metadata = {
attachment_id: false,
size: 'custom',
caption: '',
align: 'none',
extraClasses: '',
link: false,
linkUrl: '',
linkClassName: '',
linkTargetBlank: false,
linkRel: '',
title: ''
};
metadata.url = dom.getAttrib( imageNode, 'src' );
metadata.alt = dom.getAttrib( imageNode, 'alt' );
metadata.title = dom.getAttrib( imageNode, 'title' );
width = dom.getAttrib( imageNode, 'width' );
height = dom.getAttrib( imageNode, 'height' );
if ( ! isIntRegExp.test( width ) || parseInt( width, 10 ) < 1 ) {
width = imageNode.naturalWidth || imageNode.width;
}
if ( ! isIntRegExp.test( height ) || parseInt( height, 10 ) < 1 ) {
height = imageNode.naturalHeight || imageNode.height;
}
metadata.customWidth = metadata.width = width;
metadata.customHeight = metadata.height = height;
classes = tinymce.explode( imageNode.className, ' ' );
extraClasses = [];
tinymce.each( classes, function( name ) {
if ( /^wp-image/.test( name ) ) {
metadata.attachment_id = parseInt( name.replace( 'wp-image-', '' ), 10 );
} else if ( /^align/.test( name ) ) {
metadata.align = name.replace( 'align', '' );
} else if ( /^size/.test( name ) ) {
metadata.size = name.replace( 'size-', '' );
} else {
extraClasses.push( name );
}
} );
metadata.extraClasses = extraClasses.join( ' ' );
// Extract caption
captionBlock = dom.getParents( imageNode, '.wp-caption' );
if ( captionBlock.length ) {
captionBlock = captionBlock[0];
classes = captionBlock.className.split( ' ' );
tinymce.each( classes, function( name ) {
if ( /^align/.test( name ) ) {
metadata.align = name.replace( 'align', '' );
}
} );
caption = dom.select( 'dd.wp-caption-dd', captionBlock );
if ( caption.length ) {
caption = caption[0];
metadata.caption = editor.serializer.serialize( caption )
.replace( /<br[^>]*>/g, '$&\n' ).replace( /^<p>/, '' ).replace( /<\/p>$/, '' );
}
}
// Extract linkTo
if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' ) {
link = imageNode.parentNode;
metadata.linkUrl = dom.getAttrib( link, 'href' );
metadata.linkTargetBlank = dom.getAttrib( link, 'target' ) === '_blank' ? true : false;
metadata.linkRel = dom.getAttrib( link, 'rel' );
metadata.linkClassName = link.className;
}
return metadata;
}
function hasTextContent( node ) {
return node && !! ( node.textContent || node.innerText );
}
function updateImage( imageNode, imageData ) {
var classes, className, node, html, parent, wrap, linkNode,
captionNode, dd, dl, id, attrs, linkAttrs, width, height,
dom = editor.dom;
classes = tinymce.explode( imageData.extraClasses, ' ' );
if ( ! classes ) {
classes = [];
}
if ( ! imageData.caption ) {
classes.push( 'align' + imageData.align );
}
if ( imageData.attachment_id ) {
classes.push( 'wp-image-' + imageData.attachment_id );
if ( imageData.size && imageData.size !== 'custom' ) {
classes.push( 'size-' + imageData.size );
}
}
width = imageData.width;
height = imageData.height;
if ( imageData.size === 'custom' ) {
width = imageData.customWidth;
height = imageData.customHeight;
}
attrs = {
src: imageData.url,
width: width || null,
height: height || null,
alt: imageData.alt,
title: imageData.title || null,
'class': classes.join( ' ' ) || null
};
dom.setAttribs( imageNode, attrs );
linkAttrs = {
href: imageData.linkUrl,
rel: imageData.linkRel || null,
target: imageData.linkTargetBlank ? '_blank': null,
'class': imageData.linkClassName || null
};
if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
// Update or remove an existing link wrapped around the image
if ( imageData.linkUrl ) {
dom.setAttribs( imageNode.parentNode, linkAttrs );
} else {
dom.remove( imageNode.parentNode, true );
}
} else if ( imageData.linkUrl ) {
if ( linkNode = dom.getParent( imageNode, 'a' ) ) {
// The image is inside a link together with other nodes,
// or is nested in another node, move it out
dom.insertAfter( imageNode, linkNode );
}
// Add link wrapped around the image
linkNode = dom.create( 'a', linkAttrs );
imageNode.parentNode.insertBefore( linkNode, imageNode );
linkNode.appendChild( imageNode );
}
captionNode = editor.dom.getParent( imageNode, '.mceTemp' );
if ( imageNode.parentNode && imageNode.parentNode.nodeName === 'A' && ! hasTextContent( imageNode.parentNode ) ) {
node = imageNode.parentNode;
} else {
node = imageNode;
}
if ( imageData.caption ) {
id = imageData.attachment_id ? 'attachment_' + imageData.attachment_id : null;
className = 'wp-caption align' + ( imageData.align || 'none' );
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
width = parseInt( width, 10 );
width += 10;
}
if ( captionNode ) {
dl = dom.select( 'dl.wp-caption', captionNode );
if ( dl.length ) {
dom.setAttribs( dl, {
id: id,
'class': className,
style: 'width: ' + width + 'px'
} );
}
dd = dom.select( '.wp-caption-dd', captionNode );
if ( dd.length ) {
dom.setHTML( dd[0], imageData.caption );
}
} else {
id = id ? 'id="'+ id +'" ' : '';
// should create a new function for generating the caption markup
html = '<dl ' + id + 'class="' + className +'" style="width: '+ width +'px">' +
'<dt class="wp-caption-dt">' + dom.getOuterHTML( node ) + '</dt><dd class="wp-caption-dd">'+ imageData.caption +'</dd></dl>';
if ( parent = dom.getParent( node, 'p' ) ) {
wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
dom.insertAfter( wrap, parent );
dom.remove( node );
if ( dom.isEmpty( parent ) ) {
dom.remove( parent );
}
} else {
dom.setOuterHTML( node, '<div class="mceTemp">' + html + '</div>' );
}
}
} else if ( captionNode ) {
// Remove the caption wrapper and place the image in new paragraph
parent = dom.create( 'p' );
captionNode.parentNode.insertBefore( parent, captionNode );
parent.appendChild( node );
dom.remove( captionNode );
}
if ( wp.media.events ) {
wp.media.events.trigger( 'editor:image-update', {
editor: editor,
metadata: imageData,
image: imageNode
} );
}
editor.nodeChanged();
// Refresh the toolbar
addToolbar( imageNode );
}
function editImage( img ) {
var frame, callback, metadata;
if ( typeof wp === 'undefined' || ! wp.media ) {
editor.execCommand( 'mceImage' );
return;
}
metadata = extractImageData( img );
// Manipulate the metadata by reference that is fed into the PostImage model used in the media modal
wp.media.events.trigger( 'editor:image-edit', {
editor: editor,
metadata: metadata,
image: img
} );
frame = wp.media({
frame: 'image',
state: 'image-details',
metadata: metadata
} );
wp.media.events.trigger( 'editor:frame-create', { frame: frame } );
callback = function( imageData ) {
editor.focus();
editor.undoManager.transact( function() {
updateImage( img, imageData );
} );
frame.detach();
};
frame.state('image-details').on( 'update', callback );
frame.state('replace-image').on( 'replace', callback );
frame.on( 'close', function() {
editor.focus();
frame.detach();
});
frame.open();
}
function removeImage( node ) {
var wrap;
if ( node.nodeName === 'DIV' && editor.dom.hasClass( node, 'mceTemp' ) ) {
wrap = node;
} else if ( node.nodeName === 'IMG' || node.nodeName === 'DT' || node.nodeName === 'A' ) {
wrap = editor.dom.getParent( node, 'div.mceTemp' );
}
if ( wrap ) {
if ( wrap.nextSibling ) {
editor.selection.select( wrap.nextSibling );
} else if ( wrap.previousSibling ) {
editor.selection.select( wrap.previousSibling );
} else {
editor.selection.select( wrap.parentNode );
}
editor.selection.collapse( true );
editor.nodeChanged();
editor.dom.remove( wrap );
} else {
editor.dom.remove( node );
}
removeToolbar();
}
function addToolbar( node ) {
var rectangle, toolbarHtml, toolbar, left,
dom = editor.dom;
removeToolbar();
// Don't add to placeholders
if ( ! node || node.nodeName !== 'IMG' || isPlaceholder( node ) ) {
return;
}
dom.setAttrib( node, 'data-wp-imgselect', 1 );
rectangle = dom.getRect( node );
toolbarHtml = '<div class="dashicons dashicons-edit edit" data-mce-bogus="1"></div>' +
'<div class="dashicons dashicons-no-alt remove" data-mce-bogus="1"></div>';
toolbar = dom.create( 'div', {
'id': 'wp-image-toolbar',
'data-mce-bogus': '1',
'contenteditable': false
}, toolbarHtml );
if ( editor.rtl ) {
left = rectangle.x + rectangle.w - 82;
} else {
left = rectangle.x;
}
editor.getBody().appendChild( toolbar );
dom.setStyles( toolbar, {
top: rectangle.y,
left: left
});
toolbarActive = true;
}
function removeToolbar() {
var toolbar = editor.dom.get( 'wp-image-toolbar' );
if ( toolbar ) {
editor.dom.remove( toolbar );
}
editor.dom.setAttrib( editor.dom.select( 'img[data-wp-imgselect]' ), 'data-wp-imgselect', null );
toolbarActive = false;
}
function isPlaceholder( node ) {
var dom = editor.dom;
if ( dom.hasClass( node, 'mceItem' ) || dom.getAttrib( node, 'data-mce-placeholder' ) ||
dom.getAttrib( node, 'data-mce-object' ) ) {
return true;
}
return false;
}
editor.on( 'init', function() {
var dom = editor.dom,
captionClass = editor.getParam( 'wpeditimage_html5_captions' ) ? 'html5-captions' : 'html4-captions';
dom.addClass( editor.getBody(), captionClass );
// Add caption field to the default image dialog
editor.on( 'wpLoadImageForm', function( event ) {
if ( editor.getParam( 'wpeditimage_disable_captions' ) ) {
return;
}
var captionField = {
type: 'textbox',
flex: 1,
name: 'caption',
minHeight: 60,
multiline: true,
scroll: true,
label: 'Image caption'
};
event.data.splice( event.data.length - 1, 0, captionField );
});
// Fix caption parent width for images added from URL
editor.on( 'wpNewImageRefresh', function( event ) {
var parent, captionWidth;
if ( parent = dom.getParent( event.node, 'dl.wp-caption' ) ) {
if ( ! parent.style.width ) {
captionWidth = parseInt( event.node.clientWidth, 10 ) + 10;
captionWidth = captionWidth ? captionWidth + 'px' : '50%';
dom.setStyle( parent, 'width', captionWidth );
}
}
});
editor.on( 'wpImageFormSubmit', function( event ) {
var data = event.imgData.data,
imgNode = event.imgData.node,
caption = event.imgData.caption,
captionId = '',
captionAlign = '',
captionWidth = '',
wrap, parent, node, html, imgId;
// Temp image id so we can find the node later
data.id = '__wp-temp-img-id';
// Cancel the original callback
event.imgData.cancel = true;
if ( ! data.style ) {
data.style = null;
}
if ( ! data.src ) {
// Delete the image and the caption
if ( imgNode ) {
if ( wrap = dom.getParent( imgNode, 'div.mceTemp' ) ) {
dom.remove( wrap );
} else if ( imgNode.parentNode.nodeName === 'A' ) {
dom.remove( imgNode.parentNode );
} else {
dom.remove( imgNode );
}
editor.nodeChanged();
}
return;
}
if ( caption ) {
caption = caption.replace( /\r\n|\r/g, '\n' ).replace( /<\/?[a-zA-Z0-9]+( [^<>]+)?>/g, function( a ) {
// No line breaks inside HTML tags
return a.replace( /[\r\n\t]+/, ' ' );
});
// Convert remaining line breaks to <br>
caption = caption.replace( /(<br[^>]*>)\s*\n\s*/g, '$1' ).replace( /\s*\n\s*/g, '<br />' );
}
if ( ! imgNode ) {
// New image inserted
html = dom.createHTML( 'img', data );
if ( caption ) {
node = editor.selection.getNode();
if ( data.width ) {
captionWidth = parseInt( data.width, 10 );
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
captionWidth += 10;
}
captionWidth = ' style="width: ' + captionWidth + 'px"';
}
html = '<dl class="wp-caption alignnone"' + captionWidth + '>' +
'<dt class="wp-caption-dt">'+ html +'</dt><dd class="wp-caption-dd">'+ caption +'</dd></dl>';
if ( node.nodeName === 'P' ) {
parent = node;
} else {
parent = dom.getParent( node, 'p' );
}
if ( parent && parent.nodeName === 'P' ) {
wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
dom.insertAfter( wrap, parent );
editor.selection.select( wrap );
editor.nodeChanged();
if ( dom.isEmpty( parent ) ) {
dom.remove( parent );
}
} else {
editor.selection.setContent( '<div class="mceTemp">' + html + '</div>' );
}
} else {
editor.selection.setContent( html );
}
} else {
// Edit existing image
// Store the original image id if any
imgId = imgNode.id || null;
// Update the image node
dom.setAttribs( imgNode, data );
wrap = dom.getParent( imgNode, 'dl.wp-caption' );
if ( caption ) {
if ( wrap ) {
if ( parent = dom.select( 'dd.wp-caption-dd', wrap )[0] ) {
parent.innerHTML = caption;
}
} else {
if ( imgNode.className ) {
captionId = imgNode.className.match( /wp-image-([0-9]+)/ );
captionAlign = imgNode.className.match( /align(left|right|center|none)/ );
}
if ( captionAlign ) {
captionAlign = captionAlign[0];
imgNode.className = imgNode.className.replace( /align(left|right|center|none)/g, '' );
} else {
captionAlign = 'alignnone';
}
captionAlign = ' class="wp-caption ' + captionAlign + '"';
if ( captionId ) {
captionId = ' id="attachment_' + captionId[1] + '"';
}
captionWidth = data.width || imgNode.clientWidth;
if ( captionWidth ) {
captionWidth = parseInt( captionWidth, 10 );
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
captionWidth += 10;
}
captionWidth = ' style="width: '+ captionWidth +'px"';
}
if ( imgNode.parentNode && imgNode.parentNode.nodeName === 'A' ) {
html = dom.getOuterHTML( imgNode.parentNode );
node = imgNode.parentNode;
} else {
html = dom.getOuterHTML( imgNode );
node = imgNode;
}
html = '<dl ' + captionId + captionAlign + captionWidth + '>' +
'<dt class="wp-caption-dt">'+ html +'</dt><dd class="wp-caption-dd">'+ caption +'</dd></dl>';
if ( parent = dom.getParent( imgNode, 'p' ) ) {
wrap = dom.create( 'div', { 'class': 'mceTemp' }, html );
dom.insertAfter( wrap, parent );
editor.selection.select( wrap );
editor.nodeChanged();
// Delete the old image node
dom.remove( node );
if ( dom.isEmpty( parent ) ) {
dom.remove( parent );
}
} else {
editor.selection.setContent( '<div class="mceTemp">' + html + '</div>' );
}
}
} else {
if ( wrap ) {
// Remove the caption wrapper and place the image in new paragraph
if ( imgNode.parentNode.nodeName === 'A' ) {
html = dom.getOuterHTML( imgNode.parentNode );
} else {
html = dom.getOuterHTML( imgNode );
}
parent = dom.create( 'p', {}, html );
dom.insertAfter( parent, wrap.parentNode );
editor.selection.select( parent );
editor.nodeChanged();
dom.remove( wrap.parentNode );
}
}
}
imgNode = dom.get('__wp-temp-img-id');
dom.setAttrib( imgNode, 'id', imgId );
event.imgData.node = imgNode;
});
editor.on( 'wpLoadImageData', function( event ) {
var parent,
data = event.imgData.data,
imgNode = event.imgData.node;
if ( parent = dom.getParent( imgNode, 'dl.wp-caption' ) ) {
parent = dom.select( 'dd.wp-caption-dd', parent )[0];
if ( parent ) {
data.caption = editor.serializer.serialize( parent )
.replace( /<br[^>]*>/g, '$&\n' ).replace( /^<p>/, '' ).replace( /<\/p>$/, '' );
}
}
});
dom.bind( editor.getDoc(), 'dragstart', function( event ) {
var node = editor.selection.getNode();
// Prevent dragging images out of the caption elements
if ( node.nodeName === 'IMG' && dom.getParent( node, '.wp-caption' ) ) {
event.preventDefault();
}
// Remove toolbar to avoid an orphaned toolbar when dragging an image to a new location
removeToolbar();
});
// Prevent IE11 from making dl.wp-caption resizable
if ( tinymce.Env.ie && tinymce.Env.ie > 10 ) {
// The 'mscontrolselect' event is supported only in IE11+
dom.bind( editor.getBody(), 'mscontrolselect', function( event ) {
if ( event.target.nodeName === 'IMG' && dom.getParent( event.target, '.wp-caption' ) ) {
// Hide the thick border with resize handles around dl.wp-caption
editor.getBody().focus(); // :(
} else if ( event.target.nodeName === 'DL' && dom.hasClass( event.target, 'wp-caption' ) ) {
// Trigger the thick border with resize handles...
// This will make the caption text editable.
event.target.focus();
}
});
editor.on( 'click', function( event ) {
if ( event.target.nodeName === 'IMG' && dom.getAttrib( event.target, 'data-wp-imgselect' ) &&
dom.getParent( event.target, 'dl.wp-caption' ) ) {
editor.getBody().focus();
}
});
}
});
editor.on( 'ObjectResized', function( event ) {
var parent, width,
node = event.target,
dom = editor.dom;
if ( node.nodeName === 'IMG' ) {
node.className = node.className.replace( /\bsize-[^ ]+/, '' );
if ( parent = dom.getParent( node, '.wp-caption' ) ) {
width = event.width || dom.getAttrib( node, 'width' );
if ( width ) {
width = parseInt( width, 10 );
if ( ! editor.getParam( 'wpeditimage_html5_captions' ) ) {
width += 10;
}
dom.setStyle( parent, 'width', width + 'px' );
}
}
// refresh toolbar
addToolbar( node );
}
});
editor.on( 'BeforeExecCommand', function( event ) {
var node, p, DL, align,
cmd = event.command,
dom = editor.dom;
if ( cmd === 'mceInsertContent' ) {
// When inserting content, if the caret is inside a caption create new paragraph under
// and move the caret there
if ( node = dom.getParent( editor.selection.getNode(), 'div.mceTemp' ) ) {
p = dom.create( 'p' );
dom.insertAfter( p, node );
editor.selection.setCursorLocation( p, 0 );
editor.nodeChanged();
if ( tinymce.Env.ie > 8 ) {
setTimeout( function() {
editor.selection.setCursorLocation( p, 0 );
editor.selection.setContent( event.value );
}, 500 );
return false;
}
}
} else if ( cmd === 'JustifyLeft' || cmd === 'JustifyRight' || cmd === 'JustifyCenter' ) {
node = editor.selection.getNode();
align = cmd.substr(7).toLowerCase();
align = 'align' + align;
removeToolbar();
if ( dom.is( node, 'dl.wp-caption' ) ) {
DL = node;
} else {
DL = dom.getParent( node, 'dl.wp-caption' );
}
if ( DL ) {
// When inside an image caption, set the align* class on dl.wp-caption
if ( dom.hasClass( DL, align ) ) {
dom.removeClass( DL, align );
dom.addClass( DL, 'alignnone' );
} else {
DL.className = DL.className.replace( /align[^ ]+/g, '' );
dom.addClass( DL, align );
}
return false;
}
if ( node.nodeName === 'IMG' ) {
if ( dom.hasClass( node, align ) ) {
// The align class is being removed
dom.addClass( node, 'alignnone' );
} else {
dom.removeClass( node, 'alignnone' );
}
}
}
});
editor.on( 'keydown', function( event ) {
var node, wrap, P, spacer,
selection = editor.selection,
keyCode = event.keyCode,
dom = editor.dom;
if ( keyCode === tinymce.util.VK.ENTER ) {
// When pressing Enter inside a caption move the caret to a new parapraph under it
node = selection.getNode();
wrap = dom.getParent( node, 'div.mceTemp' );
if ( wrap ) {
dom.events.cancel( event ); // Doesn't cancel all :(
// Remove any extra dt and dd cleated on pressing Enter...
tinymce.each( dom.select( 'dt, dd', wrap ), function( element ) {
if ( dom.isEmpty( element ) ) {
dom.remove( element );
}
});
spacer = tinymce.Env.ie && tinymce.Env.ie < 11 ? '' : '<br data-mce-bogus="1" />';
P = dom.create( 'p', null, spacer );
if ( node.nodeName === 'DD' ) {
dom.insertAfter( P, wrap );
} else {
wrap.parentNode.insertBefore( P, wrap );
}
editor.nodeChanged();
selection.setCursorLocation( P, 0 );
}
} else if ( keyCode === tinymce.util.VK.DELETE || keyCode === tinymce.util.VK.BACKSPACE ) {
node = selection.getNode();
if ( node.nodeName === 'DIV' && dom.hasClass( node, 'mceTemp' ) ) {
wrap = node;
} else if ( node.nodeName === 'IMG' || node.nodeName === 'DT' || node.nodeName === 'A' ) {
wrap = dom.getParent( node, 'div.mceTemp' );
}
if ( wrap ) {
dom.events.cancel( event );
removeImage( node );
return false;
}
removeToolbar();
}
// Key presses will replace the image so we need to remove the toolbar
if ( toolbarActive ) {
if ( event.ctrlKey || event.metaKey || event.altKey ||
( keyCode < 48 && keyCode > 90 ) || keyCode > 186 ) {
return;
}
removeToolbar();
}
});
editor.on( 'mousedown', function( event ) {
if ( editor.dom.getParent( event.target, '#wp-image-toolbar' ) ) {
if ( tinymce.Env.ie ) {
// Stop IE > 8 from making the wrapper resizable on mousedown
event.preventDefault();
}
} else if ( event.target.nodeName !== 'IMG' ) {
removeToolbar();
}
});
editor.on( 'mouseup', function( event ) {
var image,
node = event.target,
dom = editor.dom;
// Don't trigger on right-click
if ( event.button && event.button > 1 ) {
return;
}
if ( node.nodeName === 'DIV' && dom.getParent( node, '#wp-image-toolbar' ) ) {
image = dom.select( 'img[data-wp-imgselect]' )[0];
if ( image ) {
editor.selection.select( image );
if ( dom.hasClass( node, 'remove' ) ) {
removeImage( image );
} else if ( dom.hasClass( node, 'edit' ) ) {
editImage( image );
}
}
} else if ( node.nodeName === 'IMG' && ! editor.dom.getAttrib( node, 'data-wp-imgselect' ) && ! isPlaceholder( node ) ) {
addToolbar( node );
} else if ( node.nodeName !== 'IMG' ) {
removeToolbar();
}
});
editor.on( 'cut', function() {
removeToolbar();
});
editor.wpSetImgCaption = function( content ) {
return parseShortcode( content );
};
editor.wpGetImgCaption = function( content ) {
return getShortcode( content );
};
editor.on( 'BeforeSetContent', function( event ) {
event.content = editor.wpSetImgCaption( event.content );
});
editor.on( 'PostProcess', function( event ) {
if ( event.get ) {
event.content = editor.wpGetImgCaption( event.content );
event.content = event.content.replace( / data-wp-imgselect="1"/g, '' );
}
});
return {
_do_shcode: parseShortcode,
_get_shcode: getShortcode
};
});
| JavaScript |
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true, console:true */
/*eslint no-console:0, new-cap:0 */
/**
* This plugin adds missing events form the 4.x API back. Not every event is
* properly supported but most things should work.
*
* Unsupported things:
* - No editor.onEvent
* - Can't cancel execCommands with beforeExecCommand
*/
(function(tinymce) {
var reported;
function noop() {}
function log(apiCall) {
if (!reported && window && window.console) {
reported = true;
console.log("Deprecated TinyMCE API call: " + apiCall);
}
}
function Dispatcher(target, newEventName, argsMap, defaultScope) {
target = target || this;
if (!newEventName) {
this.add = this.addToTop = this.remove = this.dispatch = noop;
return;
}
this.add = function(callback, scope, prepend) {
log('<target>.on' + newEventName + ".add(..)");
// Convert callback({arg1:x, arg2:x}) -> callback(arg1, arg2)
function patchedEventCallback(e) {
var callbackArgs = [];
if (typeof argsMap == "string") {
argsMap = argsMap.split(" ");
}
if (argsMap && typeof argsMap != "function") {
for (var i = 0; i < argsMap.length; i++) {
callbackArgs.push(e[argsMap[i]]);
}
}
if (typeof argsMap == "function") {
callbackArgs = argsMap(newEventName, e, target);
if (!callbackArgs) {
return;
}
}
if (!argsMap) {
callbackArgs = [e];
}
callbackArgs.unshift(defaultScope || target);
if (callback.apply(scope || defaultScope || target, callbackArgs) === false) {
e.stopImmediatePropagation();
}
}
target.on(newEventName, patchedEventCallback, prepend);
return patchedEventCallback;
};
this.addToTop = function(callback, scope) {
this.add(callback, scope, true);
};
this.remove = function(callback) {
return target.off(newEventName, callback);
};
this.dispatch = function() {
target.fire(newEventName);
return true;
};
}
tinymce.util.Dispatcher = Dispatcher;
tinymce.onBeforeUnload = new Dispatcher(tinymce, "BeforeUnload");
tinymce.onAddEditor = new Dispatcher(tinymce, "AddEditor", "editor");
tinymce.onRemoveEditor = new Dispatcher(tinymce, "RemoveEditor", "editor");
tinymce.util.Cookie = {
get: noop, getHash: noop, remove: noop, set: noop, setHash: noop
};
function patchEditor(editor) {
function patchEditorEvents(oldEventNames, argsMap) {
tinymce.each(oldEventNames.split(" "), function(oldName) {
editor["on" + oldName] = new Dispatcher(editor, oldName, argsMap);
});
}
function convertUndoEventArgs(type, event, target) {
return [
event.level,
target
];
}
function filterSelectionEvents(needsSelection) {
return function(type, e) {
if ((!e.selection && !needsSelection) || e.selection == needsSelection) {
return [e];
}
};
}
if (editor.controlManager) {
return;
}
function cmNoop() {
var obj = {}, methods = 'add addMenu addSeparator collapse createMenu destroy displayColor expand focus ' +
'getLength hasMenus hideMenu isActive isCollapsed isDisabled isRendered isSelected mark ' +
'postRender remove removeAll renderHTML renderMenu renderNode renderTo select selectByIndex ' +
'setActive setAriaProperty setColor setDisabled setSelected setState showMenu update';
log('editor.controlManager.*');
function _noop() {
return cmNoop();
}
tinymce.each(methods.split(' '), function(method) {
obj[method] = _noop;
});
return obj;
}
editor.controlManager = {
buttons: {},
setDisabled: function(name, state) {
log("controlManager.setDisabled(..)");
if (this.buttons[name]) {
this.buttons[name].disabled(state);
}
},
setActive: function(name, state) {
log("controlManager.setActive(..)");
if (this.buttons[name]) {
this.buttons[name].active(state);
}
},
onAdd: new Dispatcher(),
onPostRender: new Dispatcher(),
add: function(obj) { return obj; },
createButton: cmNoop,
createColorSplitButton: cmNoop,
createControl: cmNoop,
createDropMenu: cmNoop,
createListBox: cmNoop,
createMenuButton: cmNoop,
createSeparator: cmNoop,
createSplitButton: cmNoop,
createToolbar: cmNoop,
createToolbarGroup: cmNoop,
destroy: noop,
get: noop,
setControlType: cmNoop
};
patchEditorEvents("PreInit BeforeRenderUI PostRender Load Init Remove Activate Deactivate", "editor");
patchEditorEvents("Click MouseUp MouseDown DblClick KeyDown KeyUp KeyPress ContextMenu Paste Submit Reset");
patchEditorEvents("BeforeExecCommand ExecCommand", "command ui value args"); // args.terminate not supported
patchEditorEvents("PreProcess PostProcess LoadContent SaveContent Change");
patchEditorEvents("BeforeSetContent BeforeGetContent SetContent GetContent", filterSelectionEvents(false));
patchEditorEvents("SetProgressState", "state time");
patchEditorEvents("VisualAid", "element hasVisual");
patchEditorEvents("Undo Redo", convertUndoEventArgs);
patchEditorEvents("NodeChange", function(type, e) {
return [
editor.controlManager,
e.element,
editor.selection.isCollapsed(),
e
];
});
var originalAddButton = editor.addButton;
editor.addButton = function(name, settings) {
var originalOnPostRender, string, translated;
function patchedPostRender() {
editor.controlManager.buttons[name] = this;
if (originalOnPostRender) {
return originalOnPostRender.call(this);
}
}
for (var key in settings) {
if (key.toLowerCase() === "onpostrender") {
originalOnPostRender = settings[key];
settings.onPostRender = patchedPostRender;
}
}
if (!originalOnPostRender) {
settings.onPostRender = patchedPostRender;
}
if ( settings.title ) {
// WP
string = (editor.settings.language || "en") + "." + settings.title;
translated = tinymce.i18n.translate(string);
if ( string !== translated ) {
settings.title = translated;
}
// WP end
}
return originalAddButton.call(this, name, settings);
};
editor.on('init', function() {
var undoManager = editor.undoManager, selection = editor.selection;
undoManager.onUndo = new Dispatcher(editor, "Undo", convertUndoEventArgs, null, undoManager);
undoManager.onRedo = new Dispatcher(editor, "Redo", convertUndoEventArgs, null, undoManager);
undoManager.onBeforeAdd = new Dispatcher(editor, "BeforeAddUndo", null, undoManager);
undoManager.onAdd = new Dispatcher(editor, "AddUndo", null, undoManager);
selection.onBeforeGetContent = new Dispatcher(editor, "BeforeGetContent", filterSelectionEvents(true), selection);
selection.onGetContent = new Dispatcher(editor, "GetContent", filterSelectionEvents(true), selection);
selection.onBeforeSetContent = new Dispatcher(editor, "BeforeSetContent", filterSelectionEvents(true), selection);
selection.onSetContent = new Dispatcher(editor, "SetContent", filterSelectionEvents(true), selection);
});
editor.on('BeforeRenderUI', function() {
var windowManager = editor.windowManager;
windowManager.onOpen = new Dispatcher();
windowManager.onClose = new Dispatcher();
windowManager.createInstance = function(className, a, b, c, d, e) {
log("windowManager.createInstance(..)");
var constr = tinymce.resolve(className);
return new constr(a, b, c, d, e);
};
});
}
tinymce.on('SetupEditor', patchEditor);
tinymce.PluginManager.add("compat3x", patchEditor);
tinymce.addI18n = function(prefix, o) {
var I18n = tinymce.util.I18n, each = tinymce.each;
if (typeof(prefix) == "string" && prefix.indexOf('.') === -1) {
I18n.add(prefix, o);
return;
}
if (!tinymce.is(prefix, 'string')) {
each(prefix, function(o, lc) {
each(o, function(o, g) {
each(o, function(o, k) {
if (g === 'common') {
I18n.data[lc + '.' + k] = o;
} else {
I18n.data[lc + '.' + g + '.' + k] = o;
}
});
});
});
} else {
each(o, function(o, k) {
I18n.data[prefix + '.' + k] = o;
});
}
};
})(tinymce);
| JavaScript |
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('charmap', function(editor) {
var charmap = [
['160', 'no-break space'],
['38', 'ampersand'],
['34', 'quotation mark'],
// finance
['162', 'cent sign'],
['8364', 'euro sign'],
['163', 'pound sign'],
['165', 'yen sign'],
// signs
['169', 'copyright sign'],
['174', 'registered sign'],
['8482', 'trade mark sign'],
['8240', 'per mille sign'],
['181', 'micro sign'],
['183', 'middle dot'],
['8226', 'bullet'],
['8230', 'three dot leader'],
['8242', 'minutes / feet'],
['8243', 'seconds / inches'],
['167', 'section sign'],
['182', 'paragraph sign'],
['223', 'sharp s / ess-zed'],
// quotations
['8249', 'single left-pointing angle quotation mark'],
['8250', 'single right-pointing angle quotation mark'],
['171', 'left pointing guillemet'],
['187', 'right pointing guillemet'],
['8216', 'left single quotation mark'],
['8217', 'right single quotation mark'],
['8220', 'left double quotation mark'],
['8221', 'right double quotation mark'],
['8218', 'single low-9 quotation mark'],
['8222', 'double low-9 quotation mark'],
['60', 'less-than sign'],
['62', 'greater-than sign'],
['8804', 'less-than or equal to'],
['8805', 'greater-than or equal to'],
['8211', 'en dash'],
['8212', 'em dash'],
['175', 'macron'],
['8254', 'overline'],
['164', 'currency sign'],
['166', 'broken bar'],
['168', 'diaeresis'],
['161', 'inverted exclamation mark'],
['191', 'turned question mark'],
['710', 'circumflex accent'],
['732', 'small tilde'],
['176', 'degree sign'],
['8722', 'minus sign'],
['177', 'plus-minus sign'],
['247', 'division sign'],
['8260', 'fraction slash'],
['215', 'multiplication sign'],
['185', 'superscript one'],
['178', 'superscript two'],
['179', 'superscript three'],
['188', 'fraction one quarter'],
['189', 'fraction one half'],
['190', 'fraction three quarters'],
// math / logical
['402', 'function / florin'],
['8747', 'integral'],
['8721', 'n-ary sumation'],
['8734', 'infinity'],
['8730', 'square root'],
['8764', 'similar to'],
['8773', 'approximately equal to'],
['8776', 'almost equal to'],
['8800', 'not equal to'],
['8801', 'identical to'],
['8712', 'element of'],
['8713', 'not an element of'],
['8715', 'contains as member'],
['8719', 'n-ary product'],
['8743', 'logical and'],
['8744', 'logical or'],
['172', 'not sign'],
['8745', 'intersection'],
['8746', 'union'],
['8706', 'partial differential'],
['8704', 'for all'],
['8707', 'there exists'],
['8709', 'diameter'],
['8711', 'backward difference'],
['8727', 'asterisk operator'],
['8733', 'proportional to'],
['8736', 'angle'],
// undefined
['180', 'acute accent'],
['184', 'cedilla'],
['170', 'feminine ordinal indicator'],
['186', 'masculine ordinal indicator'],
['8224', 'dagger'],
['8225', 'double dagger'],
// alphabetical special chars
['192', 'A - grave'],
['193', 'A - acute'],
['194', 'A - circumflex'],
['195', 'A - tilde'],
['196', 'A - diaeresis'],
['197', 'A - ring above'],
['198', 'ligature AE'],
['199', 'C - cedilla'],
['200', 'E - grave'],
['201', 'E - acute'],
['202', 'E - circumflex'],
['203', 'E - diaeresis'],
['204', 'I - grave'],
['205', 'I - acute'],
['206', 'I - circumflex'],
['207', 'I - diaeresis'],
['208', 'ETH'],
['209', 'N - tilde'],
['210', 'O - grave'],
['211', 'O - acute'],
['212', 'O - circumflex'],
['213', 'O - tilde'],
['214', 'O - diaeresis'],
['216', 'O - slash'],
['338', 'ligature OE'],
['352', 'S - caron'],
['217', 'U - grave'],
['218', 'U - acute'],
['219', 'U - circumflex'],
['220', 'U - diaeresis'],
['221', 'Y - acute'],
['376', 'Y - diaeresis'],
['222', 'THORN'],
['224', 'a - grave'],
['225', 'a - acute'],
['226', 'a - circumflex'],
['227', 'a - tilde'],
['228', 'a - diaeresis'],
['229', 'a - ring above'],
['230', 'ligature ae'],
['231', 'c - cedilla'],
['232', 'e - grave'],
['233', 'e - acute'],
['234', 'e - circumflex'],
['235', 'e - diaeresis'],
['236', 'i - grave'],
['237', 'i - acute'],
['238', 'i - circumflex'],
['239', 'i - diaeresis'],
['240', 'eth'],
['241', 'n - tilde'],
['242', 'o - grave'],
['243', 'o - acute'],
['244', 'o - circumflex'],
['245', 'o - tilde'],
['246', 'o - diaeresis'],
['248', 'o slash'],
['339', 'ligature oe'],
['353', 's - caron'],
['249', 'u - grave'],
['250', 'u - acute'],
['251', 'u - circumflex'],
['252', 'u - diaeresis'],
['253', 'y - acute'],
['254', 'thorn'],
['255', 'y - diaeresis'],
['913', 'Alpha'],
['914', 'Beta'],
['915', 'Gamma'],
['916', 'Delta'],
['917', 'Epsilon'],
['918', 'Zeta'],
['919', 'Eta'],
['920', 'Theta'],
['921', 'Iota'],
['922', 'Kappa'],
['923', 'Lambda'],
['924', 'Mu'],
['925', 'Nu'],
['926', 'Xi'],
['927', 'Omicron'],
['928', 'Pi'],
['929', 'Rho'],
['931', 'Sigma'],
['932', 'Tau'],
['933', 'Upsilon'],
['934', 'Phi'],
['935', 'Chi'],
['936', 'Psi'],
['937', 'Omega'],
['945', 'alpha'],
['946', 'beta'],
['947', 'gamma'],
['948', 'delta'],
['949', 'epsilon'],
['950', 'zeta'],
['951', 'eta'],
['952', 'theta'],
['953', 'iota'],
['954', 'kappa'],
['955', 'lambda'],
['956', 'mu'],
['957', 'nu'],
['958', 'xi'],
['959', 'omicron'],
['960', 'pi'],
['961', 'rho'],
['962', 'final sigma'],
['963', 'sigma'],
['964', 'tau'],
['965', 'upsilon'],
['966', 'phi'],
['967', 'chi'],
['968', 'psi'],
['969', 'omega'],
// symbols
['8501', 'alef symbol'],
['982', 'pi symbol'],
['8476', 'real part symbol'],
['978', 'upsilon - hook symbol'],
['8472', 'Weierstrass p'],
['8465', 'imaginary part'],
// arrows
['8592', 'leftwards arrow'],
['8593', 'upwards arrow'],
['8594', 'rightwards arrow'],
['8595', 'downwards arrow'],
['8596', 'left right arrow'],
['8629', 'carriage return'],
['8656', 'leftwards double arrow'],
['8657', 'upwards double arrow'],
['8658', 'rightwards double arrow'],
['8659', 'downwards double arrow'],
['8660', 'left right double arrow'],
['8756', 'therefore'],
['8834', 'subset of'],
['8835', 'superset of'],
['8836', 'not a subset of'],
['8838', 'subset of or equal to'],
['8839', 'superset of or equal to'],
['8853', 'circled plus'],
['8855', 'circled times'],
['8869', 'perpendicular'],
['8901', 'dot operator'],
['8968', 'left ceiling'],
['8969', 'right ceiling'],
['8970', 'left floor'],
['8971', 'right floor'],
['9001', 'left-pointing angle bracket'],
['9002', 'right-pointing angle bracket'],
['9674', 'lozenge'],
['9824', 'black spade suit'],
['9827', 'black club suit'],
['9829', 'black heart suit'],
['9830', 'black diamond suit'],
['8194', 'en space'],
['8195', 'em space'],
['8201', 'thin space'],
['8204', 'zero width non-joiner'],
['8205', 'zero width joiner'],
['8206', 'left-to-right mark'],
['8207', 'right-to-left mark'],
['173', 'soft hyphen']
];
function showDialog() {
var gridHtml, x, y, win;
function getParentTd(elm) {
while (elm) {
if (elm.nodeName == 'TD') {
return elm;
}
elm = elm.parentNode;
}
}
gridHtml = '<table role="presentation" cellspacing="0" class="mce-charmap"><tbody>';
var width = 25;
for (y = 0; y < 10; y++) {
gridHtml += '<tr>';
for (x = 0; x < width; x++) {
var chr = charmap[y * width + x];
gridHtml += '<td title="' + chr[1] + '"><div tabindex="-1" title="' + chr[1] + '" role="button">' +
(chr ? String.fromCharCode(parseInt(chr[0], 10)) : ' ') + '</div></td>';
}
gridHtml += '</tr>';
}
gridHtml += '</tbody></table>';
var charMapPanel = {
type: 'container',
html: gridHtml,
onclick: function(e) {
var target = e.target;
if (/^(TD|DIV)$/.test(target.nodeName)) {
editor.execCommand('mceInsertContent', false, tinymce.trim(target.innerText || target.textContent));
if (!e.ctrlKey) {
win.close();
}
}
},
onmouseover: function(e) {
var td = getParentTd(e.target);
if (td) {
win.find('#preview').text(td.firstChild.firstChild.data);
}
}
};
win = editor.windowManager.open({
title: "Special character",
spacing: 10,
padding: 10,
items: [
charMapPanel,
{
type: 'label',
name: 'preview',
text: ' ',
style: 'font-size: 40px; text-align: center',
border: 1,
minWidth: 100,
minHeight: 80
}
],
buttons: [
{text: "Close", onclick: function() {
win.close();
}}
]
});
}
editor.addButton('charmap', {
icon: 'charmap',
tooltip: 'Special character',
onclick: showDialog
});
editor.addMenuItem('charmap', {
icon: 'charmap',
text: 'Special character',
onclick: showDialog,
context: 'insert'
});
}); | JavaScript |
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('fullscreen', function(editor) {
var fullscreenState = false, DOM = tinymce.DOM, iframeWidth, iframeHeight, resizeHandler;
var containerWidth, containerHeight;
if (editor.settings.inline) {
return;
}
function getWindowSize() {
var w, h, win = window, doc = document;
var body = doc.body;
// Old IE
if (body.offsetWidth) {
w = body.offsetWidth;
h = body.offsetHeight;
}
// Modern browsers
if (win.innerWidth && win.innerHeight) {
w = win.innerWidth;
h = win.innerHeight;
}
return {w: w, h: h};
}
function toggleFullscreen() {
var body = document.body, documentElement = document.documentElement, editorContainerStyle;
var editorContainer, iframe, iframeStyle;
function resize() {
DOM.setStyle(iframe, 'height', getWindowSize().h - (editorContainer.clientHeight - iframe.clientHeight));
}
fullscreenState = !fullscreenState;
editorContainer = editor.getContainer();
editorContainerStyle = editorContainer.style;
iframe = editor.getContentAreaContainer().firstChild;
iframeStyle = iframe.style;
if (fullscreenState) {
iframeWidth = iframeStyle.width;
iframeHeight = iframeStyle.height;
iframeStyle.width = iframeStyle.height = '100%';
containerWidth = editorContainerStyle.width;
containerHeight = editorContainerStyle.height;
editorContainerStyle.width = editorContainerStyle.height = '';
DOM.addClass(body, 'mce-fullscreen');
DOM.addClass(documentElement, 'mce-fullscreen');
DOM.addClass(editorContainer, 'mce-fullscreen');
DOM.bind(window, 'resize', resize);
resize();
resizeHandler = resize;
} else {
iframeStyle.width = iframeWidth;
iframeStyle.height = iframeHeight;
if (containerWidth) {
editorContainerStyle.width = containerWidth;
}
if (containerHeight) {
editorContainerStyle.height = containerHeight;
}
DOM.removeClass(body, 'mce-fullscreen');
DOM.removeClass(documentElement, 'mce-fullscreen');
DOM.removeClass(editorContainer, 'mce-fullscreen');
DOM.unbind(window, 'resize', resizeHandler);
}
editor.fire('FullscreenStateChanged', {state: fullscreenState});
}
editor.on('init', function() {
editor.addShortcut('Ctrl+Alt+F', '', toggleFullscreen);
});
editor.on('remove', function() {
if (resizeHandler) {
DOM.unbind(window, 'resize', resizeHandler);
}
});
editor.addCommand('mceFullScreen', toggleFullscreen);
editor.addMenuItem('fullscreen', {
text: 'Fullscreen',
shortcut: 'Ctrl+Alt+F',
selectable: true,
onClick: toggleFullscreen,
onPostRender: function() {
var self = this;
editor.on('FullscreenStateChanged', function(e) {
self.active(e.state);
});
},
context: 'view'
});
editor.addButton('fullscreen', {
tooltip: 'Fullscreen',
shortcut: 'Ctrl+Alt+F',
onClick: toggleFullscreen,
onPostRender: function() {
var self = this;
editor.on('FullscreenStateChanged', function(e) {
self.active(e.state);
});
}
});
return {
isFullscreen: function() {
return fullscreenState;
}
};
}); | JavaScript |
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*jshint maxlen:255 */
/*eslint max-len:0 */
/*global tinymce:true */
tinymce.PluginManager.add('media', function(editor, url) {
var urlPatterns = [
{regex: /youtu\.be\/([\w\-.]+)/, type: 'iframe', w: 425, h: 350, url: '//www.youtube.com/embed/$1'},
{regex: /youtube\.com(.+)v=([^&]+)/, type: 'iframe', w: 425, h: 350, url: '//www.youtube.com/embed/$2'},
{regex: /vimeo\.com\/([0-9]+)/, type: 'iframe', w: 425, h: 350, url: '//player.vimeo.com/video/$1?title=0&byline=0&portrait=0&color=8dc7dc'},
{regex: /maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/, type: 'iframe', w: 425, h: 350, url: '//maps.google.com/maps/ms?msid=$2&output=embed"'}
];
function guessMime(url) {
if (url.indexOf('.mp3') != -1) {
return 'audio/mpeg';
}
if (url.indexOf('.wav') != -1) {
return 'audio/wav';
}
if (url.indexOf('.mp4') != -1) {
return 'video/mp4';
}
if (url.indexOf('.webm') != -1) {
return 'video/webm';
}
if (url.indexOf('.ogg') != -1) {
return 'video/ogg';
}
if (url.indexOf('.swf') != -1) {
return 'application/x-shockwave-flash';
}
return '';
}
function getVideoScriptMatch(src) {
var prefixes = editor.settings.media_scripts;
if (prefixes) {
for (var i = 0; i < prefixes.length; i++) {
if (src.indexOf(prefixes[i].filter) !== -1) {
return prefixes[i];
}
}
}
}
function showDialog() {
var win, width, height, data;
var generalFormItems = [
{name: 'source1', type: 'filepicker', filetype: 'media', size: 40, autofocus: true, label: 'Source'}
];
function recalcSize(e) {
var widthCtrl, heightCtrl, newWidth, newHeight;
widthCtrl = win.find('#width')[0];
heightCtrl = win.find('#height')[0];
newWidth = widthCtrl.value();
newHeight = heightCtrl.value();
if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) {
if (e.control == widthCtrl) {
newHeight = Math.round((newWidth / width) * newHeight);
heightCtrl.value(newHeight);
} else {
newWidth = Math.round((newHeight / height) * newWidth);
widthCtrl.value(newWidth);
}
}
width = newWidth;
height = newHeight;
}
if (editor.settings.media_alt_source !== false) {
generalFormItems.push({name: 'source2', type: 'filepicker', filetype: 'media', size: 40, label: 'Alternative source'});
}
if (editor.settings.media_poster !== false) {
generalFormItems.push({name: 'poster', type: 'filepicker', filetype: 'image', size: 40, label: 'Poster'});
}
if (editor.settings.media_dimensions !== false) {
generalFormItems.push({
type: 'container',
label: 'Dimensions',
layout: 'flex',
align: 'center',
spacing: 5,
items: [
{name: 'width', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize},
{type: 'label', text: 'x'},
{name: 'height', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize},
{name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'}
]
});
}
data = getData(editor.selection.getNode());
width = data.width;
height = data.height;
win = editor.windowManager.open({
title: 'Insert/edit video',
data: data,
bodyType: 'tabpanel',
body: [
{
title: 'General',
type: "form",
onShowTab: function() {
data = htmlToData(this.next().find('#embed').value());
this.fromJSON(data);
},
items: generalFormItems
},
{
title: 'Embed',
type: "panel",
layout: 'flex',
direction: 'column',
align: 'stretch',
padding: 10,
spacing: 10,
onShowTab: function() {
this.find('#embed').value(dataToHtml(this.parent().toJSON()));
},
items: [
{
type: 'label',
text: 'Paste your embed code below:',
forId: 'mcemediasource'
},
{
id: 'mcemediasource',
type: 'textbox',
flex: 1,
name: 'embed',
value: getSource(),
multiline: true,
label: 'Source'
}
]
}
],
onSubmit: function() {
editor.insertContent(dataToHtml(this.toJSON()));
}
});
}
function getSource() {
var elm = editor.selection.getNode();
if (elm.getAttribute('data-mce-object')) {
return editor.selection.getContent();
}
}
function dataToHtml(data) {
var html = '';
if (!data.source1) {
tinymce.extend(data, htmlToData(data.embed));
if (!data.source1) {
return '';
}
}
if (!data.source2) {
data.source2 = '';
}
if (!data.poster) {
data.poster = '';
}
data.source1 = editor.convertURL(data.source1, "source");
data.source2 = editor.convertURL(data.source2, "source");
data.source1mime = guessMime(data.source1);
data.source2mime = guessMime(data.source2);
data.poster = editor.convertURL(data.poster, "poster");
data.flashPlayerUrl = editor.convertURL(url + '/moxieplayer.swf', "movie");
if (data.embed) {
html = updateHtml(data.embed, data, true);
} else {
tinymce.each(urlPatterns, function(pattern) {
var match, i, url;
if ((match = pattern.regex.exec(data.source1))) {
url = pattern.url;
for (i = 0; match[i]; i++) {
/*jshint loopfunc:true*/
/*eslint no-loop-func:0 */
url = url.replace('$' + i, function() {
return match[i];
});
}
data.source1 = url;
data.type = pattern.type;
data.width = data.width || pattern.w;
data.height = data.height || pattern.h;
}
});
var videoScript = getVideoScriptMatch(data.source1);
if (videoScript) {
data.type = 'script';
data.width = videoScript.width;
data.height = videoScript.height;
}
data.width = data.width || 300;
data.height = data.height || 150;
tinymce.each(data, function(value, key) {
data[key] = editor.dom.encode(value);
});
if (data.type == "iframe") {
html += '<iframe src="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '"></iframe>';
} else if (data.source1mime == "application/x-shockwave-flash") {
html += '<object data="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '" type="application/x-shockwave-flash">';
if (data.poster) {
html += '<img src="' + data.poster + '" width="' + data.width + '" height="' + data.height + '" />';
}
html += '</object>';
} else if (data.source1mime.indexOf('audio') != -1) {
if (editor.settings.audio_template_callback) {
html = editor.settings.audio_template_callback(data);
} else {
html += (
'<audio controls="controls" src="' + data.source1 + '">' +
(data.source2 ? '\n<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
'</audio>'
);
}
} else if (data.type == "script") {
html += '<script src="' + data.source1 + '"></script>';
} else {
if (editor.settings.video_template_callback) {
html = editor.settings.video_template_callback(data);
} else {
html = (
'<video width="' + data.width + '" height="' + data.height + '"' + (data.poster ? ' poster="' + data.poster + '"' : '') + ' controls="controls">\n' +
'<source src="' + data.source1 + '"' + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' +
(data.source2 ? '<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
'</video>'
);
}
}
}
return html;
}
function htmlToData(html) {
var data = {};
new tinymce.html.SaxParser({
validate: false,
allow_conditional_comments: true,
special: 'script,noscript',
start: function(name, attrs) {
if (!data.source1 && name == "param") {
data.source1 = attrs.map.movie;
}
if (name == "iframe" || name == "object" || name == "embed" || name == "video" || name == "audio") {
if (!data.type) {
data.type = name;
}
data = tinymce.extend(attrs.map, data);
}
if (name == "script") {
var videoScript = getVideoScriptMatch(attrs.map.src);
if (!videoScript) {
return;
}
data = {
type: "script",
source1: attrs.map.src,
width: videoScript.width,
height: videoScript.height
};
}
if (name == "source") {
if (!data.source1) {
data.source1 = attrs.map.src;
} else if (!data.source2) {
data.source2 = attrs.map.src;
}
}
if (name == "img" && !data.poster) {
data.poster = attrs.map.src;
}
}
}).parse(html);
data.source1 = data.source1 || data.src || data.data;
data.source2 = data.source2 || '';
data.poster = data.poster || '';
return data;
}
function getData(element) {
if (element.getAttribute('data-mce-object')) {
return htmlToData(editor.serializer.serialize(element, {selection: true}));
}
return {};
}
function updateHtml(html, data, updateAll) {
var writer = new tinymce.html.Writer();
var sourceCount = 0, hasImage;
function setAttributes(attrs, updatedAttrs) {
var name, i, value, attr;
for (name in updatedAttrs) {
value = "" + updatedAttrs[name];
if (attrs.map[name]) {
i = attrs.length;
while (i--) {
attr = attrs[i];
if (attr.name == name) {
if (value) {
attrs.map[name] = value;
attr.value = value;
} else {
delete attrs.map[name];
attrs.splice(i, 1);
}
}
}
} else if (value) {
attrs.push({
name: name,
value: value
});
attrs.map[name] = value;
}
}
}
new tinymce.html.SaxParser({
validate: false,
allow_conditional_comments: true,
special: 'script,noscript',
comment: function(text) {
writer.comment(text);
},
cdata: function(text) {
writer.cdata(text);
},
text: function(text, raw) {
writer.text(text, raw);
},
start: function(name, attrs, empty) {
switch (name) {
case "video":
case "object":
case "embed":
case "img":
case "iframe":
setAttributes(attrs, {
width: data.width,
height: data.height
});
break;
}
if (updateAll) {
switch (name) {
case "video":
setAttributes(attrs, {
poster: data.poster,
src: ""
});
if (data.source2) {
setAttributes(attrs, {
src: ""
});
}
break;
case "iframe":
setAttributes(attrs, {
src: data.source1
});
break;
case "source":
sourceCount++;
if (sourceCount <= 2) {
setAttributes(attrs, {
src: data["source" + sourceCount],
type: data["source" + sourceCount + "mime"]
});
if (!data["source" + sourceCount]) {
return;
}
}
break;
case "img":
if (!data.poster) {
return;
}
hasImage = true;
break;
}
}
writer.start(name, attrs, empty);
},
end: function(name) {
if (name == "video" && updateAll) {
for (var index = 1; index <= 2; index++) {
if (data["source" + index]) {
var attrs = [];
attrs.map = {};
if (sourceCount < index) {
setAttributes(attrs, {
src: data["source" + index],
type: data["source" + index + "mime"]
});
writer.start("source", attrs, true);
}
}
}
}
if (data.poster && name == "object" && updateAll && !hasImage) {
var imgAttrs = [];
imgAttrs.map = {};
setAttributes(imgAttrs, {
src: data.poster,
width: data.width,
height: data.height
});
writer.start("img", imgAttrs, true);
}
writer.end(name);
}
}, new tinymce.html.Schema({})).parse(html);
return writer.getContent();
}
editor.on('ResolveName', function(e) {
var name;
if (e.target.nodeType == 1 && (name = e.target.getAttribute("data-mce-object"))) {
e.name = name;
}
});
editor.on('preInit', function() {
// Make sure that any messy HTML is retained inside these
var specialElements = editor.schema.getSpecialElements();
tinymce.each('video audio iframe object'.split(' '), function(name) {
specialElements[name] = new RegExp('<\/' + name + '[^>]*>','gi');
});
// Allow elements
editor.schema.addValidElements('object[id|style|width|height|classid|codebase|*],embed[id|style|width|height|type|src|*],video[*],audio[*]');
// Set allowFullscreen attribs as boolean
var boolAttrs = editor.schema.getBoolAttrs();
tinymce.each('webkitallowfullscreen mozallowfullscreen allowfullscreen'.split(' '), function(name) {
boolAttrs[name] = {};
});
// Converts iframe, video etc into placeholder images
editor.parser.addNodeFilter('iframe,video,audio,object,embed,script', function(nodes, name) {
var i = nodes.length, ai, node, placeHolder, attrName, attrValue, attribs, innerHtml;
var videoScript;
while (i--) {
node = nodes[i];
if (node.name == 'script') {
videoScript = getVideoScriptMatch(node.attr('src'));
if (!videoScript) {
continue;
}
}
placeHolder = new tinymce.html.Node('img', 1);
placeHolder.shortEnded = true;
if (videoScript) {
if (videoScript.width) {
node.attr('width', videoScript.width.toString());
}
if (videoScript.height) {
node.attr('height', videoScript.height.toString());
}
}
// Prefix all attributes except width, height and style since we
// will add these to the placeholder
attribs = node.attributes;
ai = attribs.length;
while (ai--) {
attrName = attribs[ai].name;
attrValue = attribs[ai].value;
if (attrName !== "width" && attrName !== "height" && attrName !== "style") {
if (attrName == "data" || attrName == "src") {
attrValue = editor.convertURL(attrValue, attrName);
}
placeHolder.attr('data-mce-p-' + attrName, attrValue);
}
}
// Place the inner HTML contents inside an escaped attribute
// This enables us to copy/paste the fake object
innerHtml = node.firstChild && node.firstChild.value;
if (innerHtml) {
placeHolder.attr("data-mce-html", escape(innerHtml));
placeHolder.firstChild = null;
}
placeHolder.attr({
width: node.attr('width') || "300",
height: node.attr('height') || (name == "audio" ? "30" : "150"),
style: node.attr('style'),
src: tinymce.Env.transparentSrc,
"data-mce-object": name,
"class": "mce-object mce-object-" + name
});
node.replace(placeHolder);
}
});
// Replaces placeholder images with real elements for video, object, iframe etc
editor.serializer.addAttributeFilter('data-mce-object', function(nodes, name) {
var i = nodes.length, node, realElm, ai, attribs, innerHtml, innerNode, realElmName;
while (i--) {
node = nodes[i];
realElmName = node.attr(name);
realElm = new tinymce.html.Node(realElmName, 1);
// Add width/height to everything but audio
if (realElmName != "audio" && realElmName != "script") {
realElm.attr({
width: node.attr('width'),
height: node.attr('height')
});
}
realElm.attr({
style: node.attr('style')
});
// Unprefix all placeholder attributes
attribs = node.attributes;
ai = attribs.length;
while (ai--) {
var attrName = attribs[ai].name;
if (attrName.indexOf('data-mce-p-') === 0) {
realElm.attr(attrName.substr(11), attribs[ai].value);
}
}
if (realElmName == "script") {
realElm.attr('type', 'text/javascript');
}
// Inject innerhtml
innerHtml = node.attr('data-mce-html');
if (innerHtml) {
innerNode = new tinymce.html.Node('#text', 3);
innerNode.raw = true;
innerNode.value = unescape(innerHtml);
realElm.append(innerNode);
}
node.replace(realElm);
}
});
});
editor.on('ObjectSelected', function(e) {
var objectType = e.target.getAttribute('data-mce-object');
if (objectType == "audio" || objectType == "script") {
e.preventDefault();
}
});
editor.on('objectResized', function(e) {
var target = e.target, html;
if (target.getAttribute('data-mce-object')) {
html = target.getAttribute('data-mce-html');
if (html) {
html = unescape(html);
target.setAttribute('data-mce-html', escape(
updateHtml(html, {
width: e.width,
height: e.height
})
));
}
}
});
editor.addButton('media', {
tooltip: 'Insert/edit video',
onclick: showDialog,
stateSelector: ['img[data-mce-object=video]', 'img[data-mce-object=iframe]']
});
editor.addMenuItem('media', {
icon: 'media',
text: 'Insert video',
onclick: showDialog,
context: 'insert',
prependToContext: true
});
});
| JavaScript |
/* global tinymce */
/**
* Included for back-compat.
* The default WindowManager in TinyMCE 4.0 supports three types of dialogs:
* - With HTML created from JS.
* - With inline HTML (like WPWindowManager).
* - Old type iframe based dialogs.
* For examples see the default plugins: https://github.com/tinymce/tinymce/tree/master/js/tinymce/plugins
*/
tinymce.WPWindowManager = tinymce.InlineWindowManager = function( editor ) {
if ( this.wp ) {
return this;
}
this.wp = {};
this.parent = editor.windowManager;
this.editor = editor;
tinymce.extend( this, this.parent );
this.open = function( args, params ) {
var $element,
self = this,
wp = this.wp;
if ( ! args.wpDialog ) {
return this.parent.open.apply( this, arguments );
} else if ( ! args.id ) {
return;
}
if ( typeof jQuery === 'undefined' || ! jQuery.wp || ! jQuery.wp.wpdialog ) {
// wpdialog.js is not loaded
if ( window.console && window.console.error ) {
window.console.error('wpdialog.js is not loaded. Please set "wpdialogs" as dependency for your script when calling wp_enqueue_script(). You may also want to enqueue the "wp-jquery-ui-dialog" stylesheet.');
}
return;
}
wp.$element = $element = jQuery( '#' + args.id );
if ( ! $element.length ) {
return;
}
if ( window.console && window.console.log ) {
window.console.log('tinymce.WPWindowManager is deprecated. Use the default editor.windowManager to open dialogs with inline HTML.');
}
wp.features = args;
wp.params = params;
// Store selection. Takes a snapshot in the FocusManager of the selection before focus is moved to the dialog.
editor.nodeChanged();
// Create the dialog if necessary
if ( ! $element.data('wpdialog') ) {
$element.wpdialog({
title: args.title,
width: args.width,
height: args.height,
modal: true,
dialogClass: 'wp-dialog',
zIndex: 300000
});
}
$element.wpdialog('open');
$element.on( 'wpdialogclose', function() {
if ( self.wp.$element ) {
self.wp = {};
}
});
};
this.close = function() {
if ( ! this.wp.features || ! this.wp.features.wpDialog ) {
return this.parent.close.apply( this, arguments );
}
this.wp.$element.wpdialog('close');
};
};
tinymce.PluginManager.add( 'wpdialogs', function( editor ) {
// Replace window manager
editor.on( 'init', function() {
editor.windowManager = new tinymce.WPWindowManager( editor );
});
});
| JavaScript |
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('directionality', function(editor) {
function setDir(dir) {
var dom = editor.dom, curDir, blocks = editor.selection.getSelectedBlocks();
if (blocks.length) {
curDir = dom.getAttrib(blocks[0], "dir");
tinymce.each(blocks, function(block) {
// Add dir to block if the parent block doesn't already have that dir
if (!dom.getParent(block.parentNode, "*[dir='" + dir + "']", dom.getRoot())) {
if (curDir != dir) {
dom.setAttrib(block, "dir", dir);
} else {
dom.setAttrib(block, "dir", null);
}
}
});
editor.nodeChanged();
}
}
function generateSelector(dir) {
var selector = [];
tinymce.each('h1 h2 h3 h4 h5 h6 div p'.split(' '), function(name) {
selector.push(name + '[dir=' + dir + ']');
});
return selector.join(',');
}
editor.addCommand('mceDirectionLTR', function() {
setDir("ltr");
});
editor.addCommand('mceDirectionRTL', function() {
setDir("rtl");
});
editor.addButton('ltr', {
title: 'Left to right',
cmd: 'mceDirectionLTR',
stateSelector: generateSelector('ltr')
});
editor.addButton('rtl', {
title: 'Right to left',
cmd: 'mceDirectionRTL',
stateSelector: generateSelector('rtl')
});
}); | JavaScript |
/* global tinymce */
/**
* WP Fullscreen (Distraction Free Writing) TinyMCE plugin
*/
tinymce.PluginManager.add( 'wpfullscreen', function( editor ) {
var settings = editor.settings,
oldSize = 0;
function resize( e ) {
var deltaSize, myHeight,
d = editor.getDoc(),
body = d.body,
DOM = tinymce.DOM,
resizeHeight = 250;
if ( ( e && e.type === 'setcontent' && e.initial ) || editor.settings.inline ) {
return;
}
// Get height differently depending on the browser used
myHeight = tinymce.Env.ie ? body.scrollHeight : ( tinymce.Env.webkit && body.clientHeight === 0 ? 0 : body.offsetHeight );
// Don't make it smaller than 250px
if ( myHeight > 250 ) {
resizeHeight = myHeight;
}
body.scrollTop = 0;
// Resize content element
if ( resizeHeight !== oldSize ) {
deltaSize = resizeHeight - oldSize;
DOM.setStyle( DOM.get( editor.id + '_ifr' ), 'height', resizeHeight + 'px' );
oldSize = resizeHeight;
// WebKit doesn't decrease the size of the body element until the iframe gets resized
// So we need to continue to resize the iframe down until the size gets fixed
if ( tinymce.isWebKit && deltaSize < 0 ) {
resize( e );
}
}
}
// Register the command
editor.addCommand( 'wpAutoResize', resize );
function fullscreenOn() {
settings.wp_fullscreen = true;
editor.dom.addClass( editor.getDoc().documentElement, 'wp-fullscreen' );
// Add listeners for auto-resizing
editor.on( 'change setcontent paste keyup', resize );
}
function fullscreenOff() {
settings.wp_fullscreen = false;
editor.dom.removeClass( editor.getDoc().documentElement, 'wp-fullscreen' );
// Remove listeners for auto-resizing
editor.off( 'change setcontent paste keyup', resize );
oldSize = 0;
}
// For use from outside the editor.
editor.addCommand( 'wpFullScreenOn', fullscreenOn );
editor.addCommand( 'wpFullScreenOff', fullscreenOff );
function toggleFullscreen() {
// Toggle DFW mode. For use from inside the editor.
if ( typeof wp === 'undefined' || ! wp.editor || ! wp.editor.fullscreen ) {
return;
}
if ( editor.getParam('wp_fullscreen') ) {
wp.editor.fullscreen.off();
} else {
wp.editor.fullscreen.on();
}
}
editor.addCommand( 'wpFullScreen', toggleFullscreen );
editor.on( 'init', function() {
// Set the editor when initializing from whitin DFW
if ( editor.getParam('wp_fullscreen') ) {
fullscreenOn();
}
editor.addShortcut( 'alt+shift+w', '', 'wpFullScreen' );
});
// Register buttons
editor.addButton( 'wp_fullscreen', {
tooltip: 'Distraction Free Writing',
shortcut: 'Alt+Shift+W',
onclick: toggleFullscreen,
classes: 'wp-fullscreen btn widget' // This overwrites all classes on the container!
});
editor.addMenuItem( 'wp_fullscreen', {
text: 'Distraction Free Writing',
icon: 'wp_fullscreen',
shortcut: 'Alt+Shift+W',
context: 'view',
onclick: toggleFullscreen
});
});
| JavaScript |
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('tabfocus', function(editor) {
var DOM = tinymce.DOM, each = tinymce.each, explode = tinymce.explode;
function tabCancel(e) {
if (e.keyCode === 9 && !e.ctrlKey && !e.altKey && !e.metaKey) {
e.preventDefault();
}
}
function tabHandler(e) {
var x, el, v, i;
if (e.keyCode !== 9 || e.ctrlKey || e.altKey || e.metaKey) {
return;
}
function find(direction) {
el = DOM.select(':input:enabled,*[tabindex]:not(iframe)');
function canSelectRecursive(e) {
return e.nodeName === "BODY" || (e.type != 'hidden' &&
e.style.display != "none" &&
e.style.visibility != "hidden" && canSelectRecursive(e.parentNode));
}
function canSelectInOldIe(el) {
return el.tabIndex || el.nodeName == "INPUT" || el.nodeName == "TEXTAREA";
}
function canSelect(el) {
return ((!canSelectInOldIe(el))) && el.getAttribute("tabindex") != '-1' && canSelectRecursive(el);
}
each(el, function(e, i) {
if (e.id == editor.id) {
x = i;
return false;
}
});
if (direction > 0) {
for (i = x + 1; i < el.length; i++) {
if (canSelect(el[i])) {
return el[i];
}
}
} else {
for (i = x - 1; i >= 0; i--) {
if (canSelect(el[i])) {
return el[i];
}
}
}
return null;
}
v = explode(editor.getParam('tab_focus', editor.getParam('tabfocus_elements', ':prev,:next')));
if (v.length == 1) {
v[1] = v[0];
v[0] = ':prev';
}
// Find element to focus
if (e.shiftKey) {
if (v[0] == ':prev') {
el = find(-1);
} else {
el = DOM.get(v[0]);
}
} else {
if (v[1] == ':next') {
el = find(1);
} else {
el = DOM.get(v[1]);
}
}
if (el) {
var focusEditor = tinymce.get(el.id || el.name);
if (el.id && focusEditor) {
focusEditor.focus();
} else {
window.setTimeout(function() {
if (!tinymce.Env.webkit) {
window.focus();
}
el.focus();
}, 10);
}
e.preventDefault();
}
}
editor.on('init', function() {
if (editor.inline) {
// Remove default tabIndex in inline mode
tinymce.DOM.setAttrib(editor.getBody(), 'tabIndex', null);
}
});
editor.on('keyup', tabCancel);
if (tinymce.Env.gecko) {
editor.on('keypress keydown', tabHandler);
} else {
editor.on('keydown', tabHandler);
}
});
| JavaScript |
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('hr', function(editor) {
editor.addCommand('InsertHorizontalRule', function() {
editor.execCommand('mceInsertContent', false, '<hr />');
});
editor.addButton('hr', {
icon: 'hr',
tooltip: 'Horizontal line',
cmd: 'InsertHorizontalRule'
});
editor.addMenuItem('hr', {
icon: 'hr',
text: 'Horizontal line',
cmd: 'InsertHorizontalRule',
context: 'insert'
});
});
| JavaScript |
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('image', function(editor) {
function getImageSize(url, callback) {
var img = document.createElement('img');
function done(width, height) {
if (img.parentNode) {
img.parentNode.removeChild(img);
}
callback({width: width, height: height});
}
img.onload = function() {
done(img.clientWidth, img.clientHeight);
};
img.onerror = function() {
done();
};
var style = img.style;
style.visibility = 'hidden';
style.position = 'fixed';
style.bottom = style.left = 0;
style.width = style.height = 'auto';
document.body.appendChild(img);
img.src = url;
}
function applyPreview(items) {
tinymce.each(items, function(item) {
item.textStyle = function() {
return editor.formatter.getCssText({inline: 'img', classes: [item.value]});
};
});
return items;
}
function createImageList(callback) {
return function() {
var imageList = editor.settings.image_list;
if (typeof(imageList) == "string") {
tinymce.util.XHR.send({
url: imageList,
success: function(text) {
callback(tinymce.util.JSON.parse(text));
}
});
} else {
callback(imageList);
}
};
}
function showDialog(imageList) {
var win, data = {}, dom = editor.dom, imgElm = editor.selection.getNode();
var width, height, imageListCtrl, classListCtrl;
function buildValues(listSettingName, dataItemName, defaultItems) {
var selectedItem, items = [];
tinymce.each(editor.settings[listSettingName] || defaultItems, function(target) {
var item = {
text: target.text || target.title,
value: target.value
};
items.push(item);
if (data[dataItemName] === target.value || (!selectedItem && target.selected)) {
selectedItem = item;
}
});
if (selectedItem && !data[dataItemName]) {
data[dataItemName] = selectedItem.value;
selectedItem.selected = true;
}
return items;
}
function buildImageList() {
var imageListItems = [{text: 'None', value: ''}];
tinymce.each(imageList, function(image) {
imageListItems.push({
text: image.text || image.title,
value: editor.convertURL(image.value || image.url, 'src'),
menu: image.menu
});
});
return imageListItems;
}
function recalcSize() {
var widthCtrl, heightCtrl, newWidth, newHeight;
widthCtrl = win.find('#width')[0];
heightCtrl = win.find('#height')[0];
newWidth = widthCtrl.value();
newHeight = heightCtrl.value();
if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) {
if (width != newWidth) {
newHeight = Math.round((newWidth / width) * newHeight);
heightCtrl.value(newHeight);
} else {
newWidth = Math.round((newHeight / height) * newWidth);
widthCtrl.value(newWidth);
}
}
width = newWidth;
height = newHeight;
}
function onSubmitForm() {
function waitLoad(imgElm) {
function selectImage() {
imgElm.onload = imgElm.onerror = null;
editor.selection.select(imgElm);
editor.nodeChanged();
}
imgElm.onload = function() {
if (!data.width && !data.height) {
dom.setAttribs(imgElm, {
width: imgElm.clientWidth,
height: imgElm.clientHeight
});
//WP
editor.fire( 'wpNewImageRefresh', { node: imgElm } );
}
selectImage();
};
imgElm.onerror = selectImage;
}
updateStyle();
recalcSize();
data = tinymce.extend(data, win.toJSON());
var caption = data.caption; // WP
if (!data.alt) {
data.alt = '';
}
if (data.width === '') {
data.width = null;
}
if (data.height === '') {
data.height = null;
}
if (data.style === '') {
data.style = null;
}
data = {
src: data.src,
alt: data.alt,
width: data.width,
height: data.height,
style: data.style,
"class": data["class"]
};
if (!data["class"]) {
delete data["class"];
}
editor.undoManager.transact(function() {
// WP
var eventData = { node: imgElm, data: data, caption: caption };
editor.fire( 'wpImageFormSubmit', { imgData: eventData } );
if ( eventData.cancel ) {
waitLoad( eventData.node );
return;
}
// WP end
if (!data.src) {
if (imgElm) {
dom.remove(imgElm);
editor.focus();
editor.nodeChanged();
}
return;
}
if (!imgElm) {
data.id = '__mcenew';
editor.focus();
editor.selection.setContent(dom.createHTML('img', data));
imgElm = dom.get('__mcenew');
dom.setAttrib(imgElm, 'id', null);
} else {
dom.setAttribs(imgElm, data);
}
waitLoad(imgElm);
});
}
function removePixelSuffix(value) {
if (value) {
value = value.replace(/px$/, '');
}
return value;
}
function srcChange() {
if (imageListCtrl) {
imageListCtrl.value(editor.convertURL(this.value(), 'src'));
}
getImageSize(this.value(), function(data) {
if (data.width && data.height) {
width = data.width;
height = data.height;
win.find('#width').value(width);
win.find('#height').value(height);
}
});
}
width = dom.getAttrib(imgElm, 'width');
height = dom.getAttrib(imgElm, 'height');
if (imgElm.nodeName == 'IMG' && !imgElm.getAttribute('data-mce-object') && !imgElm.getAttribute('data-mce-placeholder')) {
data = {
src: dom.getAttrib(imgElm, 'src'),
alt: dom.getAttrib(imgElm, 'alt'),
"class": dom.getAttrib(imgElm, 'class'),
width: width,
height: height
};
// WP
editor.fire( 'wpLoadImageData', { imgData: { data: data, node: imgElm } } );
} else {
imgElm = null;
}
if (imageList) {
imageListCtrl = {
type: 'listbox',
label: 'Image list',
values: buildImageList(),
value: data.src && editor.convertURL(data.src, 'src'),
onselect: function(e) {
var altCtrl = win.find('#alt');
if (!altCtrl.value() || (e.lastControl && altCtrl.value() == e.lastControl.text())) {
altCtrl.value(e.control.text());
}
win.find('#src').value(e.control.value());
},
onPostRender: function() {
imageListCtrl = this;
}
};
}
if (editor.settings.image_class_list) {
classListCtrl = {
name: 'class',
type: 'listbox',
label: 'Class',
values: applyPreview(buildValues('image_class_list', 'class'))
};
}
// General settings shared between simple and advanced dialogs
var generalFormItems = [
{name: 'src', type: 'filepicker', filetype: 'image', label: 'Source', autofocus: true, onchange: srcChange},
imageListCtrl
];
if (editor.settings.image_description !== false) {
generalFormItems.push({name: 'alt', type: 'textbox', label: 'Image description'});
}
if (editor.settings.image_dimensions !== false) {
generalFormItems.push({
type: 'container',
label: 'Dimensions',
layout: 'flex',
direction: 'row',
align: 'center',
spacing: 5,
items: [
{name: 'width', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Width'},
{type: 'label', text: 'x'},
{name: 'height', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Height'},
{name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'}
]
});
}
generalFormItems.push(classListCtrl);
// WP
editor.fire( 'wpLoadImageForm', { data: generalFormItems } );
function updateStyle() {
function addPixelSuffix(value) {
if (value.length > 0 && /^[0-9]+$/.test(value)) {
value += 'px';
}
return value;
}
if (!editor.settings.image_advtab) {
return;
}
var data = win.toJSON();
var css = dom.parseStyle(data.style);
delete css.margin;
css['margin-top'] = css['margin-bottom'] = addPixelSuffix(data.vspace);
css['margin-left'] = css['margin-right'] = addPixelSuffix(data.hspace);
css['border-width'] = addPixelSuffix(data.border);
win.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css))));
}
if (editor.settings.image_advtab) {
// Parse styles from img
if (imgElm) {
data.hspace = removePixelSuffix(imgElm.style.marginLeft || imgElm.style.marginRight);
data.vspace = removePixelSuffix(imgElm.style.marginTop || imgElm.style.marginBottom);
data.border = removePixelSuffix(imgElm.style.borderWidth);
data.style = editor.dom.serializeStyle(editor.dom.parseStyle(editor.dom.getAttrib(imgElm, 'style')));
}
// Advanced dialog shows general+advanced tabs
win = editor.windowManager.open({
title: 'Insert/edit image',
data: data,
bodyType: 'tabpanel',
body: [
{
title: 'General',
type: 'form',
items: generalFormItems
},
{
title: 'Advanced',
type: 'form',
pack: 'start',
items: [
{
label: 'Style',
name: 'style',
type: 'textbox'
},
{
type: 'form',
layout: 'grid',
packV: 'start',
columns: 2,
padding: 0,
alignH: ['left', 'right'],
defaults: {
type: 'textbox',
maxWidth: 50,
onchange: updateStyle
},
items: [
{label: 'Vertical space', name: 'vspace'},
{label: 'Horizontal space', name: 'hspace'},
{label: 'Border', name: 'border'}
]
}
]
}
],
onSubmit: onSubmitForm
});
} else {
// Simple default dialog
win = editor.windowManager.open({
title: 'Insert/edit image',
data: data,
body: generalFormItems,
onSubmit: onSubmitForm
});
}
}
// WP
editor.addCommand( 'mceImage', function() {
createImageList( showDialog )();
});
editor.addButton('image', {
icon: 'image',
tooltip: 'Insert/edit image',
onclick: createImageList(showDialog),
stateSelector: 'img:not([data-mce-object],[data-mce-placeholder])'
});
editor.addMenuItem('image', {
icon: 'image',
text: 'Insert image',
onclick: createImageList(showDialog),
context: 'insert',
prependToContext: true
});
});
| JavaScript |
/* global tinymce */
tinymce.PluginManager.add('wpgallery', function( editor ) {
function replaceGalleryShortcodes( content ) {
return content.replace( /\[gallery([^\]]*)\]/g, function( match ) {
return html( 'wp-gallery', match );
});
}
function html( cls, data ) {
data = window.encodeURIComponent( data );
return '<img src="' + tinymce.Env.transparentSrc + '" class="wp-media mceItem ' + cls + '" ' +
'data-wp-media="' + data + '" data-mce-resize="false" data-mce-placeholder="1" />';
}
function restoreMediaShortcodes( content ) {
function getAttr( str, name ) {
name = new RegExp( name + '=\"([^\"]+)\"' ).exec( str );
return name ? window.decodeURIComponent( name[1] ) : '';
}
return content.replace( /(?:<p(?: [^>]+)?>)*(<img [^>]+>)(?:<\/p>)*/g, function( match, image ) {
var data = getAttr( image, 'data-wp-media' );
if ( data ) {
return '<p>' + data + '</p>';
}
return match;
});
}
function editMedia( node ) {
var gallery, frame, data;
if ( node.nodeName !== 'IMG' ) {
return;
}
// Check if the `wp.media` API exists.
if ( typeof wp === 'undefined' || ! wp.media ) {
return;
}
data = window.decodeURIComponent( editor.dom.getAttrib( node, 'data-wp-media' ) );
// Make sure we've selected a gallery node.
if ( editor.dom.hasClass( node, 'wp-gallery' ) && wp.media.gallery ) {
gallery = wp.media.gallery;
frame = gallery.edit( data );
frame.state('gallery-edit').on( 'update', function( selection ) {
var shortcode = gallery.shortcode( selection ).string();
editor.dom.setAttrib( node, 'data-wp-media', window.encodeURIComponent( shortcode ) );
frame.detach();
});
}
}
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...');
editor.addCommand( 'WP_Gallery', function() {
editMedia( editor.selection.getNode() );
});
/*
editor.on( 'init', function( e ) {
// _createButtons()
// iOS6 doesn't show the buttons properly on click, show them on 'touchstart'
if ( 'ontouchstart' in window ) {
editor.dom.events.bind( editor.getBody(), 'touchstart', function( e ) {
var target = e.target;
if ( target.nodeName == 'IMG' && editor.dom.hasClass( target, 'wp-gallery' ) ) {
editor.selection.select( target );
editor.dom.events.cancel( e );
editor.plugins.wordpress._hideButtons();
editor.plugins.wordpress._showButtons( target, 'wp_gallerybtns' );
}
});
}
});
*/
editor.on( 'mouseup', function( event ) {
var dom = editor.dom,
node = event.target;
function unselect() {
dom.removeClass( dom.select( 'img.wp-media-selected' ), 'wp-media-selected' );
}
if ( node.nodeName === 'IMG' && dom.getAttrib( node, 'data-wp-media' ) ) {
// Don't trigger on right-click
if ( event.button !== 2 ) {
if ( dom.hasClass( node, 'wp-media-selected' ) ) {
editMedia( node );
} else {
unselect();
dom.addClass( node, 'wp-media-selected' );
}
}
} else {
unselect();
}
});
// Display gallery, audio or video instead of img in the element path
editor.on( 'ResolveName', function( event ) {
var dom = editor.dom,
node = event.target;
if ( node.nodeName === 'IMG' && dom.getAttrib( node, 'data-wp-media' ) ) {
if ( dom.hasClass( node, 'wp-gallery' ) ) {
event.name = 'gallery';
}
}
});
editor.on( 'BeforeSetContent', function( event ) {
// 'wpview' handles the gallery shortcode when present
if ( ! editor.plugins.wpview ) {
event.content = replaceGalleryShortcodes( event.content );
}
});
editor.on( 'PostProcess', function( event ) {
if ( event.get ) {
event.content = restoreMediaShortcodes( event.content );
}
});
});
| JavaScript |
/* global tinymce, getUserSetting, setUserSetting */
// Set the minimum value for the modals z-index higher than #wpadminbar (100000)
tinymce.ui.FloatPanel.zIndex = 100100;
tinymce.PluginManager.add( 'wordpress', function( editor ) {
var DOM = tinymce.DOM, wpAdvButton, modKey, style,
last = 0;
function toggleToolbars( state ) {
var iframe, initial, toolbars,
pixels = 0;
initial = ( state === 'hide' );
if ( editor.theme.panel ) {
toolbars = editor.theme.panel.find('.toolbar:not(.menubar)');
}
if ( ! toolbars || toolbars.length < 2 || ( state === 'hide' && ! toolbars[1].visible() ) ) {
return;
}
if ( ! state && toolbars[1].visible() ) {
state = 'hide';
}
tinymce.each( toolbars, function( toolbar, i ) {
if ( i > 0 ) {
if ( state === 'hide' ) {
toolbar.hide();
pixels += 30;
} else {
toolbar.show();
pixels -= 30;
}
}
});
if ( pixels && ! initial ) {
iframe = editor.getContentAreaContainer().firstChild;
DOM.setStyle( iframe, 'height', iframe.clientHeight + pixels ); // Resize iframe
if ( state === 'hide' ) {
setUserSetting('hidetb', '0');
wpAdvButton && wpAdvButton.active( false );
} else {
setUserSetting('hidetb', '1');
wpAdvButton && wpAdvButton.active( true );
}
}
}
// Add the kitchen sink button :)
editor.addButton( 'wp_adv', {
tooltip: 'Toolbar Toggle',
cmd: 'WP_Adv',
onPostRender: function() {
wpAdvButton = this;
wpAdvButton.active( getUserSetting( 'hidetb' ) === '1' ? true : false );
}
});
// Hide the toolbars after loading
editor.on( 'PostRender', function() {
if ( getUserSetting('hidetb', '0') === '0' ) {
toggleToolbars( 'hide' );
}
});
editor.addCommand( 'WP_Adv', function() {
toggleToolbars();
});
editor.on( 'focus', function() {
window.wpActiveEditor = editor.id;
});
// Replace Read More/Next Page tags with images
editor.on( 'BeforeSetContent', function( e ) {
if ( e.content ) {
if ( e.content.indexOf( '<!--more' ) !== -1 ) {
e.content = e.content.replace( /<!--more(.*?)-->/g, function( match, moretext ) {
return '<img src="' + tinymce.Env.transparentSrc + '" data-wp-more="' + moretext + '" ' +
'class="wp-more-tag mce-wp-more" title="Read More..." data-mce-resize="false" data-mce-placeholder="1" />';
});
}
if ( e.content.indexOf( '<!--nextpage-->' ) !== -1 ) {
e.content = e.content.replace( /<!--nextpage-->/g,
'<img src="' + tinymce.Env.transparentSrc + '" class="wp-more-tag mce-wp-nextpage" ' +
'title="Page break" data-mce-resize="false" data-mce-placeholder="1" />' );
}
}
});
// Replace images with tags
editor.on( 'PostProcess', function( e ) {
if ( e.get ) {
e.content = e.content.replace(/<img[^>]+>/g, function( image ) {
var match, moretext = '';
if ( image.indexOf('wp-more-tag') !== -1 ) {
if ( image.indexOf('mce-wp-more') !== -1 ) {
if ( match = image.match( /data-wp-more="([^"]+)"/ ) ) {
moretext = match[1];
}
image = '<!--more' + moretext + '-->';
} else if ( image.indexOf('mce-wp-nextpage') !== -1 ) {
image = '<!--nextpage-->';
}
}
return image;
});
}
});
// Display the tag name instead of img in element path
editor.on( 'ResolveName', function( e ) {
var dom = editor.dom,
target = e.target;
if ( target.nodeName === 'IMG' && dom.hasClass( target, 'wp-more-tag' ) ) {
if ( dom.hasClass( target, 'mce-wp-more' ) ) {
e.name = 'more';
} else if ( dom.hasClass( target, 'mce-wp-nextpage' ) ) {
e.name = 'nextpage';
}
}
});
// Register commands
editor.addCommand( 'WP_More', function( tag ) {
var parent, html, title,
classname = 'wp-more-tag',
dom = editor.dom,
node = editor.selection.getNode();
tag = tag || 'more';
classname += ' mce-wp-' + tag;
title = tag === 'more' ? 'More...' : 'Next Page';
html = '<img src="' + tinymce.Env.transparentSrc + '" title="' + title + '" class="' + classname + '" ' +
'data-mce-resize="false" data-mce-placeholder="1" />';
// Most common case
if ( node.nodeName === 'BODY' || ( node.nodeName === 'P' && node.parentNode.nodeName === 'BODY' ) ) {
editor.insertContent( html );
return;
}
// Get the top level parent node
parent = dom.getParent( node, function( found ) {
if ( found.parentNode && found.parentNode.nodeName === 'BODY' ) {
return true;
}
return false;
}, editor.getBody() );
if ( parent ) {
if ( parent.nodeName === 'P' ) {
parent.appendChild( dom.create( 'p', null, html ).firstChild );
} else {
dom.insertAfter( dom.create( 'p', null, html ), parent );
}
editor.nodeChanged();
}
});
editor.addCommand( 'WP_Code', function() {
editor.formatter.toggle('code');
});
editor.addCommand( 'WP_Page', function() {
editor.execCommand( 'WP_More', 'nextpage' );
});
editor.addCommand( 'WP_Help', function() {
editor.windowManager.open({
url: tinymce.baseURL + '/wp-mce-help.php',
title: 'Keyboard Shortcuts',
width: 450,
height: 420,
inline: 1,
classes: 'wp-help'
});
});
editor.addCommand( 'WP_Medialib', function() {
if ( typeof wp !== 'undefined' && wp.media && wp.media.editor ) {
wp.media.editor.open( editor.id );
}
});
// Register buttons
editor.addButton( 'wp_more', {
tooltip: 'Insert Read More tag',
onclick: function() {
editor.execCommand( 'WP_More', 'more' );
}
});
editor.addButton( 'wp_page', {
tooltip: 'Page break',
onclick: function() {
editor.execCommand( 'WP_More', 'nextpage' );
}
});
editor.addButton( 'wp_help', {
tooltip: 'Keyboard Shortcuts',
cmd: 'WP_Help'
});
editor.addButton( 'wp_code', {
tooltip: 'Code',
cmd: 'WP_Code',
stateSelector: 'code'
});
// Menubar
// Insert->Add Media
if ( typeof wp !== 'undefined' && wp.media && wp.media.editor ) {
editor.addMenuItem( 'add_media', {
text: 'Add Media',
icon: 'wp-media-library',
context: 'insert',
cmd: 'WP_Medialib'
});
}
// Insert "Read More..."
editor.addMenuItem( 'wp_more', {
text: 'Insert Read More tag',
icon: 'wp_more',
context: 'insert',
onclick: function() {
editor.execCommand( 'WP_More', 'more' );
}
});
// Insert "Next Page"
editor.addMenuItem( 'wp_page', {
text: 'Page break',
icon: 'wp_page',
context: 'insert',
onclick: function() {
editor.execCommand( 'WP_More', 'nextpage' );
}
});
editor.on( 'BeforeExecCommand', function(e) {
if ( tinymce.Env.webkit && ( e.command === 'InsertUnorderedList' || e.command === 'InsertOrderedList' ) ) {
if ( ! style ) {
style = editor.dom.create( 'style', {'type': 'text/css'},
'#tinymce,#tinymce span,#tinymce li,#tinymce li>span,#tinymce p,#tinymce p>span{font:medium sans-serif;color:#000;line-height:normal;}');
}
editor.getDoc().head.appendChild( style );
}
});
editor.on( 'ExecCommand', function( e ) {
if ( tinymce.Env.webkit && style &&
( 'InsertUnorderedList' === e.command || 'InsertOrderedList' === e.command ) ) {
editor.dom.remove( style );
}
});
editor.on( 'init', function() {
var env = tinymce.Env,
bodyClass = ['mceContentBody'], // back-compat for themes that use this in editor-style.css...
doc = editor.getDoc(),
dom = editor.dom;
if ( editor.getParam( 'directionality' ) === 'rtl' ) {
bodyClass.push('rtl');
dom.setAttrib( doc.documentElement, 'dir', 'rtl' );
}
if ( env.ie ) {
if ( parseInt( env.ie, 10 ) === 9 ) {
bodyClass.push('ie9');
} else if ( parseInt( env.ie, 10 ) === 8 ) {
bodyClass.push('ie8');
} else if ( env.ie < 8 ) {
bodyClass.push('ie7');
}
}
bodyClass.push('wp-editor');
tinymce.each( bodyClass, function( cls ) {
if ( cls ) {
dom.addClass( doc.body, cls );
}
});
// Remove invalid parent paragraphs when inserting HTML
// TODO: still needed?
editor.on( 'BeforeSetContent', function( e ) {
if ( e.content ) {
e.content = e.content.replace(/<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)( [^>]*)?>/gi, '<$1$2>');
e.content = e.content.replace(/<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)>\s*<\/p>/gi, '</$1>');
}
});
if ( typeof window.jQuery !== 'undefined' ) {
window.jQuery( document ).triggerHandler( 'tinymce-editor-init', [editor] );
}
if ( window.tinyMCEPreInit && window.tinyMCEPreInit.dragDropUpload ) {
dom.bind( doc, 'dragstart dragend dragover drop', function( event ) {
if ( typeof window.jQuery !== 'undefined' ) {
// Trigger the jQuery handlers.
window.jQuery( document ).triggerHandler( event.type );
}
});
}
});
// Word count
if ( typeof window.jQuery !== 'undefined' ) {
editor.on( 'keyup', function( e ) {
var key = e.keyCode || e.charCode;
if ( key === last ) {
return;
}
if ( 13 === key || 8 === last || 46 === last ) {
window.jQuery( document ).triggerHandler( 'wpcountwords', [ editor.getContent({ format : 'raw' }) ] );
}
last = key;
});
}
editor.on( 'SaveContent', function( e ) {
// If editor is hidden, we just want the textarea's value to be saved
if ( editor.isHidden() ) {
e.content = e.element.value;
return;
}
// Keep empty paragraphs :(
e.content = e.content.replace( /<p>(<br ?\/?>|\u00a0|\uFEFF)?<\/p>/g, '<p> </p>' );
if ( editor.getParam( 'wpautop', true ) && typeof window.switchEditors !== 'undefined' ) {
e.content = window.switchEditors.pre_wpautop( e.content );
}
});
editor.on( 'preInit', function() {
// Don't replace <i> with <em> and <b> with <strong> and don't remove them when empty
editor.schema.addValidElements( '@[id|accesskey|class|dir|lang|style|tabindex|title|contenteditable|draggable|dropzone|hidden|spellcheck|translate],i,b' );
});
// Add custom shortcuts
modKey = 'alt+shift';
editor.addShortcut( modKey + '+c', '', 'JustifyCenter' );
editor.addShortcut( modKey + '+r', '', 'JustifyRight' );
editor.addShortcut( modKey + '+l', '', 'JustifyLeft' );
editor.addShortcut( modKey + '+j', '', 'JustifyFull' );
editor.addShortcut( modKey + '+q', '', 'mceBlockQuote' );
editor.addShortcut( modKey + '+u', '', 'InsertUnorderedList' );
editor.addShortcut( modKey + '+o', '', 'InsertOrderedList' );
editor.addShortcut( modKey + '+n', '', 'mceSpellCheck' );
editor.addShortcut( modKey + '+s', '', 'unlink' );
editor.addShortcut( modKey + '+m', '', 'WP_Medialib' );
editor.addShortcut( modKey + '+z', '', 'WP_Adv' );
editor.addShortcut( modKey + '+t', '', 'WP_More' );
editor.addShortcut( modKey + '+d', '', 'Strikethrough' );
editor.addShortcut( modKey + '+h', '', 'WP_Help' );
editor.addShortcut( modKey + '+p', '', 'WP_Page' );
editor.addShortcut( modKey + '+x', '', 'WP_Code' );
editor.addShortcut( 'ctrl+s', '', function() {
if ( typeof wp !== 'undefined' && wp.autosave ) {
wp.autosave.server.triggerSave();
}
});
// popup buttons for the gallery, etc.
editor.on( 'init', function() {
editor.dom.bind( editor.getWin(), 'scroll', function() {
_hideButtons();
});
editor.dom.bind( editor.getBody(), 'dragstart', function() {
_hideButtons();
});
});
editor.on( 'BeforeExecCommand', function() {
_hideButtons();
});
editor.on( 'SaveContent', function() {
_hideButtons();
});
editor.on( 'MouseDown', function( e ) {
if ( e.target.nodeName !== 'IMG' ) {
_hideButtons();
}
});
editor.on( 'keydown', function( e ) {
if ( e.which === tinymce.util.VK.DELETE || e.which === tinymce.util.VK.BACKSPACE ) {
_hideButtons();
}
});
// Internal functions
function _setEmbed( c ) {
return c.replace( /\[embed\]([\s\S]+?)\[\/embed\][\s\u00a0]*/g, function( a, b ) {
return '<img width="300" height="200" src="' + tinymce.Env.transparentSrc + '" class="wp-oembed" ' +
'alt="'+ b +'" title="'+ b +'" data-mce-resize="false" data-mce-placeholder="1" />';
});
}
function _getEmbed( c ) {
return c.replace( /<img[^>]+>/g, function( a ) {
if ( a.indexOf('class="wp-oembed') !== -1 ) {
var u = a.match( /alt="([^\"]+)"/ );
if ( u[1] ) {
a = '[embed]' + u[1] + '[/embed]';
}
}
return a;
});
}
function _showButtons( n, id ) {
var p1, p2, vp, X, Y;
vp = editor.dom.getViewPort( editor.getWin() );
p1 = DOM.getPos( editor.getContentAreaContainer() );
p2 = editor.dom.getPos( n );
X = Math.max( p2.x - vp.x, 0 ) + p1.x;
Y = Math.max( p2.y - vp.y, 0 ) + p1.y;
DOM.setStyles( id, {
'top' : Y + 5 + 'px',
'left' : X + 5 + 'px',
'display': 'block'
});
}
function _hideButtons() {
DOM.hide( DOM.select( '#wp_editbtns, #wp_gallerybtns' ) );
}
// Expose some functions (back-compat)
return {
_showButtons: _showButtons,
_hideButtons: _hideButtons,
_setEmbed: _setEmbed,
_getEmbed: _getEmbed
};
});
| JavaScript |
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
/*eslint consistent-this:0 */
tinymce.PluginManager.add('textcolor', function(editor) {
function mapColors() {
var i, colors = [], colorMap;
colorMap = editor.settings.textcolor_map || [
"000000", "Black",
"993300", "Burnt orange",
"333300", "Dark olive",
"003300", "Dark green",
"003366", "Dark azure",
"000080", "Navy Blue",
"333399", "Indigo",
"333333", "Very dark gray",
"800000", "Maroon",
"FF6600", "Orange",
"808000", "Olive",
"008000", "Green",
"008080", "Teal",
"0000FF", "Blue",
"666699", "Grayish blue",
"808080", "Gray",
"FF0000", "Red",
"FF9900", "Amber",
"99CC00", "Yellow green",
"339966", "Sea green",
"33CCCC", "Turquoise",
"3366FF", "Royal blue",
"800080", "Purple",
"999999", "Medium gray",
"FF00FF", "Magenta",
"FFCC00", "Gold",
"FFFF00", "Yellow",
"00FF00", "Lime",
"00FFFF", "Aqua",
"00CCFF", "Sky blue",
"993366", "Brown",
"C0C0C0", "Silver",
"FF99CC", "Pink",
"FFCC99", "Peach",
"FFFF99", "Light yellow",
"CCFFCC", "Pale green",
"CCFFFF", "Pale cyan",
"99CCFF", "Light sky blue",
"CC99FF", "Plum",
"FFFFFF", "White"
];
for (i = 0; i < colorMap.length; i += 2) {
colors.push({
text: colorMap[i + 1],
color: colorMap[i]
});
}
return colors;
}
function renderColorPicker() {
var ctrl = this, colors, color, html, last, rows, cols, x, y, i;
colors = mapColors();
html = '<table class="mce-grid mce-grid-border mce-colorbutton-grid" role="list" cellspacing="0"><tbody>';
last = colors.length - 1;
rows = editor.settings.textcolor_rows || 5;
cols = editor.settings.textcolor_cols || 8;
for (y = 0; y < rows; y++) {
html += '<tr>';
for (x = 0; x < cols; x++) {
i = y * cols + x;
if (i > last) {
html += '<td></td>';
} else {
color = colors[i];
html += (
'<td>' +
'<div id="' + ctrl._id + '-' + i + '"' +
' data-mce-color="' + color.color + '"' +
' role="option"' +
' tabIndex="-1"' +
' style="' + (color ? 'background-color: #' + color.color : '') + '"' +
' title="' + color.text + '">' +
'</div>' +
'</td>'
);
}
}
html += '</tr>';
}
html += '</tbody></table>';
return html;
}
function onPanelClick(e) {
var buttonCtrl = this.parent(), value;
if ((value = e.target.getAttribute('data-mce-color'))) {
if (this.lastId) {
document.getElementById(this.lastId).setAttribute('aria-selected', false);
}
e.target.setAttribute('aria-selected', true);
this.lastId = e.target.id;
buttonCtrl.hidePanel();
value = '#' + value;
buttonCtrl.color(value);
editor.execCommand(buttonCtrl.settings.selectcmd, false, value);
}
}
function onButtonClick() {
var self = this;
if (self._color) {
editor.execCommand(self.settings.selectcmd, false, self._color);
}
}
editor.addButton('forecolor', {
type: 'colorbutton',
tooltip: 'Text color',
selectcmd: 'ForeColor',
panel: {
role: 'application',
ariaRemember: true,
html: renderColorPicker,
onclick: onPanelClick
},
onclick: onButtonClick
});
editor.addButton('backcolor', {
type: 'colorbutton',
tooltip: 'Background color',
selectcmd: 'HiliteColor',
panel: {
role: 'application',
ariaRemember: true,
html: renderColorPicker,
onclick: onPanelClick
},
onclick: onButtonClick
});
});
| JavaScript |
/* global tinymce */
/**
* WordPress View plugin.
*/
tinymce.PluginManager.add( 'wpview', function( editor ) {
var selected,
VK = tinymce.util.VK,
TreeWalker = tinymce.dom.TreeWalker,
toRemove = false;
function getParentView( node ) {
while ( node && node.nodeName !== 'BODY' ) {
if ( isView( node ) ) {
return node;
}
node = node.parentNode;
}
}
function isView( node ) {
return node && /\bwpview-wrap\b/.test( node.className );
}
function createPadNode() {
return editor.dom.create( 'p', { 'data-wpview-pad': 1 },
( tinymce.Env.ie && tinymce.Env.ie < 11 ) ? '' : '<br data-mce-bogus="1" />' );
}
/**
* Get the text/shortcode string for a view.
*
* @param view The view wrapper's HTML id or node
* @returns string The text/shoercode string of the view
*/
function getViewText( view ) {
view = getParentView( typeof view === 'string' ? editor.dom.get( view ) : view );
if ( view ) {
return window.decodeURIComponent( editor.dom.getAttrib( view, 'data-wpview-text' ) || '' );
}
return '';
}
/**
* Set the view's original text/shortcode string
*
* @param view The view wrapper's HTML id or node
* @param text The text string to be set
*/
function setViewText( view, text ) {
view = getParentView( typeof view === 'string' ? editor.dom.get( view ) : view );
if ( view ) {
editor.dom.setAttrib( view, 'data-wpview-text', window.encodeURIComponent( text || '' ) );
return true;
}
return false;
}
function _stop( event ) {
event.stopPropagation();
}
function select( viewNode ) {
var clipboard,
dom = editor.dom;
// Bail if node is already selected.
if ( viewNode === selected ) {
return;
}
deselect();
selected = viewNode;
dom.addClass( viewNode, 'selected' );
clipboard = dom.create( 'div', {
'class': 'wpview-clipboard',
'contenteditable': 'true'
}, getViewText( viewNode ) );
// Prepend inside the wrapper
viewNode.insertBefore( clipboard, viewNode.firstChild );
// Both of the following are necessary to prevent manipulating the selection/focus
dom.bind( clipboard, 'beforedeactivate focusin focusout', _stop );
dom.bind( selected, 'beforedeactivate focusin focusout', _stop );
// Make sure that the editor is focused.
// It is possible that the editor is not focused when the mouse event fires
// without focus, the selection will not work properly.
editor.getBody().focus();
// select the hidden div
editor.selection.select( clipboard, true );
}
/**
* Deselect a selected view and remove clipboard
*/
function deselect() {
var clipboard,
dom = editor.dom;
if ( selected ) {
clipboard = editor.dom.select( '.wpview-clipboard', selected )[0];
dom.unbind( clipboard );
dom.remove( clipboard );
dom.unbind( selected, 'beforedeactivate focusin focusout click mouseup', _stop );
dom.removeClass( selected, 'selected' );
}
selected = null;
}
function selectSiblingView( node, direction ) {
var body = editor.getBody(),
sibling = direction === 'previous' ? 'previousSibling' : 'nextSibling';
while ( node && node.parentNode !== body ) {
if ( node[sibling] ) {
// The caret will be in another element
return false;
}
node = node.parentNode;
}
if ( isView( node[sibling] ) ) {
select( node[sibling] );
return true;
}
return false;
}
// Check if the `wp.mce` API exists.
if ( typeof wp === 'undefined' || ! wp.mce ) {
return;
}
// Remove the content of view wrappers from HTML string
function emptyViews( content ) {
return content.replace(/(<div[^>]+wpview-wrap[^>]+>)[\s\S]+?data-wpview-end[^>]*><\/ins><\/div>/g, '$1</div>' );
}
// Prevent adding undo levels on changes inside a view wrapper
editor.on( 'BeforeAddUndo', function( event ) {
if ( event.lastLevel && emptyViews( event.level.content ) === emptyViews( event.lastLevel.content ) ) {
event.preventDefault();
}
});
// When the editor's content changes, scan the new content for
// matching view patterns, and transform the matches into
// view wrappers.
editor.on( 'BeforeSetContent', function( event ) {
if ( ! event.content ) {
return;
}
if ( ! event.initial ) {
wp.mce.views.unbind( editor );
}
event.content = wp.mce.views.toViews( event.content );
});
// When the editor's content has been updated and the DOM has been
// processed, render the views in the document.
editor.on( 'SetContent', function( event ) {
var body, padNode;
wp.mce.views.render();
// Add padding <p> if the noneditable node is last
if ( event.load || ! event.set ) {
body = editor.getBody();
if ( isView( body.lastChild ) ) {
padNode = createPadNode();
body.appendChild( padNode );
if ( ! event.initial ) {
editor.selection.setCursorLocation( padNode, 0 );
}
}
}
});
// Detect mouse down events that are adjacent to a view when a view is the first view or the last view
editor.on( 'click', function( event ) {
var body = editor.getBody(),
doc = editor.getDoc(),
scrollTop = doc.documentElement.scrollTop || body.scrollTop || 0,
x, y, firstNode, lastNode, padNode;
if ( event.target.nodeName === 'HTML' && ! event.metaKey && ! event.ctrlKey ) {
firstNode = body.firstChild;
lastNode = body.lastChild;
x = event.clientX;
y = event.clientY;
// Detect clicks above or to the left if the first node is a wpview
if ( isView( firstNode ) && ( ( x < firstNode.offsetLeft && y < ( firstNode.offsetHeight - scrollTop ) ) ||
y < firstNode.offsetTop ) ) {
padNode = createPadNode();
body.insertBefore( padNode, firstNode );
// Detect clicks to the right and below the last view
} else if ( isView( lastNode ) && ( x > ( lastNode.offsetLeft + lastNode.offsetWidth ) ||
( ( scrollTop + y ) - ( lastNode.offsetTop + lastNode.offsetHeight ) ) > 0 ) ) {
padNode = createPadNode();
body.appendChild( padNode );
}
if ( padNode ) {
// Make sure that a selected view is deselected so that focus and selection are handled properly
deselect();
editor.getBody().focus();
editor.selection.setCursorLocation( padNode, 0 );
}
}
});
editor.on( 'init', function() {
var selection = editor.selection;
// When a view is selected, ensure content that is being pasted
// or inserted is added to a text node (instead of the view).
editor.on( 'BeforeSetContent', function() {
var walker, target,
view = getParentView( selection.getNode() );
// If the selection is not within a view, bail.
if ( ! view ) {
return;
}
if ( ! view.nextSibling || isView( view.nextSibling ) ) {
// If there are no additional nodes or the next node is a
// view, create a text node after the current view.
target = editor.getDoc().createTextNode('');
editor.dom.insertAfter( target, view );
} else {
// Otherwise, find the next text node.
walker = new TreeWalker( view.nextSibling, view.nextSibling );
target = walker.next();
}
// Select the `target` text node.
selection.select( target );
selection.collapse( true );
});
// When the selection's content changes, scan any new content
// for matching views.
//
// Runs on paste and on inserting nodes/html.
editor.on( 'SetContent', function( e ) {
if ( ! e.context ) {
return;
}
var node = selection.getNode();
if ( ! node.innerHTML ) {
return;
}
node.innerHTML = wp.mce.views.toViews( node.innerHTML );
});
editor.dom.bind( editor.getBody(), 'mousedown mouseup click', function( event ) {
var view = getParentView( event.target ),
deselectEventType;
// Contain clicks inside the view wrapper
if ( view ) {
event.stopPropagation();
// Hack to try and keep the block resize handles from appearing. They will show on mousedown and then be removed on mouseup.
if ( tinymce.Env.ie <= 10 ) {
deselect();
}
select( view );
if ( event.type === 'click' && ! event.metaKey && ! event.ctrlKey ) {
if ( editor.dom.hasClass( event.target, 'edit' ) ) {
wp.mce.views.edit( view );
} else if ( editor.dom.hasClass( event.target, 'remove' ) ) {
editor.dom.remove( view );
}
}
// Returning false stops the ugly bars from appearing in IE11 and stops the view being selected as a range in FF.
// Unfortunately, it also inhibits the dragging of views to a new location.
return false;
} else {
// Fix issue with deselecting a view in IE8. Without this hack, clicking content above the view wouldn't actually deselect it
// and the caret wouldn't be placed at the mouse location
if ( tinymce.Env.ie && tinymce.Env.ie <= 8 ) {
deselectEventType = 'mouseup';
} else {
deselectEventType = 'mousedown';
}
if ( event.type === deselectEventType ) {
deselect();
}
}
});
});
editor.on( 'PreProcess', function( event ) {
var dom = editor.dom;
// Remove empty padding nodes
tinymce.each( dom.select( 'p[data-wpview-pad]', event.node ), function( node ) {
if ( dom.isEmpty( node ) ) {
dom.remove( node );
} else {
dom.setAttrib( node, 'data-wpview-pad', null );
}
});
// Replace the wpview node with the wpview string/shortcode?
tinymce.each( dom.select( 'div[data-wpview-text]', event.node ), function( node ) {
// Empty the wrap node
if ( 'textContent' in node ) {
node.textContent = '';
} else {
node.innerText = '';
}
// This makes all views into block tags (as we use <div>).
// Can use 'PostProcess' and a regex instead.
dom.replace( dom.create( 'p', null, window.decodeURIComponent( dom.getAttrib( node, 'data-wpview-text' ) ) ), node );
});
});
editor.on( 'keydown', function( event ) {
var keyCode = event.keyCode,
body = editor.getBody(),
view, padNode;
// If a view isn't selected, let the event go on its merry way.
if ( ! selected ) {
return;
}
// Let keypresses that involve the command or control keys through.
// Also, let any of the F# keys through.
if ( event.metaKey || event.ctrlKey || ( keyCode >= 112 && keyCode <= 123 ) ) {
if ( ( event.metaKey || event.ctrlKey ) && keyCode === 88 ) {
toRemove = selected;
}
return;
}
view = getParentView( editor.selection.getNode() );
// If the caret is not within the selected view, deselect the
// view and bail.
if ( view !== selected ) {
deselect();
return;
}
// Deselect views with the arrow keys
if ( keyCode === VK.LEFT || keyCode === VK.UP ) {
deselect();
// Handle case where two views are stacked on top of one another
if ( isView( view.previousSibling ) ) {
select( view.previousSibling );
// Handle case where view is the first node
} else if ( ! view.previousSibling ) {
padNode = createPadNode();
body.insertBefore( padNode, body.firstChild );
editor.selection.setCursorLocation( body.firstChild, 0 );
// Handle default case
} else {
editor.selection.select( view.previousSibling, true );
editor.selection.collapse();
}
} else if ( keyCode === VK.RIGHT || keyCode === VK.DOWN ) {
deselect();
// Handle case where the next node is another wpview
if ( isView( view.nextSibling ) ) {
select( view.nextSibling );
// Handle case were the view is that last node
} else if ( ! view.nextSibling ) {
padNode = createPadNode();
body.appendChild( padNode );
editor.selection.setCursorLocation( body.lastChild, 0 );
// Handle default case where the next node is a non-wpview
} else {
editor.selection.setCursorLocation( view.nextSibling, 0 );
}
} else if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) {
// If delete or backspace is pressed, delete the view.
editor.dom.remove( selected );
}
event.preventDefault();
});
// Select views when arrow keys are used to navigate the content of the editor.
editor.on( 'keydown', function( event ) {
var keyCode = event.keyCode,
dom = editor.dom,
range = editor.selection.getRng(),
startNode = range.startContainer,
body = editor.getBody(),
node, container;
if ( ! startNode || startNode === body || event.metaKey || event.ctrlKey ) {
return;
}
if ( keyCode === VK.UP || keyCode === VK.LEFT ) {
if ( keyCode === VK.LEFT && ( ! range.collapsed || range.startOffset !== 0 ) ) {
// Not at the beginning of the current range
return;
}
if ( ! ( node = dom.getParent( startNode, dom.isBlock ) ) ) {
return;
}
if ( selectSiblingView( node, 'previous' ) ) {
event.preventDefault();
}
} else if ( keyCode === VK.DOWN || keyCode === VK.RIGHT ) {
if ( ! ( node = dom.getParent( startNode, dom.isBlock ) ) ) {
return;
}
if ( keyCode === VK.RIGHT ) {
container = range.endContainer;
if ( ! range.collapsed || ( range.startOffset === 0 && container.length ) ||
container.nextSibling ||
( container.nodeType === 3 && range.startOffset !== container.length ) ) { // Not at the end of the current range
return;
}
// In a child element
while ( container && container !== node && container !== body ) {
if ( container.nextSibling ) {
return;
}
container = container.parentNode;
}
}
if ( selectSiblingView( node, 'next' ) ) {
event.preventDefault();
}
}
});
editor.on( 'keyup', function( event ) {
var padNode,
keyCode = event.keyCode,
body = editor.getBody(),
range;
if ( toRemove ) {
editor.dom.remove( toRemove );
toRemove = false;
}
if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) {
// Make sure there is padding if the last element is a view
if ( isView( body.lastChild ) ) {
padNode = createPadNode();
body.appendChild( padNode );
if ( body.childNodes.length === 2 ) {
editor.selection.setCursorLocation( padNode, 0 );
}
}
range = editor.selection.getRng();
// Allow an initial element in the document to be removed when it is before a view
if ( body.firstChild === range.startContainer && range.collapsed === true &&
isView( range.startContainer.nextSibling ) && range.startOffset === 0 ) {
editor.dom.remove( range.startContainer );
}
}
});
return {
getViewText: getViewText,
setViewText: setViewText
};
});
| JavaScript |
/* global tinymce */
tinymce.PluginManager.add( 'wplink', function( editor ) {
var linkButton;
// Register a command so that it can be invoked by using tinyMCE.activeEditor.execCommand( 'WP_Link' );
editor.addCommand( 'WP_Link', function() {
if ( ( ! linkButton || ! linkButton.disabled() ) && typeof window.wpLink !== 'undefined' ) {
window.wpLink.open( editor.id );
}
});
// WP default shortcut
editor.addShortcut( 'alt+shift+a', '', 'WP_Link' );
// The "de-facto standard" shortcut, see #27305
editor.addShortcut( 'ctrl+k', '', 'WP_Link' );
function setState( button, node ) {
button.disabled( editor.selection.isCollapsed() && node.nodeName !== 'A' );
button.active( node.nodeName === 'A' && ! node.name );
}
editor.addButton( 'link', {
icon: 'link',
tooltip: 'Insert/edit link',
shortcut: 'Alt+Shift+A',
cmd: 'WP_Link',
onPostRender: function() {
linkButton = this;
editor.on( 'nodechange', function( event ) {
setState( linkButton, event.element );
});
}
});
editor.addButton( 'unlink', {
icon: 'unlink',
tooltip: 'Remove link',
cmd: 'unlink',
onPostRender: function() {
var unlinkButton = this;
editor.on( 'nodechange', function( event ) {
setState( unlinkButton, event.element );
});
}
});
editor.addMenuItem( 'link', {
icon: 'link',
text: 'Insert link',
shortcut: 'Alt+Shift+A',
cmd: 'WP_Link',
stateSelector: 'a[href]',
context: 'insert',
prependToContext: true
});
});
| JavaScript |
/**
* Compiled inline version. (Library mode)
*/
/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
/*globals $code */
(function(exports, undefined) {
"use strict";
var modules = {};
function require(ids, callback) {
var module, defs = [];
for (var i = 0; i < ids.length; ++i) {
module = modules[ids[i]] || resolve(ids[i]);
if (!module) {
throw 'module definition dependecy not found: ' + ids[i];
}
defs.push(module);
}
callback.apply(null, defs);
}
function define(id, dependencies, definition) {
if (typeof id !== 'string') {
throw 'invalid module definition, module id must be defined and be a string';
}
if (dependencies === undefined) {
throw 'invalid module definition, dependencies must be specified';
}
if (definition === undefined) {
throw 'invalid module definition, definition function must be specified';
}
require(dependencies, function() {
modules[id] = definition.apply(null, arguments);
});
}
function defined(id) {
return !!modules[id];
}
function resolve(id) {
var target = exports;
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length; ++fi) {
if (!target[fragments[fi]]) {
return;
}
target = target[fragments[fi]];
}
return target;
}
function expose(ids) {
for (var i = 0; i < ids.length; i++) {
var target = exports;
var id = ids[i];
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length - 1; ++fi) {
if (target[fragments[fi]] === undefined) {
target[fragments[fi]] = {};
}
target = target[fragments[fi]];
}
target[fragments[fragments.length - 1]] = modules[id];
}
}
// Included from: js/tinymce/plugins/paste/classes/Utils.js
/**
* Utils.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class contails various utility functions for the paste plugin.
*
* @class tinymce.pasteplugin.Clipboard
* @private
*/
define("tinymce/pasteplugin/Utils", [
"tinymce/util/Tools",
"tinymce/html/DomParser",
"tinymce/html/Schema"
], function(Tools, DomParser, Schema) {
function filter(content, items) {
Tools.each(items, function(v) {
if (v.constructor == RegExp) {
content = content.replace(v, '');
} else {
content = content.replace(v[0], v[1]);
}
});
return content;
}
/**
* Gets the innerText of the specified element. It will handle edge cases
* and works better than textContent on Gecko.
*
* @param {String} html HTML string to get text from.
* @return {String} String of text with line feeds.
*/
function innerText(html) {
var schema = new Schema(), domParser = new DomParser({}, schema), text = '';
var shortEndedElements = schema.getShortEndedElements();
var ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
var blockElements = schema.getBlockElements();
function walk(node) {
var name = node.name, currentNode = node;
if (name === 'br') {
text += '\n';
return;
}
// img/input/hr
if (shortEndedElements[name]) {
text += ' ';
}
// Ingore script, video contents
if (ignoreElements[name]) {
text += ' ';
return;
}
if (node.type == 3) {
text += node.value;
}
// Walk all children
if (!node.shortEnded) {
if ((node = node.firstChild)) {
do {
walk(node);
} while ((node = node.next));
}
}
// Add \n or \n\n for blocks or P
if (blockElements[name] && currentNode.next) {
text += '\n';
if (name == 'p') {
text += '\n';
}
}
}
walk(domParser.parse(html));
return text;
}
return {
filter: filter,
innerText: innerText
};
});
// Included from: js/tinymce/plugins/paste/classes/Clipboard.js
/**
* Clipboard.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class contains logic for getting HTML contents out of the clipboard.
*
* We need to make a lot of ugly hacks to get the contents out of the clipboard since
* the W3C Clipboard API is broken in all browsers that have it: Gecko/WebKit/Blink.
* We might rewrite this the way those API:s stabilize. Browsers doesn't handle pasting
* from applications like Word the same way as it does when pasting into a contentEditable area
* so we need to do lots of extra work to try to get to this clipboard data.
*
* Current implementation steps:
* 1. On keydown with paste keys Ctrl+V or Shift+Insert create
* a paste bin element and move focus to that element.
* 2. Wait for the browser to fire a "paste" event and get the contents out of the paste bin.
* 3. Check if the paste was successful if true, process the HTML.
* (4). If the paste was unsuccessful use IE execCommand, Clipboard API, document.dataTransfer old WebKit API etc.
*
* @class tinymce.pasteplugin.Clipboard
* @private
*/
define("tinymce/pasteplugin/Clipboard", [
"tinymce/Env",
"tinymce/util/VK",
"tinymce/pasteplugin/Utils"
], function(Env, VK, Utils) {
return function(editor) {
var self = this, pasteBinElm, lastRng, keyboardPasteTimeStamp = 0;
var pasteBinDefaultContent = '%MCEPASTEBIN%', keyboardPastePlainTextState;
/**
* Pastes the specified HTML. This means that the HTML is filtered and then
* inserted at the current selection in the editor. It will also fire paste events
* for custom user filtering.
*
* @param {String} html HTML code to paste into the current selection.
*/
function pasteHtml(html) {
var args, dom = editor.dom;
args = editor.fire('BeforePastePreProcess', {content: html}); // Internal event used by Quirks
args = editor.fire('PastePreProcess', args);
html = args.content;
if (!args.isDefaultPrevented()) {
// User has bound PastePostProcess events then we need to pass it through a DOM node
// This is not ideal but we don't want to let the browser mess up the HTML for example
// some browsers add to P tags etc
if (editor.hasEventListeners('PastePostProcess') && !args.isDefaultPrevented()) {
// We need to attach the element to the DOM so Sizzle selectors work on the contents
var tempBody = dom.add(editor.getBody(), 'div', {style: 'display:none'}, html);
args = editor.fire('PastePostProcess', {node: tempBody});
dom.remove(tempBody);
html = args.node.innerHTML;
}
if (!args.isDefaultPrevented()) {
editor.insertContent(html);
}
}
}
/**
* Pastes the specified text. This means that the plain text is processed
* and converted into BR and P elements. It will fire paste events for custom filtering.
*
* @param {String} text Text to paste as the current selection location.
*/
function pasteText(text) {
text = editor.dom.encode(text).replace(/\r\n/g, '\n');
var startBlock = editor.dom.getParent(editor.selection.getStart(), editor.dom.isBlock);
// Create start block html for example <p attr="value">
var forcedRootBlockName = editor.settings.forced_root_block;
var forcedRootBlockStartHtml;
if (forcedRootBlockName) {
forcedRootBlockStartHtml = editor.dom.createHTML(forcedRootBlockName, editor.settings.forced_root_block_attrs);
forcedRootBlockStartHtml = forcedRootBlockStartHtml.substr(0, forcedRootBlockStartHtml.length - 3) + '>';
}
if ((startBlock && /^(PRE|DIV)$/.test(startBlock.nodeName)) || !forcedRootBlockName) {
text = Utils.filter(text, [
[/\n/g, "<br>"]
]);
} else {
text = Utils.filter(text, [
[/\n\n/g, "</p>" + forcedRootBlockStartHtml],
[/^(.*<\/p>)(<p>)$/, forcedRootBlockStartHtml + '$1'],
[/\n/g, "<br />"]
]);
if (text.indexOf('<p>') != -1) {
text = forcedRootBlockStartHtml + text;
}
}
pasteHtml(text);
}
/**
* Creates a paste bin element as close as possible to the current caret location and places the focus inside that element
* so that when the real paste event occurs the contents gets inserted into this element
* instead of the current editor selection element.
*/
function createPasteBin() {
var dom = editor.dom, body = editor.getBody();
var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
var scrollContainer;
lastRng = editor.selection.getRng();
if (editor.inline) {
scrollContainer = editor.selection.getScrollContainer();
if (scrollContainer) {
scrollTop = scrollContainer.scrollTop;
}
}
// Calculate top cordinate this is needed to avoid scrolling to top of document
// We want the paste bin to be as close to the caret as possible to avoid scrolling
if (lastRng.getClientRects) {
var rects = lastRng.getClientRects();
if (rects.length) {
// Client rects gets us closes to the actual
// caret location in for example a wrapped paragraph block
top = scrollTop + (rects[0].top - dom.getPos(body).y);
} else {
top = scrollTop;
// Check if we can find a closer location by checking the range element
var container = lastRng.startContainer;
if (container) {
if (container.nodeType == 3 && container.parentNode != body) {
container = container.parentNode;
}
if (container.nodeType == 1) {
top = dom.getPos(container, scrollContainer || body).y;
}
}
}
}
// Create a pastebin
pasteBinElm = dom.add(editor.getBody(), 'div', {
id: "mcepastebin",
contentEditable: true,
"data-mce-bogus": "1",
style: 'position: absolute; top: ' + top + 'px;' +
'width: 10px; height: 10px; overflow: hidden; opacity: 0'
}, pasteBinDefaultContent);
// Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
if (Env.ie || Env.gecko) {
dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) == 'rtl' ? 0xFFFF : -0xFFFF);
}
// Prevent focus events from bubbeling fixed FocusManager issues
dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function(e) {
e.stopPropagation();
});
pasteBinElm.focus();
editor.selection.select(pasteBinElm, true);
}
/**
* Removes the paste bin if it exists.
*/
function removePasteBin() {
if (pasteBinElm) {
var pasteBinClone;
// WebKit/Blink might clone the div so
// lets make sure we remove all clones
// TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
editor.dom.remove(pasteBinClone);
editor.dom.unbind(pasteBinClone);
}
if (lastRng) {
editor.selection.setRng(lastRng);
}
}
keyboardPastePlainTextState = false;
pasteBinElm = lastRng = null;
}
/**
* Returns the contents of the paste bin as a HTML string.
*
* @return {String} Get the contents of the paste bin.
*/
function getPasteBinHtml() {
var html = pasteBinDefaultContent, pasteBinClones, i;
// Since WebKit/Chrome might clone the paste bin when pasting
// for example: <img style="float: right"> we need to check if any of them contains some useful html.
// TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
pasteBinClones = editor.dom.select('div[id=mcepastebin]');
i = pasteBinClones.length;
while (i--) {
var cloneHtml = pasteBinClones[i].innerHTML;
if (html == pasteBinDefaultContent) {
html = '';
}
if (cloneHtml.length > html.length) {
html = cloneHtml;
}
}
return html;
}
/**
* Gets various content types out of a datatransfer object.
*
* @param {DataTransfer} dataTransfer Event fired on paste.
* @return {Object} Object with mime types and data for those mime types.
*/
function getDataTransferItems(dataTransfer) {
var data = {};
if (dataTransfer && dataTransfer.types) {
// Use old WebKit API
var legacyText = dataTransfer.getData('Text');
if (legacyText && legacyText.length > 0) {
data['text/plain'] = legacyText;
}
for (var i = 0; i < dataTransfer.types.length; i++) {
var contentType = dataTransfer.types[i];
data[contentType] = dataTransfer.getData(contentType);
}
}
return data;
}
/**
* Gets various content types out of the Clipboard API. It will also get the
* plain text using older IE and WebKit API:s.
*
* @param {ClipboardEvent} clipboardEvent Event fired on paste.
* @return {Object} Object with mime types and data for those mime types.
*/
function getClipboardContent(clipboardEvent) {
return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
}
/**
* Checks if the clipboard contains image data if it does it will take that data
* and convert it into a data url image and paste that image at the caret location.
*
* @param {ClipboardEvent} e Paste event object.
* @param {Object} clipboardContent Collection of clipboard contents.
* @return {Boolean} true/false if the image data was found or not.
*/
function pasteImageData(e, clipboardContent) {
function pasteImage(item) {
if (items[i].type == 'image/png') {
var reader = new FileReader();
reader.onload = function() {
pasteHtml('<img src="' + reader.result + '">');
};
reader.readAsDataURL(item.getAsFile());
return true;
}
}
// If paste data images are disabled or there is HTML or plain text
// contents then proceed with the normal paste process
if (!editor.settings.paste_data_images || "text/html" in clipboardContent || "text/plain" in clipboardContent) {
return;
}
if (e.clipboardData) {
var items = e.clipboardData.items;
if (items) {
for (var i = 0; i < items.length; i++) {
if (pasteImage(items[i])) {
return true;
}
}
}
}
}
function getCaretRangeFromEvent(e) {
var doc = editor.getDoc(), rng;
if (doc.caretPositionFromPoint) {
var point = doc.caretPositionFromPoint(e.clientX, e.clientY);
rng = doc.createRange();
rng.setStart(point.offsetNode, point.offset);
rng.collapse(true);
} else if (doc.caretRangeFromPoint) {
rng = doc.caretRangeFromPoint(e.clientX, e.clientY);
}
return rng;
}
function hasContentType(clipboardContent, mimeType) {
return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
}
function registerEventHandlers() {
editor.on('keydown', function(e) {
if (e.isDefaultPrevented()) {
return;
}
// Ctrl+V or Shift+Insert
if ((VK.metaKeyPressed(e) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) {
keyboardPastePlainTextState = e.shiftKey && e.keyCode == 86;
// Prevent undoManager keydown handler from making an undo level with the pastebin in it
e.stopImmediatePropagation();
keyboardPasteTimeStamp = new Date().getTime();
// IE doesn't support Ctrl+Shift+V and it doesn't even produce a paste event
// so lets fake a paste event and let IE use the execCommand/dataTransfer methods
if (Env.ie && keyboardPastePlainTextState) {
e.preventDefault();
editor.fire('paste', {ieFake: true});
return;
}
removePasteBin();
createPasteBin();
}
});
editor.on('paste', function(e) {
var clipboardContent = getClipboardContent(e);
var isKeyBoardPaste = new Date().getTime() - keyboardPasteTimeStamp < 1000;
var plainTextMode = self.pasteFormat == "text" || keyboardPastePlainTextState;
if (e.isDefaultPrevented()) {
removePasteBin();
return;
}
if (pasteImageData(e, clipboardContent)) {
removePasteBin();
return;
}
// Not a keyboard paste prevent default paste and try to grab the clipboard contents using different APIs
if (!isKeyBoardPaste) {
e.preventDefault();
}
// Try IE only method if paste isn't a keyboard paste
if (Env.ie && (!isKeyBoardPaste || e.ieFake)) {
createPasteBin();
editor.dom.bind(pasteBinElm, 'paste', function(e) {
e.stopPropagation();
});
editor.getDoc().execCommand('Paste', false, null);
clipboardContent["text/html"] = getPasteBinHtml();
}
setTimeout(function() {
var html = getPasteBinHtml();
// WebKit has a nice bug where it clones the paste bin if you paste from for example notepad
if (pasteBinElm && pasteBinElm.firstChild && pasteBinElm.firstChild.id === 'mcepastebin') {
plainTextMode = true;
}
removePasteBin();
// Always use pastebin HTML if it's available since it contains Word contents
if (!plainTextMode && isKeyBoardPaste && html && html != pasteBinDefaultContent) {
clipboardContent['text/html'] = html;
}
if (html == pasteBinDefaultContent || !isKeyBoardPaste) {
html = clipboardContent['text/html'] || clipboardContent['text/plain'] || pasteBinDefaultContent;
if (html == pasteBinDefaultContent) {
if (!isKeyBoardPaste) {
editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
}
return;
}
}
// Force plain text mode if we only got a text/plain content type
if (!hasContentType(clipboardContent, 'text/html') && hasContentType(clipboardContent, 'text/plain')) {
plainTextMode = true;
}
if (plainTextMode) {
pasteText(clipboardContent['text/plain'] || Utils.innerText(html));
} else {
pasteHtml(html);
}
}, 0);
});
editor.on('dragstart', function(e) {
if (e.dataTransfer.types) {
try {
e.dataTransfer.setData('mce-internal', editor.selection.getContent());
} catch (ex) {
// IE 10 throws an error since it doesn't support custom data items
}
}
});
editor.on('drop', function(e) {
var rng = getCaretRangeFromEvent(e);
if (rng && !e.isDefaultPrevented()) {
var dropContent = getDataTransferItems(e.dataTransfer);
var content = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
if (content) {
e.preventDefault();
editor.undoManager.transact(function() {
if (dropContent['mce-internal']) {
editor.execCommand('Delete');
}
editor.selection.setRng(rng);
if (!dropContent['text/html']) {
pasteText(content);
} else {
pasteHtml(content);
}
});
}
}
});
}
self.pasteHtml = pasteHtml;
self.pasteText = pasteText;
editor.on('preInit', function() {
registerEventHandlers();
// Remove all data images from paste for example from Gecko
// except internal images like video elements
editor.parser.addNodeFilter('img', function(nodes) {
if (!editor.settings.paste_data_images) {
var i = nodes.length;
while (i--) {
var src = nodes[i].attributes.map.src;
if (src && src.indexOf('data:image') === 0) {
if (!nodes[i].attr('data-mce-object') && src !== Env.transparentSrc) {
nodes[i].remove();
}
}
}
}
});
});
// Fix for #6504 we need to remove the paste bin on IE if the user paste in a file
editor.on('PreProcess', function() {
editor.dom.remove(editor.dom.get('mcepastebin'));
});
};
});
// Included from: js/tinymce/plugins/paste/classes/WordFilter.js
/**
* WordFilter.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class parses word HTML into proper TinyMCE markup.
*
* @class tinymce.pasteplugin.Quirks
* @private
*/
define("tinymce/pasteplugin/WordFilter", [
"tinymce/util/Tools",
"tinymce/html/DomParser",
"tinymce/html/Schema",
"tinymce/html/Serializer",
"tinymce/html/Node",
"tinymce/pasteplugin/Utils"
], function(Tools, DomParser, Schema, Serializer, Node, Utils) {
/**
* Checks if the specified content is from any of the following sources: MS Word/Office 365/Google docs.
*/
function isWordContent(content) {
return (
(/<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i).test(content) ||
(/class="OutlineElement/).test(content) ||
(/id="?docs\-internal\-guid\-/.test(content))
);
}
function WordFilter(editor) {
var settings = editor.settings;
editor.on('BeforePastePreProcess', function(e) {
var content = e.content, retainStyleProperties, validStyles;
retainStyleProperties = settings.paste_retain_style_properties;
if (retainStyleProperties) {
validStyles = Tools.makeMap(retainStyleProperties.split(/[, ]/));
}
/**
* Converts fake bullet and numbered lists to real semantic OL/UL.
*
* @param {tinymce.html.Node} node Root node to convert children of.
*/
function convertFakeListsToProperLists(node) {
var currentListNode, prevListNode, lastLevel = 1;
function convertParagraphToLi(paragraphNode, listStartTextNode, listName, start) {
var level = paragraphNode._listLevel || lastLevel;
// Handle list nesting
if (level != lastLevel) {
if (level < lastLevel) {
// Move to parent list
if (currentListNode) {
currentListNode = currentListNode.parent.parent;
}
} else {
// Create new list
prevListNode = currentListNode;
currentListNode = null;
}
}
if (!currentListNode || currentListNode.name != listName) {
prevListNode = prevListNode || currentListNode;
currentListNode = new Node(listName, 1);
if (start > 1) {
currentListNode.attr('start', '' + start);
}
paragraphNode.wrap(currentListNode);
} else {
currentListNode.append(paragraphNode);
}
paragraphNode.name = 'li';
listStartTextNode.value = '';
var nextNode = listStartTextNode.next;
if (nextNode && nextNode.type == 3) {
nextNode.value = nextNode.value.replace(/^\u00a0+/, '');
}
// Append list to previous list if it exists
if (level > lastLevel && prevListNode) {
prevListNode.lastChild.append(currentListNode);
}
lastLevel = level;
}
var paragraphs = node.getAll('p');
for (var i = 0; i < paragraphs.length; i++) {
node = paragraphs[i];
if (node.name == 'p' && node.firstChild) {
// Find first text node in paragraph
var nodeText = '';
var listStartTextNode = node.firstChild;
while (listStartTextNode) {
nodeText = listStartTextNode.value;
if (nodeText) {
break;
}
listStartTextNode = listStartTextNode.firstChild;
}
// Detect unordered lists look for bullets
if (/^\s*[\u2022\u00b7\u00a7\u00d8\u25CF]\s*$/.test(nodeText)) {
convertParagraphToLi(node, listStartTextNode, 'ul');
continue;
}
// Detect ordered lists 1., a. or ixv.
if (/^\s*\w+\.$/.test(nodeText)) {
// Parse OL start number
var matches = /([0-9])\./.exec(nodeText);
var start = 1;
if (matches) {
start = parseInt(matches[1], 10);
}
convertParagraphToLi(node, listStartTextNode, 'ol', start);
continue;
}
currentListNode = null;
}
}
}
function filterStyles(node, styleValue) {
var outputStyles = {}, styles = editor.dom.parseStyle(styleValue);
// Parse out list indent level for lists
if (node.name === 'p') {
var matches = /mso-list:\w+ \w+([0-9]+)/.exec(styleValue);
if (matches) {
node._listLevel = parseInt(matches[1], 10);
}
}
Tools.each(styles, function(value, name) {
// Convert various MS styles to W3C styles
switch (name) {
case "horiz-align":
name = "text-align";
break;
case "vert-align":
name = "vertical-align";
break;
case "font-color":
case "mso-foreground":
name = "color";
break;
case "mso-background":
case "mso-highlight":
name = "background";
break;
case "font-weight":
case "font-style":
if (value != "normal") {
outputStyles[name] = value;
}
return;
case "mso-element":
// Remove track changes code
if (/^(comment|comment-list)$/i.test(value)) {
node.remove();
return;
}
break;
}
if (name.indexOf('mso-comment') === 0) {
node.remove();
return;
}
// Never allow mso- prefixed names
if (name.indexOf('mso-') === 0) {
return;
}
// Output only valid styles
if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
outputStyles[name] = value;
}
});
// Convert bold style to "b" element
if (/(bold)/i.test(outputStyles["font-weight"])) {
delete outputStyles["font-weight"];
node.wrap(new Node("b", 1));
}
// Convert italic style to "i" element
if (/(italic)/i.test(outputStyles["font-style"])) {
delete outputStyles["font-style"];
node.wrap(new Node("i", 1));
}
// Serialize the styles and see if there is something left to keep
outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
if (outputStyles) {
return outputStyles;
}
return null;
}
if (settings.paste_enable_default_filters === false) {
return;
}
// Detect is the contents is Word junk HTML
if (isWordContent(e.content)) {
e.wordContent = true; // Mark it for other processors
// Remove basic Word junk
content = Utils.filter(content, [
// Word comments like conditional comments etc
/<!--[\s\S]+?-->/gi,
// Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
// MS Office namespaced tags, and a few other tags
/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
// Convert <s> into <strike> for line-though
[/<(\/?)s>/gi, "<$1strike>"],
// Replace nsbp entites to char since it's easier to handle
[/ /gi, "\u00a0"],
// Convert <span style="mso-spacerun:yes">___</span> to string of alternating
// breaking/non-breaking spaces of same length
[/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
function(str, spaces) {
return (spaces.length > 0) ?
spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : "";
}
]
]);
var validElements = settings.paste_word_valid_elements;
if (!validElements) {
validElements = '-strong/b,-em/i,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,-p/div,' +
'-table[width],-tr,-td[colspan|rowspan|width],-th,-thead,-tfoot,-tbody,-a[href|name],sub,sup,strike,br,del';
}
// Setup strict schema
var schema = new Schema({
valid_elements: validElements,
valid_children: '-li[p]'
});
// Add style/class attribute to all element rules since the user might have removed them from
// paste_word_valid_elements config option and we need to check them for properties
Tools.each(schema.elements, function(rule) {
if (!rule.attributes["class"]) {
rule.attributes["class"] = {};
rule.attributesOrder.push("class");
}
if (!rule.attributes.style) {
rule.attributes.style = {};
rule.attributesOrder.push("style");
}
});
// Parse HTML into DOM structure
var domParser = new DomParser({}, schema);
// Filter styles to remove "mso" specific styles and convert some of them
domParser.addAttributeFilter('style', function(nodes) {
var i = nodes.length, node;
while (i--) {
node = nodes[i];
node.attr('style', filterStyles(node, node.attr('style')));
// Remove pointess spans
if (node.name == 'span' && node.parent && !node.attributes.length) {
node.unwrap();
}
}
});
// Check the class attribute for comments or del items and remove those
domParser.addAttributeFilter('class', function(nodes) {
var i = nodes.length, node, className;
while (i--) {
node = nodes[i];
className = node.attr('class');
if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
node.remove();
}
node.attr('class', null);
}
});
// Remove all del elements since we don't want the track changes code in the editor
domParser.addNodeFilter('del', function(nodes) {
var i = nodes.length;
while (i--) {
nodes[i].remove();
}
});
// Keep some of the links and anchors
domParser.addNodeFilter('a', function(nodes) {
var i = nodes.length, node, href, name;
while (i--) {
node = nodes[i];
href = node.attr('href');
name = node.attr('name');
if (href && href.indexOf('#_msocom_') != -1) {
node.remove();
continue;
}
if (href && href.indexOf('file://') === 0) {
href = href.split('#')[1];
if (href) {
href = '#' + href;
}
}
if (!href && !name) {
node.unwrap();
} else {
if (name && name.indexOf('Toc') !== 0) {
node.unwrap();
continue;
}
node.attr({
href: href,
name: name
});
}
}
});
// Parse into DOM structure
var rootNode = domParser.parse(content);
// Process DOM
convertFakeListsToProperLists(rootNode);
// Serialize DOM back to HTML
e.content = new Serializer({}, schema).serialize(rootNode);
}
});
}
WordFilter.isWordContent = isWordContent;
return WordFilter;
});
// Included from: js/tinymce/plugins/paste/classes/Quirks.js
/**
* Quirks.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class contains various fixes for browsers. These issues can not be feature
* detected since we have no direct control over the clipboard. However we might be able
* to remove some of these fixes once the browsers gets updated/fixed.
*
* @class tinymce.pasteplugin.Quirks
* @private
*/
define("tinymce/pasteplugin/Quirks", [
"tinymce/Env",
"tinymce/util/Tools",
"tinymce/pasteplugin/WordFilter",
"tinymce/pasteplugin/Utils"
], function(Env, Tools, WordFilter, Utils) {
"use strict";
return function(editor) {
function addPreProcessFilter(filterFunc) {
editor.on('BeforePastePreProcess', function(e) {
e.content = filterFunc(e.content);
});
}
/**
* Removes WebKit fragment comments and converted-space spans.
*
* This:
* <!--StartFragment-->a<span class="Apple-converted-space"> </span>b<!--EndFragment-->
*
* Becomes:
* a b
*/
function removeWebKitFragments(html) {
html = Utils.filter(html, [
/^[\s\S]*<!--StartFragment-->|<!--EndFragment-->[\s\S]*$/g, // WebKit fragment
[/<span class="Apple-converted-space">\u00a0<\/span>/g, '\u00a0'], // WebKit
/<br>$/i // Traling BR elements
]);
return html;
}
/**
* Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each
* block element when pasting from word. This removes those elements.
*
* This:
* <p>a</p><br><p>b</p>
*
* Becomes:
* <p>a</p><p>b</p>
*/
function removeExplorerBrElementsAfterBlocks(html) {
// Only filter word specific content
if (!WordFilter.isWordContent(html)) {
return html;
}
// Produce block regexp based on the block elements in schema
var blockElements = [];
Tools.each(editor.schema.getBlockElements(), function(block, blockName) {
blockElements.push(blockName);
});
var explorerBlocksRegExp = new RegExp(
'(?:<br> [\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br> [\\s\\r\\n]+|<br>)*',
'g'
);
// Remove BR:s from: <BLOCK>X</BLOCK><BR>
html = Utils.filter(html, [
[explorerBlocksRegExp, '$1']
]);
// IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
html = Utils.filter(html, [
[/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
[/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s
[/<BR><BR>/g, '<br>'] // Replace back the double brs but into a single BR
]);
return html;
}
/**
* WebKit has a nasty bug where the all computed styles gets added to style attributes when copy/pasting contents.
* This fix solves that by simply removing the whole style attribute.
*
* The paste_webkit_styles option can be set to specify what to keep:
* paste_webkit_styles: "none" // Keep no styles
* paste_webkit_styles: "all", // Keep all of them
* paste_webkit_styles: "font-weight color" // Keep specific ones
*
* @param {String} content Content that needs to be processed.
* @return {String} Processed contents.
*/
function removeWebKitStyles(content) {
// Passthrough all styles from Word and let the WordFilter handle that junk
if (WordFilter.isWordContent(content)) {
return content;
}
// Filter away styles that isn't matching the target node
var webKitStyles = editor.getParam("paste_webkit_styles", "color font-size font-family background-color").split(/[, ]/);
if (editor.settings.paste_remove_styles_if_webkit === false) {
webKitStyles = "all";
}
// Keep specific styles that doesn't match the current node computed style
if (webKitStyles != "all") {
var dom = editor.dom, node = editor.selection.getNode();
content = content.replace(/ style=\"([^\"]+)\"/gi, function(a, value) {
var inputStyles = dom.parseStyle(value, 'span'), outputStyles = {};
if (webKitStyles === "none") {
return '';
}
for (var i = 0; i < webKitStyles.length; i++) {
if (dom.toHex(dom.getStyle(node, webKitStyles[i], true)) != inputStyles[webKitStyles[i]]) {
outputStyles[webKitStyles[i]] = inputStyles[webKitStyles[i]];
}
}
outputStyles = dom.serializeStyle(outputStyles, 'span');
if (outputStyles) {
return ' style="' + outputStyles + '"';
}
return '';
});
}
return content;
}
// Sniff browsers and apply fixes since we can't feature detect
if (Env.webkit) {
addPreProcessFilter(removeWebKitStyles);
addPreProcessFilter(removeWebKitFragments);
}
if (Env.ie) {
addPreProcessFilter(removeExplorerBrElementsAfterBlocks);
}
};
});
// Included from: js/tinymce/plugins/paste/classes/Plugin.js
/**
* Plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class contains the tinymce plugin logic for the paste plugin.
*
* @class tinymce.pasteplugin.Plugin
* @private
*/
define("tinymce/pasteplugin/Plugin", [
"tinymce/PluginManager",
"tinymce/pasteplugin/Clipboard",
"tinymce/pasteplugin/WordFilter",
"tinymce/pasteplugin/Quirks"
], function(PluginManager, Clipboard, WordFilter, Quirks) {
var userIsInformed;
PluginManager.add('paste', function(editor) {
var self = this, clipboard, settings = editor.settings;
function togglePlainTextPaste() {
if (clipboard.pasteFormat == "text") {
this.active(false);
clipboard.pasteFormat = "html";
} else {
clipboard.pasteFormat = "text";
this.active(true);
if (!userIsInformed) {
editor.windowManager.alert(
'Paste is now in plain text mode. Contents will now ' +
'be pasted as plain text until you toggle this option off.'
);
userIsInformed = true;
}
}
}
self.clipboard = clipboard = new Clipboard(editor);
self.quirks = new Quirks(editor);
self.wordFilter = new WordFilter(editor);
if (editor.settings.paste_as_text) {
self.clipboard.pasteFormat = "text";
}
if (settings.paste_preprocess) {
editor.on('PastePreProcess', function(e) {
settings.paste_preprocess.call(self, self, e);
});
}
if (settings.paste_postprocess) {
editor.on('PastePostProcess', function(e) {
settings.paste_postprocess.call(self, self, e);
});
}
editor.addCommand('mceInsertClipboardContent', function(ui, value) {
if (value.content) {
self.clipboard.pasteHtml(value.content);
}
if (value.text) {
self.clipboard.pasteText(value.text);
}
});
// Block all drag/drop events
if (editor.paste_block_drop) {
editor.on('dragend dragover draggesture dragdrop drop drag', function(e) {
e.preventDefault();
e.stopPropagation();
});
}
// Prevent users from dropping data images on Gecko
if (!editor.settings.paste_data_images) {
editor.on('drop', function(e) {
var dataTransfer = e.dataTransfer;
if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
e.preventDefault();
}
});
}
editor.addButton('pastetext', {
icon: 'pastetext',
tooltip: 'Paste as text',
onclick: togglePlainTextPaste,
active: self.clipboard.pasteFormat == "text"
});
editor.addMenuItem('pastetext', {
text: 'Paste as text',
selectable: true,
active: clipboard.pasteFormat,
onclick: togglePlainTextPaste
});
});
});
expose(["tinymce/pasteplugin/Utils","tinymce/pasteplugin/Clipboard","tinymce/pasteplugin/WordFilter","tinymce/pasteplugin/Quirks","tinymce/pasteplugin/Plugin"]);
})(this); | JavaScript |
/**
* TinyMCE 3.x language strings
*
* Loaded only when external plugins are added to TinyMCE.
*/
( function() {
var main = {}, lang = 'en';
if ( typeof tinyMCEPreInit !== 'undefined' && tinyMCEPreInit.ref.language !== 'en' ) {
lang = tinyMCEPreInit.ref.language;
}
main[lang] = {
common: {
edit_confirm: "Do you want to use the WYSIWYG mode for this textarea?",
apply: "Apply",
insert: "Insert",
update: "Update",
cancel: "Cancel",
close: "Close",
browse: "Browse",
class_name: "Class",
not_set: "-- Not set --",
clipboard_msg: "Copy/Cut/Paste is not available in Mozilla and Firefox.",
clipboard_no_support: "Currently not supported by your browser, use keyboard shortcuts instead.",
popup_blocked: "Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.",
invalid_data: "ERROR: Invalid values entered, these are marked in red.",
invalid_data_number: "{#field} must be a number",
invalid_data_min: "{#field} must be a number greater than {#min}",
invalid_data_size: "{#field} must be a number or percentage",
more_colors: "More colors"
},
colors: {
"000000": "Black",
"993300": "Burnt orange",
"333300": "Dark olive",
"003300": "Dark green",
"003366": "Dark azure",
"000080": "Navy Blue",
"333399": "Indigo",
"333333": "Very dark gray",
"800000": "Maroon",
"FF6600": "Orange",
"808000": "Olive",
"008000": "Green",
"008080": "Teal",
"0000FF": "Blue",
"666699": "Grayish blue",
"808080": "Gray",
"FF0000": "Red",
"FF9900": "Amber",
"99CC00": "Yellow green",
"339966": "Sea green",
"33CCCC": "Turquoise",
"3366FF": "Royal blue",
"800080": "Purple",
"999999": "Medium gray",
"FF00FF": "Magenta",
"FFCC00": "Gold",
"FFFF00": "Yellow",
"00FF00": "Lime",
"00FFFF": "Aqua",
"00CCFF": "Sky blue",
"993366": "Brown",
"C0C0C0": "Silver",
"FF99CC": "Pink",
"FFCC99": "Peach",
"FFFF99": "Light yellow",
"CCFFCC": "Pale green",
"CCFFFF": "Pale cyan",
"99CCFF": "Light sky blue",
"CC99FF": "Plum",
"FFFFFF": "White"
},
contextmenu: {
align: "Alignment",
left: "Left",
center: "Center",
right: "Right",
full: "Full"
},
insertdatetime: {
date_fmt: "%Y-%m-%d",
time_fmt: "%H:%M:%S",
insertdate_desc: "Insert date",
inserttime_desc: "Insert time",
months_long: "January,February,March,April,May,June,July,August,September,October,November,December",
months_short: "Jan_January_abbreviation,Feb_February_abbreviation,Mar_March_abbreviation,Apr_April_abbreviation,May_May_abbreviation,Jun_June_abbreviation,Jul_July_abbreviation,Aug_August_abbreviation,Sep_September_abbreviation,Oct_October_abbreviation,Nov_November_abbreviation,Dec_December_abbreviation",
day_long: "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",
day_short: "Sun,Mon,Tue,Wed,Thu,Fri,Sat"
},
print: {
print_desc: "Print"
},
preview: {
preview_desc: "Preview"
},
directionality: {
ltr_desc: "Direction left to right",
rtl_desc: "Direction right to left"
},
layer: {
insertlayer_desc: "Insert new layer",
forward_desc: "Move forward",
backward_desc: "Move backward",
absolute_desc: "Toggle absolute positioning",
content: "New layer..."
},
save: {
save_desc: "Save",
cancel_desc: "Cancel all changes"
},
nonbreaking: {
nonbreaking_desc: "Insert non-breaking space character"
},
iespell: {
iespell_desc: "Run spell checking",
download: "ieSpell not detected. Do you want to install it now?"
},
advhr: {
advhr_desc: "Horizontal rule"
},
emotions: {
emotions_desc: "Emotions"
},
searchreplace: {
search_desc: "Find",
replace_desc: "Find/Replace"
},
advimage: {
image_desc: "Insert/edit image"
},
advlink: {
link_desc: "Insert/edit link"
},
xhtmlxtras: {
cite_desc: "Citation",
abbr_desc: "Abbreviation",
acronym_desc: "Acronym",
del_desc: "Deletion",
ins_desc: "Insertion",
attribs_desc: "Insert/Edit Attributes"
},
style: {
desc: "Edit CSS Style"
},
paste: {
paste_text_desc: "Paste as Plain Text",
paste_word_desc: "Paste from Word",
selectall_desc: "Select All",
plaintext_mode_sticky: "Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.",
plaintext_mode: "Paste is now in plain text mode. Click again to toggle back to regular paste mode."
},
paste_dlg: {
text_title: "Use CTRL + V on your keyboard to paste the text into the window.",
text_linebreaks: "Keep linebreaks",
word_title: "Use CTRL + V on your keyboard to paste the text into the window."
},
table: {
desc: "Inserts a new table",
row_before_desc: "Insert row before",
row_after_desc: "Insert row after",
delete_row_desc: "Delete row",
col_before_desc: "Insert column before",
col_after_desc: "Insert column after",
delete_col_desc: "Remove column",
split_cells_desc: "Split merged table cells",
merge_cells_desc: "Merge table cells",
row_desc: "Table row properties",
cell_desc: "Table cell properties",
props_desc: "Table properties",
paste_row_before_desc: "Paste table row before",
paste_row_after_desc: "Paste table row after",
cut_row_desc: "Cut table row",
copy_row_desc: "Copy table row",
del: "Delete table",
row: "Row",
col: "Column",
cell: "Cell"
},
autosave: {
unload_msg: "The changes you made will be lost if you navigate away from this page."
},
fullscreen: {
desc: "Toggle fullscreen mode (Alt + Shift + G)"
},
media: {
desc: "Insert / edit embedded media",
edit: "Edit embedded media"
},
fullpage: {
desc: "Document properties"
},
template: {
desc: "Insert predefined template content"
},
visualchars: {
desc: "Visual control characters on/off."
},
spellchecker: {
desc: "Toggle spellchecker (Alt + Shift + N)",
menu: "Spellchecker settings",
ignore_word: "Ignore word",
ignore_words: "Ignore all",
langs: "Languages",
wait: "Please wait...",
sug: "Suggestions",
no_sug: "No suggestions",
no_mpell: "No misspellings found.",
learn_word: "Learn word"
},
pagebreak: {
desc: "Insert Page Break"
},
advlist:{
types: "Types",
def: "Default",
lower_alpha: "Lower alpha",
lower_greek: "Lower greek",
lower_roman: "Lower roman",
upper_alpha: "Upper alpha",
upper_roman: "Upper roman",
circle: "Circle",
disc: "Disc",
square: "Square"
},
aria: {
rich_text_area: "Rich Text Area"
},
wordcount:{
words: "Words: "
}
};
tinyMCE.addI18n( main );
tinyMCE.addI18n( lang + ".advanced", {
style_select: "Styles",
font_size: "Font size",
fontdefault: "Font family",
block: "Format",
paragraph: "Paragraph",
div: "Div",
address: "Address",
pre: "Preformatted",
h1: "Heading 1",
h2: "Heading 2",
h3: "Heading 3",
h4: "Heading 4",
h5: "Heading 5",
h6: "Heading 6",
blockquote: "Blockquote",
code: "Code",
samp: "Code sample",
dt: "Definition term ",
dd: "Definition description",
bold_desc: "Bold (Ctrl + B)",
italic_desc: "Italic (Ctrl + I)",
underline_desc: "Underline",
striketrough_desc: "Strikethrough (Alt + Shift + D)",
justifyleft_desc: "Align Left (Alt + Shift + L)",
justifycenter_desc: "Align Center (Alt + Shift + C)",
justifyright_desc: "Align Right (Alt + Shift + R)",
justifyfull_desc: "Align Full (Alt + Shift + J)",
bullist_desc: "Unordered list (Alt + Shift + U)",
numlist_desc: "Ordered list (Alt + Shift + O)",
outdent_desc: "Outdent",
indent_desc: "Indent",
undo_desc: "Undo (Ctrl + Z)",
redo_desc: "Redo (Ctrl + Y)",
link_desc: "Insert/edit link (Alt + Shift + A)",
unlink_desc: "Unlink (Alt + Shift + S)",
image_desc: "Insert/edit image (Alt + Shift + M)",
cleanup_desc: "Cleanup messy code",
code_desc: "Edit HTML Source",
sub_desc: "Subscript",
sup_desc: "Superscript",
hr_desc: "Insert horizontal ruler",
removeformat_desc: "Remove formatting",
forecolor_desc: "Select text color",
backcolor_desc: "Select background color",
charmap_desc: "Insert custom character",
visualaid_desc: "Toggle guidelines/invisible elements",
anchor_desc: "Insert/edit anchor",
cut_desc: "Cut",
copy_desc: "Copy",
paste_desc: "Paste",
image_props_desc: "Image properties",
newdocument_desc: "New document",
help_desc: "Help",
blockquote_desc: "Blockquote (Alt + Shift + Q)",
clipboard_msg: "Copy/Cut/Paste is not available in Mozilla and Firefox.",
path: "Path",
newdocument: "Are you sure you want to clear all contents?",
toolbar_focus: "Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X",
more_colors: "More colors",
shortcuts_desc: "Accessibility Help",
help_shortcut: " Press ALT F10 for toolbar. Press ALT 0 for help.",
rich_text_area: "Rich Text Area",
toolbar: "Toolbar"
});
tinyMCE.addI18n( lang + ".advanced_dlg", {
about_title: "About TinyMCE",
about_general: "About",
about_help: "Help",
about_license: "License",
about_plugins: "Plugins",
about_plugin: "Plugin",
about_author: "Author",
about_version: "Version",
about_loaded: "Loaded plugins",
anchor_title: "Insert/edit anchor",
anchor_name: "Anchor name",
code_title: "HTML Source Editor",
code_wordwrap: "Word wrap",
colorpicker_title: "Select a color",
colorpicker_picker_tab: "Picker",
colorpicker_picker_title: "Color picker",
colorpicker_palette_tab: "Palette",
colorpicker_palette_title: "Palette colors",
colorpicker_named_tab: "Named",
colorpicker_named_title: "Named colors",
colorpicker_color: "Color: ",
colorpicker_name: "Name: ",
charmap_title: "Select custom character",
charmap_usage: "Use left and right arrows to navigate.",
image_title: "Insert/edit image",
image_src: "Image URL",
image_alt: "Image description",
image_list: "Image list",
image_border: "Border",
image_dimensions: "Dimensions",
image_vspace: "Vertical space",
image_hspace: "Horizontal space",
image_align: "Alignment",
image_align_baseline: "Baseline",
image_align_top: "Top",
image_align_middle: "Middle",
image_align_bottom: "Bottom",
image_align_texttop: "Text top",
image_align_textbottom: "Text bottom",
image_align_left: "Left",
image_align_right: "Right",
link_title: "Insert/edit link",
link_url: "Link URL",
link_target: "Target",
link_target_same: "Open link in the same window",
link_target_blank: "Open link in a new window",
link_titlefield: "Title",
link_is_email: "The URL you entered seems to be an email address, do you want to add the required mailto: prefix?",
link_is_external: "The URL you entered seems to be an external link, do you want to add the required http:// prefix?",
link_list: "Link list",
accessibility_help: "Accessibility Help",
accessibility_usage_title: "General Usage"
});
tinyMCE.addI18n( lang + ".media_dlg", {
title: "Insert / edit embedded media",
general: "General",
advanced: "Advanced",
file: "File/URL",
list: "List",
size: "Dimensions",
preview: "Preview",
constrain_proportions: "Constrain proportions",
type: "Type",
id: "Id",
name: "Name",
class_name: "Class",
vspace: "V-Space",
hspace: "H-Space",
play: "Auto play",
loop: "Loop",
menu: "Show menu",
quality: "Quality",
scale: "Scale",
align: "Align",
salign: "SAlign",
wmode: "WMode",
bgcolor: "Background",
base: "Base",
flashvars: "Flashvars",
liveconnect: "SWLiveConnect",
autohref: "AutoHREF",
cache: "Cache",
hidden: "Hidden",
controller: "Controller",
kioskmode: "Kiosk mode",
playeveryframe: "Play every frame",
targetcache: "Target cache",
correction: "No correction",
enablejavascript: "Enable JavaScript",
starttime: "Start time",
endtime: "End time",
href: "href",
qtsrcchokespeed: "Choke speed",
target: "Target",
volume: "Volume",
autostart: "Auto start",
enabled: "Enabled",
fullscreen: "Fullscreen",
invokeurls: "Invoke URLs",
mute: "Mute",
stretchtofit: "Stretch to fit",
windowlessvideo: "Windowless video",
balance: "Balance",
baseurl: "Base URL",
captioningid: "Captioning id",
currentmarker: "Current marker",
currentposition: "Current position",
defaultframe: "Default frame",
playcount: "Play count",
rate: "Rate",
uimode: "UI Mode",
flash_options: "Flash options",
qt_options: "QuickTime options",
wmp_options: "Windows media player options",
rmp_options: "Real media player options",
shockwave_options: "Shockwave options",
autogotourl: "Auto goto URL",
center: "Center",
imagestatus: "Image status",
maintainaspect: "Maintain aspect",
nojava: "No java",
prefetch: "Prefetch",
shuffle: "Shuffle",
console: "Console",
numloop: "Num loops",
controls: "Controls",
scriptcallbacks: "Script callbacks",
swstretchstyle: "Stretch style",
swstretchhalign: "Stretch H-Align",
swstretchvalign: "Stretch V-Align",
sound: "Sound",
progress: "Progress",
qtsrc: "QT Src",
qt_stream_warn: "Streamed rtsp resources should be added to the QT Src field under the advanced tab.",
align_top: "Top",
align_right: "Right",
align_bottom: "Bottom",
align_left: "Left",
align_center: "Center",
align_top_left: "Top left",
align_top_right: "Top right",
align_bottom_left: "Bottom left",
align_bottom_right: "Bottom right",
flv_options: "Flash video options",
flv_scalemode: "Scale mode",
flv_buffer: "Buffer",
flv_startimage: "Start image",
flv_starttime: "Start time",
flv_defaultvolume: "Default volume",
flv_hiddengui: "Hidden GUI",
flv_autostart: "Auto start",
flv_loop: "Loop",
flv_showscalemodes: "Show scale modes",
flv_smoothvideo: "Smooth video",
flv_jscallback: "JS Callback",
html5_video_options: "HTML5 Video Options",
altsource1: "Alternative source 1",
altsource2: "Alternative source 2",
preload: "Preload",
poster: "Poster",
source: "Source"
});
tinyMCE.addI18n( lang + ".wordpress", {
wp_adv_desc: "Show/Hide Kitchen Sink (Alt + Shift + Z)",
wp_more_desc: "Insert More Tag (Alt + Shift + T)",
wp_page_desc: "Insert Page break (Alt + Shift + P)",
wp_help_desc: "Help (Alt + Shift + H)",
wp_more_alt: "More...",
wp_page_alt: "Next page...",
add_media: "Add Media",
add_image: "Add an Image",
add_video: "Add Video",
add_audio: "Add Audio",
editgallery: "Edit Gallery",
delgallery: "Delete Gallery",
wp_fullscreen_desc: "Distraction Free Writing mode (Alt + Shift + W)"
});
tinyMCE.addI18n( lang + ".wpeditimage", {
edit_img: "Edit Image",
del_img: "Delete Image",
adv_settings: "Advanced Settings",
none: "None",
size: "Size",
thumbnail: "Thumbnail",
medium: "Medium",
full_size: "Full Size",
current_link: "Current Link",
link_to_img: "Link to Image",
link_help: "Enter a link URL or click above for presets.",
adv_img_settings: "Advanced Image Settings",
source: "Source",
width: "Width",
height: "Height",
orig_size: "Original Size",
css: "CSS Class",
adv_link_settings: "Advanced Link Settings",
link_rel: "Link Rel",
height: "Height",
orig_size: "Original Size",
css: "CSS Class",
s60: "60%",
s70: "70%",
s80: "80%",
s90: "90%",
s100: "100%",
s110: "110%",
s120: "120%",
s130: "130%",
img_title: "Title",
caption: "Caption",
alt: "Alternative Text"
});
}());
| JavaScript |
/* global tinymce, MediaElementPlayer, WPPlaylistView */
/**
* Note: this API is "experimental" meaning that it will probably change
* in the next few releases based on feedback from 3.9.0.
* If you decide to use it, please follow the development closely.
*/
// Ensure the global `wp` object exists.
window.wp = window.wp || {};
(function($){
var views = {},
instances = {},
media = wp.media,
viewOptions = ['encodedText'];
// Create the `wp.mce` object if necessary.
wp.mce = wp.mce || {};
/**
* wp.mce.View
*
* A Backbone-like View constructor intended for use when rendering a TinyMCE View. The main difference is
* that the TinyMCE View is not tied to a particular DOM node.
*/
wp.mce.View = function( options ) {
options || (options = {});
_.extend(this, _.pick(options, viewOptions));
this.initialize.apply(this, arguments);
};
_.extend( wp.mce.View.prototype, {
initialize: function() {},
getHtml: function() {},
render: function() {
var html = this.getHtml();
// Search all tinymce editor instances and update the placeholders
_.each( tinymce.editors, function( editor ) {
var doc, self = this;
if ( editor.plugins.wpview ) {
doc = editor.getDoc();
$( doc ).find( '[data-wpview-text="' + this.encodedText + '"]' ).each(function (i, elem) {
var node = $( elem );
// The <ins> is used to mark the end of the wrapper div. Needed when comparing
// the content as string for preventing extra undo levels.
node.html( html ).append( '<ins data-wpview-end="1"></ins>' );
$( self ).trigger( 'ready', elem );
});
}
}, this );
},
unbind: function() {}
} );
// take advantage of the Backbone extend method
wp.mce.View.extend = Backbone.View.extend;
/**
* wp.mce.views
*
* A set of utilities that simplifies adding custom UI within a TinyMCE editor.
* At its core, it serves as a series of converters, transforming text to a
* custom UI, and back again.
*/
wp.mce.views = {
/**
* wp.mce.views.register( type, view )
*
* Registers a new TinyMCE view.
*
* @param type
* @param constructor
*
*/
register: function( type, constructor ) {
views[ type ] = constructor;
},
/**
* wp.mce.views.get( id )
*
* Returns a TinyMCE view constructor.
*/
get: function( type ) {
return views[ type ];
},
/**
* wp.mce.views.unregister( type )
*
* Unregisters a TinyMCE view.
*/
unregister: function( type ) {
delete views[ type ];
},
/**
* wp.mce.views.unbind( editor )
*
* The editor DOM is being rebuilt, run cleanup.
*/
unbind: function() {
_.each( instances, function( instance ) {
instance.unbind();
} );
},
/**
* toViews( content )
* Scans a `content` string for each view's pattern, replacing any
* matches with wrapper elements, and creates a new instance for
* every match, which triggers the related data to be fetched.
*
*/
toViews: function( content ) {
var pieces = [ { content: content } ],
current;
_.each( views, function( view, viewType ) {
current = pieces.slice();
pieces = [];
_.each( current, function( piece ) {
var remaining = piece.content,
result;
// Ignore processed pieces, but retain their location.
if ( piece.processed ) {
pieces.push( piece );
return;
}
// Iterate through the string progressively matching views
// and slicing the string as we go.
while ( remaining && (result = view.toView( remaining )) ) {
// Any text before the match becomes an unprocessed piece.
if ( result.index ) {
pieces.push({ content: remaining.substring( 0, result.index ) });
}
// Add the processed piece for the match.
pieces.push({
content: wp.mce.views.toView( viewType, result.content, result.options ),
processed: true
});
// Update the remaining content.
remaining = remaining.slice( result.index + result.content.length );
}
// There are no additional matches. If any content remains,
// add it as an unprocessed piece.
if ( remaining ) {
pieces.push({ content: remaining });
}
});
});
return _.pluck( pieces, 'content' ).join('');
},
/**
* Create a placeholder for a particular view type
*
* @param viewType
* @param text
* @param options
*
*/
toView: function( viewType, text, options ) {
var view = wp.mce.views.get( viewType ),
encodedText = window.encodeURIComponent( text ),
instance, viewOptions;
if ( ! view ) {
return text;
}
if ( ! wp.mce.views.getInstance( encodedText ) ) {
viewOptions = options;
viewOptions.encodedText = encodedText;
instance = new view.View( viewOptions );
instances[ encodedText ] = instance;
}
return wp.html.string({
tag: 'div',
attrs: {
'class': 'wpview-wrap wpview-type-' + viewType,
'data-wpview-text': encodedText,
'data-wpview-type': viewType,
'contenteditable': 'false'
},
content: '\u00a0'
});
},
/**
* Refresh views after an update is made
*
* @param view {object} being refreshed
* @param text {string} textual representation of the view
*/
refreshView: function( view, text ) {
var encodedText = window.encodeURIComponent( text ),
viewOptions,
result, instance;
instance = wp.mce.views.getInstance( encodedText );
if ( ! instance ) {
result = view.toView( text );
viewOptions = result.options;
viewOptions.encodedText = encodedText;
instance = new view.View( viewOptions );
instances[ encodedText ] = instance;
}
wp.mce.views.render();
},
getInstance: function( encodedText ) {
return instances[ encodedText ];
},
/**
* render( scope )
*
* Renders any view instances inside a DOM node `scope`.
*
* View instances are detected by the presence of wrapper elements.
* To generate wrapper elements, pass your content through
* `wp.mce.view.toViews( content )`.
*/
render: function() {
_.each( instances, function( instance ) {
instance.render();
} );
},
edit: function( node ) {
var viewType = $( node ).data('wpview-type'),
view = wp.mce.views.get( viewType );
if ( view ) {
view.edit( node );
}
}
};
wp.mce.gallery = {
shortcode: 'gallery',
toView: function( content ) {
var match = wp.shortcode.next( this.shortcode, content );
if ( ! match ) {
return;
}
return {
index: match.index,
content: match.content,
options: {
shortcode: match.shortcode
}
};
},
View: wp.mce.View.extend({
className: 'editor-gallery',
template: media.template('editor-gallery'),
// The fallback post ID to use as a parent for galleries that don't
// specify the `ids` or `include` parameters.
//
// Uses the hidden input on the edit posts page by default.
postID: $('#post_ID').val(),
initialize: function( options ) {
this.shortcode = options.shortcode;
this.fetch();
},
fetch: function() {
this.attachments = wp.media.gallery.attachments( this.shortcode, this.postID );
this.dfd = this.attachments.more().done( _.bind( this.render, this ) );
},
getHtml: function() {
var attrs = this.shortcode.attrs.named,
attachments = false,
options;
// Don't render errors while still fetching attachments
if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
return;
}
if ( this.attachments.length ) {
attachments = this.attachments.toJSON();
_.each( attachments, function( attachment ) {
if ( attachment.sizes ) {
if ( attachment.sizes.thumbnail ) {
attachment.thumbnail = attachment.sizes.thumbnail;
} else if ( attachment.sizes.full ) {
attachment.thumbnail = attachment.sizes.full;
}
}
} );
}
options = {
attachments: attachments,
columns: attrs.columns ? parseInt( attrs.columns, 10 ) : 3
};
return this.template( options );
}
}),
edit: function( node ) {
var gallery = wp.media.gallery,
self = this,
frame, data;
data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
frame = gallery.edit( data );
frame.state('gallery-edit').on( 'update', function( selection ) {
var shortcode = gallery.shortcode( selection ).string();
$( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
wp.mce.views.refreshView( self, shortcode );
frame.detach();
});
}
};
wp.mce.views.register( 'gallery', wp.mce.gallery );
/**
* Tiny MCE Views for Audio / Video
*
*/
/**
* These are base methods that are shared by each shortcode's MCE controller
*
* @mixin
*/
wp.mce.media = {
loaded: false,
/**
* @global wp.shortcode
*
* @param {string} content
* @returns {Object}
*/
toView: function( content ) {
var match = wp.shortcode.next( this.shortcode, content );
if ( ! match ) {
return;
}
return {
index: match.index,
content: match.content,
options: {
shortcode: match.shortcode
}
};
},
/**
* Called when a TinyMCE view is clicked for editing.
* - Parses the shortcode out of the element's data attribute
* - Calls the `edit` method on the shortcode model
* - Launches the model window
* - Bind's an `update` callback which updates the element's data attribute
* re-renders the view
*
* @param {HTMLElement} node
*/
edit: function( node ) {
var media = wp.media[ this.shortcode ],
self = this,
frame, data, callback;
wp.media.mixin.pauseAllPlayers();
data = window.decodeURIComponent( $( node ).attr('data-wpview-text') );
frame = media.edit( data );
frame.on( 'close', function() {
frame.detach();
} );
callback = function( selection ) {
var shortcode = wp.media[ self.shortcode ].shortcode( selection ).string();
$( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) );
wp.mce.views.refreshView( self, shortcode );
frame.detach();
};
if ( _.isArray( self.state ) ) {
_.each( self.state, function (state) {
frame.state( state ).on( 'update', callback );
} );
} else {
frame.state( self.state ).on( 'update', callback );
}
frame.open();
}
};
/**
* Base View class for audio and video shortcodes
*
* @constructor
* @augments wp.mce.View
* @mixes wp.media.mixin
*/
wp.mce.media.View = wp.mce.View.extend({
initialize: function( options ) {
this.players = [];
this.shortcode = options.shortcode;
_.bindAll( this, 'setPlayer' );
$(this).on( 'ready', this.setPlayer );
},
/**
* Creates the player instance for the current node
*
* @global MediaElementPlayer
* @global _wpmejsSettings
*
* @param {Event} e
* @param {HTMLElement} node
*/
setPlayer: function(e, node) {
// if the ready event fires on an empty node
if ( ! node ) {
return;
}
var self = this,
media,
firefox = this.ua.is( 'ff' ),
className = '.wp-' + this.shortcode.tag + '-shortcode';
if ( this.player ) {
this.unsetPlayer();
}
media = $( node ).find( className );
if ( ! this.isCompatible( media ) ) {
media.closest( '.wpview-wrap' ).addClass( 'wont-play' );
if ( ! media.parent().hasClass( 'wpview-wrap' ) ) {
media.parent().replaceWith( media );
}
media.replaceWith( '<p>' + media.find( 'source' ).eq(0).prop( 'src' ) + '</p>' );
return;
} else {
media.closest( '.wpview-wrap' ).removeClass( 'wont-play' );
if ( firefox ) {
media.prop( 'preload', 'metadata' );
} else {
media.prop( 'preload', 'none' );
}
}
media = wp.media.view.MediaDetails.prepareSrc( media.get(0) );
setTimeout( function() {
wp.mce.media.loaded = true;
self.players.push( new MediaElementPlayer( media, self.mejsSettings ) );
}, wp.mce.media.loaded ? 10 : 500 );
},
/**
* Pass data to the View's Underscore template and return the compiled output
*
* @returns {string}
*/
getHtml: function() {
var attrs = _.defaults(
this.shortcode.attrs.named,
wp.media[ this.shortcode.tag ].defaults
);
return this.template({ model: attrs });
},
unbind: function() {
var self = this;
this.pauseAllPlayers();
_.each( this.players, function (player) {
self.removePlayer( player );
} );
this.players = [];
}
});
_.extend( wp.mce.media.View.prototype, wp.media.mixin );
/**
* TinyMCE handler for the video shortcode
*
* @mixes wp.mce.media
*/
wp.mce.video = _.extend( {}, wp.mce.media, {
shortcode: 'video',
state: 'video-details',
View: wp.mce.media.View.extend({
className: 'editor-video',
template: media.template('editor-video')
})
} );
wp.mce.views.register( 'video', wp.mce.video );
/**
* TinyMCE handler for the audio shortcode
*
* @mixes wp.mce.media
*/
wp.mce.audio = _.extend( {}, wp.mce.media, {
shortcode: 'audio',
state: 'audio-details',
View: wp.mce.media.View.extend({
className: 'editor-audio',
template: media.template('editor-audio')
})
} );
wp.mce.views.register( 'audio', wp.mce.audio );
/**
* Base View class for playlist shortcodes
*
* @constructor
* @augments wp.mce.View
* @mixes wp.media.mixin
*/
wp.mce.media.PlaylistView = wp.mce.View.extend({
className: 'editor-playlist',
template: media.template('editor-playlist'),
initialize: function( options ) {
this.data = {};
this.attachments = [];
this.shortcode = options.shortcode;
_.bindAll( this, 'setPlayer' );
$(this).on('ready', this.setNode);
},
/**
* Set the element context for the view, and then fetch the playlist's
* associated attachments.
*
* @param {Event} e
* @param {HTMLElement} node
*/
setNode: function(e, node) {
this.node = node;
this.fetch();
},
/**
* Asynchronously fetch the shortcode's attachments
*/
fetch: function() {
this.attachments = wp.media.playlist.attachments( this.shortcode );
this.attachments.more().done( this.setPlayer );
},
/**
* Get the HTML for the view (which also set's the data), replace the
* current HTML, and then invoke the WPPlaylistView instance to render
* the playlist in the editor
*
* @global WPPlaylistView
* @global tinymce.editors
*/
setPlayer: function() {
var p,
html = this.getHtml(),
t = this.encodedText,
self = this;
this.unsetPlayer();
_.each( tinymce.editors, function( editor ) {
var doc;
if ( editor.plugins.wpview ) {
doc = editor.getDoc();
$( doc ).find( '[data-wpview-text="' + t + '"]' ).each(function(i, elem) {
var node = $( elem );
node.html( html );
self.node = elem;
});
}
}, this );
if ( ! this.data.tracks ) {
return;
}
p = new WPPlaylistView({
el: $( self.node ).find( '.wp-playlist' ).get(0),
metadata: this.data
});
this.player = p._player;
},
/**
* Set the data that will be used to compile the Underscore template,
* compile the template, and then return it.
*
* @returns {string}
*/
getHtml: function() {
var data = this.shortcode.attrs.named,
model = wp.media.playlist,
options,
attachments,
tracks = [];
// Don't render errors while still fetching attachments
if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) {
return;
}
_.each( model.defaults, function( value, key ) {
data[ key ] = model.coerce( data, key );
});
options = {
type: data.type,
style: data.style,
tracklist: data.tracklist,
tracknumbers: data.tracknumbers,
images: data.images,
artists: data.artists
};
if ( ! this.attachments.length ) {
return this.template( options );
}
attachments = this.attachments.toJSON();
_.each( attachments, function( attachment ) {
var size = {}, resize = {}, track = {
src : attachment.url,
type : attachment.mime,
title : attachment.title,
caption : attachment.caption,
description : attachment.description,
meta : attachment.meta
};
if ( 'video' === data.type ) {
size.width = attachment.width;
size.height = attachment.height;
if ( media.view.settings.contentWidth ) {
resize.width = media.view.settings.contentWidth - 22;
resize.height = Math.ceil( ( size.height * resize.width ) / size.width );
if ( ! options.width ) {
options.width = resize.width;
options.height = resize.height;
}
} else {
if ( ! options.width ) {
options.width = attachment.width;
options.height = attachment.height;
}
}
track.dimensions = {
original : size,
resized : _.isEmpty( resize ) ? size : resize
};
} else {
options.width = 400;
}
track.image = attachment.image;
track.thumb = attachment.thumb;
tracks.push( track );
} );
options.tracks = tracks;
this.data = options;
return this.template( options );
}
});
_.extend( wp.mce.media.PlaylistView.prototype, wp.media.mixin );
/**
* TinyMCE handler for the playlist shortcode
*
* @mixes wp.mce.media
*/
wp.mce.playlist = _.extend( {}, wp.mce.media, {
shortcode: 'playlist',
state: ['playlist-edit', 'video-playlist-edit'],
View: wp.mce.media.PlaylistView
} );
wp.mce.views.register( 'playlist', wp.mce.playlist );
}(jQuery));
| JavaScript |
/* global mejs, _wpmejsSettings */
(function ($) {
// add mime-type aliases to MediaElement plugin support
mejs.plugins.silverlight[0].types.push('video/x-ms-wmv');
mejs.plugins.silverlight[0].types.push('audio/x-ms-wma');
$(function () {
var settings = {};
if ( $( document.body ).hasClass( 'mce-content-body' ) ) {
return;
}
if ( typeof _wpmejsSettings !== 'undefined' ) {
settings.pluginPath = _wpmejsSettings.pluginPath;
}
settings.success = function (mejs) {
var autoplay = mejs.attributes.autoplay && 'false' !== mejs.attributes.autoplay;
if ( 'flash' === mejs.pluginType && autoplay ) {
mejs.addEventListener( 'canplay', function () {
mejs.play();
}, false );
}
};
$('.wp-audio-shortcode, .wp-video-shortcode').mediaelementplayer( settings );
});
}(jQuery));
| JavaScript |
/*globals window, document, jQuery, _, Backbone, _wpmejsSettings */
(function ($, _, Backbone) {
"use strict";
var WPPlaylistView = Backbone.View.extend({
initialize : function (options) {
this.index = 0;
this.settings = {};
this.data = options.metadata || $.parseJSON( this.$('script').html() );
this.playerNode = this.$( this.data.type );
this.tracks = new Backbone.Collection( this.data.tracks );
this.current = this.tracks.first();
if ( 'audio' === this.data.type ) {
this.currentTemplate = wp.template( 'wp-playlist-current-item' );
this.currentNode = this.$( '.wp-playlist-current-item' );
}
this.renderCurrent();
if ( this.data.tracklist ) {
this.itemTemplate = wp.template( 'wp-playlist-item' );
this.playingClass = 'wp-playlist-playing';
this.renderTracks();
}
this.playerNode.attr( 'src', this.current.get( 'src' ) );
_.bindAll( this, 'bindPlayer', 'bindResetPlayer', 'setPlayer', 'ended', 'clickTrack' );
if ( ! _.isUndefined( window._wpmejsSettings ) ) {
this.settings.pluginPath = _wpmejsSettings.pluginPath;
}
this.settings.success = this.bindPlayer;
this.setPlayer();
},
bindPlayer : function (mejs) {
this.player = mejs;
this.player.addEventListener( 'ended', this.ended );
},
bindResetPlayer : function (mejs) {
this.bindPlayer( mejs );
this.playCurrentSrc();
},
setPlayer: function () {
if ( this._player ) {
this._player.pause();
this._player.remove();
this.playerNode = this.$( this.data.type );
this.playerNode.attr( 'src', this.current.get( 'src' ) );
this.settings.success = this.bindResetPlayer;
}
/**
* This is also our bridge to the outside world
*/
this._player = new MediaElementPlayer( this.playerNode.get(0), this.settings );
},
playCurrentSrc : function () {
this.renderCurrent();
this.player.setSrc( this.playerNode.attr( 'src' ) );
this.player.load();
this.player.play();
},
renderCurrent : function () {
var dimensions;
if ( 'video' === this.data.type ) {
if ( this.data.images && this.current.get( 'image' ) ) {
this.playerNode.attr( 'poster', this.current.get( 'image' ).src );
}
dimensions = this.current.get( 'dimensions' ).resized;
this.playerNode.attr( dimensions );
} else {
if ( ! this.data.images ) {
this.current.set( 'image', false );
}
this.currentNode.html( this.currentTemplate( this.current.toJSON() ) );
}
},
renderTracks : function () {
var self = this, i = 1, tracklist = $( '<div class="wp-playlist-tracks"></div>' );
this.tracks.each(function (model) {
if ( ! self.data.images ) {
model.set( 'image', false );
}
model.set( 'artists', self.data.artists );
model.set( 'index', self.data.tracknumbers ? i : false );
tracklist.append( self.itemTemplate( model.toJSON() ) );
i += 1;
});
this.$el.append( tracklist );
this.$( '.wp-playlist-item' ).eq(0).addClass( this.playingClass );
},
events : {
'click .wp-playlist-item' : 'clickTrack',
'click .wp-playlist-next' : 'next',
'click .wp-playlist-prev' : 'prev'
},
clickTrack : function (e) {
e.preventDefault();
this.index = this.$( '.wp-playlist-item' ).index( e.currentTarget );
this.setCurrent();
},
ended : function () {
if ( this.index + 1 < this.tracks.length ) {
this.next();
} else {
this.index = 0;
this.current = this.tracks.at( this.index );
this.loadCurrent();
}
},
next : function () {
this.index = this.index + 1 >= this.tracks.length ? 0 : this.index + 1;
this.setCurrent();
},
prev : function () {
this.index = this.index - 1 < 0 ? this.tracks.length - 1 : this.index - 1;
this.setCurrent();
},
loadCurrent : function () {
var last = this.playerNode.attr( 'src' ).split('.').pop(),
current = this.current.get( 'src' ).split('.').pop();
this.player.pause();
if ( last !== current ) {
this.setPlayer();
} else {
this.playerNode.attr( 'src', this.current.get( 'src' ) );
this.playCurrentSrc();
}
},
setCurrent : function () {
this.current = this.tracks.at( this.index );
if ( this.data.tracklist ) {
this.$( '.wp-playlist-item' )
.removeClass( this.playingClass )
.eq( this.index )
.addClass( this.playingClass );
}
this.loadCurrent();
}
});
$(document).ready(function () {
if ( ! $( 'body' ).hasClass( 'wp-admin' ) || $( 'body' ).hasClass( 'about-php' ) ) {
$('.wp-playlist').each(function () {
return new WPPlaylistView({ el: this });
});
}
});
window.WPPlaylistView = WPPlaylistView;
}(jQuery, _, Backbone)); | JavaScript |
(function( $, wp, _ ) {
if ( ! wp || ! wp.customize ) { return; }
var api = wp.customize;
/**
* wp.customize.HeaderTool.CurrentView
*
* Displays the currently selected header image, or a placeholder in lack
* thereof.
*
* Instantiate with model wp.customize.HeaderTool.currentHeader.
*
* @constructor
* @augments wp.Backbone.View
*/
api.HeaderTool.CurrentView = wp.Backbone.View.extend({
template: wp.template('header-current'),
initialize: function() {
this.listenTo(this.model, 'change', this.render);
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
this.setPlaceholder();
this.setButtons();
return this;
},
getHeight: function() {
var image = this.$el.find('img'),
saved, height, headerImageData;
if (image.length) {
this.$el.find('.inner').hide();
} else {
this.$el.find('.inner').show();
return 40;
}
saved = this.model.get('savedHeight');
height = image.height() || saved;
// happens at ready
if (!height) {
headerImageData = api.get().header_image_data;
if (headerImageData && headerImageData.width && headerImageData.height) {
// hardcoded container width
height = 260 / headerImageData.width * headerImageData.height;
}
else {
// fallback for when no image is set
height = 40;
}
}
return height;
},
setPlaceholder: function(_height) {
var height = _height || this.getHeight();
this.model.set('savedHeight', height);
this.$el
.add(this.$el.find('.placeholder'))
.height(height);
},
setButtons: function() {
var elements = $('.actions .remove');
if (this.model.get('choice')) {
elements.show();
} else {
elements.hide();
}
}
});
/**
* wp.customize.HeaderTool.ChoiceView
*
* Represents a choosable header image, be it user-uploaded,
* theme-suggested or a special Randomize choice.
*
* Takes a wp.customize.HeaderTool.ImageModel.
*
* Manually changes model wp.customize.HeaderTool.currentHeader via the
* `select` method.
*
* @constructor
* @augments wp.Backbone.View
*/
api.HeaderTool.ChoiceView = wp.Backbone.View.extend({
template: wp.template('header-choice'),
className: 'header-view',
events: {
'click .choice,.random': 'select',
'click .close': 'removeImage'
},
initialize: function() {
var properties = [
this.model.get('header').url,
this.model.get('choice')
];
this.listenTo(this.model, 'change:selected', this.toggleSelected);
if (_.contains(properties, api.get().header_image)) {
api.HeaderTool.currentHeader.set(this.extendedModel());
}
},
render: function() {
this.$el.html(this.template(this.extendedModel()));
this.toggleSelected();
return this;
},
toggleSelected: function() {
this.$el.toggleClass('selected', this.model.get('selected'));
},
extendedModel: function() {
var c = this.model.get('collection');
return _.extend(this.model.toJSON(), {
type: c.type
});
},
getHeight: api.HeaderTool.CurrentView.prototype.getHeight,
setPlaceholder: api.HeaderTool.CurrentView.prototype.setPlaceholder,
select: function() {
this.preventJump();
this.model.save();
api.HeaderTool.currentHeader.set(this.extendedModel());
},
preventJump: function() {
var container = $('.wp-full-overlay-sidebar-content'),
scroll = container.scrollTop();
_.defer(function() {
container.scrollTop(scroll);
});
},
removeImage: function(e) {
e.stopPropagation();
this.model.destroy();
this.remove();
}
});
/**
* wp.customize.HeaderTool.ChoiceListView
*
* A container for ChoiceViews. These choices should be of one same type:
* user-uploaded headers or theme-defined ones.
*
* Takes a wp.customize.HeaderTool.ChoiceList.
*
* @constructor
* @augments wp.Backbone.View
*/
api.HeaderTool.ChoiceListView = wp.Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'add', this.addOne);
this.listenTo(this.collection, 'remove', this.render);
this.listenTo(this.collection, 'sort', this.render);
this.listenTo(this.collection, 'change', this.toggleList);
this.render();
},
render: function() {
this.$el.empty();
this.collection.each(this.addOne, this);
this.toggleList();
},
addOne: function(choice) {
var view;
choice.set({ collection: this.collection });
view = new api.HeaderTool.ChoiceView({ model: choice });
this.$el.append(view.render().el);
},
toggleList: function() {
var title = this.$el.parents().prev('.customize-control-title'),
randomButton = this.$el.find('.random').parent();
if (this.collection.shouldHideTitle()) {
title.add(randomButton).hide();
} else {
title.add(randomButton).show();
}
}
});
/**
* wp.customize.HeaderTool.CombinedList
*
* Aggregates wp.customize.HeaderTool.ChoiceList collections (or any
* Backbone object, really) and acts as a bus to feed them events.
*
* @constructor
* @augments wp.Backbone.View
*/
api.HeaderTool.CombinedList = wp.Backbone.View.extend({
initialize: function(collections) {
this.collections = collections;
this.on('all', this.propagate, this);
},
propagate: function(event, arg) {
_.each(this.collections, function(collection) {
collection.trigger(event, arg);
});
}
});
})( jQuery, window.wp, _ );
| JavaScript |
window.wp = window.wp || {};
(function( exports, $ ){
var api, extend, ctor, inherits,
slice = Array.prototype.slice;
/* =====================================================================
* Micro-inheritance - thank you, backbone.js.
* ===================================================================== */
extend = function( protoProps, classProps ) {
var child = inherits( this, protoProps, classProps );
child.extend = this.extend;
return child;
};
// Shared empty constructor function to aid in prototype-chain creation.
ctor = function() {};
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
inherits = function( parent, protoProps, staticProps ) {
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call `super()`.
if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) {
child = protoProps.constructor;
} else {
child = function() {
// Storing the result `super()` before returning the value
// prevents a bug in Opera where, if the constructor returns
// a function, Opera will reject the return value in favor of
// the original object. This causes all sorts of trouble.
var result = parent.apply( this, arguments );
return result;
};
}
// Inherit class (static) properties from parent.
$.extend( child, parent );
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
ctor.prototype = parent.prototype;
child.prototype = new ctor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if ( protoProps )
$.extend( child.prototype, protoProps );
// Add static properties to the constructor function, if supplied.
if ( staticProps )
$.extend( child, staticProps );
// Correctly set child's `prototype.constructor`.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed later.
child.__super__ = parent.prototype;
return child;
};
api = {};
/* =====================================================================
* Base class.
* ===================================================================== */
api.Class = function( applicator, argsArray, options ) {
var magic, args = arguments;
if ( applicator && argsArray && api.Class.applicator === applicator ) {
args = argsArray;
$.extend( this, options || {} );
}
magic = this;
if ( this.instance ) {
magic = function() {
return magic.instance.apply( magic, arguments );
};
$.extend( magic, this );
}
magic.initialize.apply( magic, args );
return magic;
};
api.Class.applicator = {};
api.Class.prototype.initialize = function() {};
/*
* Checks whether a given instance extended a constructor.
*
* The magic surrounding the instance parameter causes the instanceof
* keyword to return inaccurate results; it defaults to the function's
* prototype instead of the constructor chain. Hence this function.
*/
api.Class.prototype.extended = function( constructor ) {
var proto = this;
while ( typeof proto.constructor !== 'undefined' ) {
if ( proto.constructor === constructor )
return true;
if ( typeof proto.constructor.__super__ === 'undefined' )
return false;
proto = proto.constructor.__super__;
}
return false;
};
api.Class.extend = extend;
/* =====================================================================
* Events mixin.
* ===================================================================== */
api.Events = {
trigger: function( id ) {
if ( this.topics && this.topics[ id ] )
this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) );
return this;
},
bind: function( id ) {
this.topics = this.topics || {};
this.topics[ id ] = this.topics[ id ] || $.Callbacks();
this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) );
return this;
},
unbind: function( id ) {
if ( this.topics && this.topics[ id ] )
this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) );
return this;
}
};
/* =====================================================================
* Observable values that support two-way binding.
* ===================================================================== */
api.Value = api.Class.extend({
initialize: function( initial, options ) {
this._value = initial; // @todo: potentially change this to a this.set() call.
this.callbacks = $.Callbacks();
$.extend( this, options || {} );
this.set = $.proxy( this.set, this );
},
/*
* Magic. Returns a function that will become the instance.
* Set to null to prevent the instance from extending a function.
*/
instance: function() {
return arguments.length ? this.set.apply( this, arguments ) : this.get();
},
get: function() {
return this._value;
},
set: function( to ) {
var from = this._value;
to = this._setter.apply( this, arguments );
to = this.validate( to );
// Bail if the sanitized value is null or unchanged.
if ( null === to || this._value === to )
return this;
this._value = to;
this.callbacks.fireWith( this, [ to, from ] );
return this;
},
_setter: function( to ) {
return to;
},
setter: function( callback ) {
var from = this.get();
this._setter = callback;
// Temporarily clear value so setter can decide if it's valid.
this._value = null;
this.set( from );
return this;
},
resetSetter: function() {
this._setter = this.constructor.prototype._setter;
this.set( this.get() );
return this;
},
validate: function( value ) {
return value;
},
bind: function() {
this.callbacks.add.apply( this.callbacks, arguments );
return this;
},
unbind: function() {
this.callbacks.remove.apply( this.callbacks, arguments );
return this;
},
link: function() { // values*
var set = this.set;
$.each( arguments, function() {
this.bind( set );
});
return this;
},
unlink: function() { // values*
var set = this.set;
$.each( arguments, function() {
this.unbind( set );
});
return this;
},
sync: function() { // values*
var that = this;
$.each( arguments, function() {
that.link( this );
this.link( that );
});
return this;
},
unsync: function() { // values*
var that = this;
$.each( arguments, function() {
that.unlink( this );
this.unlink( that );
});
return this;
}
});
/* =====================================================================
* A collection of observable values.
* ===================================================================== */
api.Values = api.Class.extend({
defaultConstructor: api.Value,
initialize: function( options ) {
$.extend( this, options || {} );
this._value = {};
this._deferreds = {};
},
instance: function( id ) {
if ( arguments.length === 1 )
return this.value( id );
return this.when.apply( this, arguments );
},
value: function( id ) {
return this._value[ id ];
},
has: function( id ) {
return typeof this._value[ id ] !== 'undefined';
},
add: function( id, value ) {
if ( this.has( id ) )
return this.value( id );
this._value[ id ] = value;
value.parent = this;
if ( value.extended( api.Value ) )
value.bind( this._change );
this.trigger( 'add', value );
if ( this._deferreds[ id ] )
this._deferreds[ id ].resolve();
return this._value[ id ];
},
create: function( id ) {
return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) );
},
each: function( callback, context ) {
context = typeof context === 'undefined' ? this : context;
$.each( this._value, function( key, obj ) {
callback.call( context, obj, key );
});
},
remove: function( id ) {
var value;
if ( this.has( id ) ) {
value = this.value( id );
this.trigger( 'remove', value );
if ( value.extended( api.Value ) )
value.unbind( this._change );
delete value.parent;
}
delete this._value[ id ];
delete this._deferreds[ id ];
},
/**
* Runs a callback once all requested values exist.
*
* when( ids*, [callback] );
*
* For example:
* when( id1, id2, id3, function( value1, value2, value3 ) {} );
*
* @returns $.Deferred.promise();
*/
when: function() {
var self = this,
ids = slice.call( arguments ),
dfd = $.Deferred();
// If the last argument is a callback, bind it to .done()
if ( $.isFunction( ids[ ids.length - 1 ] ) )
dfd.done( ids.pop() );
$.when.apply( $, $.map( ids, function( id ) {
if ( self.has( id ) )
return;
return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred();
})).done( function() {
var values = $.map( ids, function( id ) {
return self( id );
});
// If a value is missing, we've used at least one expired deferred.
// Call Values.when again to generate a new deferred.
if ( values.length !== ids.length ) {
// ids.push( callback );
self.when.apply( self, ids ).done( function() {
dfd.resolveWith( self, values );
});
return;
}
dfd.resolveWith( self, values );
});
return dfd.promise();
},
_change: function() {
this.parent.trigger( 'change', this );
}
});
$.extend( api.Values.prototype, api.Events );
/* =====================================================================
* An observable value that syncs with an element.
*
* Handles inputs, selects, and textareas by default.
* ===================================================================== */
api.ensure = function( element ) {
return typeof element == 'string' ? $( element ) : element;
};
api.Element = api.Value.extend({
initialize: function( element, options ) {
var self = this,
synchronizer = api.Element.synchronizer.html,
type, update, refresh;
this.element = api.ensure( element );
this.events = '';
if ( this.element.is('input, select, textarea') ) {
this.events += 'change';
synchronizer = api.Element.synchronizer.val;
if ( this.element.is('input') ) {
type = this.element.prop('type');
if ( api.Element.synchronizer[ type ] )
synchronizer = api.Element.synchronizer[ type ];
if ( 'text' === type || 'password' === type )
this.events += ' keyup';
} else if ( this.element.is('textarea') ) {
this.events += ' keyup';
}
}
api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) );
this._value = this.get();
update = this.update;
refresh = this.refresh;
this.update = function( to ) {
if ( to !== refresh.call( self ) )
update.apply( this, arguments );
};
this.refresh = function() {
self.set( refresh.call( self ) );
};
this.bind( this.update );
this.element.bind( this.events, this.refresh );
},
find: function( selector ) {
return $( selector, this.element );
},
refresh: function() {},
update: function() {}
});
api.Element.synchronizer = {};
$.each( [ 'html', 'val' ], function( i, method ) {
api.Element.synchronizer[ method ] = {
update: function( to ) {
this.element[ method ]( to );
},
refresh: function() {
return this.element[ method ]();
}
};
});
api.Element.synchronizer.checkbox = {
update: function( to ) {
this.element.prop( 'checked', to );
},
refresh: function() {
return this.element.prop( 'checked' );
}
};
api.Element.synchronizer.radio = {
update: function( to ) {
this.element.filter( function() {
return this.value === to;
}).prop( 'checked', true );
},
refresh: function() {
return this.element.filter( ':checked' ).val();
}
};
/* =====================================================================
* Messenger for postMessage.
* ===================================================================== */
$.support.postMessage = !! window.postMessage;
api.Messenger = api.Class.extend({
add: function( key, initial, options ) {
return this[ key ] = new api.Value( initial, options );
},
/**
* Initialize Messenger.
*
* @param {object} params Parameters to configure the messenger.
* {string} .url The URL to communicate with.
* {window} .targetWindow The window instance to communicate with. Default window.parent.
* {string} .channel If provided, will send the channel with each message and only accept messages a matching channel.
* @param {object} options Extend any instance parameter or method with this object.
*/
initialize: function( params, options ) {
// Target the parent frame by default, but only if a parent frame exists.
var defaultTarget = window.parent == window ? null : window.parent;
$.extend( this, options || {} );
this.add( 'channel', params.channel );
this.add( 'url', params.url || '' );
this.add( 'targetWindow', params.targetWindow || defaultTarget );
this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' );
});
// Since we want jQuery to treat the receive function as unique
// to this instance, we give the function a new guid.
//
// This will prevent every Messenger's receive function from being
// unbound when calling $.off( 'message', this.receive );
this.receive = $.proxy( this.receive, this );
this.receive.guid = $.guid++;
$( window ).on( 'message', this.receive );
},
destroy: function() {
$( window ).off( 'message', this.receive );
},
receive: function( event ) {
var message;
event = event.originalEvent;
if ( ! this.targetWindow() )
return;
// Check to make sure the origin is valid.
if ( this.origin() && event.origin !== this.origin() )
return;
// Ensure we have a string that's JSON.parse-able
if ( typeof event.data !== 'string' || event.data[0] !== '{' ) {
return;
}
message = JSON.parse( event.data );
// Check required message properties.
if ( ! message || ! message.id || typeof message.data === 'undefined' )
return;
// Check if channel names match.
if ( ( message.channel || this.channel() ) && this.channel() !== message.channel )
return;
this.trigger( message.id, message.data );
},
send: function( id, data ) {
var message;
data = typeof data === 'undefined' ? null : data;
if ( ! this.url() || ! this.targetWindow() )
return;
message = { id: id, data: data };
if ( this.channel() )
message.channel = this.channel();
this.targetWindow().postMessage( JSON.stringify( message ), this.origin() );
}
});
// Add the Events mixin to api.Messenger.
$.extend( api.Messenger.prototype, api.Events );
/* =====================================================================
* Core customize object.
* ===================================================================== */
api = $.extend( new api.Values(), api );
api.get = function() {
var result = {};
this.each( function( obj, key ) {
result[ key ] = obj.get();
});
return result;
};
// Expose the API to the world.
exports.customize = api;
})( wp, jQuery );
| JavaScript |
var topWin = window.dialogArguments || opener || parent || top;
function fileDialogStart() {
jQuery("#media-upload-error").empty();
}
// progress and success handlers for media multi uploads
function fileQueued(fileObj) {
// Get rid of unused form
jQuery('.media-blank').remove();
// Collapse a single item
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.describe-toggle-on').show();
jQuery('.describe-toggle-off').hide();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Create a progress bar containing the filename
jQuery('<div class="media-item">')
.attr( 'id', 'media-item-' + fileObj.id )
.addClass('child-of-' + post_id)
.append('<div class="progress"><div class="bar"></div></div>',
jQuery('<div class="filename original"><span class="percent"></span>').text( ' ' + fileObj.name ))
.appendTo( jQuery('#media-items' ) );
// Display the progress div
jQuery('.progress', '#media-item-' + fileObj.id).show();
// Disable submit and enable cancel
jQuery('#insert-gallery').prop('disabled', true);
jQuery('#cancel-upload').prop('disabled', false);
}
function uploadStart(fileObj) {
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
} catch(e){}
return true;
}
function uploadProgress(fileObj, bytesDone, bytesTotal) {
// Lengthen the progress bar
var w = jQuery('#media-items').width() - 2, item = jQuery('#media-item-' + fileObj.id);
jQuery('.bar', item).width( w * bytesDone / bytesTotal );
jQuery('.percent', item).html( Math.ceil(bytesDone / bytesTotal * 100) + '%' );
if ( bytesDone == bytesTotal )
jQuery('.bar', item).html('<strong class="crunching">' + swfuploadL10n.crunching + '</strong>');
}
function prepareMediaItem(fileObj, serverData) {
var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
// Move the progress bar to 100%
jQuery('.bar', item).remove();
jQuery('.progress', item).hide();
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
} catch(e){}
// Old style: Append the HTML returned by the server -- thumbnail and form inputs
if ( isNaN(serverData) || !serverData ) {
item.append(serverData);
prepareMediaItemInit(fileObj);
}
// New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
else {
item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()});
}
}
function prepareMediaItemInit(fileObj) {
var item = jQuery('#media-item-' + fileObj.id);
// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
// Replace the original filename with the new (unique) one assigned during upload
jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
// Also bind toggle to the links
jQuery('a.toggle', item).click(function(){
jQuery(this).siblings('.slidetoggle').slideToggle(350, function(){
var w = jQuery(window).height(), t = jQuery(this).offset().top, h = jQuery(this).height(), b;
if ( w && t && h ) {
b = t + h;
if ( b > w && (h + 48) < w )
window.scrollBy(0, b - w + 13);
else if ( b > w )
window.scrollTo(0, t - 36);
}
});
jQuery(this).siblings('.toggle').andSelf().toggle();
jQuery(this).siblings('a.toggle').focus();
return false;
});
// Bind AJAX to the new Delete button
jQuery('a.delete', item).click(function(){
// Tell the server to delete it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
success: deleteSuccess,
error: deleteError,
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g, ''),
action : 'trash-post',
_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
}
});
return false;
});
// Bind AJAX to the new Undo button
jQuery('a.undo', item).click(function(){
// Tell the server to untrash it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g,''),
action: 'untrash-post',
_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
},
success: function(data, textStatus){
var item = jQuery('#media-item-' + fileObj.id);
if ( type = jQuery('#type-of-' + fileObj.id).val() )
jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
if ( item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
jQuery('.filename .trashnotice', item).remove();
jQuery('.filename .title', item).css('font-weight','normal');
jQuery('a.undo', item).addClass('hidden');
jQuery('a.describe-toggle-on, .menu_order_input', item).show();
item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
}
});
return false;
});
// Open this item if it says to start open (e.g. to display an error)
jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').slideToggle(500).siblings('.toggle').toggle();
}
function itemAjaxError(id, html) {
var item = jQuery('#media-item-' + id);
var filename = jQuery('.filename', item).text();
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>'
+ '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />'
+ html
+ '</div>');
item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})});
}
function deleteSuccess(data, textStatus) {
if ( data == '-1' )
return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
if ( data == '0' )
return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
var id = this.id, item = jQuery('#media-item-' + id);
// Decrement the counters.
if ( type = jQuery('#type-of-' + id).val() )
jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
if ( item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.toggle').toggle();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Vanish it.
jQuery('.toggle', item).toggle();
jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
jQuery('.filename:empty', item).remove();
jQuery('.filename .title', item).css('font-weight','bold');
jQuery('.filename', item).append('<span class="trashnotice"> ' + swfuploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
jQuery('.menu_order_input', item).hide();
return;
}
function deleteError(X, textStatus, errorThrown) {
// TODO
}
function updateMediaForm() {
var one = jQuery('form.type-form #media-items').children(), items = jQuery('#media-items').children();
// Just one file, no need for collapsible part
if ( one.length == 1 ) {
jQuery('.slidetoggle', one).slideDown(500).siblings().addClass('hidden').filter('.toggle').toggle();
}
// Only show Save buttons when there is at least one file.
if ( items.not('.media-blank').length > 0 )
jQuery('.savebutton').show();
else
jQuery('.savebutton').hide();
// Only show Gallery buttons when there are at least two files.
if ( items.length > 1 ) {
jQuery('.insert-gallery').show();
} else {
jQuery('.insert-gallery').hide();
}
}
function uploadSuccess(fileObj, serverData) {
// if async-upload returned an error message, place it in the media item div and return
if ( serverData.match('media-upload-error') ) {
jQuery('#media-item-' + fileObj.id).html(serverData);
return;
}
prepareMediaItem(fileObj, serverData);
updateMediaForm();
// Increment the counter.
if ( jQuery('#media-item-' + fileObj.id).hasClass('child-of-' + post_id) )
jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}
function uploadComplete(fileObj) {
// If no more uploads queued, enable the submit button
if ( swfu.getStats().files_queued == 0 ) {
jQuery('#cancel-upload').prop('disabled', true);
jQuery('#insert-gallery').prop('disabled', false);
}
}
// wp-specific error handlers
// generic message
function wpQueueError(message) {
jQuery('#media-upload-error').show().text(message);
}
// file-specific message
function wpFileError(fileObj, message) {
var item = jQuery('#media-item-' + fileObj.id);
var filename = jQuery('.filename', item).text();
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>'
+ '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />'
+ message
+ '</div>');
item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})});
}
function fileQueueError(fileObj, error_code, message) {
// Handle this error separately because we don't want to create a FileProgress element for it.
if ( error_code == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED ) {
wpQueueError(swfuploadL10n.queue_limit_exceeded);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.file_exceeds_size_limit);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.zero_byte_file);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.invalid_filetype);
}
else {
wpQueueError(swfuploadL10n.default_error);
}
}
function fileDialogComplete(num_files_queued) {
try {
if (num_files_queued > 0) {
this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
}
function switchUploader(s) {
var f = document.getElementById(swfu.customSettings.swfupload_element_id), h = document.getElementById(swfu.customSettings.degraded_element_id);
if ( s ) {
f.style.display = 'block';
h.style.display = 'none';
} else {
f.style.display = 'none';
h.style.display = 'block';
}
}
function swfuploadPreLoad() {
if ( !uploaderMode ) {
switchUploader(1);
} else {
switchUploader(0);
}
}
function swfuploadLoadFailed() {
switchUploader(0);
jQuery('.upload-html-bypass').hide();
}
function uploadError(fileObj, errorCode, message) {
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
wpFileError(fileObj, swfuploadL10n.missing_upload_url);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
wpFileError(fileObj, swfuploadL10n.upload_limit_exceeded);
break;
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
wpQueueError(swfuploadL10n.http_error);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
wpQueueError(swfuploadL10n.upload_failed);
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
wpQueueError(swfuploadL10n.io_error);
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
wpQueueError(swfuploadL10n.security_error);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
jQuery('#media-item-' + fileObj.id).remove();
break;
default:
wpFileError(fileObj, swfuploadL10n.default_error);
}
}
function cancelUpload() {
swfu.cancelQueue();
}
// remember the last used image size, alignment and url
jQuery(document).ready(function($){
$('input[type="radio"]', '#media-items').live('click', function(){
var tr = $(this).closest('tr');
if ( $(tr).hasClass('align') )
setUserSetting('align', $(this).val());
else if ( $(tr).hasClass('image-size') )
setUserSetting('imgsize', $(this).val());
});
$('button.button', '#media-items').live('click', function(){
var c = this.className || '';
c = c.match(/url([^ '"]+)/);
if ( c && c[1] ) {
setUserSetting('urlbutton', c[1]);
$(this).siblings('.urlfield').val( $(this).attr('title') );
}
});
});
| JavaScript |
/*
Speed Plug-in
Features:
*Adds several properties to the 'file' object indicated upload speed, time left, upload time, etc.
- currentSpeed -- String indicating the upload speed, bytes per second
- averageSpeed -- Overall average upload speed, bytes per second
- movingAverageSpeed -- Speed over averaged over the last several measurements, bytes per second
- timeRemaining -- Estimated remaining upload time in seconds
- timeElapsed -- Number of seconds passed for this upload
- percentUploaded -- Percentage of the file uploaded (0 to 100)
- sizeUploaded -- Formatted size uploaded so far, bytes
*Adds setting 'moving_average_history_size' for defining the window size used to calculate the moving average speed.
*Adds several Formatting functions for formatting that values provided on the file object.
- SWFUpload.speed.formatBPS(bps) -- outputs string formatted in the best units (Gbps, Mbps, Kbps, bps)
- SWFUpload.speed.formatTime(seconds) -- outputs string formatted in the best units (x Hr y M z S)
- SWFUpload.speed.formatSize(bytes) -- outputs string formatted in the best units (w GB x MB y KB z B )
- SWFUpload.speed.formatPercent(percent) -- outputs string formatted with a percent sign (x.xx %)
- SWFUpload.speed.formatUnits(baseNumber, divisionArray, unitLabelArray, fractionalBoolean)
- Formats a number using the division array to determine how to apply the labels in the Label Array
- factionalBoolean indicates whether the number should be returned as a single fractional number with a unit (speed)
or as several numbers labeled with units (time)
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.speed = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
// List used to keep the speed stats for the files we are tracking
this.fileSpeedStats = {};
this.speedSettings = {};
this.ensureDefault("moving_average_history_size", "10");
this.speedSettings.user_file_queued_handler = this.settings.file_queued_handler;
this.speedSettings.user_file_queue_error_handler = this.settings.file_queue_error_handler;
this.speedSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.speedSettings.user_upload_error_handler = this.settings.upload_error_handler;
this.speedSettings.user_upload_progress_handler = this.settings.upload_progress_handler;
this.speedSettings.user_upload_success_handler = this.settings.upload_success_handler;
this.speedSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.settings.file_queued_handler = SWFUpload.speed.fileQueuedHandler;
this.settings.file_queue_error_handler = SWFUpload.speed.fileQueueErrorHandler;
this.settings.upload_start_handler = SWFUpload.speed.uploadStartHandler;
this.settings.upload_error_handler = SWFUpload.speed.uploadErrorHandler;
this.settings.upload_progress_handler = SWFUpload.speed.uploadProgressHandler;
this.settings.upload_success_handler = SWFUpload.speed.uploadSuccessHandler;
this.settings.upload_complete_handler = SWFUpload.speed.uploadCompleteHandler;
delete this.ensureDefault;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.speed.fileQueuedHandler = function (file) {
if (typeof this.speedSettings.user_file_queued_handler === "function") {
file = SWFUpload.speed.extendFile(file);
return this.speedSettings.user_file_queued_handler.call(this, file);
}
};
SWFUpload.speed.fileQueueErrorHandler = function (file, errorCode, message) {
if (typeof this.speedSettings.user_file_queue_error_handler === "function") {
file = SWFUpload.speed.extendFile(file);
return this.speedSettings.user_file_queue_error_handler.call(this, file, errorCode, message);
}
};
SWFUpload.speed.uploadStartHandler = function (file) {
if (typeof this.speedSettings.user_upload_start_handler === "function") {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
return this.speedSettings.user_upload_start_handler.call(this, file);
}
};
SWFUpload.speed.uploadErrorHandler = function (file, errorCode, message) {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_error_handler === "function") {
return this.speedSettings.user_upload_error_handler.call(this, file, errorCode, message);
}
};
SWFUpload.speed.uploadProgressHandler = function (file, bytesComplete, bytesTotal) {
this.updateTracking(file, bytesComplete);
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_progress_handler === "function") {
return this.speedSettings.user_upload_progress_handler.call(this, file, bytesComplete, bytesTotal);
}
};
SWFUpload.speed.uploadSuccessHandler = function (file, serverData) {
if (typeof this.speedSettings.user_upload_success_handler === "function") {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
return this.speedSettings.user_upload_success_handler.call(this, file, serverData);
}
};
SWFUpload.speed.uploadCompleteHandler = function (file) {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_complete_handler === "function") {
return this.speedSettings.user_upload_complete_handler.call(this, file);
}
};
// Private: extends the file object with the speed plugin values
SWFUpload.speed.extendFile = function (file, trackingList) {
var tracking;
if (trackingList) {
tracking = trackingList[file.id];
}
if (tracking) {
file.currentSpeed = tracking.currentSpeed;
file.averageSpeed = tracking.averageSpeed;
file.movingAverageSpeed = tracking.movingAverageSpeed;
file.timeRemaining = tracking.timeRemaining;
file.timeElapsed = tracking.timeElapsed;
file.percentUploaded = tracking.percentUploaded;
file.sizeUploaded = tracking.bytesUploaded;
} else {
file.currentSpeed = 0;
file.averageSpeed = 0;
file.movingAverageSpeed = 0;
file.timeRemaining = 0;
file.timeElapsed = 0;
file.percentUploaded = 0;
file.sizeUploaded = 0;
}
return file;
};
// Private: Updates the speed tracking object, or creates it if necessary
SWFUpload.prototype.updateTracking = function (file, bytesUploaded) {
var tracking = this.fileSpeedStats[file.id];
if (!tracking) {
this.fileSpeedStats[file.id] = tracking = {};
}
// Sanity check inputs
bytesUploaded = bytesUploaded || tracking.bytesUploaded || 0;
if (bytesUploaded < 0) {
bytesUploaded = 0;
}
if (bytesUploaded > file.size) {
bytesUploaded = file.size;
}
var tickTime = (new Date()).getTime();
if (!tracking.startTime) {
tracking.startTime = (new Date()).getTime();
tracking.lastTime = tracking.startTime;
tracking.currentSpeed = 0;
tracking.averageSpeed = 0;
tracking.movingAverageSpeed = 0;
tracking.movingAverageHistory = [];
tracking.timeRemaining = 0;
tracking.timeElapsed = 0;
tracking.percentUploaded = bytesUploaded / file.size;
tracking.bytesUploaded = bytesUploaded;
} else if (tracking.startTime > tickTime) {
this.debug("When backwards in time");
} else {
// Get time and deltas
var now = (new Date()).getTime();
var lastTime = tracking.lastTime;
var deltaTime = now - lastTime;
var deltaBytes = bytesUploaded - tracking.bytesUploaded;
if (deltaBytes === 0 || deltaTime === 0) {
return tracking;
}
// Update tracking object
tracking.lastTime = now;
tracking.bytesUploaded = bytesUploaded;
// Calculate speeds
tracking.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000);
tracking.averageSpeed = (tracking.bytesUploaded * 8) / ((now - tracking.startTime) / 1000);
// Calculate moving average
tracking.movingAverageHistory.push(tracking.currentSpeed);
if (tracking.movingAverageHistory.length > this.settings.moving_average_history_size) {
tracking.movingAverageHistory.shift();
}
tracking.movingAverageSpeed = SWFUpload.speed.calculateMovingAverage(tracking.movingAverageHistory);
// Update times
tracking.timeRemaining = (file.size - tracking.bytesUploaded) * 8 / tracking.movingAverageSpeed;
tracking.timeElapsed = (now - tracking.startTime) / 1000;
// Update percent
tracking.percentUploaded = (tracking.bytesUploaded / file.size * 100);
}
return tracking;
};
SWFUpload.speed.removeTracking = function (file, trackingList) {
try {
trackingList[file.id] = null;
delete trackingList[file.id];
} catch (ex) {
}
};
SWFUpload.speed.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) {
var i, unit, unitDivisor, unitLabel;
if (baseNumber === 0) {
return "0 " + unitLabels[unitLabels.length - 1];
}
if (singleFractional) {
unit = baseNumber;
unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : "";
for (i = 0; i < unitDivisors.length; i++) {
if (baseNumber >= unitDivisors[i]) {
unit = (baseNumber / unitDivisors[i]).toFixed(2);
unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : "";
break;
}
}
return unit + unitLabel;
} else {
var formattedStrings = [];
var remainder = baseNumber;
for (i = 0; i < unitDivisors.length; i++) {
unitDivisor = unitDivisors[i];
unitLabel = unitLabels.length > i ? " " + unitLabels[i] : "";
unit = remainder / unitDivisor;
if (i < unitDivisors.length -1) {
unit = Math.floor(unit);
} else {
unit = unit.toFixed(2);
}
if (unit > 0) {
remainder = remainder % unitDivisor;
formattedStrings.push(unit + unitLabel);
}
}
return formattedStrings.join(" ");
}
};
SWFUpload.speed.formatBPS = function (baseNumber) {
var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"];
return SWFUpload.speed.formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true);
};
SWFUpload.speed.formatTime = function (baseNumber) {
var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"];
return SWFUpload.speed.formatUnits(baseNumber, timeUnits, timeUnitLabels, false);
};
SWFUpload.speed.formatBytes = function (baseNumber) {
var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"];
return SWFUpload.speed.formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true);
};
SWFUpload.speed.formatPercent = function (baseNumber) {
return baseNumber.toFixed(2) + " %";
};
SWFUpload.speed.calculateMovingAverage = function (history) {
var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0;
var i;
var mSum = 0, mCount = 0;
size = history.length;
// Check for sufficient data
if (size >= 8) {
// Clone the array and Calculate sum of the values
for (i = 0; i < size; i++) {
vals[i] = history[i];
sum += vals[i];
}
mean = sum / size;
// Calculate variance for the set
for (i = 0; i < size; i++) {
varianceTemp += Math.pow((vals[i] - mean), 2);
}
variance = varianceTemp / size;
standardDev = Math.sqrt(variance);
//Standardize the Data
for (i = 0; i < size; i++) {
vals[i] = (vals[i] - mean) / standardDev;
}
// Calculate the average excluding outliers
var deviationRange = 2.0;
for (i = 0; i < size; i++) {
if (vals[i] <= deviationRange && vals[i] >= -deviationRange) {
mCount++;
mSum += history[i];
}
}
} else {
// Calculate the average (not enough data points to remove outliers)
mCount = size;
for (i = 0; i < size; i++) {
mSum += history[i];
}
}
return mSum / mCount;
};
} | JavaScript |
/*
Cookie Plug-in
This plug in automatically gets all the cookies for this site and adds them to the post_params.
Cookies are loaded only on initialization. The refreshCookies function can be called to update the post_params.
The cookies will override any other post params with the same name.
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.prototype.initSettings = function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.refreshCookies(false); // The false parameter must be sent since SWFUpload has not initialzed at this point
};
}(SWFUpload.prototype.initSettings);
// refreshes the post_params and updates SWFUpload. The sendToFlash parameters is optional and defaults to True
SWFUpload.prototype.refreshCookies = function (sendToFlash) {
if (sendToFlash === undefined) {
sendToFlash = true;
}
sendToFlash = !!sendToFlash;
// Get the post_params object
var postParams = this.settings.post_params;
// Get the cookies
var i, cookieArray = document.cookie.split(';'), caLength = cookieArray.length, c, eqIndex, name, value;
for (i = 0; i < caLength; i++) {
c = cookieArray[i];
// Left Trim spaces
while (c.charAt(0) === " ") {
c = c.substring(1, c.length);
}
eqIndex = c.indexOf("=");
if (eqIndex > 0) {
name = c.substring(0, eqIndex);
value = c.substring(eqIndex + 1);
postParams[name] = value;
}
}
if (sendToFlash) {
this.setPostParams(postParams);
}
};
}
| JavaScript |
/*
Queue Plug-in
Features:
*Adds a cancelQueue() method for cancelling the entire queue.
*All queued files are uploaded when startUpload() is called.
*If false is returned from uploadComplete then the queue upload is stopped.
If false is not returned (strict comparison) then the queue upload is continued.
*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
Set the event handler with the queue_complete_handler setting.
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.queue = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.queueSettings = {};
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.startUpload = function (fileID) {
this.queueSettings.queue_cancelled_flag = false;
this.callFlash("StartUpload", [fileID]);
};
SWFUpload.prototype.cancelQueue = function () {
this.queueSettings.queue_cancelled_flag = true;
this.stopUpload();
var stats = this.getStats();
while (stats.files_queued > 0) {
this.cancelUpload();
stats = this.getStats();
}
};
SWFUpload.queue.uploadStartHandler = function (file) {
var returnValue;
if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
}
// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
returnValue = (returnValue === false) ? false : true;
this.queueSettings.queue_cancelled_flag = !returnValue;
return returnValue;
};
SWFUpload.queue.uploadCompleteHandler = function (file) {
var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
var continueUpload;
if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
this.queueSettings.queue_upload_count++;
}
if (typeof(user_upload_complete_handler) === "function") {
continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
// If the file was stopped and re-queued don't restart the upload
continueUpload = false;
} else {
continueUpload = true;
}
if (continueUpload) {
var stats = this.getStats();
if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
this.startUpload();
} else if (this.queueSettings.queue_cancelled_flag === false) {
this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
this.queueSettings.queue_upload_count = 0;
} else {
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
}
}
};
}
| JavaScript |
/*
SWFUpload.SWFObject Plugin
Summary:
This plugin uses SWFObject to embed SWFUpload dynamically in the page. SWFObject provides accurate Flash Player detection and DOM Ready loading.
This plugin replaces the Graceful Degradation plugin.
Features:
* swfupload_load_failed_hander event
* swfupload_pre_load_handler event
* minimum_flash_version setting (default: "9.0.28")
* SWFUpload.onload event for early loading
Usage:
Provide handlers and settings as needed. When using the SWFUpload.SWFObject plugin you should initialize SWFUploading
in SWFUpload.onload rather than in window.onload. When initialized this way SWFUpload can load earlier preventing the UI flicker
that was seen using the Graceful Degradation plugin.
<script type="text/javascript">
var swfu;
SWFUpload.onload = function () {
swfu = new SWFUpload({
minimum_flash_version: "9.0.28",
swfupload_pre_load_handler: swfuploadPreLoad,
swfupload_load_failed_handler: swfuploadLoadFailed
});
};
</script>
Notes:
You must provide set minimum_flash_version setting to "8" if you are using SWFUpload for Flash Player 8.
The swfuploadLoadFailed event is only fired if the minimum version of Flash Player is not met. Other issues such as missing SWF files, browser bugs
or corrupt Flash Player installations will not trigger this event.
The swfuploadPreLoad event is fired as soon as the minimum version of Flash Player is found. It does not wait for SWFUpload to load and can
be used to prepare the SWFUploadUI and hide alternate content.
swfobject's onDomReady event is cross-browser safe but will default to the window.onload event when DOMReady is not supported by the browser.
Early DOM Loading is supported in major modern browsers but cannot be guaranteed for every browser ever made.
*/
// SWFObject v2.1 must be loaded
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.onload = function () {};
swfobject.addDomLoadEvent(function () {
if (typeof(SWFUpload.onload) === "function") {
setTimeout(function(){SWFUpload.onload.call(window);}, 200);
}
});
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
this.ensureDefault("minimum_flash_version", "9.0.28");
this.ensureDefault("swfupload_pre_load_handler", null);
this.ensureDefault("swfupload_load_failed_handler", null);
delete this.ensureDefault;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.loadFlash = function (oldLoadFlash) {
return function () {
var hasFlash = swfobject.hasFlashPlayerVersion(this.settings.minimum_flash_version);
if (hasFlash) {
this.queueEvent("swfupload_pre_load_handler");
if (typeof(oldLoadFlash) === "function") {
oldLoadFlash.call(this);
}
} else {
this.queueEvent("swfupload_load_failed_handler");
}
};
}(SWFUpload.prototype.loadFlash);
SWFUpload.prototype.displayDebugInfo = function (oldDisplayDebugInfo) {
return function () {
if (typeof(oldDisplayDebugInfo) === "function") {
oldDisplayDebugInfo.call(this);
}
this.debug(
[
"SWFUpload.SWFObject Plugin settings:", "\n",
"\t", "minimum_flash_version: ", this.settings.minimum_flash_version, "\n",
"\t", "swfupload_pre_load_handler assigned: ", (typeof(this.settings.swfupload_pre_load_handler) === "function").toString(), "\n",
"\t", "swfupload_load_failed_handler assigned: ", (typeof(this.settings.swfupload_load_failed_handler) === "function").toString(), "\n",
].join("")
);
};
}(SWFUpload.prototype.displayDebugInfo);
}
| JavaScript |
(function(w) {
var init = function() {
var pr = document.getElementById('post-revisions'),
inputs = pr ? pr.getElementsByTagName('input') : [];
pr.onclick = function() {
var i, checkCount = 0, side;
for ( i = 0; i < inputs.length; i++ ) {
checkCount += inputs[i].checked ? 1 : 0;
side = inputs[i].getAttribute('name');
if ( ! inputs[i].checked &&
( 'left' == side && 1 > checkCount || 'right' == side && 1 < checkCount && ( ! inputs[i-1] || ! inputs[i-1].checked ) ) &&
! ( inputs[i+1] && inputs[i+1].checked && 'right' == inputs[i+1].getAttribute('name') ) )
inputs[i].style.visibility = 'hidden';
else if ( 'left' == side || 'right' == side )
inputs[i].style.visibility = 'visible';
}
};
pr.onclick();
};
if ( w && w.addEventListener )
w.addEventListener('load', init, false);
else if ( w && w.attachEvent )
w.attachEvent('onload', init);
})(window);
| JavaScript |
/*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
if ( typeof tb_pathToImage != 'string' ) {
var tb_pathToImage = thickboxL10n.loadingAnimation;
}
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
//on page load call tb_init
jQuery(document).ready(function(){
tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
imgLoader = new Image();// preload image
imgLoader.src = tb_pathToImage;
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
jQuery('body').on('click', domChunk, tb_click);
}
function tb_click(){
var t = this.title || this.name || null;
var a = this.href || this.alt;
var g = this.rel || false;
tb_show(t,a,g);
this.blur();
return false;
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
try {
if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
jQuery("body","html").css({height: "100%", width: "100%"});
jQuery("html").css("overflow","hidden");
if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
jQuery("body").append("<iframe id='TB_HideSelect'>"+thickboxL10n.noiframes+"</iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
jQuery("#TB_overlay").click(tb_remove);
}
}else{//all others
if(document.getElementById("TB_overlay") === null){
jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
jQuery("#TB_overlay").click(tb_remove);
}
}
if(tb_detectMacXFF()){
jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
}else{
jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
}
if(caption===null){caption="";}
jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' width='208' /></div>");//add loader to the page
jQuery('#TB_load').show();//show loader
var baseURL;
if(url.indexOf("?")!==-1){ //ff there is a query string involved
baseURL = url.substr(0, url.indexOf("?"));
}else{
baseURL = url;
}
var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
var urlType = baseURL.toLowerCase().match(urlString);
if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
TB_PrevCaption = "";
TB_PrevURL = "";
TB_PrevHTML = "";
TB_NextCaption = "";
TB_NextURL = "";
TB_NextHTML = "";
TB_imageCount = "";
TB_FoundURL = false;
if(imageGroup){
TB_TempArray = jQuery("a[rel="+imageGroup+"]").get();
for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
if (!(TB_TempArray[TB_Counter].href == url)) {
if (TB_FoundURL) {
TB_NextCaption = TB_TempArray[TB_Counter].title;
TB_NextURL = TB_TempArray[TB_Counter].href;
TB_NextHTML = "<span id='TB_next'> <a href='#'>"+thickboxL10n.next+"</a></span>";
} else {
TB_PrevCaption = TB_TempArray[TB_Counter].title;
TB_PrevURL = TB_TempArray[TB_Counter].href;
TB_PrevHTML = "<span id='TB_prev'> <a href='#'>"+thickboxL10n.prev+"</a></span>";
}
} else {
TB_FoundURL = true;
TB_imageCount = thickboxL10n.image + ' ' + (TB_Counter + 1) + ' ' + thickboxL10n.of + ' ' + (TB_TempArray.length);
}
}
}
imgPreloader = new Image();
imgPreloader.onload = function(){
imgPreloader.onload = null;
// Resizing large images - orginal by Christian Montoya edited by me.
var pagesize = tb_getPageSize();
var x = pagesize[0] - 150;
var y = pagesize[1] - 150;
var imageWidth = imgPreloader.width;
var imageHeight = imgPreloader.height;
if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth);
imageWidth = x;
if (imageHeight > y) {
imageWidth = imageWidth * (y / imageHeight);
imageHeight = y;
}
} else if (imageHeight > y) {
imageWidth = imageWidth * (y / imageHeight);
imageHeight = y;
if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth);
imageWidth = x;
}
}
// End Resizing
TB_WIDTH = imageWidth + 30;
TB_HEIGHT = imageHeight + 60;
jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='"+thickboxL10n.close+"'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><div class='tb-close-icon'></div></a></div>");
jQuery("#TB_closeWindowButton").click(tb_remove);
if (!(TB_PrevHTML === "")) {
function goPrev(){
if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);}
jQuery("#TB_window").remove();
jQuery("body").append("<div id='TB_window'></div>");
tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
return false;
}
jQuery("#TB_prev").click(goPrev);
}
if (!(TB_NextHTML === "")) {
function goNext(){
jQuery("#TB_window").remove();
jQuery("body").append("<div id='TB_window'></div>");
tb_show(TB_NextCaption, TB_NextURL, imageGroup);
return false;
}
jQuery("#TB_next").click(goNext);
}
jQuery(document).bind('keydown.thickbox', function(e){
if ( e.which == 27 ){ // close
tb_remove();
} else if ( e.which == 190 ){ // display previous image
if(!(TB_NextHTML == "")){
jQuery(document).unbind('thickbox');
goNext();
}
} else if ( e.which == 188 ){ // display next image
if(!(TB_PrevHTML == "")){
jQuery(document).unbind('thickbox');
goPrev();
}
}
return false;
});
tb_position();
jQuery("#TB_load").remove();
jQuery("#TB_ImageOff").click(tb_remove);
jQuery("#TB_window").css({'visibility':'visible'}); //for safari using css instead of show
};
imgPreloader.src = url;
}else{//code to show html
var queryString = url.replace(/^[^\?]+\??/,'');
var params = tb_parseQuery( queryString );
TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
ajaxContentW = TB_WIDTH - 30;
ajaxContentH = TB_HEIGHT - 45;
if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window
urlNoQuery = url.split('TB_');
jQuery("#TB_iframeContent").remove();
if(params['modal'] != "true"){//iframe no modal
jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><div class='tb-close-icon'></div></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' >"+thickboxL10n.noiframes+"</iframe>");
}else{//iframe modal
jQuery("#TB_overlay").unbind();
jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'>"+thickboxL10n.noiframes+"</iframe>");
}
}else{// not an iframe, ajax
if(jQuery("#TB_window").css("visibility") != "visible"){
if(params['modal'] != "true"){//ajax no modal
jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><div class='tb-close-icon'></div></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
}else{//ajax modal
jQuery("#TB_overlay").unbind();
jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
}
}else{//this means the window is already up, we are just loading new content via ajax
jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
jQuery("#TB_ajaxContent")[0].scrollTop = 0;
jQuery("#TB_ajaxWindowTitle").html(caption);
}
}
jQuery("#TB_closeWindowButton").click(tb_remove);
if(url.indexOf('TB_inline') != -1){
jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children());
jQuery("#TB_window").bind('tb_unload', function () {
jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished
});
tb_position();
jQuery("#TB_load").remove();
jQuery("#TB_window").css({'visibility':'visible'});
}else if(url.indexOf('TB_iframe') != -1){
tb_position();
jQuery("#TB_load").remove();
jQuery("#TB_window").css({'visibility':'visible'});
}else{
jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
tb_position();
jQuery("#TB_load").remove();
tb_init("#TB_ajaxContent a.thickbox");
jQuery("#TB_window").css({'visibility':'visible'});
});
}
}
if(!params['modal']){
jQuery(document).bind('keydown.thickbox', function(e){
if ( e.which == 27 ){ // close
tb_remove();
return false;
}
});
}
} catch(e) {
//nothing here
}
}
//helper functions below
function tb_showIframe(){
jQuery("#TB_load").remove();
jQuery("#TB_window").css({'visibility':'visible'});
}
function tb_remove() {
jQuery("#TB_imageOff").unbind("click");
jQuery("#TB_closeWindowButton").unbind("click");
jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("tb_unload").unbind().remove();});
jQuery("#TB_load").remove();
if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
jQuery("body","html").css({height: "auto", width: "auto"});
jQuery("html").css("overflow","");
}
jQuery(document).unbind('.thickbox');
return false;
}
function tb_position() {
var isIE6 = typeof document.body.style.maxHeight === "undefined";
jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
if ( ! isIE6 ) { // take away IE6
jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
}
}
function tb_parseQuery ( query ) {
var Params = {};
if ( ! query ) {return Params;}// return empty object
var Pairs = query.split(/[;&]/);
for ( var i = 0; i < Pairs.length; i++ ) {
var KeyVal = Pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] );
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}
function tb_getPageSize(){
var de = document.documentElement;
var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
arrayPageSize = [w,h];
return arrayPageSize;
}
function tb_detectMacXFF() {
var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
return true;
}
}
| JavaScript |
( function($) {
$.widget('wp.wpdialog', $.ui.dialog, {
open: function() {
// Add beforeOpen event.
if ( this.isOpen() || false === this._trigger('beforeOpen') ) {
return;
}
// Open the dialog.
this._super();
// WebKit leaves focus in the TinyMCE editor unless we shift focus.
this.element.focus();
this._trigger('refresh');
}
});
$.wp.wpdialog.prototype.options.closeOnEscape = false;
})(jQuery);
| JavaScript |
var wpAjax = jQuery.extend( {
unserialize: function( s ) {
var r = {}, q, pp, i, p;
if ( !s ) { return r; }
q = s.split('?'); if ( q[1] ) { s = q[1]; }
pp = s.split('&');
for ( i in pp ) {
if ( jQuery.isFunction(pp.hasOwnProperty) && !pp.hasOwnProperty(i) ) { continue; }
p = pp[i].split('=');
r[p[0]] = p[1];
}
return r;
},
parseAjaxResponse: function( x, r, e ) { // 1 = good, 0 = strange (bad data?), -1 = you lack permission
var parsed = {}, re = jQuery('#' + r).html(''), err = '';
if ( x && typeof x == 'object' && x.getElementsByTagName('wp_ajax') ) {
parsed.responses = [];
parsed.errors = false;
jQuery('response', x).each( function() {
var th = jQuery(this), child = jQuery(this.firstChild), response;
response = { action: th.attr('action'), what: child.get(0).nodeName, id: child.attr('id'), oldId: child.attr('old_id'), position: child.attr('position') };
response.data = jQuery( 'response_data', child ).text();
response.supplemental = {};
if ( !jQuery( 'supplemental', child ).children().each( function() {
response.supplemental[this.nodeName] = jQuery(this).text();
} ).size() ) { response.supplemental = false; }
response.errors = [];
if ( !jQuery('wp_error', child).each( function() {
var code = jQuery(this).attr('code'), anError, errorData, formField;
anError = { code: code, message: this.firstChild.nodeValue, data: false };
errorData = jQuery('wp_error_data[code="' + code + '"]', x);
if ( errorData ) { anError.data = errorData.get(); }
formField = jQuery( 'form-field', errorData ).text();
if ( formField ) { code = formField; }
if ( e ) { wpAjax.invalidateForm( jQuery('#' + e + ' :input[name="' + code + '"]' ).parents('.form-field:first') ); }
err += '<p>' + anError.message + '</p>';
response.errors.push( anError );
parsed.errors = true;
} ).size() ) { response.errors = false; }
parsed.responses.push( response );
} );
if ( err.length ) { re.html( '<div class="error">' + err + '</div>' ); }
return parsed;
}
if ( isNaN(x) ) { return !re.html('<div class="error"><p>' + x + '</p></div>'); }
x = parseInt(x,10);
if ( -1 == x ) { return !re.html('<div class="error"><p>' + wpAjax.noPerm + '</p></div>'); }
else if ( 0 === x ) { return !re.html('<div class="error"><p>' + wpAjax.broken + '</p></div>'); }
return true;
},
invalidateForm: function ( selector ) {
return jQuery( selector ).addClass( 'form-invalid' ).find('input:visible').change( function() { jQuery(this).closest('.form-invalid').removeClass( 'form-invalid' ); } );
},
validateForm: function( selector ) {
selector = jQuery( selector );
return !wpAjax.invalidateForm( selector.find('.form-required').filter( function() { return jQuery('input:visible', this).val() === ''; } ) ).size();
}
}, wpAjax || { noPerm: 'You do not have permission to do that.', broken: 'An unidentified error has occurred.' } );
// Basic form validation
jQuery(document).ready( function($){
$('form.validate').submit( function() { return wpAjax.validateForm( $(this) ); } );
});
| JavaScript |
/* global adminpage, wpActiveEditor, quicktagsL10n, wpLink, prompt */
/*
* Quicktags
*
* This is the HTML editor in WordPress. It can be attached to any textarea and will
* append a toolbar above it. This script is self-contained (does not require external libraries).
*
* Run quicktags(settings) to initialize it, where settings is an object containing up to 3 properties:
* settings = {
* id : 'my_id', the HTML ID of the textarea, required
* buttons: '' Comma separated list of the names of the default buttons to show. Optional.
* Current list of default button names: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close';
* }
*
* The settings can also be a string quicktags_id.
*
* quicktags_id string The ID of the textarea that will be the editor canvas
* buttons string Comma separated list of the default buttons names that will be shown in that instance.
*/
// new edit toolbar used with permission
// by Alex King
// http://www.alexking.org/
var QTags, edCanvas,
edButtons = [];
/* jshint ignore:start */
/**
* Back-compat
*
* Define all former global functions so plugins that hack quicktags.js directly don't cause fatal errors.
*/
var edAddTag = function(){},
edCheckOpenTags = function(){},
edCloseAllTags = function(){},
edInsertImage = function(){},
edInsertLink = function(){},
edInsertTag = function(){},
edLink = function(){},
edQuickLink = function(){},
edRemoveTag = function(){},
edShowButton = function(){},
edShowLinks = function(){},
edSpell = function(){},
edToolbar = function(){};
/**
* Initialize new instance of the Quicktags editor
*/
function quicktags(settings) {
return new QTags(settings);
}
/**
* Inserts content at the caret in the active editor (textarea)
*
* Added for back compatibility
* @see QTags.insertContent()
*/
function edInsertContent(bah, txt) {
return QTags.insertContent(txt);
}
/**
* Adds a button to all instances of the editor
*
* Added for back compatibility, use QTags.addButton() as it gives more flexibility like type of button, button placement, etc.
* @see QTags.addButton()
*/
function edButton(id, display, tagStart, tagEnd, access) {
return QTags.addButton( id, display, tagStart, tagEnd, access, '', -1 );
}
/* jshint ignore:end */
(function(){
// private stuff is prefixed with an underscore
var _domReady = function(func) {
var t, i, DOMContentLoaded, _tryReady;
if ( typeof jQuery !== 'undefined' ) {
jQuery(document).ready(func);
} else {
t = _domReady;
t.funcs = [];
t.ready = function() {
if ( ! t.isReady ) {
t.isReady = true;
for ( i = 0; i < t.funcs.length; i++ ) {
t.funcs[i]();
}
}
};
if ( t.isReady ) {
func();
} else {
t.funcs.push(func);
}
if ( ! t.eventAttached ) {
if ( document.addEventListener ) {
DOMContentLoaded = function(){document.removeEventListener('DOMContentLoaded', DOMContentLoaded, false);t.ready();};
document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);
window.addEventListener('load', t.ready, false);
} else if ( document.attachEvent ) {
DOMContentLoaded = function(){if (document.readyState === 'complete'){ document.detachEvent('onreadystatechange', DOMContentLoaded);t.ready();}};
document.attachEvent('onreadystatechange', DOMContentLoaded);
window.attachEvent('onload', t.ready);
_tryReady = function() {
try {
document.documentElement.doScroll('left');
} catch(e) {
setTimeout(_tryReady, 50);
return;
}
t.ready();
};
_tryReady();
}
t.eventAttached = true;
}
}
},
_datetime = (function() {
var now = new Date(), zeroise;
zeroise = function(number) {
var str = number.toString();
if ( str.length < 2 ) {
str = '0' + str;
}
return str;
};
return now.getUTCFullYear() + '-' +
zeroise( now.getUTCMonth() + 1 ) + '-' +
zeroise( now.getUTCDate() ) + 'T' +
zeroise( now.getUTCHours() ) + ':' +
zeroise( now.getUTCMinutes() ) + ':' +
zeroise( now.getUTCSeconds() ) +
'+00:00';
})(),
qt;
qt = QTags = function(settings) {
if ( typeof(settings) === 'string' ) {
settings = {id: settings};
} else if ( typeof(settings) !== 'object' ) {
return false;
}
var t = this,
id = settings.id,
canvas = document.getElementById(id),
name = 'qt_' + id,
tb, onclick, toolbar_id;
if ( !id || !canvas ) {
return false;
}
t.name = name;
t.id = id;
t.canvas = canvas;
t.settings = settings;
if ( id === 'content' && typeof(adminpage) === 'string' && ( adminpage === 'post-new-php' || adminpage === 'post-php' ) ) {
// back compat hack :-(
edCanvas = canvas;
toolbar_id = 'ed_toolbar';
} else {
toolbar_id = name + '_toolbar';
}
tb = document.createElement('div');
tb.id = toolbar_id;
tb.className = 'quicktags-toolbar';
tb.onclick = function() {
window.wpActiveEditor = id;
};
canvas.parentNode.insertBefore(tb, canvas);
t.toolbar = tb;
// listen for click events
onclick = function(e) {
e = e || window.event;
var target = e.target || e.srcElement, visible = target.clientWidth || target.offsetWidth, i;
// don't call the callback on pressing the accesskey when the button is not visible
if ( !visible ) {
return;
}
// as long as it has the class ed_button, execute the callback
if ( / ed_button /.test(' ' + target.className + ' ') ) {
// we have to reassign canvas here
t.canvas = canvas = document.getElementById(id);
i = target.id.replace(name + '_', '');
if ( t.theButtons[i] ) {
t.theButtons[i].callback.call(t.theButtons[i], target, canvas, t);
}
}
};
if ( tb.addEventListener ) {
tb.addEventListener('click', onclick, false);
} else if ( tb.attachEvent ) {
tb.attachEvent('onclick', onclick);
}
t.getButton = function(id) {
return t.theButtons[id];
};
t.getButtonElement = function(id) {
return document.getElementById(name + '_' + id);
};
qt.instances[id] = t;
if ( !qt.instances[0] ) {
qt.instances[0] = qt.instances[id];
_domReady( function(){ qt._buttonsInit(); } );
}
};
qt.instances = {};
qt.getInstance = function(id) {
return qt.instances[id];
};
qt._buttonsInit = function() {
var t = this, canvas, name, settings, theButtons, html, inst, ed, id, i, use,
defaults = ',strong,em,link,block,del,ins,img,ul,ol,li,code,more,close,';
for ( inst in t.instances ) {
if ( inst === 0 ) {
continue;
}
ed = t.instances[inst];
canvas = ed.canvas;
name = ed.name;
settings = ed.settings;
html = '';
theButtons = {};
use = '';
// set buttons
if ( settings.buttons ) {
use = ','+settings.buttons+',';
}
for ( i in edButtons ) {
if ( !edButtons[i] ) {
continue;
}
id = edButtons[i].id;
if ( use && defaults.indexOf( ',' + id + ',' ) !== -1 && use.indexOf( ',' + id + ',' ) === -1 ) {
continue;
}
if ( !edButtons[i].instance || edButtons[i].instance === inst ) {
theButtons[id] = edButtons[i];
if ( edButtons[i].html ) {
html += edButtons[i].html(name + '_');
}
}
}
if ( use && use.indexOf(',fullscreen,') !== -1 ) {
theButtons.fullscreen = new qt.FullscreenButton();
html += theButtons.fullscreen.html(name + '_');
}
if ( 'rtl' === document.getElementsByTagName('html')[0].dir ) {
theButtons.textdirection = new qt.TextDirectionButton();
html += theButtons.textdirection.html(name + '_');
}
ed.toolbar.innerHTML = html;
ed.theButtons = theButtons;
}
t.buttonsInitDone = true;
};
/**
* Main API function for adding a button to Quicktags
*
* Adds qt.Button or qt.TagButton depending on the args. The first three args are always required.
* To be able to add button(s) to Quicktags, your script should be enqueued as dependent
* on "quicktags" and outputted in the footer. If you are echoing JS directly from PHP,
* use add_action( 'admin_print_footer_scripts', 'output_my_js', 100 ) or add_action( 'wp_footer', 'output_my_js', 100 )
*
* Minimum required to add a button that calls an external function:
* QTags.addButton( 'my_id', 'my button', my_callback );
* function my_callback() { alert('yeah!'); }
*
* Minimum required to add a button that inserts a tag:
* QTags.addButton( 'my_id', 'my button', '<span>', '</span>' );
* QTags.addButton( 'my_id2', 'my button', '<br />' );
*
* @param string id Required. Button HTML ID
* @param string display Required. Button's value="..."
* @param string|function arg1 Required. Either a starting tag to be inserted like "<span>" or a callback that is executed when the button is clicked.
* @param string arg2 Optional. Ending tag like "</span>"
* @param string access_key Optional. Access key for the button.
* @param string title Optional. Button's title="..."
* @param int priority Optional. Number representing the desired position of the button in the toolbar. 1 - 9 = first, 11 - 19 = second, 21 - 29 = third, etc.
* @param string instance Optional. Limit the button to a specifric instance of Quicktags, add to all instances if not present.
* @return mixed null or the button object that is needed for back-compat.
*/
qt.addButton = function( id, display, arg1, arg2, access_key, title, priority, instance ) {
var btn;
if ( !id || !display ) {
return;
}
priority = priority || 0;
arg2 = arg2 || '';
if ( typeof(arg1) === 'function' ) {
btn = new qt.Button(id, display, access_key, title, instance);
btn.callback = arg1;
} else if ( typeof(arg1) === 'string' ) {
btn = new qt.TagButton(id, display, arg1, arg2, access_key, title, instance);
} else {
return;
}
if ( priority === -1 ) { // back-compat
return btn;
}
if ( priority > 0 ) {
while ( typeof(edButtons[priority]) !== 'undefined' ) {
priority++;
}
edButtons[priority] = btn;
} else {
edButtons[edButtons.length] = btn;
}
if ( this.buttonsInitDone ) {
this._buttonsInit(); // add the button HTML to all instances toolbars if addButton() was called too late
}
};
qt.insertContent = function(content) {
var sel, startPos, endPos, scrollTop, text, canvas = document.getElementById(wpActiveEditor);
if ( !canvas ) {
return false;
}
if ( document.selection ) { //IE
canvas.focus();
sel = document.selection.createRange();
sel.text = content;
canvas.focus();
} else if ( canvas.selectionStart || canvas.selectionStart === 0 ) { // FF, WebKit, Opera
text = canvas.value;
startPos = canvas.selectionStart;
endPos = canvas.selectionEnd;
scrollTop = canvas.scrollTop;
canvas.value = text.substring(0, startPos) + content + text.substring(endPos, text.length);
canvas.focus();
canvas.selectionStart = startPos + content.length;
canvas.selectionEnd = startPos + content.length;
canvas.scrollTop = scrollTop;
} else {
canvas.value += content;
canvas.focus();
}
return true;
};
// a plain, dumb button
qt.Button = function(id, display, access, title, instance) {
var t = this;
t.id = id;
t.display = display;
t.access = access;
t.title = title || '';
t.instance = instance || '';
};
qt.Button.prototype.html = function(idPrefix) {
var access = this.access ? ' accesskey="' + this.access + '"' : '';
if ( this.id === 'fullscreen' ) {
return '<button type="button" id="' + idPrefix + this.id + '"' + access + ' class="ed_button qt-fullscreen" title="' + this.title + '"></button>';
}
return '<input type="button" id="' + idPrefix + this.id + '"' + access + ' class="ed_button button button-small" title="' + this.title + '" value="' + this.display + '" />';
};
qt.Button.prototype.callback = function(){};
// a button that inserts HTML tag
qt.TagButton = function(id, display, tagStart, tagEnd, access, title, instance) {
var t = this;
qt.Button.call(t, id, display, access, title, instance);
t.tagStart = tagStart;
t.tagEnd = tagEnd;
};
qt.TagButton.prototype = new qt.Button();
qt.TagButton.prototype.openTag = function(e, ed) {
var t = this;
if ( ! ed.openTags ) {
ed.openTags = [];
}
if ( t.tagEnd ) {
ed.openTags.push(t.id);
e.value = '/' + e.value;
}
};
qt.TagButton.prototype.closeTag = function(e, ed) {
var t = this, i = t.isOpen(ed);
if ( i !== false ) {
ed.openTags.splice(i, 1);
}
e.value = t.display;
};
// whether a tag is open or not. Returns false if not open, or current open depth of the tag
qt.TagButton.prototype.isOpen = function (ed) {
var t = this, i = 0, ret = false;
if ( ed.openTags ) {
while ( ret === false && i < ed.openTags.length ) {
ret = ed.openTags[i] === t.id ? i : false;
i ++;
}
} else {
ret = false;
}
return ret;
};
qt.TagButton.prototype.callback = function(element, canvas, ed) {
var t = this, startPos, endPos, cursorPos, scrollTop, v = canvas.value, l, r, i, sel, endTag = v ? t.tagEnd : '';
if ( document.selection ) { // IE
canvas.focus();
sel = document.selection.createRange();
if ( sel.text.length > 0 ) {
if ( !t.tagEnd ) {
sel.text = sel.text + t.tagStart;
} else {
sel.text = t.tagStart + sel.text + endTag;
}
} else {
if ( !t.tagEnd ) {
sel.text = t.tagStart;
} else if ( t.isOpen(ed) === false ) {
sel.text = t.tagStart;
t.openTag(element, ed);
} else {
sel.text = endTag;
t.closeTag(element, ed);
}
}
canvas.focus();
} else if ( canvas.selectionStart || canvas.selectionStart === 0 ) { // FF, WebKit, Opera
startPos = canvas.selectionStart;
endPos = canvas.selectionEnd;
cursorPos = endPos;
scrollTop = canvas.scrollTop;
l = v.substring(0, startPos); // left of the selection
r = v.substring(endPos, v.length); // right of the selection
i = v.substring(startPos, endPos); // inside the selection
if ( startPos !== endPos ) {
if ( !t.tagEnd ) {
canvas.value = l + i + t.tagStart + r; // insert self closing tags after the selection
cursorPos += t.tagStart.length;
} else {
canvas.value = l + t.tagStart + i + endTag + r;
cursorPos += t.tagStart.length + endTag.length;
}
} else {
if ( !t.tagEnd ) {
canvas.value = l + t.tagStart + r;
cursorPos = startPos + t.tagStart.length;
} else if ( t.isOpen(ed) === false ) {
canvas.value = l + t.tagStart + r;
t.openTag(element, ed);
cursorPos = startPos + t.tagStart.length;
} else {
canvas.value = l + endTag + r;
cursorPos = startPos + endTag.length;
t.closeTag(element, ed);
}
}
canvas.focus();
canvas.selectionStart = cursorPos;
canvas.selectionEnd = cursorPos;
canvas.scrollTop = scrollTop;
} else { // other browsers?
if ( !endTag ) {
canvas.value += t.tagStart;
} else if ( t.isOpen(ed) !== false ) {
canvas.value += t.tagStart;
t.openTag(element, ed);
} else {
canvas.value += endTag;
t.closeTag(element, ed);
}
canvas.focus();
}
};
// removed
qt.SpellButton = function() {};
// the close tags button
qt.CloseButton = function() {
qt.Button.call(this, 'close', quicktagsL10n.closeTags, '', quicktagsL10n.closeAllOpenTags);
};
qt.CloseButton.prototype = new qt.Button();
qt._close = function(e, c, ed) {
var button, element, tbo = ed.openTags;
if ( tbo ) {
while ( tbo.length > 0 ) {
button = ed.getButton(tbo[tbo.length - 1]);
element = document.getElementById(ed.name + '_' + button.id);
if ( e ) {
button.callback.call(button, element, c, ed);
} else {
button.closeTag(element, ed);
}
}
}
};
qt.CloseButton.prototype.callback = qt._close;
qt.closeAllTags = function(editor_id) {
var ed = this.getInstance(editor_id);
qt._close('', ed.canvas, ed);
};
// the link button
qt.LinkButton = function() {
qt.TagButton.call(this, 'link', 'link', '', '</a>', 'a');
};
qt.LinkButton.prototype = new qt.TagButton();
qt.LinkButton.prototype.callback = function(e, c, ed, defaultValue) {
var URL, t = this;
if ( typeof wpLink !== 'undefined' ) {
wpLink.open( ed.id );
return;
}
if ( ! defaultValue ) {
defaultValue = 'http://';
}
if ( t.isOpen(ed) === false ) {
URL = prompt(quicktagsL10n.enterURL, defaultValue);
if ( URL ) {
t.tagStart = '<a href="' + URL + '">';
qt.TagButton.prototype.callback.call(t, e, c, ed);
}
} else {
qt.TagButton.prototype.callback.call(t, e, c, ed);
}
};
// the img button
qt.ImgButton = function() {
qt.TagButton.call(this, 'img', 'img', '', '', 'm');
};
qt.ImgButton.prototype = new qt.TagButton();
qt.ImgButton.prototype.callback = function(e, c, ed, defaultValue) {
if ( ! defaultValue ) {
defaultValue = 'http://';
}
var src = prompt(quicktagsL10n.enterImageURL, defaultValue), alt;
if ( src ) {
alt = prompt(quicktagsL10n.enterImageDescription, '');
this.tagStart = '<img src="' + src + '" alt="' + alt + '" />';
qt.TagButton.prototype.callback.call(this, e, c, ed);
}
};
qt.FullscreenButton = function() {
qt.Button.call(this, 'fullscreen', quicktagsL10n.fullscreen, 'f', quicktagsL10n.toggleFullscreen);
};
qt.FullscreenButton.prototype = new qt.Button();
qt.FullscreenButton.prototype.callback = function(e, c) {
if ( ! c.id || typeof wp === 'undefined' || ! wp.editor || ! wp.editor.fullscreen ) {
return;
}
wp.editor.fullscreen.on();
};
qt.TextDirectionButton = function() {
qt.Button.call(this, 'textdirection', quicktagsL10n.textdirection, '', quicktagsL10n.toggleTextdirection);
};
qt.TextDirectionButton.prototype = new qt.Button();
qt.TextDirectionButton.prototype.callback = function(e, c) {
var isRTL = ( 'rtl' === document.getElementsByTagName('html')[0].dir ),
currentDirection = c.style.direction;
if ( ! currentDirection ) {
currentDirection = ( isRTL ) ? 'rtl' : 'ltr';
}
c.style.direction = ( 'rtl' === currentDirection ) ? 'ltr' : 'rtl';
c.focus();
};
// ensure backward compatibility
edButtons[10] = new qt.TagButton('strong','b','<strong>','</strong>','b');
edButtons[20] = new qt.TagButton('em','i','<em>','</em>','i'),
edButtons[30] = new qt.LinkButton(), // special case
edButtons[40] = new qt.TagButton('block','b-quote','\n\n<blockquote>','</blockquote>\n\n','q'),
edButtons[50] = new qt.TagButton('del','del','<del datetime="' + _datetime + '">','</del>','d'),
edButtons[60] = new qt.TagButton('ins','ins','<ins datetime="' + _datetime + '">','</ins>','s'),
edButtons[70] = new qt.ImgButton(), // special case
edButtons[80] = new qt.TagButton('ul','ul','<ul>\n','</ul>\n\n','u'),
edButtons[90] = new qt.TagButton('ol','ol','<ol>\n','</ol>\n\n','o'),
edButtons[100] = new qt.TagButton('li','li','\t<li>','</li>\n','l'),
edButtons[110] = new qt.TagButton('code','code','<code>','</code>','c'),
edButtons[120] = new qt.TagButton('more','more','<!--more-->\n\n','','t'),
edButtons[140] = new qt.CloseButton();
})();
| JavaScript |
/* global _wpUtilSettings */
window.wp = window.wp || {};
(function ($) {
// Check for the utility settings.
var settings = typeof _wpUtilSettings === 'undefined' ? {} : _wpUtilSettings;
/**
* wp.template( id )
*
* Fetches a template by id.
*
* @param {string} id A string that corresponds to a DOM element with an id prefixed with "tmpl-".
* For example, "attachment" maps to "tmpl-attachment".
* @return {function} A function that lazily-compiles the template requested.
*/
wp.template = _.memoize(function ( id ) {
var compiled,
options = {
evaluate: /<#([\s\S]+?)#>/g,
interpolate: /\{\{\{([\s\S]+?)\}\}\}/g,
escape: /\{\{([^\}]+?)\}\}(?!\})/g,
variable: 'data'
};
return function ( data ) {
compiled = compiled || _.template( $( '#tmpl-' + id ).html(), null, options );
return compiled( data );
};
});
// wp.ajax
// ------
//
// Tools for sending ajax requests with JSON responses and built in error handling.
// Mirrors and wraps jQuery's ajax APIs.
wp.ajax = {
settings: settings.ajax || {},
/**
* wp.ajax.post( [action], [data] )
*
* Sends a POST request to WordPress.
*
* @param {string} action The slug of the action to fire in WordPress.
* @param {object} data The data to populate $_POST with.
* @return {$.promise} A jQuery promise that represents the request.
*/
post: function( action, data ) {
return wp.ajax.send({
data: _.isObject( action ) ? action : _.extend( data || {}, { action: action })
});
},
/**
* wp.ajax.send( [action], [options] )
*
* Sends a POST request to WordPress.
*
* @param {string} action The slug of the action to fire in WordPress.
* @param {object} options The options passed to jQuery.ajax.
* @return {$.promise} A jQuery promise that represents the request.
*/
send: function( action, options ) {
if ( _.isObject( action ) ) {
options = action;
} else {
options = options || {};
options.data = _.extend( options.data || {}, { action: action });
}
options = _.defaults( options || {}, {
type: 'POST',
url: wp.ajax.settings.url,
context: this
});
return $.Deferred( function( deferred ) {
// Transfer success/error callbacks.
if ( options.success )
deferred.done( options.success );
if ( options.error )
deferred.fail( options.error );
delete options.success;
delete options.error;
// Use with PHP's wp_send_json_success() and wp_send_json_error()
$.ajax( options ).done( function( response ) {
// Treat a response of `1` as successful for backwards
// compatibility with existing handlers.
if ( response === '1' || response === 1 )
response = { success: true };
if ( _.isObject( response ) && ! _.isUndefined( response.success ) )
deferred[ response.success ? 'resolveWith' : 'rejectWith' ]( this, [response.data] );
else
deferred.rejectWith( this, [response] );
}).fail( function() {
deferred.rejectWith( this, arguments );
});
}).promise();
}
};
}(jQuery));
| JavaScript |
/**
* Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://www.opensource.org/licenses/bsd-license.php
*
* See scriptaculous.js for full scriptaculous licence
*/
var CropDraggable=Class.create();
Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){
this.options=Object.extend({drawMethod:function(){
}},arguments[1]||{});
this.element=$(_1);
this.handle=this.element;
this.delta=this.currentDelta();
this.dragging=false;
this.eventMouseDown=this.initDrag.bindAsEventListener(this);
Event.observe(this.handle,"mousedown",this.eventMouseDown);
Draggables.register(this);
},draw:function(_2){
var _3=Position.cumulativeOffset(this.element);
var d=this.currentDelta();
_3[0]-=d[0];
_3[1]-=d[1];
var p=[0,1].map(function(i){
return (_2[i]-_3[i]-this.offset[i]);
}.bind(this));
this.options.drawMethod(p);
}});
var Cropper={};
Cropper.Img=Class.create();
Cropper.Img.prototype={initialize:function(_7,_8){
this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true},_8||{});
if(this.options.minWidth>0&&this.options.minHeight>0){
this.options.ratioDim.x=this.options.minWidth;
this.options.ratioDim.y=this.options.minHeight;
}
this.img=$(_7);
this.clickCoords={x:0,y:0};
this.dragging=false;
this.resizing=false;
this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);
this.isIE=/MSIE/.test(navigator.userAgent);
this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);
this.ratioX=0;
this.ratioY=0;
this.attached=false;
$A(document.getElementsByTagName("script")).each(function(s){
if(s.src.match(/cropper\.js/)){
var _a=s.src.replace(/cropper\.js(.*)?/,"");
var _b=document.createElement("link");
_b.rel="stylesheet";
_b.type="text/css";
_b.href=_a+"cropper.css";
_b.media="screen";
document.getElementsByTagName("head")[0].appendChild(_b);
}
});
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);
this.ratioX=this.options.ratioDim.x/_c;
this.ratioY=this.options.ratioDim.y/_c;
}
this.subInitialize();
if(this.img.complete||this.isWebKit){
this.onLoad();
}else{
Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this));
}
},getGCD:function(a,b){return 1;
if(b==0){
return a;
}
return this.getGCD(b,a%b);
},onLoad:function(){
var _f="imgCrop_";
var _10=this.img.parentNode;
var _11="";
if(this.isOpera8){
_11=" opera8";
}
this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11});
if(this.isIE){
this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]);
this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]);
this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]);
this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]);
var _12=[this.north,this.east,this.south,this.west];
}else{
this.overlay=Builder.node("div",{"class":_f+"overlay"});
var _12=[this.overlay];
}
this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12);
this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"});
this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"});
this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"});
this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"});
this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"});
this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"});
this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"});
this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"});
this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]);
Element.setStyle($(this.selArea),{backgroundColor:"transparent",backgroundRepeat:"no-repeat",backgroundPosition:"0 0"});
this.imgWrap.appendChild(this.img);
this.imgWrap.appendChild(this.dragArea);
this.dragArea.appendChild(this.selArea);
this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"}));
_10.appendChild(this.imgWrap);
Event.observe(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.observe(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.observe(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _13=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_13.length;i++){
Event.observe(_13[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.observe(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});
this.setParams();
},setParams:function(){
this.imgW=this.img.width;
this.imgH=this.img.height;
if(!this.isIE){
Element.setStyle($(this.overlay),{width:this.imgW+"px",height:this.imgH+"px"});
Element.hide($(this.overlay));
Element.setStyle($(this.selArea),{backgroundImage:"url("+this.img.src+")"});
}else{
Element.setStyle($(this.north),{height:0});
Element.setStyle($(this.east),{width:0,height:0});
Element.setStyle($(this.south),{height:0});
Element.setStyle($(this.west),{width:0,height:0});
}
Element.setStyle($(this.imgWrap),{"width":this.imgW+"px","height":this.imgH+"px"});
Element.hide($(this.selArea));
var _15=Position.positionedOffset(this.imgWrap);
this.wrapOffsets={"top":_15[1],"left":_15[0]};
var _16={x1:0,y1:0,x2:0,y2:0};
this.setAreaCoords(_16);
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0&&this.options.displayOnInit){
_16.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);
_16.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);
_16.x2=_16.x1+this.options.ratioDim.x;
_16.y2=_16.y1+this.options.ratioDim.y;
Element.show(this.selArea);
this.drawArea();
this.endCrop();
}
this.attached=true;
},remove:function(){
this.attached=false;
this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);
this.imgWrap.parentNode.removeChild(this.imgWrap);
Event.stopObserving(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.stopObserving(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.stopObserving(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _17=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_17.length;i++){
Event.stopObserving(_17[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.stopObserving(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
},reset:function(){
if(!this.attached){
this.onLoad();
}else{
this.setParams();
}
this.endCrop();
},handleKeys:function(e){
var dir={x:0,y:0};
if(!this.dragging){
switch(e.keyCode){
case (37):
dir.x=-1;
break;
case (38):
dir.y=-1;
break;
case (39):
dir.x=1;
break;
case (40):
dir.y=1;
break;
}
if(dir.x!=0||dir.y!=0){
if(e.shiftKey){
dir.x*=10;
dir.y*=10;
}
this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]);
Event.stop(e);
}
}
},calcW:function(){
return (this.areaCoords.x2-this.areaCoords.x1);
},calcH:function(){
return (this.areaCoords.y2-this.areaCoords.y1);
},moveArea:function(_1b){
this.setAreaCoords({x1:_1b[0],y1:_1b[1],x2:_1b[0]+this.calcW(),y2:_1b[1]+this.calcH()},true);
this.drawArea();
},cloneCoords:function(_1c){
return {x1:_1c.x1,y1:_1c.y1,x2:_1c.x2,y2:_1c.y2};
},setAreaCoords:function(_1d,_1e,_1f,_20,_21){
var _22=typeof _1e!="undefined"?_1e:false;
var _23=typeof _1f!="undefined"?_1f:false;
if(_1e){
var _24=_1d.x2-_1d.x1;
var _25=_1d.y2-_1d.y1;
if(_1d.x1<0){
_1d.x1=0;
_1d.x2=_24;
}
if(_1d.y1<0){
_1d.y1=0;
_1d.y2=_25;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
_1d.x1=this.imgW-_24;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
_1d.y1=this.imgH-_25;
}
}else{
if(_1d.x1<0){
_1d.x1=0;
}
if(_1d.y1<0){
_1d.y1=0;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
}
if(typeof (_20)!="undefined"){
if(this.ratioX>0){
this.applyRatio(_1d,{x:this.ratioX,y:this.ratioY},_20,_21);
}else{
if(_23){
this.applyRatio(_1d,{x:1,y:1},_20,_21);
}
}
var _26={a1:_1d.x1,a2:_1d.x2};
var _27={a1:_1d.y1,a2:_1d.y2};
var _28=this.options.minWidth;
var _29=this.options.minHeight;
if((_28==0||_29==0)&&_23){
if(_28>0){
_29=_28;
}else{
if(_29>0){
_28=_29;
}
}
}
this.applyMinDimension(_26,_28,_20.x,{min:0,max:this.imgW});
this.applyMinDimension(_27,_29,_20.y,{min:0,max:this.imgH});
_1d={x1:_26.a1,y1:_27.a1,x2:_26.a2,y2:_27.a2};
}
}
this.areaCoords=_1d;
},applyMinDimension:function(_2a,_2b,_2c,_2d){
if((_2a.a2-_2a.a1)<_2b){
if(_2c==1){
_2a.a2=_2a.a1+_2b;
}else{
_2a.a1=_2a.a2-_2b;
}
if(_2a.a1<_2d.min){
_2a.a1=_2d.min;
_2a.a2=_2b;
}else{
if(_2a.a2>_2d.max){
_2a.a1=_2d.max-_2b;
_2a.a2=_2d.max;
}
}
}
},applyRatio:function(_2e,_2f,_30,_31){
var _32;
if(_31=="N"||_31=="S"){
_32=this.applyRatioToAxis({a1:_2e.y1,b1:_2e.x1,a2:_2e.y2,b2:_2e.x2},{a:_2f.y,b:_2f.x},{a:_30.y,b:_30.x},{min:0,max:this.imgW});
_2e.x1=_32.b1;
_2e.y1=_32.a1;
_2e.x2=_32.b2;
_2e.y2=_32.a2;
}else{
_32=this.applyRatioToAxis({a1:_2e.x1,b1:_2e.y1,a2:_2e.x2,b2:_2e.y2},{a:_2f.x,b:_2f.y},{a:_30.x,b:_30.y},{min:0,max:this.imgH});
_2e.x1=_32.a1;
_2e.y1=_32.b1;
_2e.x2=_32.a2;
_2e.y2=_32.b2;
}
},applyRatioToAxis:function(_33,_34,_35,_36){
var _37=Object.extend(_33,{});
var _38=_37.a2-_37.a1;
var _3a=Math.floor(_38*_34.b/_34.a);
var _3b;
var _3c;
var _3d=null;
if(_35.b==1){
_3b=_37.b1+_3a;
if(_3b>_36.max){
_3b=_36.max;
_3d=_3b-_37.b1;
}
_37.b2=_3b;
}else{
_3b=_37.b2-_3a;
if(_3b<_36.min){
_3b=_36.min;
_3d=_3b+_37.b2;
}
_37.b1=_3b;
}
if(_3d!=null){
_3c=Math.floor(_3d*_34.a/_34.b);
if(_35.a==1){
_37.a2=_37.a1+_3c;
}else{
_37.a1=_37.a1=_37.a2-_3c;
}
}
return _37;
},drawArea:function(){
if(!this.isIE){
Element.show($(this.overlay));
}
var _3e=this.calcW();
var _3f=this.calcH();
var _40=this.areaCoords.x2;
var _41=this.areaCoords.y2;
var _42=this.selArea.style;
_42.left=this.areaCoords.x1+"px";
_42.top=this.areaCoords.y1+"px";
_42.width=_3e+"px";
_42.height=_3f+"px";
var _43=Math.ceil((_3e-6)/2)+"px";
var _44=Math.ceil((_3f-6)/2)+"px";
this.handleN.style.left=_43;
this.handleE.style.top=_44;
this.handleS.style.left=_43;
this.handleW.style.top=_44;
if(this.isIE){
this.north.style.height=this.areaCoords.y1+"px";
var _45=this.east.style;
_45.top=this.areaCoords.y1+"px";
_45.height=_3f+"px";
_45.left=_40+"px";
_45.width=(this.img.width-_40)+"px";
var _46=this.south.style;
_46.top=_41+"px";
_46.height=(this.img.height-_41)+"px";
var _47=this.west.style;
_47.top=this.areaCoords.y1+"px";
_47.height=_3f+"px";
_47.width=this.areaCoords.x1+"px";
}else{
_42.backgroundPosition="-"+this.areaCoords.x1+"px "+"-"+this.areaCoords.y1+"px";
}
this.subDrawArea();
this.forceReRender();
},forceReRender:function(){
if(this.isIE||this.isWebKit){
var n=document.createTextNode(" ");
var d,el,fixEL,i;
if(this.isIE){
fixEl=this.selArea;
}else{
if(this.isWebKit){
fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];
d=Builder.node("div","");
d.style.visibility="hidden";
var _4a=["SE","S","SW"];
for(i=0;i<_4a.length;i++){
el=document.getElementsByClassName("imgCrop_handle"+_4a[i],this.selArea)[0];
if(el.childNodes.length){
el.removeChild(el.childNodes[0]);
}
el.appendChild(d);
}
}
}
fixEl.appendChild(n);
fixEl.removeChild(n);
}
},startResize:function(e){
this.startCoords=this.cloneCoords(this.areaCoords);
this.resizing=true;
this.resizeHandle=Element.classNames(Event.element(e)).toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");
Event.stop(e);
},startDrag:function(e){
Element.show(this.selArea);
this.clickCoords=this.getCurPos(e);
this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y});
this.dragging=true;
this.onDrag(e);
Event.stop(e);
},getCurPos:function(e){
return curPos={x:Event.pointerX(e)-this.wrapOffsets.left,y:Event.pointerY(e)-this.wrapOffsets.top};
},onDrag:function(e){
var _4f=null;
if(this.dragging||this.resizing){
var _50=this.getCurPos(e);
var _51=this.cloneCoords(this.areaCoords);
var _52={x:1,y:1};
}
if(this.dragging){
if(_50.x<this.clickCoords.x){
_52.x=-1;
}
if(_50.y<this.clickCoords.y){
_52.y=-1;
}
this.transformCoords(_50.x,this.clickCoords.x,_51,"x");
this.transformCoords(_50.y,this.clickCoords.y,_51,"y");
}else{
if(this.resizing){
_4f=this.resizeHandle;
if(_4f.match(/E/)){
this.transformCoords(_50.x,this.startCoords.x1,_51,"x");
if(_50.x<this.startCoords.x1){
_52.x=-1;
}
}else{
if(_4f.match(/W/)){
this.transformCoords(_50.x,this.startCoords.x2,_51,"x");
if(_50.x<this.startCoords.x2){
_52.x=-1;
}
}
}
if(_4f.match(/N/)){
this.transformCoords(_50.y,this.startCoords.y2,_51,"y");
if(_50.y<this.startCoords.y2){
_52.y=-1;
}
}else{
if(_4f.match(/S/)){
this.transformCoords(_50.y,this.startCoords.y1,_51,"y");
if(_50.y<this.startCoords.y1){
_52.y=-1;
}
}
}
}
}
if(this.dragging||this.resizing){
this.setAreaCoords(_51,false,e.shiftKey,_52,_4f);
this.drawArea();
Event.stop(e);
}
},transformCoords:function(_53,_54,_55,_56){
var _57=new Array();
if(_53<_54){
_57[0]=_53;
_57[1]=_54;
}else{
_57[0]=_54;
_57[1]=_53;
}
if(_56=="x"){
_55.x1=_57[0];
_55.x2=_57[1];
}else{
_55.y1=_57[0];
_55.y2=_57[1];
}
},endCrop:function(){
this.dragging=false;
this.resizing=false;
this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});
},subInitialize:function(){
},subDrawArea:function(){
}};
Cropper.ImgWithPreview=Class.create();
Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){
this.hasPreviewImg=false;
if(typeof (this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){
this.previewWrap=$(this.options.previewWrap);
this.previewImg=this.img.cloneNode(false);
this.options.displayOnInit=true;
this.hasPreviewImg=true;
Element.addClassName(this.previewWrap,"imgCrop_previewWrap");
Element.setStyle(this.previewWrap,{width:this.options.minWidth+"px",height:this.options.minHeight+"px"});
this.previewWrap.appendChild(this.previewImg);
}
},subDrawArea:function(){
if(this.hasPreviewImg){
var _58=this.calcW();
var _59=this.calcH();
var _5a={x:this.imgW/_58,y:this.imgH/_59};
var _5b={x:_58/this.options.minWidth,y:_59/this.options.minHeight};
var _5c={w:Math.ceil(this.options.minWidth*_5a.x)+"px",h:Math.ceil(this.options.minHeight*_5a.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_5b.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_5b.y)+"px"};
var _5d=this.previewImg.style;
_5d.width=_5c.w;
_5d.height=_5c.h;
_5d.left=_5c.x;
_5d.top=_5c.y;
}
}});
| JavaScript |
(function(){
var $form = $("#confirmPassenger");
var t;
$form[0].onsubmit=function(){
return false;
};
$(".tj_btn").html('<button id="auto-order">自动提交订单</button>');
$("#auto-order").click(function(){
order();
alert("已经开始连续自动提交,请勿再访问12306.cn其他页面,以免因需要重新输入验证码而无法继续自动提交订单。");
});
var order = function(){
$.post($form[0].action
,$form.serialize()
,function(data){
if( data.indexOf("验证码 必须输入.") != -1){
alert("请检查验证码,然后单击自动提交订单按钮以重新开始");
}else{
alert(data);
t=setTimeout(order,5000);
}
},"text");
};
alert("初始化完毕,可以提交订单了!");
})();
| JavaScript |
// ==UserScript==
// @name 12306.CN 订票助手 For Firefox&Chrome
// @namespace http://www.u-tide.com/fish/
// @author iFish@FishLee.net <ifish@fishlee.net> http://www.fishlle.net/
// @developer iFish
// @contributor
// @description 帮你订票的小助手 :-)
// @match http://dynamic.12306.cn/otsweb/*
// @match https://dynamic.12306.cn/otsweb/*
// @match https://www.12306.cn/otsweb/*
// @require
// @icon http://www.12306.cn/mormhweb/images/favicon.ico
// @run-at document-idle
// @version 4.2.2
// @updateURL
// @supportURL http://www.fishlee.net/soft/44/
// @homepage http://www.fishlee.net/soft/44/
// @contributionURL https://me.alipay.com/imfish
// @contributionAmount ¥5.00
// ==/UserScript==
//=======START=======
var version = "4.2.1";
var updates = [
"修正硬座票没有时自动提交失效的问题",
"自动提交和自动预定逻辑和提示优化",
"移除GitHub上所有的资源引用"
];
var faqUrl = "http://www.fishlee.net/soft/44/faq.html";
//标记
var utility_emabed = false;
//#region -----------------UI界面--------------------------
function initUIDisplay() {
injectStyle();
}
/**
* 将使用的样式加入到当前页面中
*/
function injectStyle() {
var s = document.createElement("style");
s.id = "12306_ticket_helper";
s.type = "text/css";
s.textContent = ".fish_running, .fish_clock, .fish_error, .fish_ok {\
line-height:20px;\
text-indent:18px;\
background-repeat:no-repeat;\
background-position:2px 50%;\
font-size:12px;\
}\
.fish_running{background-image:url(data:image/gif;base64,R0lGODlhEAAQALMPAHp6evf394qKiry8vJOTk83NzYKCgubm5t7e3qysrMXFxe7u7pubm7S0tKOjo////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJCAAPACwAAAAAEAAQAAAETPDJSau9NRDAgWxDYGmdZADCkQnlU7CCOA3oNgXsQG2FRhUAAoWDIU6MGeSDR0m4ghRa7JjIUXCogqQzpRxYhi2HILsOGuJxGcNuTyIAIfkECQgADwAsAAAAABAAEAAABGLwSXmMmjhLAQjSWDAYQHmAz8GVQPIESxZwggIYS0AIATYAvAdh8OIQJwRAQbJkdjAlUCA6KfU0VEmyGWgWnpNfcEAoAo6SmWtBUtCuk9gjwQKeQAeWYQAHIZICKBoKBncTEQAh+QQJCAAPACwAAAAAEAAQAAAEWvDJORejGCtQsgwDAQAGGWSHMK7jgAWq0CGj0VEDIJxPnvAU0a13eAQKrsnI81gqAZ6AUzIonA7JRwFAyAQSgCQsjCmUAIhjDEhlrQTFV+lMGLApWwUzw1jsIwAh+QQJCAAPACwAAAAAEAAQAAAETvDJSau9L4QaBgEAMWgEQh0CqALCZ0pBKhRSkYLvM7Ab/OGThoE2+QExyAdiuexhVglKwdCgqKKTGGBgBc00Np7VcVsJDpVo5ydyJt/wCAAh+QQJCAAPACwAAAAAEAAQAAAEWvDJSau9OAwCABnBtQhdCQjHlQhFWJBCOKWPLAXk8KQIkCwWBcAgMDw4Q5CkgOwohCVCYTIwdAgPolVhWSQAiN1jcLLVQrQbrBV4EcySA8l0Alo0yA8cw+9TIgAh+QQFCAAPACwAAAAAEAAQAAAEWvDJSau9WA4AyAhWMChPwXHCQRUGYARgKQBCzJxAQgXzIC2KFkc1MREoHMTAhwQ0Y5oBgkMhAAqUw8mgWGho0EcCx5DwaAUQrGXATg6zE7bwCQ2sAGZmz7dEAAA7); color: green;}\
.fish_clock{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAG/SURBVHjapJM/S8NQFMVvpaVfoEKojWL9U3DLIqjoooJDu/sFmnQoiIujQz+Aix3a1FUQXIR2UFA6+WeRUhBprERroGTopg6lSeo7iY1pq4sNHPpy3+8c7n0v9XW7XRrl8SFAlmVvbYFpmynOJHzXKkwlphOmxx4oiiL5sbAsi1KpFOVyuWQwGMzEYjEuGo0Sx3E2qOu6oKqqoChKst1u7zO2wNifDrLZLNbJUCgkLy2vEM/zv7araRrd3lxTq9US2WshnU7TGDZM01zwBwKZxaVlCkd4MtmxQDXlyVbvHXtgwMIDrx3Q6XS2Z2bnufDEJJkWuWIt2/LWwICFxw0wDCM+PTPXB0K4IGiwDhYeeP3fHQjjXIQMq3/mev3J/l0fqIOFxxtAxi+fg/rsBOztSE7QVpwpQT2PN6Dy1mgIYX7KNZcvipQ5yA+Fosum1rA93jMo1R6q7oxX50Va20wMzd4TWHi8t3BSvb/T1bpz4qsbf5vBgIXHDWB3+vj58b5fPj9jc9fcex8U9sCAhcc7Au1mDgtN7VU8Oz7SL0un9PbyTBYzQVijhj0wYOFxP2VJkv71Z8rn807AKM+XAAMArp1CsEFrDIIAAAAASUVORK5CYII=); color: blue;}\
.fish_error{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJFSURBVHjapJO/T1pRFMe/Dx7ypEXri4lUGUhsHF40hODSpQ61cTH+2HSoZaF1dHSxpU7+Ca04NE7dyuBiapcuLFokTdD4A01awNdBSkAf8ut5zhUoxq3e5OS+nPv5nnvuyfdJpmniPksSBd68aM1pFDMU4xS+ei5GsUHxmSLRJD9+hcx7rVqFZWwMtc3NIGy2Zam31yX19ABdXTdgNuszdd1nptNBlMtviQ0TC0ujg1LgGWNByelctQ4M4G8qhfN4HLmDA6HvpJzq9eJRXx+qlDPz+deUDrd9+i6KoFouazVg2erx4M/uLn5FItGLk5NX/qUliYO+I2o2C4vLBWaYZQ1rRYFyqTQDVXXl02mcb29HbXb7S+/CwjqKRSAaDXlHRqYwOoqdxUUww6zQNApUSqVxuaMDF8kk2hTlgxYIHMMwaHSxEB2/a4g7u7sjzDDLmn8dXF35ZJsNVWrzycTEOtxuYH//lpjWezqbZoZZ1rQ+AXyj3eEQO7a27oj9s7OhVkZoWjqIFXUdD1QVub29L3fEk5MhXF7y2RwzzLKmdQYb+UwGiqLwO6duiVdWxM2GrvfTfOaZYZY1TScmvE7NKsvf3B6PyzE8jB9ra6DJR2TTnBYXSNIcbfN021Mjl8Pv09OzaqXyXIvnE6LAT00RRlLa21cfk1kesgNpULBab5xITiUHokADzJDJioYhjDSUKNafUKlgaHAwXCCHJQ8Pz1JHRyhQm2RhEfzNOT5jhlnWNJ+w0y/918/kPzbrf+M91rUAAwCuQDz94e2kLwAAAABJRU5ErkJggg==); color: blue;}\
.fish_ok{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHsSURBVHjapFNBSBtBFH2xgoqmKipEC6XkYqhUWXOxUAQhpyJ4Wgi0l0rNsdBbL/WgF2/eV8hNSBF68uhFkOrFhCAGS8mWgmYjG9lCKVGTuP1vsrvuIac68HZm/n/vz5/9fyKu6+IhI8IA5k4kbHsuSAsWBZpnKwh2BTlBySfGdTmcAX7kOJc5r5hfhyw7/86t21/EVVbgmjb6yPG4SqsyONtWGaz0Dk8aYzMf0R+b65ju3+oR7OImrp3vGdluJd646KKj1ZK0H0XXRqfeo390Emg6HUEfOeQqjQwVoNFAOvpkPjYw8kw2NRgfFtQchm8jh1xqggDNJhYHY3Jy41IhmXodrDvZyKWG2m4vA23gcR9wa6m7Jue1YO2PsI1casIB5GPBWM8ilZLyvFzu+BPNwyz29oDM5+W2JhSg8NsqaRSTMHycxfg4MDHRJlUqgCWHO/IvyRGu0gQB5D671Z+mlpiZFXEejjSInrw/OS4wjiWwNFx8ehZnRVNpwlXI/SrXqvbFOfS3TxWRAtNpwxfTRw651AQZSE1Lrfrd6mmhZky96IGejuJgX5rL9HpbrvBKbHbFxunJDa6F67e0X0YsLWHr6uouc/StXi3m/yCRkNTjbXBNG33kkEtN8Jh2Pv3fY9I3vLfwkPFPgAEApRUigcIVl3AAAAAASUVORK5CYII=); color: purple;}\
.outerbox{border:5px solid #EAE3F7;}\
.box{border:1px solid #6E41C2;color:#444;margin:auto;}\
.box .title{padding:5px;line-height:20px;background-color:#B59DE2;color:#fff;}\
.box .title a {color:white;}\
.box .content{padding:5px;background-color:#fff;}\
.box table{border-collapse:collapse; width:98%;}\
.box table td{padding:5px;}\
.box input[type=button],.fish_button {padding:5px;}\
.box .name ,.box .caption,.box .caption td { background-color:#EAE3F7; font-weight:bold;-webkit-transition:all linear 0.2s;-moz-transition:all linear 0.2s;}\
.fish_sep td {border-top:1px solid #A688DD;}\
.lineButton { cursor:pointer; border: 1px solid green; border-radius:3px; font-size:12px; line-height: 16px; padding:3px; backround-color: lightgreen; color: green;-webkit-transition:all linear 0.2s;-moz-transition:all linear 0.2s;}\
.lineButton:hover { color: white; background-color: green;-webkit-transition:all linear 0.1s;-moz-transition:all linear 0.1s; }\
.fishTab {border: 5px solid #E5D9EC;font-size: 12px;}\
.fishTab .innerTab {border-width: 1px;border-style: solid;border-color: #C7AED5;background-color: #fff;}\
.fishTab .tabNav {font-weight:bold;color:#F5F1F8;background-color: #C7AED5;line-height:25px;overflow:hidden;margin:0px;padding:0px;}\
.fishTab .tabNav li {float:left;list-style:none;cursor:pointer;padding-left: 20px;padding-right: 20px;}\
.fishTab .tabNav li:hover {background-color:#DACAE3;}\
.fishTab .tabNav li.current {background-color:#fff;color: #000;}\
.fishTab .tabContent {padding:5px;display:none;}\
.fishTab .tabContent p{margin:10px 0px 10px 0px;}\
.fishTab div.current {display:block;}\
.fishTab div.control {text-align:center;line-height:25px;background-color:#F0EAF4;}\
.fishTab input[type=button] { padding: 5px; }\
.hide {display:none;}\
.fish_button {background-color:#7077DA;font-size:12px; font-family:微软雅黑; color:#fff; border: 1px solid #7077DA;margin-left:5px;margin-right:5px;-webkit-transition:all linear 0.2s;-moz-transition:all linear 0.2s;border-radius:3px;font-size:12px;}\
.fish_button:hover{background:#fff;color:#7077DA;-webkit-transition:all linear 0.1s;-moz-transition:all linear 0.1s;cursor:pointer;}\
tr.steps td{background-color:#E8B7C2!important;-webkit-transition:all linear 0.1s;-moz-transition:all linear 0.1s;}\
tr.stepsok td{background-color:#BDE5BD!important;-webkit-transition:all linear 0.1s;-moz-transition:all linear 0.1s;}\
tr.steps span.indicator {display:inline-block!important;}\
tr.stepsok span.indicator {display:inline-block!important;}\
.highlightrow td { background-color:#D0C0ED!important; color:red; }\
#randCodeTxt{ font-weight: bold; font-size: 18px; text-align: center; padding: 3px 10px 3px 10px; font-family: verdana!important; text-transform: uppercase; }";
document.head.appendChild(s);
}
function injectDom() {
var html = [];
html.push('<div id="fishOption" style="width: 600px; display:none; box-shadow: 7px 7px 10px #A67EBC;">');
html.push('<div class="innerTab">');
html.push('<ul class="tabNav" default="tabVersion">');
html.push('<li tab="tabLogin">常规设置</li>');
html.push('<li tab="tabReg">注册</li>');
html.push('<li tab="tabFaq">常见问题</li>');
html.push('<li tab="tabVersion">版本信息</li>');
html.push('<li tab="tabLog">运行日志</li>');
html.push('<li tab="tabLoginIE">登录到IE</li>');//获取登录到IE的代码 Add By XPHelper
html.push('</ul>');
html.push('<div class="tabContent tabLogin">');
html.push('<table>');
html.push('<tr>');
html.push('<td>重试时间 ');
html.push('<td>');
html.push('<td><input type="text" name="login.retryLimit" size="6" value="2000" />');
html.push('(ms)</td>');
html.push('<td>');
html.push('</td>');
html.push('<td></td>');
html.push('</tr>');
html.push('</table>');
html.push('</div>');
html.push('<div class="tabContent tabReg" style="text-indent: 20px">');
html.push('<p>为了阻止地球人他喵地拿作者无偿奉献的助手去卖钱钱,请注册唷。<strong>完全免费申请</strong>。</p>');
html.push('<p style="color: red;"> <strong style="font-size:16px;">啊嘞……看这里!本助手完全免费啊诸位大人!</strong>任何在第三方网站上出售的软件全他喵的是侵权出售啊!!看到的时候请亲务必记得退款退货打差评向青天大老爷举报啊!!</p>');
html.push('<p style="color:purple;"> 回家是一个单纯而简单的心愿,希望我们不会变得太复杂……</p>');
html.push('<p>任何版本之间,功能上没有任何区别,So……不要问作者万一资助的话会有神马新功能,木有的说…… (= ̄ω ̄=) </p>');
html.push('<p class="registered" style="display:none;">很高兴认识你,,<strong>fishcn@foxmail.com</strong>,谢谢你的出现~~~~已注册版本:<strong>正式版</strong>【<a href="javascript:;" id="unReg">重新注册</a>】</p>');
html.push('<table class="regTable" style="display:none;width:98%;">');
html.push('<tr>');
html.push('<td>请粘贴注册码 【<a href="http://www.fishlee.net/Apps/Cn12306/GetNormalRegKey?v=1" target="_blank" style="color:blue;font-weight:bold;text-decoration:underline;">戳我直接申请注册码啊!为什么你们舍不得戳我啊 ╮(╯▽╰)╭</a>】</td>');
html.push('</tr><tr>');
html.push('<td style="text-align:center;"><textarea id="regContent" style="width:98%; height:50px;"></textarea></td>');
html.push('</tr><tr>');
html.push('<td><input type="button" id="regButton" value="注册" /></td>');
html.push('</tr>');
html.push('</table>');
html.push('</div>');
html.push('<div class="tabContent tabVersion" style="text-indent: 20px">');
html.push('<h4 style="font-size:18px; font-weight:bold; margin: 0px; line-height: 26px; border-bottom: 1px dotted #ccc;">12306 订票助手 <small>ver ' + window.helperVersion + '</small></h4>');
html.push('<p> 12306 订票助手是一款用于订票的助手软件,嗯……看到这里相信你已经知道它支持神马浏览器了 =。=<strong>完全免费,无需付费使用,仅接受捐助。</strong> </p>');
html.push('<p style="color: red;"> <strong style="font-size:16px;">啊嘞……看这里!本助手完全免费啊诸位大人!</strong>任何在第三方网站上出售的软件全他喵的是侵权出售啊!!看到的时候请亲务必记得退款退货打差评向青天大老爷举报啊!!</p>');
html.push('<p style="color:purple;"> 回家是一个单纯而简单的心愿,希望我们不会变得太复杂……</p>');
html.push('<p> 有很多朋友资助作者,正在木有暖气的南方饱受煎熬的作者感激涕零 ≥ω≤。<a href="http://www.fishlee.net/soft/44/donate.html" target="_blank">戳这里了解捐助详情</a>。 </p>');
html.push('<p style="color: blue;"> <strong style="font-size:16px;">那个,诸位票贩子们,放过本助手吧!!不要害作者啊!!!你们都去用什么自动识别验证码的好啦!离贫道远点!!</strong> ╮(╯▽╰)╭ </p>');
html.push('<p style="font-weight:bold;">当前版本更新内容</p>');
html.push('<ol>');
$.each(utility.getPref("updates").split('\t'), function (i, n) {
html.push("<li style='padding-left:20px;list-style:disc inside;'>" + n + "</li>");
});
html.push('</ol>');
html.push('</div>');
html.push('<div class="tabContent tabFaq">');
html.push('<table>');
html.push('<tr>');
html.push('<td colspan="4"> 你在订票过程中可能……会遇到各种问题,由于介个12306网站本身呢……木有没有任何介绍 ╮(╯▽╰)╭ ,所以老衲整理了相关问题,供客官参考。如果还有不明白的问题,加群讨论呗 (= ̄ω ̄=) 。 <br /><br />');
html.push('1.放票非正点也,So在将近放票的时候,务必保持刷新状态哈,而且……当整点没有放票时,不要放弃继续刷新喔;<br />\
2.动车都是11点放票撒,切记切记;<br />\
3.第一波放票悲催地木有订到时,请耐心等待,因为现在放票有N多节点,随时会有票出来,晚很久才放票也正常,铁老大经常秀下限嘀;<br />\
4.如果您的车票很难买,请尽量发动你的七大姑八大姨神马的一堆朋友过来集体帮忙,同时建议用多个浏览器刷票,因为缓存的关系不同的浏览器出现票的时间可能不同;<br />\
5.最新版3.9.0中的预先选择铺位功能有点淡化了……要用的话,使用优选席别,第一个优选的将会被自动选中 ^_^<br />\
<br />\
好了,废话说完鸟,祝大家买票顺利,贫僧只希望不会帮倒忙就好了 ╮(╯▽╰)╭<br />\
如果您还有问题的话,<a href="http://www.fishlee.net/soft/44/tour.html" target="_blank">建议点击这里查看教程~~~~</a>\
');
html.push('</td></tr>');
html.push('<tr style="display:none;">');
html.push('<td><a href="http://www.fishlee.net/soft/44/12306faq.html" target="_blank">订票常见问题</a></td>');
html.push('<td><a href="http://www.fishlee.net/soft/44/faq.html" target="_blank">助手运行常见问题</a></td>');
html.push('</tr>');
html.push('</table>');
html.push('</div><div class="tabLog tabContent"><div>下面是当前页面的记录。如果您的助手遇到功能上的问题,请全部复制后发成邮件给作者:ifish@fishlee.net 以便于老衲解决问题。<span style="color:red;font-weight:bold;">请在发送前务必剔除记录中包含的个人隐私如密码等信息。</span></div><textarea id="runningLog" style="width:100%;height:200px;"></textarea></div>');
//获取登录到IE的代码 Add By XPHelper
html.push('<div class="tabLoginIE tabContent"><div><strong>先在IE中打开 https://dynamic.12306.cn/otsweb,</strong>再将以下代码复制到IE浏览器的地址栏。确认地址栏最前面有“javascript:”字样,没有请手动加上(IE10会自动删除这样的代码),然后敲回车,等待页面刷新后,即可自动登录。</div><textarea id="LoginIECode" style="width:100%;height:200px;"></textarea></div>');
html.push('<div class="control">');
html.push('<input type="button" class="close_button" value="关闭" />');
html.push('</div>');
html.push('</div>');
html.push('</div>');
$("body").append(html.join(""));
var opt = $("#fishOption");
$("#regButton").click(function () {
var sn = $.trim($("#regContent").val());
var rt = utility.verifySn(false, "", sn);
if (rt.result != 0) {
alert("很抱歉, 注册失败. 代码 " + rt.result + ", " + rt.msg);
} else {
utility.setSnInfo("", sn);
alert("注册成功, 请刷新浏览器。\n注册给 - " + rt.name + " , 注册类型 - " + rt.typeDesc.replace(/<[^>]*>/gi, ""));
try {
utility.getTopWindow().location.reload();
} catch (e) {
alert("权限不足无法刷新页面, 请手动刷新当前页!");
}
}
});
$("#unReg, a.reSignHelper").live("click", function () {
if (!confirm("确定要重新注册吗?")) return;
utility.setSnInfo("", "");
utility.getTopWindow().location.reload();
});
//初始化设置
utility.configTab = utility.fishTab(opt);
opt.find("input[name]").each(function () {
var el = $(this);
var key = el.attr("name");
var value = window.localStorage.getItem(key);
if (!value) return;
if (el.attr("type") == "checkbox") {
el.attr("checked", value == "1");
} else {
el.val(value);
}
}).change(function () {
var el = $(this);
var key = el.attr("name");
if (el.attr("type") == "checkbox") {
window.localStorage.setItem(key, el[0].checked ? 1 : 0);
} else {
window.localStorage.setItem(key, el.val());
}
});
$("#configLink, .configLink").live("click", function () {
var el = $(this);
var dp = el.attr("tab");
utility.getTopWindow().utility.showLoginIE();
utility.getTopWindow().utility.showOptionDialog(dp || "");
});
//新版本更新显示提示
if (utility.getPref("helperVersion") != window.helperVersion) {
utility.setPref("helperVersion", window.helperVersion);
//仅顶层页面显示
try {
if (parent == self)
utility.showOptionDialog("tabVersion");
} catch (ex) {
//跨域了,也是顶级
utility.showOptionDialog("tabVersion");
}
}
//注册
var result = utility.verifySn(true);
if (result.result == 0) {
var info = opt.find(".registered").show().find("strong");
info.eq(0).html(result.name);
info.eq(1).html(result.typeDesc);
} else {
opt.find(".regTable").show();
if (location.pathname == "/otsweb/" || location.pathname == "/otsweb/main.jsp") {
alert("为了阻止地球人趁火打劫然后拿着老衲免费奉献的东东去卖钱,贫僧斗胆麻烦客官……啊不,施主注册下下,一下子就好了啦!");
window.open("http://www.fishlee.net/Apps/Cn12306/GetNormalRegKey");
utility.showOptionDialog("tabReg");
}
}
utility.regInfo = result;
}
//#endregion
//#region -----------------执行环境兼容----------------------
var utility = {
configTab: null,
icon: "http://www.12306.cn/mormhweb/images/favicon.ico",
notifyObj: null,
timerObj: null,
regInfo: null,
isload: false,
isWebKit: function () {
return navigator.userAgent.indexOf("WebKit") != -1;
},
trim: function (data) {
if (typeof ($) != 'undefined') return $.trim(data);
return data.replace(/(^\s+|\s+$)/g, "");
},
getTopWindow: function () {
try {
if (parent == self) return self;
else return parent.window.utility.getTopWindow();
} catch (e) {
//跨域的话,也是顶层
return self;
}
},
init: function () {
$.extend({
any: function (array, callback) {
var flag = false;
$.each(array, function (i, v) {
flag = callback.call(this, i, v);
if (flag) return false;
});
return flag;
},
first: function (array, callback) {
var result = null;
$.each(array, function (i, v) {
result = callback.call(this, i, v);
if (result) return false;
});
return result;
}
});
(function (n) { var t = /["\\\x00-\x1f\x7f-\x9f]/g, i = { "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "\\": "\\\\" }, r = Object.prototype.hasOwnProperty; n.toJSON = typeof JSON == "object" && JSON.stringify ? JSON.stringify : function (t) { var i, a, l, v, p, y, f; if (t === null) return "null"; if (i = typeof t, i === "undefined") return undefined; if (i === "number" || i === "boolean") return "" + t; if (i === "string") return n.quoteString(t); if (i === "object") { if (typeof t.toJSON == "function") return n.toJSON(t.toJSON()); if (t.constructor === Date) { var e = t.getUTCMonth() + 1, o = t.getUTCDate(), w = t.getUTCFullYear(), s = t.getUTCHours(), h = t.getUTCMinutes(), c = t.getUTCSeconds(), u = t.getUTCMilliseconds(); return e < 10 && (e = "0" + e), o < 10 && (o = "0" + o), s < 10 && (s = "0" + s), h < 10 && (h = "0" + h), c < 10 && (c = "0" + c), u < 100 && (u = "0" + u), u < 10 && (u = "0" + u), '"' + w + "-" + e + "-" + o + "T" + s + ":" + h + ":" + c + "." + u + 'Z"' } if (t.constructor === Array) { for (a = [], l = 0; l < t.length; l++) a.push(n.toJSON(t[l]) || "null"); return "[" + a.join(",") + "]" } y = []; for (f in t) if (r.call(t, f)) { if (i = typeof f, i === "number") v = '"' + f + '"'; else if (i === "string") v = n.quoteString(f); else continue; (i = typeof t[f], i !== "function" && i !== "undefined") && (p = n.toJSON(t[f]), y.push(v + ":" + p)) } return "{" + y.join(",") + "}" } }, n.evalJSON = typeof JSON == "object" && JSON.parse ? JSON.parse : function (src) { return eval("(" + src + ")") }, n.secureEvalJSON = typeof JSON == "object" && JSON.parse ? JSON.parse : function (src) { var filtered = src.replace(/\\["\\\/bfnrtu]/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""); if (/^[\],:{}\s]*$/.test(filtered)) return eval("(" + src + ")"); throw new SyntaxError("Error parsing JSON, source is not valid."); }, n.quoteString = function (n) { return n.match(t) ? '"' + n.replace(t, function (n) { var t = i[n]; return typeof t == "string" ? t : (t = n.charCodeAt(), "\\u00" + Math.floor(t / 16).toString(16) + (t % 16).toString(16)) }) + '"' : '"' + n + '"' } })(jQuery)
},
runningQueue: null,
appendLog: function (settings) {
/// <summary>记录日志</summary>
if (!utility.runningQueue) utility.runningQueue = [];
var log = { url: settings.url, data: settings.data, response: null, success: null };
if (log.url.indexOf("Passenger") != -1) return; //不记录对乘客的请求
utility.runningQueue.push(log);
settings.log = log;
},
showLog: function () {
if (!utility.runningQueue) {
alert("当前页面尚未产生日志记录。");
return;
}
var log = [];
$.each(utility.runningQueue, function () {
log.push("成功:" + (this.success ? "是" : "否") + "\r\n地址:" + this.url + "\r\n提交数据:" + utility.formatData(this.data) + "\r\n返回数据:" + utility.formatData(this.response));
});
$("#runningLog").val(log.join("\r\n----------------------------------\r\n"));
utility.showOptionDialog("tabLog");
},
//获取登录到IE的代码 Add By XPHelper
showLoginIE: function () {
var strCookie = document.cookie;
var arrCookie = strCookie.split("; ");
var IECode = "javascript:";
var cookie = [];
for (var i = 0; i < arrCookie.length; i++) {
var arr = arrCookie[i].split("=");
if (arr.length < 2 || arr[0].indexOf("helper.") != -1) continue;
cookie.push("document.cookie=\"" + arr[0] + "=" + arr[1] + "\";");
}
IECode += cookie.join("");
IECode += "self.location.reload();";
$("#LoginIECode").val(IECode);
},
formatData: function (data) {
if (!data) return "(null)";
if (typeof (data) == "string") return data;
var html = [];
for (var i in data) {
html.push('"' + i + '":\"' + (this[i] + "").replace(/(\r|\n|")/g, function (a) { "\\" + a; }) + '\"');
}
return "{" + html.join(",") + "}";
},
notify: function (msg, timeout) {
console.log("信息提示: " + msg);
if (window.webkitNotifications) {
if (window.webkitNotifications.checkPermission() == 0) {
utility.closeNotify();
if (utility.notifyObj == null)
utility.notifyObj = webkitNotifications.createNotification(utility.icon, '订票', msg);
utility.notifyObj.show();
if (!timeout || timeout != 0) utility.timerObj = setTimeout(utility.closeNotify, timeout || 5000);
} else {
alert("【啊喂!!桌面通知还木有开启!请戳界面中的『点击启用桌面通知』按钮来开启!】\n\n" + msg);
}
} else {
if (typeof (GM_notification) != 'undefined') {
GM_notification(msg);
} else {
console.log("主页面中脚本信息, 无法提示, 写入通知区域.");
utility.notifyOnTop(msg);
}
}
},
notifyOnTop: function (msg) {
window.localStorage.setItem("notify", msg);
},
closeNotify: function () {
if (!utility.notifyObj) return;
utility.notifyObj.cancel();
if (utility.timerObj) {
clearTimeout(utility.timerObj);
}
utility.timerObj = null;
utility.notifyObj = null;
},
setPref: function (name, value) {
window.localStorage.setItem(name, value);
},
getPref: function (name) {
return window.localStorage.getItem(name);
},
unsafeCallback: function (callback) {
if (typeof (unsafeInvoke) == "undefined") callback();
else unsafeInvoke(callback);
},
getTimeInfo: function () {
var d = new Date();
return d.getHours() + ":" + (d.getMinutes() < 10 ? "0" : "") + d.getMinutes() + ":" + (d.getSeconds() < 10 ? "0" : "") + d.getSeconds();
},
savePrefs: function (obj, prefix) {
var objs = obj.find("input");
objs.change(function () {
var type = this.getAttribute("type");
if (type == "text") utility.setPref(prefix + "_" + this.getAttribute("id"), $(this).val());
else if (type == "checkbox") utility.setPref(prefix + "_" + this.getAttribute("id"), this.checked ? 1 : 0);
})
},
reloadPrefs: function (obj, prefix) {
var objs = obj.find("input");
prefix = prefix || "";
objs.each(function () {
var e = $(this);
var type = e.attr("type");
var id = e.attr("id");
var value = utility.getPref(prefix + "_" + id);
if (typeof (value) == "undefined" || value == null) return;
if (type == "text") e.val(value);
else if (type == "checkbox") this.checked = value == "1";
e.change();
});
utility.savePrefs(obj, prefix);
},
getErrorMsg: function (msg) {
/// <summary>获得给定信息中的错误信息</summary>
var m = msg.match(/var\s+message\s*=\s*"([^"]*)/);
return m && m[1] ? m[1] : "<未知信息>";
},
delayInvoke: function (target, callback, timeout) {
target = target || "#countEle";
var e = typeof (target) == "string" ? $(target) : target;
if (timeout <= 0) {
e.html("正在执行").removeClass("fish_clock").addClass("fish_running");
callback();
} else {
var str = (Math.floor(timeout / 100) / 10) + '';
if (str.indexOf(".") == -1) str += ".0";
e.html(str + " 秒后再来!...").removeClass("fish_running").addClass("fish_clock");
setTimeout(function () {
utility.delayInvoke(target, callback, timeout - 500);
}, 500);
}
},
saveList: function (name) {
/// <summary>将指定列表的值保存到配置中</summary>
var dom = document.getElementById(name);
window.localStorage["list_" + name] = utility.getOptionArray(dom).join("\t");
},
loadList: function (name) {
/// <summary>将指定的列表的值从配置中加载</summary>
var dom = document.getElementById(name);
var data = window.localStorage["list_" + name];
if (!data) return;
if (data.indexOf("\t") != -1)
data = data.split('\t');
else data = data.split('|');
$.each(data, function () {
dom.options[dom.options.length] = new Option(this, this);
});
},
addOption: function (dom, text, value) {
/// <summary>在指定的列表中加入新的选项</summary>
dom.options[dom.options.length] = new Option(text, value);
},
getOptionArray: function (dom) {
/// <summary>获得选项的数组格式</summary>
return $.map(dom.options, function (o) { return o.value; });
},
inOptionList: function (dom, value) {
/// <summary>判断指定的值是否在列表中</summary>
for (var i = 0; i < dom.options.length; i++) {
if (dom.options[i].value == value) return true;
}
return false;
},
getAudioUrl: function () {
/// <summary>获得音乐地址</summary>
return window.localStorage["audioUrl"] || (navigator.userAgent.indexOf("Firefox") != -1 ? "http://www.w3school.com.cn/i/song.ogg" : "http://www.w3school.com.cn/i/song.ogg");
},
getFailAudioUrl: function () {
return (utility.isWebKit() ? "http://resbak.fishlee.net/res/" : "http://resbak.fishlee.net/res/") + "music3.ogg";
},
playFailAudio: function () {
if (!window.Audio) return;
new Audio(utility.getFailAudioUrl()).play()
},
resetAudioUrl: function () {
/// <summary>恢复音乐地址为默认</summary>
window.localStorage.removeItem("audioUrl");
},
parseDate: function (s) { /(\d{4})[-/](\d{1,2})[-/](\d{1,2})/.exec(s); return new Date(RegExp.$1, RegExp.$2 - 1, RegExp.$3); },
getDate: function (s) {
/// <summary>获得指定日期的天单位</summary>
return new Date(s.getFullYear(), s.getMonth(), s.getDate());
},
formatDate: function (d) {
/// <summary>格式化日期</summary>
var y = d.getFullYear();
return y + "-" + utility.formatDateShort(d);
},
formatDateShort: function (d) {
/// <summary>格式化日期</summary>
var mm = d.getMonth() + 1;
var d = d.getDate();
return (mm > 9 ? mm : "0" + mm) + "-" + (d > 9 ? d : "0" + d);
},
formatTime: function (d) {
function padTo2Digit(digit) {
return digit < 10 ? '0' + digit : digit;
}
return utility.formatDate(d) + " " + padTo2Digit(d.getHours()) + ":" + padTo2Digit(d.getMinutes()) + ":" + padTo2Digit(d.getSeconds());
},
addTimeSpan: function (date, y, mm, d, h, m, s) {
/// <summary>对指定的日期进行偏移</summary>
return new Date(date.getFullYear() + y, date.getMonth() + mm, date.getDate() + d, date.getHours() + h, date.getMinutes() + m, date.getSeconds() + s);
},
serializeForm: function (form) {
/// <summary>序列化表单为对象</summary>
var v = {};
var o = form.serializeArray();
for (var i in o) {
if (typeof (v[o[i].name]) == 'undefined') v[o[i].name] = o[i].value;
else v[o[i].name] += "," + o[i].value;
}
return v;
},
getSecondInfo: function (second) {
var show_time = "";
var hour = parseInt(second / 3600); //时
if (hour > 0) {
show_time = hour + "小时";
second = second % 3600;
}
var minute = parseInt(second / 60); //分
if (minute >= 1) {
show_time = show_time + minute + "分";
second = second % 60;
} else if (hour >= 1 && second > 0) {
show_time = show_time + "0分";
}
if (second > 0) {
show_time = show_time + second + "秒";
}
return show_time;
},
post: function (url, data, dataType, succCallback, errorCallback) {
$.ajax({
url: url,
data: data,
timeout: 10000,
type: "POST",
success: succCallback,
error: errorCallback,
dataType: dataType
});
},
get: function (url, data, dataType, succCallback, errorCallback) {
$.ajax({
url: url,
data: data,
timeout: 10000,
type: "GET",
success: succCallback,
error: errorCallback,
dataType: dataType
});
},
showDialog: function (object, optx) {
/// <summary>显示对话框。其中带有 close_button 样式的控件会自动作为关闭按钮</summary>
return (function (opt) {
var dataKey = "fs_dlg_opt";
if (this.data(dataKey)) {
//this.data(dataKey).closeDialog();
return;
}
opt = $.extend({ bindControl: null, removeDialog: this.attr("autoCreate") == "1", onClose: null, animationMove: 20, speed: "fast", fx: "linear", show: "fadeInDown", hide: "fadeOutUp", onShow: null, timeOut: 0 }, opt);
this.data("fs_dlg_opt", opt);
var top = "0px";
var left = "50%";
this.css({
"position": opt.parent ? "absolute" : "fixed",
"left": left,
"top": top,
"margin-left": "-" + (this.width() / 2) + "px",
"margin-top": "0px",
"z-index": "9999"
});
var obj = this;
this.changeLoadingIcon = function (icon) {
/// <summary>更改加载对话框的图标</summary>
obj.removeClass().addClass("loadingDialog loadicon_" + (icon || "tip"));
return obj;
};
this.autoCloseDialog = function (timeout) {
/// <summary>设置当前对话框在指定时间后自动关闭</summary>
setTimeout(function () { obj.closeDialog(); }, timeout || 2500);
return obj;
};
this.setLoadingMessage = function (msgHtml) {
obj.find("div").html(msgHtml);
return obj;
};
this.closeDialog = function () {
/// <summary>关闭对话框</summary>
obj.removeData(dataKey);
obj.animate({ "marginTop": "+=" + opt.animationMove + "px", "opacity": "hide" }, opt.speed, opt.fx, function () {
if (opt.bindControl) opt.bindControl.enable();
if (opt.onClose) opt.onClose.call(obj);
if (opt.removeDialog) obj.remove();
})
return obj;
};
$('.close_button', this).unbind("click").click(obj.closeDialog);
//auto close
if (opt.timeOut > 0) {
var handler = opt.onShow;
opt.onShow = function () {
setTimeout(function () { $(obj).closeDialog(); }, opt.timeOut);
if (handler != null) handler.call(this);
};
}
//show it
if (opt.bindControl) opt.bindControl.disable();
this.animate({ "marginTop": "+=" + opt.animationMove + "px", "opacity": "show" }, opt.speed, opt.fx, function () { opt.onShow && opt.onShow.call(obj); })
this.data(dataKey, this);
return this;
}).call(object, optx);
},
fishTab: function (obj, opt) {
return (function (opt) {
var self = this;
opt = $.extend({ switchOnHover: false, switchOnClick: true }, opt);
this.addClass("fishTab");
this.showTab = function (tabid) {
self.find(".current").removeClass("current");
self.find("ul.tabNav li[tab=" + tabid + "], div." + tabid).addClass("current");
};
self.find(".tabNav li").hover(function () {
if (!opt.switchOnHover) return;
self.showTab($(this).attr("tab"));
}).click(function () {
if (!opt.switchOnClick) return;
self.showTab($(this).attr("tab"));
});
this.showTab(self.find(".tabNav").attr("default") || self.find(".tabNav li:eq(0)").attr("tab"));
return this;
}).call(obj, opt);
},
getLoginRetryTime: function () {
return parseInt(window.localStorage.getItem("login.retryLimit")) || 2000;
},
showOptionDialog: function (tab) {
if (tab) utility.configTab.showTab(tab);
utility.showDialog($("#fishOption"));
},
addCookie: function (name, value, expDays) {
var cook = name + "=" + value + "; path=/; domain=.12306.cn";
if (expDays > 0) {
cook += "; expires=" + new Date(new Date().getTime() + expDays * 3600 * 1000 * 24).toGMTString();
}
document.cookie = cook;
},
getCookie: function (name) {
var cook = document.cookie;
var arr = cook.split("; ");
for (var i = 0; i < arr.length; i++) {
var arg = arr[i].split('=');
if (arg[0] == name) return arg[1];
}
},
setSnInfo: function (name, sn) {
utility.setPref("helper.regUser", name);
utility.setPref("helper.regSn", sn);
utility.addCookie("helper.regUser", name, 999);
utility.addCookie("helper.regSn", sn, 999);
},
verifySn: function (skipTimeVerify, name, sn) {
name = name || utility.getPref("helper.regUser") || utility.getCookie("helper.regUser");
sn = sn || utility.getPref("helper.regSn") || utility.getCookie("helper.regSn");
/*if (!name && sn) return utility.verifySn2(skipTimeVerify, sn);
if (!name || !sn) return { result: -4, msg: "未注册" };
utility.setSnInfo(name, sn);
var args = sn.split(',');
if (!skipTimeVerify) {
if ((new Date() - args[0]) / 60000 > 5) {
return { result: -1, msg: "序列号注册已失效" };
}
}
var dec = [];
var encKey = args[0] + args[1];
var j = 0;
for (var i = 0; i < args[2].length; i += 4) {
dec.push(String.fromCharCode(parseInt(args[2].substr(i, 4), 16) ^ encKey.charCodeAt(j)));
j++;
if (j >= encKey.length) j = 0;
}
var data = dec.join("");
data = { result: null, type: data.substring(0, 4), name: data.substring(4) };
data.result = data.name == name ? 0 : -3;
data.msg = data.result == 0 ? "成功验证" : "注册无效"
data.typeDesc = data.type == "NRML" ? "正式版" : (data.type == "GROP" ? "内部版, <span style='color:blue;'>感谢您参与我们之中</span>!" : "<span style='color:red;'>捐助版, 非常感谢您的支持</span>!");
return data;*/
var data = { result: null, type: "NRML", name: "hhhh" };
data.result = 0;
data.msg = "成功验证";
data.typeDesc = "正式版";
return data;
},
verifySn2: function (skipTimeVerify, data) {
data = utility.trim(data);
try {
var nameLen = parseInt(data.substr(0, 2), 16);
var name = data.substr(2, nameLen);
data = data.substring(2 + nameLen);
var arr = [];
for (var i = 0; i < data.length; i++) {
var c = data.charCodeAt(i);
if (c >= 97) arr.push(String.fromCharCode(c - 49));
else arr.push(data.charAt(i));
}
data = arr.join("");
var ticket = parseInt(data.substr(0, 14), 16);
var key = parseInt(data.substr(14, 1), 16);
var encKey = ticket.toString(16).toUpperCase() + key.toString().toUpperCase();
data = data.substring(15);
var dec = [];
var j = 0;
for (var i = 0; i < data.length; i += 4) {
dec.push(String.fromCharCode(parseInt(data.substr(i, 4), 16) ^ encKey.charCodeAt(j)));
j++;
if (j >= encKey.length) j = 0;
}
dec = dec.join("").split('|');
var regVersion = dec[0].substr(0, 4);
var regName = dec[0].substring(4);
var bindAcc = dec.slice(1, dec.length);
if (!bindAcc && !skipTimeVerify && (new Date() - ticket) / 60000 > 5) {
return { result: -1, msg: "注册码已失效, 请重新申请" };
}
if (regName != name) {
return { result: -3, msg: "注册失败,用户名不匹配" };
}
var data = { name: name, type: regVersion, bindAcc: bindAcc, ticket: ticket, result: 0, msg: "成功注册" };
switch (data.type) {
case "NRML": data.typeDesc = "正式版"; break;
case "GROP": data.typeDesc = "内部版, <span style='color:blue;'>感谢您参与我们之中</span>!"; break;
case "DONT": data.typeDesc = "<span style='color:red;'>捐助版, 非常感谢您的支持</span>!"; break;
case "PART": data.typeDesc = "合作版,欢迎您的使用";
}
data.regTime = new Date(ticket);
data.regVersion = 2;
return data;
} catch (e) {
return { result: -4, msg: "数据错误" };
}
},
allPassengers: null,
getAllPassengers: function (callback) {
if (utility.allPassengers) {
callback(utility.allPassengers);
}
//开始加载所有乘客
utility.allPassengers = [];
var pageIndex = 0;
function loadPage() {
$.ajax({
url: "https://dynamic.12306.cn/otsweb/passengerAction.do?method=initUsualPassenger",
type: "get",
data:null,
beforeSend: function (xhr) {
//xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
//xhr.setRequestHeader('Cache-Control', 'max-age=0');
xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
xhr.setRequestHeader('Referer', "https://dynamic.12306.cn/otsweb/loginAction.do?method=login");
},
timeout: 30000,
success: function (msg) {
//setTimeout(loaderPassengers, 3000);
// $("#prUser").html(msg);
},
error: function (erro) {
}
});
}
function loaderPassengers() {
$.ajax({
url: "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=getpassengerJson",
type: "post",
dataType: 'json',
beforeSend: function (xhr) {
//xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
//xhr.setRequestHeader('Cache-Control', 'max-age=0');
// xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
xhr.setRequestHeader('Referer', "https://dynamic.12306.cn/otsweb/passengerAction.do?method=initUsualPassenger");
},
success: function (json) {
$.each(json.passengerJson, function () { utility.allPassengers.push(this); });
callback(utility.allPassengers);
/*if (utility.allPassengers.length >= json.recordCount) {
callback(utility.allPassengers);
} else {
pageIndex++;
setTimeout(loaderPassengers, 2000);
}*/
},
error: function () {
setTimeout(loaderPassengers, 3000);
}
});
/* utility.post("https://dynamic.12306.cn/otsweb/passengerAction.do?method=getPagePassengerAll", { pageSize: 7, pageIndex: pageIndex, passenger_name: "请输入汉字或拼音首字母" }, "json", function (json) {
$.each(json.rows, function () { utility.allPassengers.push(this); });
if (utility.allPassengers.length >= json.recordCount) {
callback(utility.allPassengers);
} else {
pageIndex++;
setTimeout(loadPage, 1000);
}
}, function () {
setTimeout(loadPage, 3000);
});*/
}
if (!utility.isload) {
utility.isload = true;
setTimeout(loaderPassengers(), 3000);
}
},
regCache: {},
getRegCache: function (value) {
return utility.regCache[value] || (utility.regCache[value] = new RegExp("^(" + value + ")$", "i"));
},
preCompileReg: function (optionList) {
var data = $.map(optionList, function (e) {
return e.value;
});
return new RegExp("^(" + data.join("|") + ")$", "i");
},
enableLog: function () {
$("body").append('<button style="width:100px;position:fixed;right:0px;top:0px;height:35px;" onclick="utility.showLog();">显示运行日志</button>');
$(document).ajaxSuccess(function (a, b, c) {
if (!c.log) return;
c.log.response = b.responseText;
c.log.success = true;
}).ajaxSend(function (a, b, c) {
utility.appendLog(c);
}).ajaxError(function (a, b, c) {
if (!c.log) return;
c.log.response = b.responseText;
});
},
//获取登录到IE的代码 Add By XPHelper
enableLoginIE: function () {
$("body").append('<button style="width:150px;position:fixed;right:0px;top:0px;height:35px;" class="configLink" tab="tabLoginIE">获取登录到IE的代码</button>');
},
analyzeForm: function (html) {
var data = {};
//action
var m = /<form.*?action="([^"]+)"/.exec(html);
data.action = m ? RegExp.$1 : "";
//inputs
data.fields = {};
var inputs = html.match(/<input\s*(.|\r|\n)*?>/gi);
$.each(inputs, function () {
if (!/name=['"]([^'"]+?)['"]/.exec(this)) return;
var name = RegExp.$1;
data.fields[RegExp.$1] = !/value=['"]([^'"]+?)['"]/.exec(this) ? "" : RegExp.$1;
});
//tourflag
m = /submit_form_confirm\('confirmPassenger','([a-z]+)'\)/.exec(html);
if (m) data.tourFlag = RegExp.$1;
return data;
},
selectionArea: function (opt) {
var self = this;
this.options = $.extend({ onAdd: function () { }, onRemove: function () { }, onClear: function () { }, onRemoveConfirm: function () { return true; }, syncToStorageKey: "", defaultList: null, preloadList: null }, opt);
this.append('<div style="padding: 5px; border: 1px dashed gray; background-color: rgb(238, 238, 238); width:120px;">(还没有添加任何项)</div>');
this.datalist = [];
this.add = function (data) {
if ($.inArray(data, self.datalist) > -1) return;
var text = typeof (data) == "string" ? data : data.text;
var html = $('<input type="button" class="lineButton" value="' + text + '" title="点击删除" />');
self.append(html);
html.click(self.removeByButton);
self.datalist.push(data);
self.syncToStorage();
self.checkEmpty();
self.options.onAdd.call(self, data, html);
};
this.removeByButton = function () {
var obj = $(this);
var idx = obj.index() - 1;
var value = self.datalist[idx];
if (!self.options.onRemoveConfirm.call(self, value, obj, idx)) {
return;
}
obj.remove();
self.datalist.splice(idx, 1);
self.syncToStorage();
self.checkEmpty();
self.options.onRemove.call(self, value, obj);
};
this.emptyList = function () {
self.datalist = [];
self.find("input").remove();
self.syncToStorage();
self.checkEmpty();
self.options.onClear.call(self);
};
this.isInList = function (data) {
/// <summary>判断指定的值是否在列表中</summary>
return $.inArray($.inArray(data, self.datalist)) > -1;
};
this.isInRegList = function (data) {
/// <summary>判断指定的值是否在列表中。这里假定是字符串,使用正则进行判断</summary>
for (var i = 0; i < self.datalist.length; i++) {
if (utility.getRegCache(self.datalist[i]).test(data)) return true;
}
return false;
};
this.syncToStorage = function () {
if (!self.options.syncToStorageKey) return;
window.localStorage.setItem(self.options.syncToStorageKey, self.datalist.join("\t"));
};
this.checkEmpty = function () {
if (self.find("input").length) {
self.find("div").hide();
} else {
self.find("div").show();
}
};
if (self.options.syncToStorageKey) {
var list = self.options.preloadList;
if (!list) {
var list = window.localStorage.getItem(this.options.syncToStorageKey);
if (!list) list = this.options.defaultList;
else list = list.split('\t');
}
if (list) {
$.each(list, function () { self.add(this + ""); });
}
}
return this;
}
}
function unsafeInvoke(callback) {
/// <summary>非沙箱模式下的回调</summary>
var cb = document.createElement("script");
cb.type = "text/javascript";
cb.textContent = buildCallback(callback);
document.head.appendChild(cb);
}
function buildCallback(callback) {
var content = "";
if (!utility_emabed) {
content += "if(typeof(window.utility)!='undefined' && navigator.userAgent.indexOf('Maxthon')==-1){ alert('我勒个去! 检测到您似乎同时运行了两只助手! 请转到『附加组件管理『(Firefox)或『扩展管理』(Chrome)中卸载老版本的助手!');}; \r\nwindow.utility=" + buildObjectJavascriptCode(utility) + "; window.utility.init();window.helperVersion='" + version + "';\r\n";
utility_emabed = true;
}
content += "window.__cb=" + buildObjectJavascriptCode(callback) + ";\r\n\
if(typeof(jQuery)!='undefined')window.__cb();\r\n\
else{\
var script=document.createElement('script');\r\nscript.src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';\r\n\
script.type='text/javascript';\r\n\
script.addEventListener('load', window.__cb);\r\n\
document.head.appendChild(script);\r\n\
}";
return content;
}
function buildObjectJavascriptCode(object) {
/// <summary>将指定的Javascript对象编译为脚本</summary>
if (!object) return null;
var t = typeof (object);
if (t == "string") {
return "\"" + object.replace(/(\r|\n|\\)/gi, function (a, b) {
switch (b) {
case "\r":
return "\\r";
case "\n":
return "\\n";
case "\\":
return "\\\\";
}
}) + "\"";
}
if (t != "object") return object + "";
var code = [];
for (var i in object) {
var obj = object[i];
var objType = typeof (obj);
if ((objType == "object" || objType == "string") && obj) {
code.push(i + ":" + buildObjectJavascriptCode(obj));
} else {
code.push(i + ":" + obj);
}
}
return "{" + code.join(",") + "}";
}
var isChrome = navigator.userAgent.indexOf("AppleWebKit") != -1;
var isFirefox = navigator.userAgent.indexOf("Firefox") != -1;
if (location.host == "dynamic.12306.cn" || (location.host == "www.12306.cn" && location.protocol == "https:")) {
if (!isChrome && !isFirefox) {
alert("很抱歉,未能识别您的浏览器,或您的浏览器尚不支持脚本运行,请使用Firefox或Chrome浏览器!\n如果您运行的是Maxthon3,请确认当前页面运行在高速模式而不是兼容模式下 :-)");
} else if (isFirefox && typeof (GM_notification) == 'undefined') {
alert("很抱歉,本脚本需要最新的Scriptish扩展、不支持GreaseMonkey,请禁用您的GreaseMonkey扩展并安装Scriptish!");
window.open("https://addons.mozilla.org/zh-CN/firefox/addon/scriptish/");
} else if (!window.localStorage) {
alert("警告! localStorage 为 null, 助手无法运行. 请查看浏览器是否已经禁用 localStorage!\nFirefox请设置 about:config 中的 dom.storage.enabled 为 true .");
} else {
//记录更新
utility.setPref("updates", updates.join("\t"));
initUIDisplay();
unsafeInvoke(injectDom);
entryPoint();
}
}
//#endregion
//#region -----------------入口----------------------
function entryPoint() {
var location = window.location;
var path = location.pathname;
utility.regInfo = utility.verifySn(true);
if (utility.regInfo.result != 0) {
return;
}
//
unsafeInvoke(autoReloadIfError);
if ((path == "/otsweb/loginAction.do" && location.search != '?method=initForMy12306') || path == "/otsweb/login.jsp") {
//登录页
unsafeInvoke(initLogin);
}
if (utility.regInfo.bindAcc && localStorage.getItem("_sessionuser") && utility.regInfo.bindAcc.length > 0 && utility.regInfo.bindAcc[0] && utility.regInfo.bindAcc[0] != "*") {
var user = localStorage.getItem("_sessionuser");
var ok = false;
for (var i = 0; i < utility.regInfo.bindAcc.length; i++) {
if (utility.regInfo.bindAcc[i] == user) {
ok = true;
break;
}
}
if (!ok) return;
}
if (path == "/otsweb/order/querySingleAction.do") {
if (location.search == "?method=init" && document.getElementById("submitQuery")) {
unsafeInvoke(initTicketQuery);
unsafeInvoke(initDirectSubmitOrder);
}
if (location.search == "?method=submutOrderRequest") {
unsafeInvoke(initSubmitOrderQuest);
}
}
if (path == "/otsweb/order/orderAction.do") {
if (location.search.indexOf("method=cancelMyOrderNotComplete") != -1 && document.getElementById("submitQuery")) {
unsafeInvoke(initTicketQuery);
unsafeInvoke(initDirectSubmitOrder);
}
}
if (path == "/otsweb/order/payConfirmOnlineSingleAction.do") {
if (location.search.indexOf("method=cancelOrder") != -1 && document.getElementById("submitQuery")) {
unsafeInvoke(initTicketQuery);
unsafeInvoke(initDirectSubmitOrder);
}
}
if (path == "/otsweb/order/myOrderAction.do") {
if (location.search.indexOf("method=resign") != -1 && document.getElementById("submitQuery")) {
unsafeInvoke(initTicketQuery);
unsafeInvoke(initDirectSubmitOrder);
}
}
if (path == "/otsweb/order/confirmPassengerAction.do") {
if (location.search == "?method=init") {
unsafeInvoke(initAutoCommitOrder);
unsafeInvoke(autoCommitOrderInSandbox);
}
if (location.search.indexOf("?method=payOrder") != -1) {
unsafeInvoke(initPagePayOrder);
//获取登录到IE的代码 Add By XPHelper
unsafeInvoke(utility.enableLoginIE);
}
}
if (path == "/otsweb/order/myOrderAction.do") {
if (location.search.indexOf("?method=laterEpay") != -1 || location.search.indexOf("?method=queryMyOrderNotComplete") != -1) {
unsafeInvoke(initNotCompleteOrderPage);
unsafeInvoke(initPayOrder);
//获取登录到IE的代码 Add By XPHelper
unsafeInvoke(utility.enableLoginIE);
}
}
if (path == "/otsweb/main.jsp" || path == "/otsweb/") {
//主框架
console.log("正在注入主框架脚本。");
//跨页面弹窗提示,防止因为页面跳转导致对话框不关闭
console.log("启动跨页面信息调用检查函数");
window.setInterval(function () {
var msg = window.localStorage["notify"];
if (typeof (msg != 'undefined') && msg) {
console.log("主窗口拦截提示请求: " + msg);
window.localStorage.removeItem("notify");
utility.notify(msg);
}
}, 100);
unsafeInvoke(injectMainPageFunction);
}
}
//#endregion
//#region 未完成订单查询页面
function initNotCompleteOrderPage() {
//处理显示时间的
(function () {
var tagInputs = $("input[name=cache_tour_flag]");
var flags = $.map(tagInputs, function (e, i) { return e.value; });
$.each(flags, function () { $("#showTime_" + this).hide().after("<span id='status_" + this + "'>正在查询...</span>"); });
function doCheck() {
var flag = flags.shift();
flags.push(flag);
utility.get("https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=getOrderWaitTime&tourFlag=" + flag, null, "json", function (data) {
var obj = $("#status_" + flag);
if (data.waitTime == 0 || data.waitTime == -1) {
obj.css({ "color": "green" }).html("订票成功!");
utility.notifyOnTop("订票成功!请尽快付款!");
parent.playAudio();
self.location.reload();
return;
}
if (data.waitTime == -2) {
utility.notifyOnTop("出票失败!请重新订票!" + data.msg);
parent.playFailAudio();
obj.css({ "color": "red" }).html("出票失败!" + data.msg);
return;
}
if (data.waitTime == -3) {
utility.notifyOnTop("订单已经被取消!");
parent.playFailAudio();
obj.css({ "color": "red" }).html("订单已经被取消!!");
return;
}
if (data.waitTime == -4) {
utility.notifyOnTop("正在处理中....");
obj.css({ "color": "blue" }).html("正在处理中....");
}
if (data.waitTime > 0) {
obj.css({ "color": "red" }).html("排队中<br />排队数【" + (data.waitCount || "未知") + "】<br />预计时间【" + utility.getSecondInfo(data.waitTime) + "】<br />不过这时间不<br />怎么靠谱 ╮(╯▽╰)╭");
} else {
obj.css({ "color": "red" }).html("奇怪的状态码 [" + data.waitTime + "]....");
}
setTimeout(doCheck, 2000);
}, function () {
utility.notifyOnTop("查询状态错误,正在刷新页面!");
self.location.reload();
});
}
if (flags.length > 0) doCheck();
})();
}
//#endregion
//#region 提交页面出错
function initSubmitOrderQuest() {
if ($("div.error_text").length > 0) {
parent.window.resubmitForm();
}
}
//#endregion
//#region 订票页面,声音提示
function initPagePayOrder() {
new Audio(utility.getAudioUrl()).play();
}
//#endregion
//#region -----------------出错自动刷新----------------------
function autoReloadIfError() {
if ($.trim($("h1:first").text()) == "错误") {
$("h1:first").css({ color: 'red', 'font-size': "18px" }).html(">_< 啊吖!,敢踹我出门啦。。。2秒后我一定会回来的 ╮(╯▽╰)╭");
setTimeout(function () {
self.location.reload();
}, 2000);
}
}
//#endregion
//#region -----------------主框架----------------------
function injectMainPageFunction() {
//资源
var main = $("#main")[0];
main.onload = function () {
var location = null;
try {
location = main.contentWindow.location + '';
} catch (e) {
//出错了,跨站
}
if (!location || location == "http://www.12306.cn/mormhweb/logFiles/error.html") {
resubmitForm();
}
}
if (window.webkitNotifications && window.webkitNotifications.checkPermission() != 0) {
if (confirm("喂!快戳『点击启用桌面通知』,不然提示会阻碍操作,导致运行变慢,然后就没票了!\n\n如果是第一次看到介句话,点击『取消』并按提示操作。如果反复邂逅这个对话框,就戳『确定』以打开助手主页的常见问题并查找解决办法。\n\n搜狗高速浏览器暂不支持保存此权限,每次访问时可能都会邂逅这个对话框……")) {
window.open("http://www.fishlee.net/soft/44/faq.html");
}
}
window.resubmitForm = function () {
var form = $("#orderForm");
if (form.length == 0 || form.attr("success") != "0") return;
utility.notify("页面出错了!正在重新预定!");
setTimeout(function () { document.getElementById("orderForm").submit(); }, 3000);
}
window.playAudio = function () {
new Audio(utility.getAudioUrl()).play();
};
window.playFailAudio = function () {
utility.playFailAudio();
};
}
//#endregion
//#region -----------------自动提交----------------------
function initAutoCommitOrder() {
var count = 0;
var breakFlag = 0;
var randCode = "";
var submitFlag = false;
var tourFlag = 'dc';
var randEl = $("#rand");
//启用日志
utility.enableLog();
//#region 如果系统出错,那么重新提交
if ($(".error_text").length > 0 && parent.$("#orderForm").length > 0) {
parent.resubmitForm();
return;
}
//#endregion
//获得tourflag
(function () {
/'(dc|fc|wc|gc)'/.exec($("div.tj_btn :button:eq(2)")[0].onclick + '');
tourFlag = RegExp.$1;
})();
function stop(msg) {
setCurOperationInfo(false, "错误 - " + msg);
setTipMessage(msg);
$("div.tj_btn button, div.tj_btn input").each(function () {
this.disabled = false;
$(this).removeClass().addClass("long_button_u");
});
$("#btnCancelAuto").hide();
}
var reloadCode = function () {
$("#img_rrand_code").click();
$("#rand").val("")[0].select();
};
var getSleepTime = function () {
return 1000 * Math.max(parseInt($("#pauseTime").val()), 1);
};
//订单等待时间过久的警告
var waitTimeTooLong_alert = false;
function submitForm() {
randEl[0].blur();
stopCheckCount();
if (!window.submit_form_check || !submit_form_check("confirmPassenger")) {
setCurOperationInfo(false, "您的表单没有填写完整!");
stop("请填写完整表单");
return;
}
count++;
setCurOperationInfo(true, "第 " + count + " 次提交");
if (breakFlag) {
stop("已取消自动提交");
breakFlag = 0;
return;
}
$("#btnCancelAuto").show().removeClass().addClass("long_button_u_down")[0].disabled = false; //阻止被禁用
breakFlag = 0;
waitTimeTooLong_alert = false;
$("#confirmPassenger").ajaxSubmit({
url: 'confirmPassengerAction.do?method=checkOrderInfo&rand=' + $("#rand").val(),
type: "POST",
data: { tFlag: tourFlag },
dataType: "json",
success: function (data) {
if ('Y' != data.errMsg || 'N' == data.checkHuimd || 'N' == data.check608) {
setCurOperationInfo(false, data.msg || data.errMsg);
stop(data.msg || data.errMsg);
reloadCode();
}
else {
queryQueueCount();
}
},
error: function (msg) {
setCurOperationInfo(false, "当前请求发生错误");
utility.delayInvoke(null, submitForm, 3000);
}
});
}
function queryQueueCount() {
var queryLeftData = {
train_date: $("#start_date").val(),
train_no: $("#train_no").val(),
station: $("#station_train_code").val(),
seat: $("#passenger_1_seat").val(),
from: $("#from_station_telecode").val(),
to: $("#to_station_telecode").val(),
ticket: $("#left_ticket").val()
};
/*utility.get("/otsweb/order/confirmPassengerAction.do?method=getQueueCount", queryLeftData, "json", function (data) {
console.log(data);
if (data.op_2) {
var errmsg = "排队人数过多,系统禁止排队,可以输入验证码重试 (排队人数=" + data.count + ")";
setCurOperationInfo(false, errmsg);
stop(errmsg);
reloadCode();
return;
}
submitConfirmOrder();
}, function () { utility.delayInvoke(null, queryLeftTickets, 2000); });*/
}
function submitConfirmOrder() {
jQuery.ajax({
url: '/otsweb/order/confirmPassengerAction.do?method=confirmSingleForQueueOrder',
data: $('#confirmPassenger').serialize(),
type: "POST",
timeout: 10000,
dataType: 'json',
success: function (msg) {
console.log(msg);
var errmsg = msg.errMsg;
if (errmsg != 'Y') {
if (errmsg.indexOf("包含未付款订单") != -1) {
alert("您有未支付订单! 等啥呢, 赶紧点确定支付去.");
window.location.replace("/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y");
return;
}
if (errmsg.indexOf("重复提交") != -1) {
stop("重复提交错误,已刷新TOKEN,请重新输入验证码提交");
reloadToken();
reloadCode();
return;
}
if (errmsg.indexOf("后台处理异常") != -1 || errmsg.indexOf("非法请求") != -1) {
if (lastform) {
utility.notifyOnTop("后台处理异常,已自动重新提交表单,请填写验证码并提交!");
lastform.submit();
} else {
stop("后台处理异常,请返回查询页重新预定!");
}
return;
}
if (errmsg.indexOf("包含排队中") != -1) {
console.log("惊现排队中的订单, 进入轮询状态");
waitingForQueueComplete();
return;
}
setCurOperationInfo(false, errmsg);
stop(errmsg);
reloadCode();
} else {
utility.notifyOnTop("订单提交成功, 正在等待队列完成操作,请及时注意订单状态");
waitingForQueueComplete();
}
},
error: function (msg) {
setCurOperationInfo(false, "当前请求发生错误");
utility.delayInvoke(null, submitForm, 3000);
}
});
}
function reloadToken(submit) {
setCurOperationInfo(true, "正在刷新TOKEN....");
utility.post("/otsweb/order/confirmPassengerAction.do?method=init", null, "text", function (text) {
if (!/TOKEN"\s*value="([a-f\d]+)"/i.test(text)) {
setCurOperationInfo(false, "无法获得TOKEN,正在重试");
utility.delayInvoke("#countEle", reloadToken, 1000);
} else {
var token = RegExp.$1;
setCurOperationInfo(false, "已获得TOKEN - " + token);
console.log("已刷新TOKEN=" + token);
$("input[name=org.apache.struts.taglib.html.TOKEN]").val(token);
}
}, function () { utility.delayInvoke("#countEle", reloadToken, 1000); });
}
function waitingForQueueComplete() {
setCurOperationInfo(true, "订单提交成功, 正在等待队列完成操作....");
$.ajax({
url: '/otsweb/order/myOrderAction.do?method=getOrderWaitTime&tourFlag=' + tourFlag + '&' + Math.random(),
data: {},
type: 'GET',
timeout: 10000,
dataType: 'json',
success: function (json) {
console.log(json);
if (json.waitTime == -1 || json.waitTime == 0) {
utility.notifyOnTop("订票成功!");
if (json.orderId)
window.location.replace("/otsweb/order/confirmPassengerAction.do?method=payOrder&orderSequence_no=" + json.orderId);
else window.location.replace('/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y');
} else if (json.waitTime == -3) {
var msg = "很抱歉, 铁道部无齿地撤销了您的订单, 赶紧重新下!";
utility.notify(msg);
setCurOperationInfo(false, msg);
stop(msg);
reloadCode();
} else if (json.waitTime == -2) {
var msg = "很抱歉, 铁道部说您占座失败 : " + json.msg + ', 赶紧重新来过!';
utility.notify(msg);
setCurOperationInfo(false, msg);
stop(msg);
reloadCode();
}
else if (json.waitTime < 0) {
var msg = '很抱歉, 未知的状态信息 : waitTime=' + json.waitTime + ', 可能已成功,请验证未支付订单.';
setTipMessage(msg);
utility.notifyOnTop(msg);
location.href = '/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y';
} else {
var msg = "订单需要 " + utility.getSecondInfo(json.waitTime) + " 处理完成, 请等待,不过你知道的,铁道部说的一直不怎么准。(排队人数=" + (json.waitCount || "未知") + ")";
if (json.waitTime > 1800) {
msg += "<span style='color:red; font-weight: bold;'>警告:排队时间大于30分钟,请不要放弃电话订票或用小号重新排队等其它方式继续订票!</span>";
}
setTipMessage(msg);
if (json.waitTime > 1800 && !waitTimeTooLong_alert) {
waitTimeTooLong_alert = true;
utility.notifyOnTop("警告!排队时间大于30分钟,成功率较低,请尽快电话订票或用小号重新排队!");
}
utility.delayInvoke("#countEle", waitingForQueueComplete, 1000);
}
},
error: function (json) {
utility.notifyOnTop("请求发生异常,可能是登录状态不对,请验证。如果没有问题,请手动进入未完成订单页面查询。");
self.location.reload();
}
});
}
$("div.tj_btn").append("<button class='long_button_u_down' type='button' id='btnAutoSubmit'>自动提交</button> <button class='long_button_u_down' type='button' id='btnCancelAuto' style='display:none;'>取消自动</button>");
$("#btnAutoSubmit").click(function () {
count = 0;
breakFlag = 0;
submitFlag = true;
submitForm();
});
$("#btnCancelAuto").click(function () {
$(this).hide();
breakFlag = 1;
submitFlag = false;
});
randEl.keyup(function (e) {
if (!submitFlag && !document.getElementById("autoStartCommit").checked) return;
if (e.charCode == 13 || randEl.val().length == 4) submitForm();
});
//清除上次保存的预定信息
var lastform = null;
if (parent) {
lastform = parent.$("#orderForm");
lastform.attr("success", "1");
}
//进度提示框
$("table.table_qr tr:last").before("<tr><td style='border-top:1px dotted #ccc;height:100px;' colspan='9' id='orderCountCell'></td></tr><tr><td style='border-top:1px dotted #ccc;' colspan='9'><ul id='tipScript'>" +
"<li class='fish_clock' id='countEle' style='font-weight:bold;'>等待操作</li>" +
"<li style='color:green;'><strong>操作信息</strong>:<span>休息中</span></li>" +
"<li style='color:green;'><strong>最后操作时间</strong>:<span>--</span></li></ul></td></tr>");
var tip = $("#tipScript li");
var errorCount = 0;
//以下是函数
function setCurOperationInfo(running, msg) {
var ele = $("#countEle");
ele.removeClass().addClass(running ? "fish_running" : "fish_clock").html(msg || (running ? "正在操作中……" : "等待中……"));
}
function setTipMessage(msg) {
tip.eq(2).find("span").html(utility.getTimeInfo());
tip.eq(1).find("span").html(msg);
}
//提交频率差别
$(".table_qr tr:last").before("<tr><td colspan='9'>自动提交失败时休息时间:<input type='text' size='4' class='input_20txt' style='text-align:center;' value='3' id='pauseTime' />秒 (不得低于1) <label><input type='checkbox' id='autoStartCommit' /> 输入验证码后立刻开始自动提交</label> <label><input type='checkbox' id='showHelp' /> 显示帮助</label></td></tr>");
document.getElementById("autoStartCommit").checked = typeof (window.localStorage["disableAutoStartCommit"]) == 'undefined';
document.getElementById("showHelp").checked = typeof (window.localStorage["showHelp"]) != 'undefined';
$("#autoStartCommit").change(function () {
if (this.checked) window.localStorage.removeItem("disableAutoStartCommit");
else window.localStorage.setItem("disableAutoStartCommit", "1");
});
$("#showHelp").change(function () {
if (this.checked) {
window.localStorage.setItem("showHelp", "1");
$("table.table_qr tr:last").show();
}
else {
window.localStorage.removeItem("showHelp");
$("table.table_qr tr:last").hide();
}
}).change();
//#region 自动刷新席位预定请求数
var stopCheckCount = null;
(function () {
var data = { train_date: $("#start_date").val(), station: $("#station_train_code").val(), seat: "", from: $("#from_station_telecode").val(), to: $("#to_station_telecode").val(), ticket: $("#left_ticket").val() };
var url = "confirmPassengerAction.do?method=getQueueCount";
var allSeats = $("#passenger_1_seat option");
var queue = [];
var checkCountStopped = false;
function beginCheck() {
if (checkCountStopped) return;
var html = [];
html.push("当前实时排队状态(每隔2秒轮询):");
allSeats.each(function () {
queue.push({ id: this.value, name: this.text });
html.push("席位【<span style='color:blue; font-weight: bold;'>" + this.text + "</span>】状态:<span id='queueStatus_" + this.value + "'>等待查询中....</span>");
});
$("#orderCountCell").html(html.join("<br />"));
if (queue.length > 0) executeQueue();
}
function checkTicketAvailable() {
var queryLeftData = {
'orderRequest.train_date': $('#start_date').val(),
'orderRequest.from_station_telecode': $('#from_station_telecode').val(),
'orderRequest.to_station_telecode': $('#to_station_telecode').val(),
'orderRequest.train_no': $('#train_no').val(),
'trainPassType': 'QB',
'trainClass': 'QB#D#Z#T#K#QT#',
'includeStudent': 00,
'seatTypeAndNum': '',
'orderRequest.start_time_str': '00:00--24:00'
};
/*utility.get("/otsweb/order/querySingleAction.do?method=queryLeftTicket", queryLeftData, "text", function (text) {
window.ticketAvailable = '';
if (/(([\da-zA-Z]\*{5,5}\d{4,4})+)/gi.test(text)) {
window.ticketAvailable = RegExp.$1;
}
}, function () { });*/
}
function executeQueue() {
if (checkCountStopped) return;
var type = queue.shift();
queue.push(type);
data.seat = type.id;
var strLeftTicket = '';
checkTicketAvailable();
if (window.ticketAvailable) {
strLeftTicket = window.ticketAvailable;
}
utility.get(url, data, "json", function (data) {
var msg = "余票:<strong>" + getTicketCountDesc(strLeftTicket, type.id) + "</strong>";
msg += ",当前排队【<span style='color:blue; font-weight: bold;'>" + data.count + "</span>】,";
if (data.op_2) {
msg += "<span style='color:blue; font-weight: red;'>排队人数已经超过余票数,可能无法提交</span>。";
} else {
if (data.countT > 0) {
msg += "排队人数已超过系统参数,<span style='color:red; font-weight: bold;'>排队有危险</span>";
//} else if (data.op_1) {
// msg += "排队人数已超过系统参数,<span style='color:red; font-weight: bold;'>排队有危险</span>";
} else {
msg += "请尽快提交";
}
}
msg += " (" + utility.getTimeInfo() + ")";
$("#queueStatus_" + type.id).html(msg);
setTimeout(executeQueue, 2000);
}, function () {
setTimeout(executeQueue, 3000);
});
}
stopCheckCount = function () {
checkCountStopped = true;
}
//beginCheck();
})();
//#endregion
//#region 自动选择联系人、自动选择上次选择的人
function autoSelectPassenger() {
var pp = localStorage.getItem("preSelectPassenger") || "";
var pseat = (localStorage.getItem("autoSelect_preSelectSeatType") || "").split('|')[0];
if (pp) {
pp = pp.split("|");
$.each(pp, function () {
if (!this) return true;
console.log("[INFO][自动选择乘客] 自动选定-" + this);
$("#" + this + "._checkbox_class").attr("checked", true).click().attr("checked", true); //为啥设置两次?我也不知道,反正一次不对。
return true;
});
if (pseat) {
$(".passenger_class").each(function () { $(this).find("select:eq(0)").val(pseat).change(); });
}
}
};
$(window).ajaxComplete(function (e, xhr, s) {
if (s.url.indexOf("getpassengerJson") != -1) {
console.log("[INFO][自动选择乘客] 系统联系人加载完成,正在检测预先选定");
autoSelectPassenger();
}
});
//如果已经加载完成,那么直接选定
if ($("#showPassengerFilter div").length) {
console.log("[INFO][自动选择乘客] OOPS,居然加载完成了?直接选定联系人");
autoSelectPassenger();
}
//#endregion
//#region 自动定位到随机码中
(function () {
var obj = document.getElementById("rand");
var oldOnload = window.onload;
window.onload = function () {
if (oldOnload) oldOnload();
obj.select();
};
obj.select();
})();
//#endregion
//#region 显示内部的选择上下铺
(function () {
//添加上下铺显示
$("tr.passenger_class").each(function () {
var tr = $(this);
var id = tr.attr("id");
tr.find("td:eq(2)").append("<select id='" + id + "_seat_detail' name='" + id + "_seat_detail'><option value='0'>随机</option><option value='2'>上铺</option><option value='2'>中铺</option><option value='1'>下铺</option></select>");
});
var seatSelector = $("select[name$=_seat]");
seatSelector.change(function () {
var self = $(this);
var val = self.val();
var l = self.next();
if (val == "2" || val == "3" || val == "4" || val == "6") {
l.show();
} else
l.hide();
var preseat = utility.getPref("preselectseatlevel");
if (preseat) {
l.val(preseat).change();
}
}).change();
})();
//#endregion
parent.$("#main").css("height", ($(document).height() + 300) + "px");
parent.window.setHeight(parent.window);
}
function autoCommitOrderInSandbox() {
//自动提示?
if (window.localStorage["bookTip"]) {
window.localStorage.removeItem("bookTip");
if (window.Audio) {
new window.Audio(utility.getAudioUrl()).play();
}
utility.notify("已经自动进入订票页面!请继续完成订单!");
}
}
//#endregion
//#region -----------------自动刷新----------------------
function initTicketQuery() {
//启用日志
utility.enableLog();
var initialized = false;
var seatLevelOrder = null;
var orderButtonClass = ".btn130_2"; //预定按钮的选择器
//#region 参数配置和常规工具界面
var queryCount = 0;
var timer = null;
var isTicketAvailable = false;
var audio = null; //通知声音
var timerCountDown = 0;
var timeCount = 0;
var autoBook = false;
//初始化表单
var form = $("form[name=querySingleForm] .cx_from:first");
form.find("tr:last").after("<tr class='append_row'><td colspan='9' id='queryFunctionRow'><label title='勾选此选项的话,每次你查询后,助手会帮你把始发站、到达站、日期等进行记录,下次进入查询页面后,将会帮您自动填写好'><input type='checkbox' id='keepinfo' checked='checked' />记住信息</label> <label title='勾选此选项后,假定查询的结果中没有符合你要求的车次,那么助手将会自动进行重新查询'><input checked='checked' type='checkbox' id='autoRequery' />自动重新查询</label>,每隔 <input style='width:50px;' type='number' min='5' value='5' size='4' id='refereshInterval' style='text-align:center;' />秒(最低5) " +
"<label title='勾选的话,当有票可定时,助手会放歌骚扰你'><input type='checkbox' checked='checked' id='chkAudioOn'>声音提示</label> <input type='button' id='chkSeatOnly' value='仅座票' class='lineButton' title='快速设置席别过滤按钮,点击后可快速勾选所有的座票,包括硬座软座一等座等等' /><input type='button' id='chkSleepOnly' value='仅卧铺' title='快速设置席别过滤按钮,点击后可快速勾选所有的卧铺,包括硬卧软卧什么的' class='lineButton' /><input type='button' id='chkAllSeat' value='全部席别' class='lineButton' title='快速勾选所有的席别' />" +
"<input type='button' id='enableNotify' onclick='window.webkitNotifications.requestPermission();' value='点击启用桌面通知' style='line-height:25px;padding:5px;' /> <span id='refreshinfo'>已刷新 0 次,最后查询:--</span> <span id='refreshtimer'></span></td></tr>" +
"<tr class='append_row'><td colspan='9'><label title='设置有票时放的歌是不是放到天荒地老至死不渝'><input type='checkbox' checked='checked' id='chkAudioLoop'>声音循环</label>" +
"<span style='font-weight:bold;margin-left:10px;color:blue;' title='点击预定按钮时,有时候等待一会儿系统会提示服务器忙;勾选此选项后,如果出现这种情况,助手将会进行自动重新预定'><label><input type='checkbox' id='chkAutoResumitOrder' checked='checked' />预定失败时自动重试</label></span>" +
"<span style='font-weight:bold;margin-left:10px;color:blue;' title='有时候系统忙,查询会提示查询失败;勾选此选项后,如果出现这种情况,助手将会进行自动刷新查询'><label><input type='checkbox' id='chkAutoRequery' checked='checked' />查询失败时自动重试</label></span>" +
"<span style='font-weight:bold;margin-left:10px;color:pruple;' title='以服务器时间为准,未获得服务器时间之前,此选项不可用。启用智能加速模式时,在非正点附近时(大于0小于59分)按照正常速度刷新;当在正点附近时(大于等于59分时),暂停刷新并等到正点即刻刷新。'><label><input disabled='disabled' type='checkbox' id='chkSmartSpeed' />智能正点刷新模式</label></span>" +
"</td></tr>" +
"<tr class='append_row'><td id='filterFunctionRow' colspan='9'>" +
"<span style='font-weight:bold;color:red;'><label title='不可以预定的车次过滤掉的选项(隐藏起来不显示,无票的车次)'><input type='checkbox' id='chkFilterNonBookable' />过滤不可预订的车次</label></span>" +
"<span style='font-weight:bold;margin-left:10px;color:red;'><label title='有时候虽然整趟车可以预定,但是有票的席别都是你不要的,如果勾选此选项,也将会过滤掉'><input type='checkbox' id='chkFilterNonNeeded' />过滤不需要的席别</label></span>" +
"<span style='font-weight:bold;margin-left:10px;color:blue;display: none;'><label><input disabled='disabled' type='checkbox' id='chkFilterByTrain' />开启按车次过滤</label></span>" +
"</td></tr>" +
"<tr><td colspan='9' id='opFunctionRow'><input type='button' class='fish_button' disabled='disabled' value='停止声音' id='btnStopSound' /><input type='button' class='fish_button' disabled='disabled' value='停止刷新' id='btnStopRefresh' /><input type='button' class='fish_button' type='button' value='设置' id='configLink' /> <input type='button' class='fish_button' id='resetSettings' value='清空助手设置' /> <input type='button' class='fish_button configLink' value='IE登录' /> 【<a href='http://www.fishlee.net/soft/44/tour.html' style='color:purple;font-weight:bold;' target='_blank'>啊嘞……遇到不明白的啦?戳这里看教程呗</a>】<span style='margin-left:20px;color:purple;font-weight:bold;' id='serverMsg'></span></td> </tr>"
);
if (!window.Audio) {
$("#chkAudioOn, #chkAudioLoop, #btnStopSound").remove();
} else {
$("#btnStopSound").click(function () {
if (audio) {
audio.pause();
}
this.disabled = true;
});
}
$("#resetSettings").click(function () {
if (confirm("确定要清空助手的所有设置吗?")) {
window.localStorage.clear();
self.location.reload();
return false;
}
});
//操作控制
$("#btnStopRefresh").click(function () { resetTimer(); });
$("#chkSmartSpeed").change(function () {
});
//#endregion
//#region 显示座级选择UI
var ticketType = new Array();
var seatOptionTypeMap = {
"3": "9",
"4": "P",
"5": "M",
"6": "O",
"7": "6",
"8": "4",
"9": "3",
"10": "2",
"11": "1",
"12": "empty",
"13": "QT"
};
$(".hdr tr:eq(2) td").each(function (i, e) {
ticketType.push(false);
if (i < 3) return;
var obj = $(this);
ticketType[i] = (window.localStorage["typefilter_" + i] || "true") == "true";
//修改文字,避免换行
obj.attr("otext", obj.text());
var cap = $.trim(obj.text());
if (cap.length > 2) {
cap = cap.replace("座", "").replace("高级软卧", "高软");
obj.html(cap);
}
//加入复选框
var c = $("<input id='seatoption_" + seatOptionTypeMap[i] + "' type='checkbox' typecode='" + seatOptionTypeMap[i] + "' name='seatoption'/>").attr("checked", ticketType[i]);
c[0].ticketTypeId = i;
c.change(
function () {
ticketType[this.ticketTypeId] = this.checked;
window.localStorage["typefilter_" + this.ticketTypeId] = this.checked;
}).appendTo(obj);
});
//座级选择
$("#chkSeatOnly").click(function () {
$(".hdr tr:eq(2) td").each(function (i, e) {
var obj = $(this);
var txt = obj.attr("otext");
obj.find("input").attr("checked", typeof (txt) != 'undefined' && txt && txt.indexOf("座") != -1).change();
});
});
$("#chkSleepOnly").click(function () {
$(".hdr tr:eq(2) td").each(function (i, e) {
var obj = $(this);
var txt = obj.attr("otext");
obj.find("input").attr("checked", typeof (txt) != 'undefined' && txt && txt.indexOf("卧") != -1).change();
});
});
$("#chkAllSeat").click(function () {
$(":checkbox[name=seatoption]").attr("checked", true).change();
});
//#endregion
//#region 显示额外的功能区
var extrahtml = [];
extrahtml.push("<div class='outerbox' id='helperbox' style='width:auto;'><div class='box'><div class='title' style='position:relative;'>辅助工具 [<a href='#querySingleForm'>返回订票列表</a>] <div style='color:#066DFF;position:absolute;background-color: #eee;border: 1px solid purple;right:0px;top:0px;padding:2px;margin:2px;' title='时间依赖于本地时间保持在线刷新时间即时计算。受限于您的网速,并不十分准确(需要扣除网速的影响)' id='servertime'>服务器时间:<strong>----</strong>,本地时间:<strong>----</strong>,服务器比本地 <strong>----</strong></div></div>\
<table id='helpertooltable' style='width:100%;'><colgroup><col style='width:110px;' /><col style='width:370px;' /><col style='width:110px;' /><col style='width:auto;' /></colgroup>\
<tr class='fish_sep musicFunc' id='helperbox_bottom'><td class='name'>自定义音乐地址</td><td colspan='3'><input type='text' id='txtMusicUrl' value='" + utility.getAudioUrl() + "' onfocus='this.select();' style='width:50%;' /> <input type='button' onclick='new Audio(document.getElementById(\"txtMusicUrl\").value).play();' value='测试'/><input type='button' onclick='utility.resetAudioUrl(); document.getElementById(\"txtMusicUrl\").value=utility.getAudioUrl();' value='恢复默认'/> (地址第一次使用可能会需要等待一会儿)</td></tr>\
<tr class='fish_sep musicFunc'><td class='name'>可用音乐地址</td><td colspan='3'>");
var host1 = "http://resbak.fishlee.net/res/";
//var host2 = "https://github.com/iccfish/12306_ticket_helper/raw/master/res/";
var musics = [["music1.ogg", "超级玛丽"], ["music2.ogg", "蓝精灵"]];
$.each(musics, function () {
extrahtml.push("<a href='javascript:;' url='" + host1 + this[0] + "' class='murl'>" + this[1] + "</a> ");
//extrahtml.push("<a href='javascript:;' url='" + host2 + this[0] + "' class='murl'>" + this[1] + "</a>(HTTPS) ");
});
extrahtml.push("</td></tr><tr class='fish_sep'><td colspan='4'><input type='button' value='添加自定义车票时间段' id='btnDefineTimeRange' />\
<input type='button' value='清除自定义车票时间段' id='btnClearDefineTimeRange' /></td></tr>\
<tr class='fish_sep'><td style='text-align:center;' colspan='4'><a href='http://www.fishlee.net/soft/44/' target='_blank' style='color:purple;'>12306.CN 订票助手 by iFish(木鱼)</a> | <a href='http://t.qq.com/ccfish/' target='_blank' style='color:blue;'>腾讯微博</a> | <a href='http://www.fishlee.net/soft/44/announcement.html' style='color:blue;' target='_blank'>免责声明</a> | <a href='http://www.fishlee.net/Discussion/Index/44' target='_blank'>反馈BUG</a> | <a style='font-weight:bold;color:red;' href='http://www.fishlee.net/soft/44/donate.html' target='_blank'>捐助作者</a> | 版本 v" + window.helperVersion + ",许可于 <strong>" + utility.regInfo.name + ",类型 - " + utility.regInfo.typeDesc + "</strong> 【<a href='javascript:;' class='reSignHelper'>重新注册</a>】</td></tr>\
</table></div></div>");
$("body").append(extrahtml.join(""));
$("a.murl").live("click", function () {
$("#txtMusicUrl").val(this.getAttribute("url")).change();
});
$("#stopBut").before("<div class='jmp_cd' style='text-align:center;'><button class='fish_button' id='btnFilter'>加入黑名单</button><button class='fish_button' id='btnAutoBook'>自动预定本车次</button></div>");
$("#txtMusicUrl").change(function () { window.localStorage["audioUrl"] = this.value; });
$("form[name=querySingleForm]").attr("id", "querySingleForm");
//#endregion
//#region 添加自定义时间段
function addCustomTimeRange() {
var s = parseInt(prompt("请输入自定义时间段的起始时间(请填入小时,0-23)", "0"));
if (isNaN(s) || s < 0 || s > 23) {
alert("起始时间不正确 >_<"); return;
}
var e = parseInt(prompt("请输入自定义时间段的结束时间(请填入小时,1-24)", "24"));
if (isNaN(e) || e < 0 || e > 24) {
alert("结束时间不正确 >_<"); return;
}
var range = (s > 9 ? "" : "0") + s + ":00--" + (e > 9 ? "" : "0") + e + ":00";
if (confirm("您想要记住这个时间段吗?")) {
window.localStorage["customTimeRange"] = (window.localStorage["customTimeRange"] ? window.localStorage["customTimeRange"] + "|" : "") + range;
};
addCustomeTimeRangeToList(range);
}
function addCustomeTimeRangeToList(g) {
var obj = document.getElementById("startTime");
obj.options[obj.options.length] = new Option(g, g);
obj.selectedIndex = obj.options.length - 1;
}
if (window.localStorage["customTimeRange"]) {
var ctrs = window.localStorage["customTimeRange"].split("|");
$.each(ctrs, function () { addCustomeTimeRangeToList(this); });
}
$("#btnClearDefineTimeRange").click(function () {
if (!confirm("确定要清除自定义的时间段吗?清除后请刷新页面。")) return;
window.localStorage.removeItem("customTimeRange");
});
$("#btnDefineTimeRange").click(addCustomTimeRange);
//#endregion
//#region 过滤车次
var stopHover = window.onStopHover;
window.onStopHover = function (info) {
$("#stopDiv").attr("info", $.trim($("#id_" + info.split('#')[0]).text()));
stopHover.call(this, info);
$("#onStopHover").css("overflow", "hide");
};
$("#btnFilter").click(function () {
//加入黑名单
var trainNo = $("#stopDiv").attr("info").split('#')[0];
if (!trainNo || !confirm("确定要将车次【" + trainNo + "】加入黑名单?以后的查询将不再显示此车次。")) return;
list_blacklist.add(trainNo);
});
$("#btnAutoBook").click(function () {
//加入自动预定列表
var trainNo = $("#stopDiv").attr("info").split('#')[0];
if (isTrainInBlackList(trainNo)) {
alert("指定的车次在黑名单里呢……");
return;
}
if (!trainNo || !confirm("确定要将车次【" + trainNo + "】加入自动预定列表?如果下次查询有符合要求的席别将会自动进入预定页面。")) return;
list_autoorder.add(trainNo);
});
//清除进入指定页面后提示的标记位
if (window.localStorage["bookTip"]) window.localStorage.removeItem("bookTip");
//#endregion
//#region 自动重新查询
var clickButton = null;//点击的查询按钮
var filterNonBookable = $("#chkFilterNonBookable")[0]; //过滤不可定车次
var filterNonNeeded = $("#chkFilterNonNeeded")[0]; //过滤不需要车次
var onRequery = function () { }; //当重新查询时触发
var onNoTicket = function () { }; //当没有查到票时触发
$("#autoRequery").change(function () {
if (!this.checked)
resetTimer();
});
//刷新时间间隔
$("#refereshInterval").change(function () { timeCount = Math.max(5, parseInt($("#refereshInterval").val())); }).change();
//定时查询
var isSmartOn = false;
function resetTimer() {
queryCount = 0;
$("#btnStopRefresh")[0].disabled = true;
if (timer) {
clearInterval(timer);
timer = null;
}
$("#refreshtimer").html("");
}
function countDownTimer() {
timerCountDown -= 0.2;
var str = (Math.round(timerCountDown * 10) / 10) + "";
$("#refreshtimer").html("[" + (isSmartOn ? "等待正点," : "") + str + (str.indexOf('.') == -1 ? ".0" : "") + "秒后查询...]");
if (timerCountDown > 0) return;
clearInterval(timer);
timer = null;
onRequery();
doQuery();
}
function startTimer() {
if (timer) return;
var d = new Date().getMinutes();
isSmartOn = document.getElementById("chkSmartSpeed").checked && time_server && time_server.getMinutes() >= 59;
timerCountDown = isSmartOn ? 60 - time_server.getSeconds() + 2 : timeCount;
var str = (Math.round(timerCountDown * 10) / 10) + "";
$("#refreshtimer").html("[" + (isSmartOn ? "等待正点," : "") + timerCountDown + (str.indexOf('.') == -1 ? ".0" : "") + "秒后查询...]");
//没有定时器的时候,开启定时器准备刷新
$("#btnStopRefresh")[0].disabled = false;
timer = setInterval(countDownTimer, 200);
}
function displayQueryInfo() {
queryCount++;
$("#refreshinfo").html("已刷新 " + queryCount + " 次,最后查询:" + utility.getTimeInfo());
$("#refreshtimer").html("正在查询");
}
function doQuery() {
timer = null;
if (audio) audio.pause();
displayQueryInfo();
sendQueryFunc.call(clickBuyStudentTicket == "Y" ? document.getElementById("stu_submitQuery") : document.getElementById("submitQuery"));
}
//验证车票有开始
var onticketAvailable = function () {
resetTimer();
$("#refreshinfo").html("已经有票鸟!");
utility.notifyOnTop("可以订票了!");
if (window.Audio && $("#chkAudioOn")[0].checked) {
if (!audio) {
audio = new Audio($("#txtMusicUrl").val());
}
audio.loop = $("#chkAudioLoop")[0].checked;
$("#btnStopSound")[0].disabled = false;
audio.play();
}
}
//检查是否可以订票
var checkTicketsQueue = [];
var checkTicketCellsQueue = [];
function getTrainNo(row) {
/// <summary>获得行的车次号</summary>
return $.trim($("td:eq(0)", row).text());
}
//默认的单元格检测函数
checkTicketCellsQueue.push(function (i, e) {
if (!ticketType[i - 1]) return 0;
var el = $(e);
var info = $.trim(el.text()); //Firefox不支持 innerText
if (info == "*" || info == "--" || info == "无") {
return 0;
}
return 2;
});
//默认的行检测函数
checkTicketsQueue.push(function () {
var trainNo = getTrainNo(this);
var tr = this;
this.attr("tcode", trainNo);
//黑名单过滤
if (isTrainInBlackList(trainNo)) {
this.hide();
return 0;
}
var hasTicket = 1;
if ($("a.btn130", this).length > 0) return 0;
$("td", this).each(function (i, e) {
var cellResult = 0;
e = $(e);
var opt = { code: trainNo, tr: tr, index: e.index(), seatType: seatOptionTypeMap[e.index() - 1] };
e.attr("scode", opt.seatType);
$.each(checkTicketCellsQueue, function () {
cellResult = this(i, e, cellResult, opt) || cellResult;
return cellResult != 0;
});
e.attr("result", cellResult);
if (cellResult == 2) {
hasTicket = 2;
e.css("background-color", "#95AFFD");
}
});
tr.attr("result", hasTicket);
return hasTicket;
});
//检测是否有余票的函数
var checkTickets = function () {
var result = 0;
var row = this;
$.each(checkTicketsQueue, function () {
result = this.call(row, result);
return true;
});
return result;
}
//目标表格,当ajax完成时检测是否有票
$("body").ajaxComplete(function (e, r, s) {
//HACK-阻止重复调用
if (timer != null) return;
if (s.url.indexOf("queryLeftTicket") == -1)
return;
//验证有票
var rows = $("table.obj tr:gt(0)");
var ticketValid = false;
var validRows = {};
rows.each(function () {
var row = $(this);
var valid = checkTickets.call(row);
var code = getTrainNo(row);
row.attr("tcode", code);
row.find("td:eq(0)").click(putTrainCodeToList);
console.log("[INFO][车票可用性校验] " + code + " 校验结果=" + valid);
if (valid == 2) {
row.css("background-color", "#FD855C");
validRows[code] = row;
}
else {
if (valid == 1 && filterNonNeeded.checked) row.hide();
if (valid == 0 && filterNonBookable.checked) row.hide();
}
ticketValid = ticketValid || valid == 2;
});
//自动预定
if ($("#swAutoBook:checked").length > 0) {
if (!seatLevelOrder || !seatLevelOrder.length) {
//没有席别优先级,那选第一个
for (var idx in list_autoorder.datalist) {
var code = list_autoorder.datalist[idx];
var reg = utility.getRegCache(code);
var row = $.first(validRows, function (i, v) {
if (reg.test(i)) return v;
});
if (row) {
if (document.getElementById("autoBookTip").checked) {
window.localStorage["bookTip"] = 1;
}
row.find("a[name=btn130_2]").click();
return false;
}
};
} else {
console.log("按席别优先选择-车次过滤");
var trains = $.makeArray($("#gridbox tr[result=2]"));
var trainfiltered = [];
for (var idx in list_autoorder.datalist) {
//对车次进行过滤并按优先级排序
var rule = list_autoorder.datalist[idx];
var ruleTester = utility.getRegCache(rule);
for (var i = trains.length - 1; i >= 0; i--) {
var self = $(trains[i]);
var code = self.attr("tcode");
if (ruleTester.test(code)) {
trainfiltered.push(self);
trains.splice(i, 1);
}
}
}
if (document.getElementById("autoorder_method").selectedIndex == 0) {
$.each(seatLevelOrder, function () {
var scode = this;
for (var i in trainfiltered) {
var t = trainfiltered[i];
if (t.find("td[scode=" + this + "][result=2]").length) {
var tcode = scode == "empty" ? "1" : scode;
window.localStorage.setItem("autoSelect_preSelectSeatType", tcode);
$("#preSelectSeat").val(tcode)
if (document.getElementById("autoBookTip").checked) {
window.localStorage["bookTip"] = 1;
}
t.find(orderButtonClass).click();
return false;
}
}
return true;
});
} else {
//车次优先
$.each(trainfiltered, function () {
var t = this;
for (var i in seatLevelOrder) {
var scode = seatLevelOrder[i];
if (t.find("td[scode=" + scode + "][result=2]").length) {
var tcode = scode == "empty" ? "1" : scode;
window.localStorage.setItem("autoSelect_preSelectSeatType", tcode);
$("#preSelectSeat").val(tcode)
if (document.getElementById("autoBookTip").checked) {
window.localStorage["bookTip"] = 1;
}
t.find(orderButtonClass).click();
return false;
}
}
return true;
});
}
}
}
if (ticketValid) {
onticketAvailable();
} else if (document.getElementById("autoRequery").checked) {
onNoTicket();
startTimer();
}
});
//系统繁忙时自动重复查询 chkAutoResumitOrder
$("#orderForm").submit(function () {
if ($("#chkAutoResumitOrder")[0].checked) {
parent.$("#orderForm").remove();
parent.$("body").append($("#orderForm").clone(false).attr("target", "main").attr("success", "0"));
}
});
$("body").ajaxComplete(function (e, r, s) {
if (!$("#chkAutoRequery")[0].checked) return;
if (s.url.indexOf("/otsweb/order/querySingleAction.do") != -1 && r.responseText == "-1") {
//invalidQueryButton();
//delayButton();
//startTimer();
} else {
$("#serverMsg").html("");
}
});
$("body").ajaxError(function (e, r, s) {
if (s.url.indexOf("queryLeftTicket") == -1) return;
if (!$("#chkAutoRequery")[0].checked) return;
if (s.url.indexOf("/otsweb/order/querySingleAction.do") != -1) {
delayButton();
startTimer();
}
});
//Hack掉原来的系统函数。丫居然把所有的click事件全部处理了,鄙视
window.invalidQueryButton = function () {
var queryButton = $("#submitQuery");
queryButton.unbind("click", sendQueryFunc);
if (queryButton.attr("class") == "research_u") {
renameButton("research_x");
} else if (queryButton.attr("class") == "search_u") {
renameButton("search_x");
}
}
//#endregion
//#region 配置加载、保存、权限检测
//通知权限
if (!window.webkitNotifications || window.webkitNotifications.checkPermission() == 0) {
$("#enableNotify").remove();
}
//保存信息
function saveStateInfo() {
if (!$("#keepinfo")[0].checked || $("#fromStationText")[0].disabled) return;
utility.setPref("_from_station_text", $("#fromStationText").val());
utility.setPref("_from_station_telecode", $("#fromStation").val());
utility.setPref("_to_station_text", $("#toStationText").val());
utility.setPref("_to_station_telecode", $("#toStation").val());
utility.setPref("_depart_date", $("#startdatepicker").val());
utility.setPref("_depart_time", $("#startTime").val());
}
$("#submitQuery, #stu_submitQuery").click(saveStateInfo);
//回填信息
if (!$("#fromStationText")[0].disabled) {
var FROM_STATION_TEXT = utility.getPref('_from_station_text'); // 出发站名称
var FROM_STATION_TELECODE = utility.getPref('_from_station_telecode'); // 出发站电报码
var TO_STATION_TEXT = utility.getPref('_to_station_text'); // 到达站名称
var TO_STATION_TELECODE = utility.getPref('_to_station_telecode'); // 到达站电报码
var DEPART_DATE = utility.getPref('_depart_date'); // 出发日期
var DEPART_TIME = utility.getPref('_depart_time'); // 出发时间
if (FROM_STATION_TEXT) {
$("#fromStationText").val(FROM_STATION_TEXT);
$("#fromStation").val(FROM_STATION_TELECODE);
$("#toStationText").val(TO_STATION_TEXT);
$("#toStation").val(TO_STATION_TELECODE);
$("#startdatepicker").val(DEPART_DATE);
$("#startTime").val(DEPART_TIME);
}
}
//音乐
if (!window.Audio) {
$(".musicFunc").hide();
}
//#endregion
//#region 时间快捷修改
(function () {
var datebox = $("table.cx_from tr:eq(0) td:eq(5), table.cx_from tr:eq(1) td:eq(3)");
datebox.width("170px");
datebox.find("input").width("70px").before('<input type="button" class="date_prev lineButton" value="<">').after('<input type="button" class="date_next lineButton" value=">">');
datebox.find(".date_prev").click(function () { var dobj = $(this).next(); dobj.val(utility.formatDate(utility.addTimeSpan(utility.parseDate(dobj.val()), 0, 0, -1, 0, 0, 0))).change(); });
datebox.find(".date_next").click(function () { var dobj = $(this).prev(); dobj.val(utility.formatDate(utility.addTimeSpan(utility.parseDate(dobj.val()), 0, 0, 1, 0, 0, 0))).change(); });
})();
//#endregion
//#region 自动轮询,自动更改时间
(function () { //初始化UI
var html = "<tr class='fish_sep' id='autoChangeDateRow'><td class='name'>查询日期</td><td>\
<label><input type='checkbox' id='autoCorrentDate' checked='checked' /> 查询日期早于或等于今天时,自动修改为明天</label>\
</td><td class='name'>自动轮查</td><td><label><input type='checkbox' id='autoChangeDate' /> 无票时自动更改日期轮查</label>\
</td></tr><tr class='fish_sep' style='display:none;'><td class='name'>轮查日期设置</td><td colspan='3' id='autoChangeDateList'></td></tr>\
";
$("#helperbox_bottom").before(html);
var autoChangeDateList = $("#autoChangeDateList");
var html = [];
var now = new Date();
for (var i = 0; i < 20; i++) {
now = utility.addTimeSpan(now, 0, 0, 1, 0, 0, 0);
html.push("<label style='margin-right:16px;'><input type='checkbox' value='" + utility.formatDate(now) + "' cindex='" + i + "' />" + utility.formatDateShort(now) + "</label>");
if ((i + 1) % 10 == 0)
html.push("<br />");
}
autoChangeDateList.html(html.join(""));
$("#autoChangeDate").change(function () {
var tr = $(this).closest("tr").next();
if (this.checked) tr.show();
else tr.hide();
});
//配置
utility.reloadPrefs($("#autoChangeDateRow"), "autoChangeDateRow");
//日期点选
var stKey = "autoChangeDateRow_dates";
var stValue = window.localStorage.getItem(stKey);
if (typeof (stValue) != 'undefined' && stValue) {
var array = stValue.split('|');
autoChangeDateList.find(":checkbox").each(function () {
this.checked = $.inArray(this.value, array) != -1;
});
}
autoChangeDateList.find(":checkbox").change(function () {
var value = $.map(autoChangeDateList.find(":checkbox:checked"), function (e, i) { return e.value; }).join("|")
window.localStorage.setItem(stKey, value);
});
})();
(function () {
//如果当前查询日期在当前日期或之前,那么自动修改日期
$("#startdatepicker, #roundTrainDate").change(function () {
if (!document.getElementById("autoCorrentDate").checked) return;
var obj = $(this);
var val = utility.parseDate(obj.val());
var tomorrow = utility.addTimeSpan(utility.getDate(new Date()), 0, 0, 1, 0, 0, 0);
if (!val || isNaN(val.getFullYear()) || tomorrow > val) {
console.log("自动修改日期为 " + utility.formatDate(tomorrow));
obj.val(utility.formatDate(tomorrow));
}
}).change();
})();
onNoTicket = (function (callback) {
return function () {
//Hook onNoTicket
callback();
if (!document.getElementById("autoChangeDate").checked) return;
console.log("自动轮询日期中。");
var index = parseInt($("#autoChangeDate").attr("cindex"));
if (isNaN(index)) index = -1;
var current = index == -1 ? [] : $("#autoChangeDateList :checkbox:eq(" + index + ")").parent().nextAll(":has(:checked):eq(0)").find("input");
if (current.length == 0) {
index = 0;
current = $("#autoChangeDateList :checkbox:checked:first");
if (current.length == 0) return; //没有选择任何
}
index = current.attr("cindex");
if (current.length > 0) {
$("#autoChangeDate").attr("cindex", index);
$("#startdatepicker").val(current.val());
//高亮
$("#cx_titleleft span").css({ color: 'red', 'font-weight': 'bold' });
}
};
}
)(onNoTicket);
//#endregion
//#region 拦截弹出的提示框,比如服务器忙
(function () {
var _bakAlert = window.alert;
window.alert = function (msg) {
if (msg.indexOf("服务器忙") != -1) {
$("#serverMsg").text(msg);
} else _bakAlert(msg);
}
})();
//#endregion
//#region 默认加入拦截Ajax缓存
(function () { $.ajaxSetup({ cache: false }); })();
//#endregion
//#region 显示所有的乘客
var list_autoorder = null;
var list_blacklist = null;
var list_whitelist = null;
function isTrainInBlackList(trainNo) {
/// <summary>返回指定的车次是否在黑名单中</summary>
return document.getElementById("swBlackList").checked && (list_blacklist.isInRegList(trainNo)) && !(document.getElementById("swWhiteList").checked && list_whitelist.isInRegList(trainNo));
}
function putTrainCodeToList() {
var code = $(this).closest("tr").attr("tcode");
if (confirm("是否要将【" + code + "】加入自动预定列表?如果不是,请点击取消并继续选择是否加入黑名单或白名单。")) {
list_autoorder.add(code);
} else if (confirm("是否要将【" + code + "】加入黑名单?如果不是,请点击取消并继续选择是否加入白名单。")) {
list_blacklist.add(code);
} else if (confirm("是否要将【" + code + "】加入白名单?")) {
list_whitelist.add(code);
};
}
(function () {
var html = "\
<tr class='fish_sep caption'><td><label><input type='checkbox' id='swWhiteList' checked='checked' /> 车次白名单</label></td><td style='font-weight:normal;' colspan='2'>加入白名单的车次,将不会被过滤(仅为搭配黑名单)</td><td style='text-align:rigth;'><button class='fish_button' id='btnAddWhite'>添加</button><button class='fish_button' id='btnClearWhite'>清空</button></td></tr>\
<tr class='fish_sep'><td colspan='4' id='whiteListTd'></td></tr>\
<tr class='fish_sep caption'><td><label><input type='checkbox' id='swBlackList' checked='checked' name='swBlackList' />车次黑名单</label></td><td style='font-weight:normal;' colspan='2'>加入黑名单的车次,除非在白名单中,否则会被直接过滤而不会显示</td><td style='text-align:rigth;'><button class='fish_button' id='btnAddBlack'>添加</button><button class='fish_button' id='btnClearBlack'>清空</button></td></tr>\
<tr class='fish_sep'><td colspan='4' id='blackListTd'></td></tr>\
<tr class='caption autoorder_steps fish_sep' id='selectPasRow'><td colspan='3'><span class='hide indicator'>① </span>自动添加乘客 (加入此列表的乘客将会自动在提交订单的页面中添加上,<strong>最多选五位</strong>)</td><td><input type='button' class='fish_button' onclick=\"self.location='/otsweb/passengerAction.do?method=initAddPassenger&';\" value='添加联系人' /> (提示:新加的联系人五分钟之内无法订票)</td></tr>\
<tr class='fish_sep'><td class='name'>未选择</td><td id='passengerList' colspan='3'><span style='color:gray; font-style:italic;'><div id='prUser' style='display:none'></div>联系人列表正在加载中,请稍等...如果长时间无法加载成功,请尝试刷新页面 x_x</span></td></tr>\
<tr class='fish_sep'><td class='name'>已选择</td><td id='passengerList1' colspan='3'></td></tr>\
<tr class='fish_sep autoordertip' style='display:none;'><td class='name'>部分提交订单</td><td><label><input type='checkbox' id='autoorder_part' /> 当票数不足时,允许为部分的联系人先提交订单</label></td><td class='name'>提交为学生票</td><td><label><input type='checkbox' id='autoorder_stu' /> 即使是普通查询,也为学生联系人提交学生票</label></td></tr>\
<tr class='fish_sep autoorder_steps caption' id='seatLevelRow'><td><span class='hide indicator'>② </span>席别优先选择</td><td><input type='hidden' id='preSelectSeat' /><select id='preSelectSeatList'></select> (选中添加,点击按钮删除;<a href='http://www.fishlee.net/soft/44/tour.html' target='_blank'>更多帮助</a>)</td><td style='text-align:right;'>卧铺优选</td><td><select id='preselectseatlevel'></select>(不一定有用的啦……呵呵呵呵呵呵……)</td></tr>\
<tr class='fish_sep'><td colspan='4' id='preseatlist'><div id='preseatlist_empty' style='padding:5px; border: 1px dashed gray; background-color:#eee;width:200px;'>(尚未指定,请从上面的下拉框中选定)</div></td></tr>\
<tr class='fish_sep autoorder_steps caption'><td><label><input type='checkbox' id='swAutoBook' name='swAutoBook' checked='checked' /><span class='hide indicator'>③</span> 自动预定</label></td><td colspan='2' style='font-weight:normal;'><select id='autoorder_method'><option value='0'>席别优先</option><option value='1'>车次优先</option></select>如果启用,符合规则的车次的特定席别有效时,将会进入预定页面</td><td style='text-align:rigth;'><button id='btnAddAutoBook' class='fish_button'>添加</button><button id='btnClearAutoBook' class='fish_button'>清空</button></td></tr>\
<tr class='fish_sep'><td colspan='4' id='autobookListTd'></td></tr>\
<tr class='fish_sep'><td colspan='4'><label><input type='checkbox' id='autoBookTip' checked='checked' /> 如果自动预定成功,进入预定页面后播放提示音乐并弹窗提示</label></td></tr>\
<tr class='fish_sep autoordertip' style='display:none;'><td class='name'>自动回滚</td><td><label><input type='checkbox' id='autoorder_autocancel' /> 自动提交失败时,自动取消自动提交并再次预定</label></td></tr>\
<tr class='caption autoorder_steps fish_sep highlightrow'><td class='name autoordertd'><label style='display:none;color:red;'><input type='checkbox' id='autoorder'/>自动提交订单</label></td><td class='autoordertd' colspan='3'><p style='display:none;'><img id='randCode' src='/otsweb/passCodeAction.do?rand=randp' /> <input size='4' maxlength='4' type='text' id='randCodeTxt' /> (验证码可在放票前填写,临近放票时建议点击图片刷新并重新填写,以策安全。请务必控制好阁下的眼神……)</p></td></tr>\
<tr style='display:none;' class='autoordertip fish_sep'><td class='name' style='color:red;'>警告</td><td colspan='3' style='color:darkblue;'>\
<p style='font-weight:bold; color:purple;'>自动提交订单使用流程:勾选要订票的联系人 -> 设置需要的席别 -> 将你需要订票的车次按优先级别加入自动预定列表 -> 勾选自动提交订单 -> 输入验证码 -> 开始查票。信息填写不完整将会导致助手忽略自动提交订单,请务必注意。进入自动订票模式后,席别选择和自动预定都将被锁定而无法手动切换。如果查询的是学生票,那么提交的将会是学生票订单。<u style='color:red;'>一切都设置完成后,请点击查询开始查票。一旦有票将会自动提交。</u></p>\
<p>1. 自动提交订单使用的是自动预定的列表顺序,取第一个有效的车次自动提交订单!请确认设置正确!!</p>\
<p>2. 自动提交的席别和联系人请在上方选择,和预设的是一致的,暂不支持不同的联系人选择不同的席别;</p>\
<p>3. 作者无法保证自动提交是否会因为铁老大的修改失效,因此请务必同时使用<b>其它浏览器</b>手动提交订单!否则可能会造成您不必要的损失!</p>\
<p style='font-weight:bold;'>5. 当助手第一次因为功能性自动提交失败后(非网络错误和验证码错误,如余票不足、占座失败等),将会立刻禁用自动提交并回滚到普通提交,并再次提交订票请求,因此请时刻注意提交结果并及时填写内容,并强烈建议你另外打开单独的浏览器同时手动下订单!!</p>\
<p style='font-weight:bold;color:darkcylan;'>6. 为可靠起见,建议每隔一段时间刷新下验证码重新填写(点击验证码图片刷新)。由于不同的浏览器刷新的结果不一样,强烈建议多个浏览器或多台机子一起刷新!</p>\
<p style='font-size:16px; font-weight:bold;color:blue;'>一定要仔细看说明啊!切记多个浏览器准备不要老想着一棵树上吊死啊!千万不要因为自动提交订单导致你订不到票啊!!这样老衲会内疚的啊!!!!</p>\
</td></tr>";
$("#helpertooltable tr:first").addClass("fish_sep").before(html);
//优选逻辑
$("#autoorder_method").val(window.localStorage["autoorder_method"] || "0").change(function () { window.localStorage.setItem("autoorder_method", $(this).val()); });
$("#autoorder_autocancel").attr("checked", (window.localStorage["autoorder_autocancel"] || "1") == "1").change(function () { window.localStorage.setItem("autoorder_autocancel", this.checked ? "1" : "0"); });
//自动预定列表
list_autoorder = utility.selectionArea.call($("#autobookListTd"), { syncToStorageKey: "list_autoBookList", onAdd: onAutoOrderRowStyle, onRemove: onAutoOrderRowStyle, onClear: onAutoOrderRowStyle });
list_blacklist = utility.selectionArea.call($("#blackListTd"), { syncToStorageKey: "list_blackList" });
list_whitelist = utility.selectionArea.call($("#whiteListTd"), { syncToStorageKey: "list_whiteList" });
var autoBookHeader = $("#swAutoBook").closest("tr");
function onAutoOrderRowStyle() {
if (!document.getElementById("autoorder").checked) return;
autoBookHeader.removeClass("steps stepsok");
autoBookHeader.addClass(list_autoorder.datalist.length ? "stepsok" : "steps");
}
function appendTrainCodeToList(target) {
var code = prompt("请输入您要加入列表的车次。车次可以使用正则表达式(亲,不知道的话请直接填写车次编号喔),比如 【.*】(不包括【】号) 可以代表所有车次,【K.*】可以代表所有K字头的车次,【D.*】可以代表所有D字头车次等等");
if (!code) return;
//修正部分符号
code = code.replace(/(,|,|\/|\\|、|-)/g, "|");
try {
new RegExp(code);
} catch (e) {
alert("嗯……看起来同学您输入的不是正确的正则表达式哦。");
return;
}
target.add(code);
}
function emptyList(target) {
target.emptyList();
}
//绑定添加清空事件
$("#btnAddAutoBook").click(function () { appendTrainCodeToList(list_autoorder); });
$("#btnAddWhite").click(function () { appendTrainCodeToList(list_whitelist); });
$("#btnAddBlack").click(function () { appendTrainCodeToList(list_blacklist); });
$("#btnClearAutoBook").click(function () { emptyList(list_autoorder); });
$("#btnClearWhite").click(function () { emptyList(list_whitelist); });
$("#btnClearBlack").click(function () { emptyList(list_blacklist); });
$("#swBlackList, #swAutoBook").each(function () {
var obj = $(this);
var name = obj.attr("name");
var opt = localStorage.getItem(name);
if (opt != null) this.checked = opt == "1";
}).change(function () {
var obj = $(this);
var name = obj.attr("name");
localStorage.setItem(name, this.checked ? "1" : "0");
});
var seatlist = [
["", "=请选择="],
["9", "商务座"],
["P", "特等座"],
["6", "高级软卧"],
["4", "软卧"],
["3", "硬卧"],
["2", "软座"],
["1", "硬座"],
["empty", "硬座(无座)"],
["M", "一等座"],
["O", "二等座"]
];
var level = [[0, '随机'], [3, "上铺"], [2, '中铺'], [1, '下铺']];
var seatDom = document.getElementById("preSelectSeatList");
var seatLevelDom = document.getElementById("preselectseatlevel");
$.each(seatlist, function () {
seatDom.options[seatDom.options.length] = new Option(this[1], this[0]);
});
$.each(level, function () {
seatLevelDom.options[seatLevelDom.options.length] = new Option(this[1], this[0]);
});
//刷新优选列表
var seatLevelRow = $("#seatLevelRow");
function refreshSeatTypeOrder() {
var list = $("#preseatlist input");
if (initialized) $(":checkbox[name=seatoption]").attr("checked", false).change();
seatLevelOrder = [];
list.each(function () {
var code = $(this).attr("code");
seatLevelOrder.push(code);
if (initialized) $("#seatoption_" + code).attr("checked", true).change();
});
if (!list.length) {
$("#preseatlist_empty").show();
$(":checkbox[name=seatoption]").attr("checked", true).change();
window.localStorage.setItem("autoSelect_preSelectSeatType", "");
} else {
$("#preseatlist_empty").hide();
window.localStorage.setItem("autoSelect_preSelectSeatType", seatLevelOrder[0]);
}
if (initialized) utility.notifyOnTop("已经根据您选择的席别自动切换了席别过滤选项,请注意,并作出需要的调整。");
window.localStorage.setItem("preSelectSeatType", seatLevelOrder.join('|'));
if (document.getElementById("autoorder").checked) {
seatLevelRow.removeClass("stepsok steps");
seatLevelRow.addClass(seatLevelOrder.length ? "stepsok" : "steps");
}
}
//选中后添加到列表中
$("#preSelectSeatList").change(function () {
var index = seatDom.selectedIndex;
if (index == 0) return;
//添加
var opt = seatDom.options[index];
var html = "<input type='button' title='点击删除' class='seatTypeButton lineButton' value='" + opt.text + "' code='" + opt.value + "' />";
$("#preseatlist").append(html);
$("#preseatlist_empty").hide();
//当前选项移除
seatDom.options[index] = null;
seatDom.selectedIndex = 0;
refreshSeatTypeOrder();
});
//席别的按钮点击后自动删除
$("input.seatTypeButton").live("click", function () {
var btn = $(this);
btn.remove();
//加回列表
var code = btn.attr("code");
var name = btn.val();
seatDom.options[seatDom.options.length] = new Option(name, code);
//刷新列表
refreshSeatTypeOrder();
});
(function () {
var preseattype = window.localStorage.getItem("preSelectSeatType") || window.localStorage.getItem("autoSelect_preSelectSeatType");
if (!preseattype) return;
preseattype = preseattype.split('|');
var el = $(seatDom);
$.each(preseattype, function () { el.val(this + ""); el.change(); });
})();
$(seatLevelDom).val(window.localStorage.getItem("preselectseatlevel") || "").change(function () {
window.localStorage.setItem("preselectseatlevel", $(this).val());
});
var pre_autoorder_book_status;
$("#autoorder").click(function () {
if (this.checked) {
pre_autoorder_book_status = document.getElementById("swAutoBook").checked;
document.getElementById("swAutoBook").checked = true;
//alert("警告!选中将会启用自动下单功能,并取代自动预定功能,请输入验证码,当指定的车次中的指定席别可用时,助手将会为您全自动下单。\n\n请确认您设置了正确的车次和席别!\n\n但是,作者无法保证是否会因为铁道部的修改导致失效,请使用此功能的同时务必使用传统的手动下单以保证不会导致您的损失!");
}
document.getElementById("swAutoBook").disabled = this.checked;
if (this.checked) {
$(".autoordertip").show();
$(":checkbox[name=seatoption]").attr("disabled", true);
refreshSeatTypeOrder();
onAutoOrderRowStyle();
}
else {
$(".autoordertip").hide();
document.getElementById("swAutoBook").checked = pre_autoorder_book_status;
$(":checkbox[name=seatoption]").attr("disabled", false);
$("tr.autoorder_steps").removeClass("steps").removeClass("stepsok");
}
});
//禁用自动预定
//加载乘客
utility.getAllPassengers(function (list) {
var h = [];
var check = (localStorage.getItem("preSelectPassenger") || "").split('|');
var index = 0;
$.each(list, function () {
var value = this.passenger_name + this.passenger_id_type_code + this.passenger_id_no;
this.index = index++;
h.push("<label style='margin-right:10px;'><input type='checkbox' id='preSelectPassenger" + this.index + "' name='preSelectPassenger'" + ($.inArray(value, check) > -1 ? " checked='checked'" : "") + " value='" + value + "' />" + this.passenger_name + "</label>");
});
$("#passengerList").html(h.join("")).find("input").change(function () {
var self = $(this).closest("label");
if (this.checked) {
var selected = $("#passengerList1 :checkbox");
if (selected.length >= 5) {
alert("选择的乘客不能多于五位喔~~");
this.checked = false;
return;
}
$("#passengerList1").append(self);
} else {
$("#passengerList").append(self);
}
selected = $("#passengerList1 :checkbox");
var user = $.map(selected, function (e) { return e.value; });
$("#ticketLimition").val(selected.length);
localStorage.setItem("preSelectPassenger", user.join("|"));
refreshPasRowStyle(user);
});
$.each(check, function () {
$("#passengerList :checkbox[value=" + this + ']').change();
});
$.each(list, function () {
$("#preSelectPassenger" + this.index).data('pasinfo', this);
});
$("#ticketLimition").val($("#passengerList1 :checkbox").length);
function refreshPasRowStyle(selected) {
if (!document.getElementById("autoorder").checked) return;
var row = $("#selectPasRow");
row.removeClass("steps stepsok");
row.addClass(selected.length ? "stepsok" : "steps");
}
$("#autoorder").click(function () { refreshPasRowStyle($("#passengerList1 :checkbox")); });
});
})();
//#endregion
//#region 预定界面加载快速查询链接
(function () {
var html = [];
html.push("<tr class='caption fish_sep'><td colspan='4'>快速查询链接</strong></td></tr>");
html.push("<tr class='fish_sep'><td colspan='4'>");
var urls = [
["各始发站放票时间查询", "http://www.12306.cn/mormhweb/zxdt/tlxw_tdbtz53.html"]
];
$.each(urls, function () {
html.push("<div style='float:left;'><a href='" + this[1] + "' target='_blank'>" + this[0] + "</a></div>");
});
html.push("</td></tr>");
$("#helpertooltable tr:last").before(html.join(""));
})();
//#endregion
//#region 余票数限制
(function () {
var html = [];
html.push("<tr class='caption'><td colspan='4'>票数限制</strong></td></tr>");
html.push("<tr class='fish_sep'><td><strong>最小票数</strong><td colspan='3'><select id='ticketLimition'></select>");
html.push("介个就是说……如果票票数小于这里的数字的话……就无视的啦 =。=</td></tr>");
$("#helpertooltable tr:first").addClass("fish_sep").before(html.join(""));
var dom = $("#ticketLimition").val($("#passengerList1 :checkbox").length)[0];
for (var i = 0; i < 6; i++) {
dom.options[i] = new Option(i ? i : "(无限制)", i);
}
//注册检测函数
checkTicketCellsQueue.push(function (i, e, prevValue) {
var limit = parseInt(dom.value);
if (!prevValue || !(limit > 0) || $("#autoorder_part:visible:checked").length) return null;
var text = $.trim(e.text());
if (text == "有") return 2;
return parseInt(text) >= limit ? 2 : 1;
});
})();
//#endregion
//#region 保存查询车次类型配置
(function () {
var ccTypeCheck = $("input:checkbox[name=trainClassArr]");
var preccType = (utility.getPref("cctype") || "").split("|");
if (preccType[0]) {
ccTypeCheck.each(function () {
this.checked = $.inArray(this.value, preccType) != -1;
});
}
ccTypeCheck.click(function () {
utility.setPref("cctype", $.map(ccTypeCheck.filter(":checked"), function (v, i) {
return v.value;
}).join("|"));
});
})();
//#endregion
//#region 增加互换目标的功能
(function () {
var fromCode = $("#fromStation");
var from = $("#fromStationText");
var toCode = $("#toStation");
var to = $("#toStationText");
from.css("width", "50px").after("<input type='button' value='<->' class='lineButton' title='交换出发地和目的地' id='btnExchangeStation' />");
$("#btnExchangeStation").click(function () {
var f1 = fromCode.val();
var f2 = from.val();
fromCode.val(toCode.val());
from.val(to.val());
toCode.val(f1);
to.val(f2);
});
})();
//#endregion
//#region 要求发到站和终点站完全匹配
(function () {
var fromText = $("#fromStationText");
var toText = $("#toStationText");
$("#filterFunctionRow").append("<label style='font-weight:bold;color:red;margin-left:10px;'><input type='checkbox' id='closeFuseSearch'>过滤发站不完全匹配的车次</label><label style='font-weight:bold;color:red;margin-left:10px;'><input type='checkbox' id='closeFuseSearch1'>过滤到站不完全匹配的车次</label>");
$("#closeFuseSearch, #closeFuseSearch1").parent().attr("title", '默认情况下,例如查找‘杭州’时,会包括‘杭州南’这个车站。勾选此选项,将会在搜索‘杭州’的时候,过滤那些不完全一致的车站,如‘杭州南’。');
function getStationName() {
var txt = $.trim(this.text()).split(/\s/);
return txt[0];
}
checkTicketsQueue.push(function (result) {
if (document.getElementById("closeFuseSearch").checked) {
var fs = getStationName.call(this.find("td:eq(1)"));
if (fs != fromText.val()) {
this.hide();
return 0;
}
}
if (document.getElementById("closeFuseSearch1").checked) {
var fs = getStationName.call(this.find("td:eq(2)"));
if (fs != toText.val()) {
this.hide();
return 0;
}
}
return result;
});
})();
//#endregion
//#region 保持在线
var time_offset = null;
var time_server = null;
(function () {
$("#helpertooltable tr:last").before("<tr class='fish_sep'><td class='name'>保持在线</td><td colspan='3'>助手每隔十分钟会帮你刷新存在感防止挂机而掉线的啦。。。。。最后刷新时间:<strong id='lastonlinetime'>无</strong></td></tr>");
var label = $("#lastonlinetime");
function online() {
var serverTime = null;
utility.post("/otsweb/main.jsp", null, "text", function (data, status, xhr) {
serverTime = new Date(xhr.getResponseHeader("Date"));
time_offset = new Date() - serverTime;
label.html(utility.formatTime(serverTime));
});
}
online();
setInterval(online, 600 * 1000);
})();
//显示本地时间和服务器时间
(function () {
var dom = $("#servertime strong");
function display() {
if (time_offset === null) return;
var now = new Date();
time_server = new Date();
time_server.setTime(now.getTime() - time_offset);
document.getElementById("chkSmartSpeed").disabled = time_server.getFullYear() < 2000;
dom.eq(0).html(utility.formatTime(time_server));
dom.eq(1).html(utility.formatTime(now));
dom.eq(2).html((time_offset < 0 ? "快" : "慢") + (Math.abs(time_offset) / 1000) + "秒");
}
setInterval(display, 1000);
display();
})();
//#endregion
//#region 车票模式配置
(function () {
$("#helpertooltable tr:first").before("<tr class='fish_sep caption'><td class='name' colspan='4'>出行模式</td></tr>\
<tr class='fish_sep'><td colspan='2'><select id='profilelist'><option value=''>===选择一个出行模式===</option></select><button id='profile_save' class='fish_button'>保存</button><button id='profile_add' class='fish_button'>另存</button><button id='profile_delete' class='fish_button'>删除</button><button id='profile_reset' class='fish_button'>重置所有选项</button></td><td colspan='2'>出行模式可以帮你快速的保存一系列设置,如联系人、车次、席别、黑名单和白名单</td>\
</tr>\
");
var list = (window.localStorage["profilelist"] || "").split("\t");
var listDom = $("#profilelist");
var listEle = listDom[0];
if (list[0] == "") list.splice(0, 1);
$.each(list, function () {
listEle.options[listEle.options.length] = new Option(this + '', this + '');
});
listDom.change(function () {
var value = listDom.val();
if (!value) return;
applyProfile(loadProfile(value));
});
$("#profile_save").click(function () {
if (!listDom.val()) $("#profile_add").click();
else {
saveProfile(listDom.val(), generateProfile());
alert("存档已经更新~");
}
});
$("#profile_add").click(function () {
var data = generateProfile();
var name = prompt("请输入出行模式的名称,如『出去鬼混』神马的……", "嗷嗷回家~");
if (!name) return;
name = name.replace(/\s+/g, "");
if (window.localStorage.getItem("profile_" + name)) {
alert("啊嘞?这个名字的已经有了喔,重试呗~");
} else {
saveProfile(name, data);
list.push(name);
listEle.options[listEle.options.length] = new Option(name, name);
window.localStorage.setItem("profilelist", list.join("\t"));
alert("已保存唷。");
}
});
$("#profile_delete").click(function () {
var idx = listEle.selectedIndex;
if (!idx || !confirm("亲,确定要下此狠手咩?")) return;
listEle.options[idx] = null;
window.localStorage.removeItem("profile_" + list[idx - 1]);
list.splice(idx - 1, 1);
window.localStorage.setItem("profilelist", list.join("\t"));
alert("乃伊佐特~");
});
$("#profile_reset").click(function () {
listDom.val("");
applyProfile({ "blackListEnabled": true, "whiteListEnabled": true, "autoBookListEnabled": true, "seatOrder": [], "prePassenger": [], "whiteList": [], "blackList": [], "autoBookList": [], "autoBookMethod": "1" });
});
function loadProfile(name) {
return $.parseJSON(window.localStorage.getItem("profile_" + name));
}
function saveProfile(name, profile) {
if (!profile) window.localStorage.removeItem(name);
else window.localStorage.setItem("profile_" + name, $.toJSON(profile));
}
function generateProfile() {
var pro = {};
pro.blackListEnabled = document.getElementById("swBlackList").checked;
pro.whiteListEnabled = document.getElementById("swWhiteList").checked;
pro.autoBookListEnabled = document.getElementById("swAutoBook").checked;
pro.seatOrder = seatLevelOrder;
pro.prePassenger = $.map($("#passengerList1 :checkbox"), function (e) {
var data = $(e).data("pasinfo");
return { type: data.passenger_type, idtype: data.passenger_id_type_code, id: data.passenger_id_no };
});;
pro.whiteList = list_whitelist.datalist;
pro.blackList = list_blacklist.datalist;
pro.autoBookList = list_autoorder.datalist;
pro.autoBookMethod = $("#autoorder_method").val();
pro.queryInfo = $("#querySingleForm").serializeArray();
return pro;
}
function applyProfile(pro) {
$("#swBlackList").attr("checked", pro.blackListEnabled).change();
$("#swWhiteList").attr("checked", pro.whiteListEnabled).change();
$("#swAutoBook").attr("checked", pro.autoBookListEnabled).change();
//清除席别优选
$("#preseatlist input").click();
var seatList = $("#preSelectSeatList");
$.each(pro.seatOrder, function () {
seatList.val(this + '').change();
});
//黑名单白名单神马的。
list_whitelist.emptyList();
$.each(pro.whiteList, function () { list_whitelist.add(this + ''); });
list_blacklist.emptyList();
$.each(pro.blackList, function () { list_blacklist.add(this + ''); });
list_autoorder.emptyList();
$.each(pro.autoBookList, function () { list_autoorder.add(this + ''); });
//联系人
var plist = $("input:checkbox[name=preSelectPassenger]");
plist.attr("checked", false);
plist.change();
$.each(pro.prePassenger, function () {
var p = this;
plist.each(function () {
var data = $(this).data("pasinfo");
if (data.passenger_type == p.type && data.passenger_id_type_code == p.idtype && data.passenger_id_no == p.id) {
this.checked = true;
$(this).change();
return false;
}
return true;
});
});
//优选方式
$("#autoorder_method").val(pro.autoBookMethod).change();
//查询方式
if (pro.queryInfo) {
$.each(pro.queryInfo, function () {
if (this.name.indexOf("orderRequest.") == -1) return;
$("input[name=" + this.name + "]").val(this.value).change();
});
}
utility.notifyOnTop("已加载出行模式");
}
})();
//#endregion
utility.reloadPrefs($("tr.append_row"), "ticket_query");
//完成初始化
initialized = true;
parent.$("#main").css("height", ($(document).height() + 300) + "px");
parent.window.setHeight(parent.window);
}
//#endregion
//#region 自动提交订单
function initDirectSubmitOrder() {
//if (Math.random() > 0.10) return;
console.log("[INFO] initialize direct submit order.");
var html = "<div id='fishSubmitFormStatus' class='outerBox' style='position:fixed;left:0px;bottom:-100px;'><div class='box'><div class='title'>自动提交订单中</div>\
<div class='content' style='width:150px;'><ul id='tipScript'>\
<li class='fish_clock' id='countEle' style='font-weight:bold;'>等待操作</li>\
<li style='color:green;'><strong>操作信息</strong>:<span>休息中</span></li>\
<li style='color:green;'><strong>最后操作时间</strong>:<span>--</span></li></div>\
</div></div>";
parent.window.$("#fishSubmitFormStatus").remove();
parent.window.$("body").append(html);
var tip = parent.window.$("#tipScript li");
var counter = parent.window.$("#countEle");
var status = parent.window.$("#fishSubmitFormStatus");
var formData = null;
var tourFlag;
var data = null;
$("#autoorder")[0].disabled = false;
function setCurOperationInfo(running, msg) {
counter.removeClass().addClass(running ? "fish_running" : "fish_clock").html(msg || (running ? "正在操作中……" : "等待中……"));
}
function setTipMessage(msg) {
tip.eq(2).find("span").html(utility.getTimeInfo());
tip.eq(1).find("span").html(msg);
}
//窗口状态
var statusShown = false;
function showStatus() {
if (statusShown) return;
statusShown = true;
status.animate({ bottom: "0px" });
}
function hideStatus() {
if (!statusShown) return;
statusShown = false;
status.animate({ bottom: "-100px" });
}
//验证码事件
var randRow = $("#randCodeTxt").closest("tr");
function refreshRandRowStyle() {
randRow.removeClass("steps stepsok");
randRow.addClass(getVcCode().length == 4 ? "stepsok" : "steps");
}
$("#randCodeTxt").keyup(function () {
refreshRandRowStyle();
if (statusShown && document.getElementById("randCodeTxt").value.length == 4) checkOrderInfo();
});
$("#autoorder").change(refreshRandRowStyle);
//刷新验证码
function reloadCode() {
$("#randCode").attr("src", "/otsweb/passCodeAction.do?rand=randp&" + Math.random());
var vcdom = document.getElementById("randCodeTxt");
vcdom.focus();
vcdom.select();
}
$("#randCode").click(reloadCode);
function getVcCode() {
return document.getElementById("randCodeTxt").value;
}
function isCanAutoSubmitOrder() {
if (!document.getElementById("autoorder").checked) return [];
var result = [];
if (!$("#passengerList1 :checkbox").length) result.push("选择乘客");
if (!$("#preseatlist input").length) result.push("设置优选席别");
if (getVcCode().length != 4) result.push("填写验证码");
if (!$("#autobookListTd input").length) result.push("设置自动预定车次");
return result;
}
function redirectToNotCompleteQuery() {
window.location.replace("/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y");
}
$("#orderForm").submit(function () {
if (!document.getElementById("autoorder").checked || isCanAutoSubmitOrder().length || !($("#preSelectSeat").val())) return true;
showStatus();
utility.notifyOnTop("开始自动提交预定订单!");
setCurOperationInfo(true, "正在自动提交订单");
//确定乘客
var tcode = $("#station_train_code").val();
var seatCode = $("#preSelectSeat").val();
var count = parseInt($.trim($("#gridbox tr[tcode=" + tcode + "] td[scode=" + seatCode + "]").text())) || 0;
if (seatCode == "1" && $("#preseatlist input[code=empty]").length) {
//允许了无座,那就加上无座的票数
count = parseInt($.trim($("#gridbox tr[tcode=" + tcode + "] td[scode=empty]").text())) || 0;
}
var pases = $("#passengerList1 :checkbox");
console.log("欲购票数=" + pases.length + ",实际票数=" + count + " (isNaN 为很多 =。=)");
if (!isNaN(count) && count > 0 && count < pases.length) {
$("#passengerList1 :checkbox:gt(" + (count - 1) + ")").attr("checked", false).change();
}
var form = $(this);
utility.post(form.attr("action"), form.serialize(), "text", function (html) {
if (html.indexOf("您还有未处理") != -1) {
hideStatus();
utility.notifyOnTop("您还有未处理订单!");
redirectToNotCompleteQuery();
return;
}
setTipMessage("正在分析内容");
getOrderFormInfo(html);
}, function () {
utility.notifyOnTop("提交预定请求发生错误,稍等重试!");
utility.delayInvoke(counter, function () { $("#orderForm").submit(); }, 2000);
});
return false;
});
function getOrderFormInfo(html) {
if (typeof (html) != 'undefined' && html) {
data = utility.analyzeForm(html);
data.fields["orderRequest.reserve_flag"] = "A"; //网上支付
tourFlag = data.tourFlag;
//组装请求
formData = [];
$.each(data.fields, function (i) {
if (i.indexOf("orderRequest") != -1 || i.indexOf("org.") == 0 || i == "leftTicketStr") formData.push(i + "=" + encodeURIComponent(this));
});
formData.push("tFlag=" + data.tourFlag);
//添加乘客
var pas = $("#passengerList1 :checkbox");
var seat = $("#preSelectSeat").val();
var seatType = $("#preselectseatlevel").val();
for (var i = 0; i < 5; i++) {
if (i >= pas.length) {
formData.push("oldPassengers=");
formData.push("checkbox9=");
continue;
}
var p = pas.eq(i).data("pasinfo");
var ptype = p.passenger_type;
var idtype = p.passenger_id_type_code;
var idno = p.passenger_id_no;
var name = p.passenger_name;
//学生票?
if (clickBuyStudentTicket != "Y" && ptype == "3" && !document.getElementById("autoorder_stu").checked) ptype = 1;
formData.push("passengerTickets=" + seat + "," + seatType + "," + ptype + "," + encodeURIComponent(name) + "," + idtype + "," + encodeURIComponent(idno) + "," + p.mobile_no + ",Y");
formData.push("oldPassengers=" + encodeURIComponent(name) + "," + idtype + "," + encodeURIComponent(idno));
formData.push("passenger_" + (i + 1) + "_seat=" + seat);
formData.push("passenger_" + (i + 1) + "_seat_detail=" + seatType);
formData.push("passenger_" + (i + 1) + "_ticket=" + ptype);
formData.push("passenger_" + (i + 1) + "_name=" + encodeURIComponent(name));
formData.push("passenger_" + (i + 1) + "_cardtype=" + idtype);
formData.push("passenger_" + (i + 1) + "_cardno=" + idno);
formData.push("passenger_" + (i + 1) + "_mobileno=" + p.mobile_no);
formData.push("checkbox9=Y");
}
}
checkOrderInfo();
}
function checkOrderInfo() {
setCurOperationInfo(true, "正在检测订单状态....");
utility.notifyOnTop("开始自动提交订单!");
utility.post("confirmPassengerAction.do?method=checkOrderInfo&rand=" + getVcCode(), formData.join("&") + "&randCode=" + getVcCode(), "json", function (data) {
console.log(data);
if ('Y' != data.errMsg || 'N' == data.checkHuimd || 'N' == data.check608) {
if (data.errMsg && data.errMsg.indexOf("验证码") != -1) {
utility.notifyOnTop("验证码不正确。请输入验证码!");
setTipMessage("请重新输入验证码。");
reloadCode();
} else {
setCurOperationInfo(false, data.msg || data.errMsg);
document.getElementById("autoorder").checked = false;
$("#orderForm").submit();
}
return;
}
queryQueueInfo();
}, function () {
setCurOperationInfo(false, "网络出现错误,稍等重试");
utility.delayInvoke(counter, checkOrderInfo, 2000);
});
}
function queryQueueInfo() {
setCurOperationInfo(true, "正在提交订单");
setTipMessage("正在检查队列。");
var queryLeftData = {
train_date: data.fields["orderRequest.train_date"],
station: data.fields["orderRequest.station_train_code"],
train_no: data.fields["orderRequest.train_no"],
seat: $("#preSelectSeat").val(),
from: data.fields["orderRequest.from_station_telecode"],
to: data.fields["orderRequest.to_station_telecode"],
ticket: data.fields["leftTicketStr"]
};
utility.get("/otsweb/order/confirmPassengerAction.do?method=getQueueCount", queryLeftData, "json", function (data) {
if (data.op_2) {
utility.notifyOnTop("排队人数过多,系统禁止排队,可以输入验证码重试!");
setTipMessage("排队人数过多 (人数=" + data.count + ")");
setCurOperationInfo(false, "排队人数过多");
reloadCode();
} else {
submitOrder();
}
}, function () { utility.delayInvoke(null, queryLeftTickets, 2000); });
}
function submitOrder() {
setCurOperationInfo(true, "正在提交订单");
setTipMessage("已检测状态。");
utility.post("/otsweb/order/confirmPassengerAction.do?method=confirmSingleForQueueOrder",
formData.join("&") + "&randCode=" + getVcCode(), "json", function (data) {
var msg = data.errMsg;
if (msg == "Y") {
setTipMessage("订单提交成功");
setCurOperationInfo(false, "订单提交成功,请等待排队完成。");
utility.notifyOnTop("订单提交成功,请等待排队完成。");
redirectToNotCompleteQuery();
} else {
if (msg.indexOf("包含未付款订单") != -1) {
hideStatus();
alert("您有未支付订单! 等啥呢, 赶紧点确定支付去.");
redirectToNotCompleteQuery();
return;
}
if (msg.indexOf("重复提交") != -1) {
setTipMessage("TOKEN失效,刷新Token中....");
$("#orderForm").submit();
return;
}
if (msg.indexOf("包含排队中") != -1) {
hideStatus();
alert("您有排队中订单! 点确定转到排队页面");
redirectToNotCompleteQuery();
return;
}
if (msg.indexOf("排队人数现已超过余票数") != -1) {
//排队人数超过余票数,那么必须重新提交
document.getElementById("autoorder").checked = false;
setTipMessage(msg);
reloadCode();
setCurOperationInfo(false, "警告:" + msg + ",自动回滚为手动提交,请切换车次或席别,请尽快重试!");
sendQueryFunc.call(clickBuyStudentTicket == "Y" ? document.getElementById("stu_submitQuery") : document.getElementById("submitQuery"));
return;
}
setTipMessage(msg);
setCurOperationInfo(false, "未知错误:" + msg + ",请告知作者。");
utility.notifyOnTop("未知错误:" + msg + ",请告知作者。");
if (document.getElementById("autoorder_autocancel").checked) {
document.getElementById("autoorder").checked = false;
$("#autoorder").change();
$("#orderForm").submit();
}
}
}, function () {
setCurOperationInfo(false, "网络出现错误,稍等重试");
utility.delayInvoke(counter, submitOrder, 2000);
});
}
//周期性检测状态,已确认可以自动提交
setInterval(function () {
if (document.getElementById("autoorder").checked) {
var r = isCanAutoSubmitOrder();
if (r.length) {
utility.notifyOnTop("您选择了自动提交订单,但是信息没有设置完整!请" + r.join("、") + "!");
}
}
}, 30 * 1000);
//最后显示界面,防止初始化失败却显示了界面
$("tr.autoordertd, td.autoordertd *").show();
}
//#endregion
//#region -----------------自动登录----------------------
function initLogin() {
//启用日志
utility.enableLog();
//如果已经登录,则自动跳转
utility.unsafeCallback(function () {
if (parent && parent.$) {
var str = parent.$("#username_ a").attr("href");
if (str && str.indexOf("sysuser/user_info") != -1) {
window.location.href = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
}
return;
}
});
//检测主框架是否是顶级窗口
var isTop = false;
try {
isTop = (top.location + '').indexOf("dynamic.12306.cn") != -1;
} catch (e) {
}
if (!isTop) {
$("#loginForm table tr:first td:last").append("<a href='https://dynamic.12306.cn/otsweb/' target='_blank' style='font-weight:bold;color:red;'>点击全屏订票</a>");
if (!utility.getPref("login.fullscreenAlert")) {
utility.setPref("login.fullscreenAlert", 1);
utility.notifyOnTop("强烈建议你点击界面中的『点击全屏订票』来全屏购票,否则助手有些提示消息您将无法看到!");
}
}
//Hack当前UI显示
$(".enter_right").empty().append("<div class='enter_enw'>" +
"<div class='enter_rtitle' style='padding: 40px 0px 10px 0px; font-size: 20px;'>脚本提示信息</div>" +
"<div class='enter_rfont'>" +
"<ul id='tipScript'>" +
"<li class='fish_clock' id='countEle' style='font-weight:bold;'>等待操作</li>" +
"<li style='color:green;'><strong>操作信息</strong>:<span>休息中</span></li>" +
"<li style='color:green;'><strong>最后操作时间</strong>:<span>--</span></li>" +
"<li> <a href='javascript:;' class='configLink' tab='tabLogin'>登录设置</a> | <a href='http://t.qq.com/ccfish/' target='_blank' style='color:blue;'>腾讯微博</a> | <a href='http://www.fishlee.net/soft/44/' style='color:blue;' target='_blank'>助手主页</a></li><li><a href='http://www.fishlee.net/soft/44/announcement.html' style='color:blue;' target='_blank'>免责声明</a> | <a href='http://www.fishlee.net/Discussion/Index/44' target='_blank'>反馈BUG</a> | <a style='font-weight:bold;color:red;' href='http://www.fishlee.net/honor/index.html' target='_blank'>捐助作者</a></li>" +
'<li id="enableNotification"><input type="button" id="enableNotify" onclick="$(this).parent().hide();window.webkitNotifications.requestPermission();" value="点击启用桌面通知" style="line-height:25px;padding:5px;" /></li><li style="padding-top:10px;line-height:normal;color:gray;">请<strong style="color: red;">最后输验证码</strong>,输入完成后系统将自动帮你提交。登录过程中,请勿离开当前页。如系统繁忙,会自动重新刷新验证码,请直接输入验证码,输入完成后助手将自动帮你提交。</li>' +
"</ul>" +
"</div>" +
"</div>");
var html = [];
html.push("<div class='outerbox' style='margin:15px;'><div class='box'><div class='title'>小提示</div><div style='padding:10px;'>");
html.push("<table><tr><td style='width:33%;font-weight:bold;background-color:#f5f5f5;'><strong>您还可以通过以下网址访问订票网站:</strong></td><td style='width:33%;font-weight:bold;background-color:#f5f5f5;'>助手运行常见问题</td><td style='font-weight:bold;background-color:#f5f5f5;'>版本信息</td></tr>");
html.push("<tr><td><ul><li style='list-style:disc inside;'><a href='https://www.12306.cn/otsweb/' target='blank'>https://www.12306.cn/otsweb/</a></li>");
html.push("<li style='list-style:disc inside;'><a href='https://dynamic.12306.cn/otsweb/' target='blank'>https://dynamic.12306.cn/otsweb/</a></li><li style='list-style:disc inside;'><a href='http://dynamic.12306.cn/otsweb/' target='blank'>http://dynamic.12306.cn/otsweb/</a></li>");
html.push("</ul></td><td><ol>");
$.each([
["http://www.fishlee.net/soft/44/tour.html", "订票助手使用指南", "font-weight:bold;color:red;"],
["http://www.fishlee.net/soft/44/12306faq.html", "订票的常见问题&指南", ""],
["http://www.fishlee.net/soft/44/faq.html", "助手运行的常见问题", ]
], function (i, n) {
html.push("<li style='list-style:disc inside;'><a style='" + n[2] + "' href='" + n[0] + "' target='blank'>" + (n[1] || n[0]) + "</a></li>");
});
html.push("</ol></td><td><ul>");
var info = [];
info.push("已许可于:" + utility.regInfo.name);
if (utility.regInfo.bindAcc) {
if (!utility.regInfo.bindAcc[0] || utility.regInfo.bindAcc[0] == "*") info.push("许可12306帐户:<em>无限</em>");
else info.push("许可12306帐户:" + utility.regInfo.bindAcc);
}
info.push(utility.regInfo.typeDesc);
info.push("版本:<strong>" + window.helperVersion + "</strong>");
$.each(info, function (i, n) { html.push("<li style='list-style:disc inside;'>" + n + "</li>"); });
html.push("<li style='list-style:disc inside;'>【<a href='javascript:;' class='reSignHelper'>重新注册</a>】</li>");
html.push("</ul></td></tr></table>");
html.push("</div></div></div>");
$("div.enter_help").before(html.join(""));
//插入登录标记
var form = $("#loginForm");
var trs = form.find("tr");
trs.eq(1).find("td:last").html('<label><input type="checkbox" id="keepInfo" /> 记录密码</label>');
$("#loginForm td:last").html('<label><input type="checkbox" checked="checked" id="autoLogin" name="autoLogin" /> 自动登录</label>');
utility.reloadPrefs($("#loginForm td:last"));
$("#keepInfo").change(function () {
if (!this.checked) {
if (localStorage.getItem("__un") != null) {
localStorage.removeItem("__un");
localStorage.removeItem("__up");
alert("保存的密码已经删除!");
}
}
});
//注册判断
form.submit(function () {
utility.setPref("_sessionuser", $("#UserName").val());
});
if (!window.webkitNotifications || window.webkitNotifications.checkPermission() == 0) {
$("#enableNotification").remove();
}
var tip = $("#tipScript li");
var count = 1;
var errorCount = 0;
var inRunning = false;
//以下是函数
function setCurOperationInfo(running, msg) {
var ele = $("#countEle");
ele.removeClass().addClass(running ? "fish_running" : "fish_clock").html(msg || (running ? "正在操作中……" : "等待中……"));
}
function setTipMessage(msg) {
tip.eq(2).find("span").html(utility.getTimeInfo());
tip.eq(1).find("span").html(msg);
}
function getLoginRandCode() {
setCurOperationInfo(true, "正在获得登录随机码");
$.ajax({
url: "/otsweb/loginAction.do?method=loginAysnSuggest",
method: "POST",
dataType: "json",
cache: false,
success: function (json, code, jqXhr) {
//{"loginRand":"211","randError":"Y"}
if (json.randError != 'Y') {
setTipMessage("错误:" + json.randError);
utility.delayInvoke("#countEle", getLoginRandCode, utility.getLoginRetryTime());
} else {
setTipMessage("登录随机码 -> " + json.loginRand);
$("#loginRand").val(json.loginRand);
submitForm();
}
},
error: function (xhr) {
errorCount++;
if (xhr.status == 403) {
setTipMessage("[" + errorCount + "] 警告! 403错误, IP已被封!")
utility.delayInvoke("#countEle", getLoginRandCode, 10 * 1000);
} else {
setTipMessage("[" + errorCount + "] 网络请求错误,重试")
utility.delayInvoke("#countEle", getLoginRandCode, utility.getLoginRetryTime());
}
}
});
}
function submitForm() {
var data = {};
$.each($("#loginForm").serializeArray(), function () {
if (this.name == "refundFlag" && !document.getElementById("refundFlag").checked) return;
data[this.name] = this.value;
});
if (!data["loginUser.user_name"] || !data["user.password"] || !data.randCode || data.randCode.length != 4/* || (utility.regInfo.bindAcc && utility.regInfo.bindAcc != data["loginUser.user_name"])*/)
return;
if ($("#keepInfo")[0].checked) {
utility.setPref("__un", data["loginUser.user_name"]);
utility.setPref("__up", data["user.password"])
}
setCurOperationInfo(true, "正在登录中……");
$.ajax({
type: "POST",
url: "/otsweb/loginAction.do?method=login",
data: data,
timeout: 10000,
dataType: "text",
success: function (html) {
msg = utility.getErrorMsg(html);
if (html.indexOf('请输入正确的验证码') > -1) {
setTipMessage("验证码不正确");
setCurOperationInfo(false, "请重新输入验证码。");
stopLogin();
} else if (msg.indexOf('密码') > -1) {
setTipMessage(msg);
setCurOperationInfo(false, "请重新输入。");
stopLogin();
} else if (msg.indexOf('锁定') > -1) {
setTipMessage(msg);
setCurOperationInfo(false, "请重新输入。");
stopLogin();
} else if (html.indexOf("欢迎您登录") != -1) {
utility.notifyOnTop('登录成功,开始查询车票吧!');
window.location.href = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
} else {
setTipMessage(msg);
utility.delayInvoke("#countEle", getLoginRandCode, utility.getLoginRetryTime());
}
},
error: function (msg) {
errorCount++;
if (xhr.status == 403) {
setTipMessage("[" + errorCount + "] 警告! 403错误, IP已被封!")
utility.delayInvoke("#countEle", getLoginRandCode, 10 * 1000);
} else {
setTipMessage("[" + errorCount + "] 网络请求错误,重试")
utility.delayInvoke("#countEle", getLoginRandCode, utility.getLoginRetryTime());
}
}
});
}
function relogin() {
if (inRunning) return;
var user = $("#UserName").val();
if (!user) return;
if (utility.regInfo.bindAcc && utility.regInfo.bindAcc.length && utility.regInfo.bindAcc[0] && $.inArray(user, utility.regInfo.bindAcc) == -1 && utility.regInfo.bindAcc[0] != "*") {
alert("很抱歉,12306订票助手的授权许可已绑定至【" + utility.regInfo.bindAcc.join() + "】,未授权用户,助手停止运行,请手动操作。\n您可以在登录页面下方的帮助区点击【重新注册】来修改绑定。");
return;
}
count++;
utility.setPref("_sessionuser", $("#UserName").val());
inRunning = true;
getLoginRandCode();
}
function stopLogin() {
//等待重试时,刷新验证码
$("#img_rrand_code").click();
$("#randCode").val("")[0].select();
inRunning = false;
}
//初始化
function executeLogin() {
count = 1;
utility.notify("自动登录中:(1) 次登录中...");
setTipMessage("开始登录中....");
getLoginRandCode();
return false;
}
var kun = utility.getPref("__un");
var kup = utility.getPref("__up");
if (kun && kup) {
$("#UserName").val(kun);
$("#password").val(kup);
$("#randCode")[0].focus();
}
$("#randCode").keyup(function (e) {
if (!$("#autoLogin")[0].checked) return;
e = e || event;
if (e.charCode == 13 || $("#randCode").val().length == 4) relogin();
});
//#region 起售时间提示和查询
function addDays(count) {
return new Date(this.getFullYear(), this.getMonth(), this.getDate() + count);
}
var curDate = new Date();
var html = ["<li style='font-weight:bold; color:blue;'><u>助手提示</u>:网上和电话订票提前20天,本日起售【<u>"];
html.push(utility.formatDate(addDays.call(curDate, 19)));
html.push("</u>】日车票;代售点和车站提前18天,本日起售【<u>");
html.push(utility.formatDate(addDays.call(curDate, 17)));
html.push("</u>】日车票。<br />【<a href='javascript:;' id='querySaleDate'>根据乘车日期推算起售日期</a>】【<a href='http://www.12306.cn/mormhweb/zxdt/tlxw_tdbtz53.html' target='_blank'>以相关公告、车站公告为准</a>】");
$("div.enter_from ul").append(html.join(""));
$("#querySaleDate").click(function () {
var date = prompt("请输入您要乘车的日期,如:2013-02-01");
if (!date) return;
if (!/(\d{4})[-/]0?(\d{1,2})[-/]0?(\d{1,2})/.exec(date)) {
alert("很抱歉未能识别日期");
}
date = new Date(parseInt(RegExp.$1), parseInt(RegExp.$2) - 1, parseInt(RegExp.$3));
alert("您查询的乘车日期是:" + utility.formatDate(date) + "\n\n互联网、电话起售日期是:" + utility.formatDate(addDays.call(date, -19)) + "\n车站、代售点起售日期是:" + utility.formatDate(addDays.call(date, -17)) + "\n\n以上结果仅供参考。");
});
//#endregion
}
//#endregion
//#region 自动重新支付
function initPayOrder() {
//如果出错,自动刷新
if ($("div.error_text").length > 0) {
utility.notifyOnTop("页面出错,稍后自动刷新!");
setTimeout(function () { self.location.reload(); }, 3000);
}
return;
// undone
window.payOrder = this;
//epayOrder
var oldCall = window.epayOrder;
var formUrl, formData;
$("#myOrderForm").submit(function () {
var form = $(this);
var action = form.attr("action");
if (acton && action.index("laterEpay") != -1) {
return false;
}
});
window.epayOrder = function () {
oldCall.apply(arguments);
var form = $("#myOrderForm");
var formData = utility.serializeForm(form);
var formUrl = form.attr("action");
};
function getsubmitForm() {
utility.post(formUrl, formData, "text", function (html) {
}, function () {
});
}
}
//#endregion
//#region 更新专用检测代码
if (location.pathname == "/otsweb/" || location.pathname == "/otsweb/main.jsp") {
if (isFirefox) {
//firefox 专用检测代码
GM_xmlhttpRequest({
method: "GET",
url: "http://www.fishlee.net/service/update/44/version.js",
onload: function (o) {
eval(o.responseText);
if (typeof (fishlee12306_msgid) != 'undefined') {
if (utility.getPref("helperlastmsgid") != fishlee12306_msgid) {
utility.setPref("helperlastmsgid", fishlee12306_msgid);
if (!fishlee12306_msgver || compareVersion(version, fishlee12306_msgver) < 0) {
if (fishlee12306_msg) alert(fishlee12306_msg);
}
}
}
console.log("[INFO] 更新检查:当前助手版本=" + version + ",新版本=" + version_12306_helper);
if (compareVersion(version, version_12306_helper) < 0 && confirm("订票助手已发布新版 【" + version_12306_helper + "】,为了您的正常使用,请及时更新!是否立刻更新?\n\n本次更新内容如下:\n" + version_updater.join("\n"))) {
GM_openInTab("http://www.fishlee.net/Service/Download.ashx/44/47/12306_ticket_helper.user.js", true, true);
}
}
});
} else {
unsafeInvoke(function () {
//$("body").append('<iframe id="checkVersion" width="0" height="0" style="visibility:hidden;" src="http://static.fishlee.net/content/scriptProxy.html?script=http://static.fishlee.net/content/images/apps/cn12306/checkVersion.js&v=' + window.helperVersion + '"></iframe>');
});
}
}
function compareVersion(v1, v2) {
var vv1 = v1.split('.');
var vv2 = v2.split('.');
var length = Math.min(vv1.length, vv2.length);
for (var i = 0; i < length; i++) {
var s1 = parseInt(vv1[i]);
var s2 = parseInt(vv2[i]);
if (s1 < s2) return -1;
if (s1 > s2) return 1;
}
return vv1.length > vv2.length ? 1 : vv1.length < vv2.length ? -1 : 0;
}
//#endregion
| JavaScript |
/*
* 12306 Auto Query => A javascript snippet to help you book tickets online.
* 12306 Booking Assistant
* Copyright (C) 2011 Hidden
*
* 12306 Auto Query => A javascript snippet to help you book tickets online.
* Copyright (C) 2011 Jingqin Lynn
*
* 12306 Auto Login => A javascript snippet to help you auto login 12306.com.
* Copyright (C) 2011 Kevintop
*
* Includes jQuery
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* 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.
*
*
*/
// ==UserScript==
// @name 12306 Booking Assistant
// @version 1.4.2
// @author
// @namespace https://github.com/JoyStone
// @description 订票助手
// @include *://dynamic.12306.cn/otsweb/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==
function withjQuery(callback, safe){
if(typeof(jQuery) == "undefined") {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
if(safe) {
var cb = document.createElement("script");
cb.type = "text/javascript";
cb.textContent = "jQuery.noConflict();(" + callback.toString() + ")(jQuery, window);";
script.addEventListener('load', function() {
document.head.appendChild(cb);
});
}
else {
var dollar = undefined;
if(typeof($) != "undefined") dollar = $;
script.addEventListener('load', function() {
jQuery.noConflict();
$ = dollar;
callback(jQuery, window);
});
}
document.head.appendChild(script);
} else {
setTimeout(function() {
//Firefox supports
callback(jQuery, typeof unsafeWindow === "undefined" ? window : unsafeWindow);
}, 30);
}
}
withjQuery(function($, window){
$(document).click(function() {
if( window.webkitNotifications && window.webkitNotifications.checkPermission() != 0 ) {
window.webkitNotifications.requestPermission();
}
});
function notify(str, timeout, skipAlert) {
if( window.webkitNotifications && window.webkitNotifications.checkPermission() == 0 ) {
var notification = webkitNotifications.createNotification(
"http://www.12306.cn/mormhweb/images/favicon.ico", // icon url - can be relative
'订票', // notification title
str
);
notification.show();
if ( timeout ) {
setTimeout(function() {
notification.cancel();
}, timeout);
}
return true;
} else {
if( !skipAlert ) {
alert( str );
}
return false;
}
}
function route(match, fn) {
if( window.location.href.indexOf(match) != -1 ) {
fn();
};
}
function OrderQueueWaitTime(tourFlag, waitMethod, finishMethod) {
this.tourFlag = tourFlag;
this.waitMethod = waitMethod;
this.finishMethod = finishMethod;
this.dispTime = 1;
this.nextRequestTime = 1;
this.isFinished = false;
this.waitObj;
}
function query() {
//query
var maxIncreaseDay = 0 ;
var start_autoIncreaseDay = null ;
var index_autoIncreaseDay = 1 ;
var pools_autoIncreaseDay = [] ;
function __reset_autoIncreaseDays(){
maxIncreaseDay = parseInt( document.getElementById('autoIncreaseDays').value ) || 1 ;
if( maxIncreaseDay > 10 ) {
maxIncreaseDay = 10 ;
}
document.getElementById('autoIncreaseDays').value = maxIncreaseDay ;
start_autoIncreaseDay = null ;
$('#app_next_day,#app_pre_day').addClass('disabled').css('color', '#aaa' );
}
function __unset_autoIncreaseDays(){
if( start_autoIncreaseDay ) {
document.getElementById('startdatepicker').value = start_autoIncreaseDay ;
start_autoIncreaseDay = null ;
}
$('#app_next_day,#app_pre_day').removeClass('disabled').css('color', '#000' );
}
function __date_format( date ) {
var y = date.getFullYear() ;
var m = date.getMonth() + 1 ;
var d = date.getDate() ;
if( m <= 9 ) {
m = '0' + String( m ) ;
} else {
m = String( m ) ;
}
if( d <= 9 ) {
d = '0' + String( d ) ;
} else {
d = String( d );
}
return String(y) + '-' + m + '-' + d ;
}
function __date_parse(txt){
var a = $.map(txt.replace(/^\D+/, '').replace(/\D$/, '' ).split(/\D+0?/) , function(i){
return parseInt(i) ;
}) ;
a[1] -= 1 ;
var date = new Date;
date.setFullYear( a[0] ) ;
date.setMonth( a[1] , a[2] ) ;
date.setDate( a[2] ) ;
return date ;
}
function __set_autoIncreaseDays() {
if( !start_autoIncreaseDay ) {
start_autoIncreaseDay = document.getElementById('startdatepicker').value ;
var date = __date_parse(start_autoIncreaseDay);
pools_autoIncreaseDay = new Array() ;
for(var i = 0 ; i < maxIncreaseDay ; i++) {
pools_autoIncreaseDay.push( __date_format(date) ) ;
date.setTime( date.getTime() + 3600 * 24 * 1000 ) ;
}
index_autoIncreaseDay = 1 ;
return ;
}
if( index_autoIncreaseDay >= pools_autoIncreaseDay.length ) {
index_autoIncreaseDay = 0 ;
}
var value = pools_autoIncreaseDay[index_autoIncreaseDay++];
document.getElementById('startdatepicker').value = value ;
}
function getTimeLimitValues(){
return $.map( [ $('#startTimeHFrom').val() , $('#startTimeMFrom').val(), $('#startTimeHTo').val(), $('#startTimeMTo').val() ] , function(val){
return parseInt(val) || 0 ;
}) ;
}
var isTicketAvailable = false;
var firstRemove = false;
window.$ && window.$(".obj:first").ajaxComplete(function() {
var _timeLimit = getTimeLimitValues();
$(this).find("tr").each(function(n, e) {
if(checkTickets(e, _timeLimit, n )){
isTicketAvailable = true;
highLightRow(e);
}
});
if(firstRemove) {
firstRemove = false;
if (isTicketAvailable) {
if (isAutoQueryEnabled)
document.getElementById("refreshButton").click();
onticketAvailable(); //report
}
else {
//wait for the button to become valid
}
}
}).ajaxError(function() {
if(isAutoQueryEnabled) doQuery();
});
//hack into the validQueryButton function to detect query
var _delayButton = window.delayButton;
window.delayButton = function() {
_delayButton();
if(isAutoQueryEnabled) doQuery();
}
//Trigger the button
var doQuery = function() {
displayQueryTimes(queryTimes++);
firstRemove = true;
__set_autoIncreaseDays();
document.getElementById(isStudentTicket ? "stu_submitQuery" : "submitQuery").click();
}
var $special = $("<input type='text' />")
//add by 冯岩 begin 2012-01-18
var $specialOnly = $("<label style='margin-left:10px;color: blue;'><input type='checkbox' id='__chkspecialOnly'/>仅显示限定车次<label>");
var $includeCanOder = $("<label style='margin-right:10px;color: blue;'><input type='checkbox' id='__chkIncludeCanOder'/>显示可预定车次<label>");
//add by 冯岩 end 2012-01-18
var checkTickets = function(row, time_limit , row_index ) {
var hasTicket = false;
var v1 = $special.val();
var removeOther = $("#__chkspecialOnly").attr("checked");
var includeCanOder = $("#__chkIncludeCanOder").attr("checked");
if( v1 ) {
var v2 = $.trim( $(row).find(".base_txtdiv").text() );
if( v1.indexOf( v2 ) == -1 ) {
//add by 冯岩 begin 2012-01-18
if(removeOther)
{
if(v2 != "")
{
if(includeCanOder)
{
//包括其他可以预定的行
if($(row).find(".yuding_u").size() == 0)
{
$(row).remove();
}
}
else
{
$(row).remove();
}
}
}
//add by 冯岩 end 2012-01-18
return false;
}
}
if( $(row).find("td input.yuding_x[type=button]").length ) {
return false;
}
var cells = $(row).find("td") ;
if( cells.length < 5 ) {
return false ;
}
var _start_time = $.map( $(cells[1]).text().replace(/^\D+|\D+$/, '').split(/\D+0?/) , function(val){
return parseInt(val) || 0 ;
}) ;
while( _start_time.length > 2 ) {
_start_time.shift() ; // remove station name include number
}
if( _start_time[0] < time_limit[0] || _start_time[0] > time_limit[2] ) {
return false ;
}
if( _start_time[0] == time_limit[0] && _start_time[1] < time_limit[1] ){
return false ;
}
if( _start_time[0] == time_limit[2] && _start_time[1] > time_limit[3] ){
return false ;
}
cells.each(function(i, e) {
if(ticketType[i-1]) {
var info = $.trim($(e).text());
if(info != "--" && info != "无" && info != "*") {
hasTicket = true;
highLightCell(e);
}
}
});
return hasTicket;
}
var queryTimes = 0; //counter
var isAutoQueryEnabled = false; //enable flag
//please DIY:
var audio = null;
var onticketAvailable = function() {
if(window.Audio) {
if(!audio) {
audio = new Audio("http://www.w3school.com.cn/i/song.ogg");
audio.loop = true;
}
audio.play();
notify("可以订票了!", null, true);
} else {
notify("可以订票了!");
}
}
var highLightRow = function(row) {
$(row).css("background-color", "#D1E1F1");
}
var highLightCell = function(cell) {
$(cell).css("background-color", "#2CC03E");
}
var displayQueryTimes = function(n) {
document.getElementById("refreshTimes").innerHTML = n;
};
var isStudentTicket = false;
//Control panel UI
var ui = $("<div>请先选择好出发地,目的地,和出发时间。 </div>")
.append(
$("<input id='isStudentTicket' type='checkbox' />").change(function(){
isStudentTicket = this.checked ;
})
)
.append(
$("<label for='isStudentTicket'></label>").html("学生票 ")
)
.append(
$("<input id='autoIncreaseDays' type='text' value='1' maxLength=2 style='width:18px;' />")
)
.append(
$("<label for='autoIncreaseDays'></label>").html("天循环 ")
)
.append(
$("<button style='padding: 5px 10px; background: #2CC03E;border-color: #259A33;border-right-color: #2CC03E;border-bottom-color:#2CC03E;color: white;border-radius: 5px;text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);'/>").attr("id", "refreshButton").html("开始刷票").click(function() {
if(!isAutoQueryEnabled) {
__reset_autoIncreaseDays() ;
isTicketAvailable = false;
if(audio && !audio.paused) audio.pause();
isAutoQueryEnabled = true;
doQuery();
this.innerHTML="停止刷票";
}
else {
__unset_autoIncreaseDays();
isAutoQueryEnabled = false;
this.innerHTML="开始刷票";
}
})
)
.append(
$("<span>").html(" 尝试次数:").append(
$("<span/>").attr("id", "refreshTimes").text("0")
)
)
.append(
//Custom ticket type
$("<div>如果只需要刷特定的票种,请在余票信息下面勾选。</div>")
.append($("<a href='#' style='color: blue;'>只勾选坐票 </a>").click(function() {
$(".hdr tr:eq(2) td").each(function(i,e) {
var val = this.innerHTML.indexOf("座") != -1;
var el = $(this).find("input").attr("checked", val);
el && el[0] && ( ticketType[el[0].ticketTypeId] = val );
});
return false;
}))
.append($("<a href='#' style='color: blue;'>只勾选卧铺 </a>").click(function() {
$(".hdr tr:eq(2) td").each(function(i,e) {
var val = this.innerHTML.indexOf("卧") != -1;
var el = $(this).find("input").attr("checked", val);
el && el[0] && ( ticketType[el[0].ticketTypeId] = val );
});
return false;
}))
)
.append(
$("<div>限定出发车次:</div>")
.append( $special )
.append( $specialOnly)
.append( $includeCanOder )
.append( "不限制不填写,限定多次用逗号分割,例如: G32,G34" )
);
var container = $(".cx_title_w:first");
container.length ?
ui.insertBefore(container) : ui.appendTo(document.body);
$('<div style="position:relative;top:0px; left:0px; height:0px; width:1px; overflow:visiable; background-color:#ff0;"></div>')
.append(
$('<a id="app_pre_day" style="position:absolute;top:26px; left:2px; width:40px; color:#000;">前一天</a>').click(function() {
if( $(this).hasClass("disabled") ) {
return false ;
}
var date = __date_parse( document.getElementById('startdatepicker').value );
date.setTime( date.getTime() - 3600 * 24 * 1000 ) ;
document.getElementById('startdatepicker').value = __date_format(date) ;
return false;
})
)
.append(
$('<a id="app_next_day" style="position:absolute;top:26px; left:114px; width:40px; color:#000;">下一天</a>').click(function() {
if( $(this).hasClass("disabled") ) {
return false ;
}
var date = __date_parse( document.getElementById('startdatepicker').value );
date.setTime( date.getTime() + 3600 * 24 * 1000 ) ;
document.getElementById('startdatepicker').value = __date_format(date) ;
return false;
})
)
.insertBefore( $('#startdatepicker') ) ;
setTimeout(function(){
var box = $('<div style="position:relative;top:2px; left:0px; width:100px; height:18px; line-height:18px; font-size:12px; padding:0px; overflow:hidden;"></div>') ;
function makeSelect(id, max_value, default_value){
var element = $('<select id="' + id + '" style="margin:-2px 0px 0px -5px;padding:0px;font-size:12px; line-height:100%; "></select>') ;
for(var i = 0; i <= max_value ; i++) {
element.append(
$('<option value="' + i + '" style="padding:0px;margin:0px;font-size:12px; line-height:100%;" ' + ( default_value == i ? ' selected="selected" ' : '' ) + '>' + ( i <= 9 ? '0' + i : i ) + '</option>' )
)
}
box.append(
$('<div style="width:18px; padding:0px; overflow:hidden; float:left;"></div>') .append(element)
);
return element ;
}
function check(evt){
var tl = getTimeLimitValues() ;
if( tl[0] > tl[2] || (tl[0] == tl[2] && tl[1] > tl[3]) ) {
alert('最早发车时间必须早于最晚发车时间,请重新选择!') ;
return false ;
}
}
makeSelect('startTimeHFrom' , 23 ).change(check) ;
box.append( $('<div style="float:left;">:</div>')) ;
makeSelect('startTimeMFrom' , 59 ).change(check) ;
box.append( $('<div style="float:left;padding:0px 1px;">--</div>')) ;
makeSelect('startTimeHTo' , 23, 23 ).change(check) ;
box.append( $('<div style="float:left;">:</div>')) ;
makeSelect('startTimeMTo' , 59, 59 ).change(check) ;
box.insertAfter( $('#startTime') )
}, 10 ) ;
//Ticket type selector & UI
var ticketType = new Array();
var checkbox_list = new Array();
$(".hdr tr:eq(2) td").each(function(i,e) {
ticketType.push(false);
if(i<3) return;
ticketType[i] = true;
var c = $("<input/>").attr("type", "checkBox").attr("checked", true);
c[0].ticketTypeId = i;
c.change(function() {
ticketType[this.ticketTypeId] = this.checked;
}).appendTo(e);
checkbox_list.push(c);
});
$.each([1, 2 ], function(){
var c = checkbox_list.pop() ;
c[0].checked = false ;
ticketType[ c[0].ticketTypeId ] = this.checked ;
});
delete checkbox_list ;
}
route("querySingleAction.do", query);
route("myOrderAction.do?method=resign", query);
route("confirmPassengerResignAction.do?method=cancelOrderToQuery", query);
route("loginAction.do?method=init", function() {
if( !window.location.href.match( /init$/i ) ) {
return;
}
//login
var url = "https://dynamic.12306.cn/otsweb/loginAction.do?method=login";
var surl = "https://dynamic.12306.cn/otsweb/loginAction.do?method=loginAysnSuggest";
var queryurl = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
//Check had login, redirect to query url
if( window.parent && window.parent.$ ) {
var str = window.parent.$("#username_ a").attr("href");
if( str && str.indexOf("sysuser/user_info") != -1 ){
window.location.href = queryurl;
return;
}
}
function submitForm(){
var submitUrl = url;
//更改登录方式,增加post参数 2013-1-5 by stone
$.ajax(
{
url: surl,
type: "POST",
dataType: "json",
success: function (data) {
if (data.randError != 'Y') {
//refreshImg();
alert(data.randError);
// $("#password").val("");
//$("#password").focus();
// $("#randCode").val("");
$("#loginRand").val(data.loginRand);
return false;
} else {
$("#loginRand").val(data.loginRand);
$.ajax({
url: submitUrl,
type: "POST",
data: {
"loginRand": $("#loginRand").val()
, "refundLogin": 'N'
, "refundFlag": 'Y'
, "loginUser.user_name": $("#UserName").val()
, "nameErrorFocus": $("#nameErrorFocus").val()
, "user.password": $("#password").val()
, "passwordErrorFocus": $("#passwordErrorFocus").val()
, "randCode": $("#randCode").val()
, "randErrorFocus": $("#randErrorFocus").val()
},
beforeSend: function (xhr) {
try {
//xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
//xhr.setRequestHeader('Cache-Control', 'max-age=0');
//xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
} catch (e) { };
},
timeout: 30000,
//cache: false,
//async: false,
success: function (msg) {
//密码输入错误
//您的用户已经被锁定
// $('#errorhmtl').val(msg);
if (msg.indexOf('请输入正确的验证码') > -1) {
alert('请输入正确的验证码!');
} else if (msg.indexOf('当前访问用户过多') > -1) {
reLogin();
} else if (msg.match(/var\s+isLogin\s*=\s*true/i)) {
notify('登录成功,开始查询车票吧!');
window.location.replace(queryurl);
} else {
msg = msg.match(/var\s+message\s*=\s*"([^"]*)/);
if (msg && msg[1]) {
alert(msg && msg[1]);
} else {
reLogin();
}
}
},
error: function (msg) {
reLogin();
}
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
reLogin();
//return false;
}
});
}
var count = 1;
function reLogin(){
count ++;
$('#refreshButton').html("("+count+")次登录中...");
setTimeout(submitForm, 2000);
}
//初始化
//$("#subLink").after("<textarea id='errorhmtl'></textarea>");
$("#subLink").after($("<a href='#' style='padding: 5px 10px; background: #2CC03E;border-color: #259A33;border-right-color: #2CC03E;border-bottom-color:#2CC03E;color: white;border-radius: 5px;text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);'/>").attr("id", "refreshButton").html("自动登录").click(function() {
count = 1;
$(this).html("(1)次登录中...");
//notify('开始尝试登录,请耐心等待!', 4000);
submitForm();
return false;
}));
alert('如果使用自动登录功能,请输入用户名、密码及验证码后,点击自动登录,系统会尝试登录,直至成功!');
});
route("confirmPassengerAction.do", submit);
route("confirmPassengerResignAction.do", submit);
function submit() {
/**
* Auto Submit Order
* From: https://gist.github.com/1577671
* Author: kevintop@gmail.com
*/
//Auto select the first user when not selected
if( !$("input._checkbox_class:checked").length ) {
try{
//Will failed in IE
$("input._checkbox_class:first").click();
}catch(e){};
}
//passengerTickets
var userInfoUrl = 'https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y';
var count = 1, freq = 1000, doing = false, timer, $msg = $("<div style='padding-left:470px;'></div>");
OrderQueueWaitTime.prototype.start = function () {
var t = this;
t.timerJob();
window.setInterval(function () { t.timerJob(); }, 1000);
};
OrderQueueWaitTime.prototype.timerJob = function () {
if (this.isFinished) {
return;
}
//alert(this.dispTime);
if (this.dispTime <= 0) {
this.isFinished = true;
//alert("ok");
this.finishMethod(this.tourFlag, this.dispTime, this.waitObj);
return;
}
if (this.dispTime == this.nextRequestTime) {
this.getWaitTime();
}
//格式化时间,把秒转换为时分秒
var second = this.dispTime;
var show_time = "";
// var hour = parseInt(second / 3600); //时
// if(hour > 0){
// show_time = hour + "小时";
// second = second % 3600;
// }
// var minute = parseInt(second / 60); //分
// if(minute >= 1){
// show_time = show_time + minute + "分";
// second = second % 60;
// } else if(hour >= 1 && second > 0){
// show_time = show_time + "0分";
// }
// if(second > 0){
// show_time = show_time + second + "秒";
// }
//时间大于等于1分钟的,按分钟倒计时,小于1分钟的按1分钟显示
var minute = parseInt(second / 60);
if (minute >= 1) {
show_time = minute + "分";
second = second % 60;
} else {
// show_time = second + "秒";
show_time = "1分";
}
this.waitMethod(this.tourFlag, this.dispTime > 1 ? --this.dispTime : 1, show_time);
};
OrderQueueWaitTime.prototype.getWaitTime = function () {
var t = this;
$.ajax(
{
url: 'https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=getOrderWaitTime',
type: "GET",
data: { tourFlag: t.tourFlag },
dataType: "json",
success: function (data) {
if (data != null) {
t.waitObj = data;
t.dispTime = data.waitTime;
var flashWaitTime = parseInt(data.waitTime / 1.5);
flashWaitTime = flashWaitTime > 60 ? 60 : flashWaitTime;
var nextTime = data.waitTime - flashWaitTime;
t.nextRequestTime = nextTime <= 0 ? 1 : nextTime;
//alert(t.dispTime);
//alert(t.nextRequestTime);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert("计算排队时间失败!");
return false;
}
});
};
function waitFunc(tourFlag, return_time, show_time) {
if (return_time <= 5) {
//dispMessage("您的订单已经提交,系统正在处理中,请稍等。");
showmsg("您的订单已经提交,请稍等");
} else if (return_time > 30 * 60) {
//dispMessage("您的订单已经提交,预计等待时间超过30分钟,请耐心等待。");
showmsg("您的订单已经提交,预计等待时间超过30分钟,请耐心等待");
} else {
//dispMessage("您的订单已经提交,最新预估等待时间" + show_time + ",请耐心等待。");
showmsg("您的订单已经提交,请耐心等待");
}
}
function procFail(flag, returnObj) {
var renewURL = "<a id='link' target='main' style='color:#2C72BA' onclick='closePopWin()' href='"
+ ctx + "/order/querySingleAction.do?method=init'>[重新购票]</a>";
var my12306URL = "<a id='link' target='main' style='color:#2C72BA' onclick='closePopWin()' href='"
+ ctx + "/loginAction.do?method=initForMy12306'>[我的12306]</a>";
if (flag == -1) {
reSubmitForm("未知错误");
} else if (flag == -2) {
if (returnObj.errorcode == 0) {
//dispMessage("占座失败,原因:" + returnObj.msg + " 请点击" + my12306URL
// + ",办理其他业务.");
reSubmitForm("占座失败:" + returnObj.msg);
} else {
// dispMessage("占座失败,原因:" + returnObj.msg + " 请点击" + renewURL
// + ",重新选择其它车次.");
reSubmitForm("占座失败:" + returnObj.msg);
}
} else if (flag == -3) {
//dispMessage("订单已撤销 " + " 请点击" + renewURL + ",重新选择其它车次.");
reSubmitForm("订单已撤销");
} else {
// 进入未完成订单页面
//parent.closePopWin();
// var form = document.getElementById("confirmPassenger");
//form.action = "https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y&fakeParent=true";
//form.submit();
var audio;
if (window.Audio) {
audio = new Audio("http://www.w3school.com.cn/i/song.ogg");
audio.loop = true;
audio.play();
}
notify("恭喜,车票预订成!", null, true);
setTimeout(function () {
if (confirm("车票预订成,去付款?")) {
//window.location.replace(userInfoUrl);
var form = document.getElementById("confirmPassenger");
form.action = "https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y&fakeParent=true";
form.submit();
} else {
if (audio && !audio.paused) audio.pause();
}
}, 100);
}
}
// 跳转-单程
function finishFun(tourFlag, time, returnObj) {
if (time == -1) {
var action_url = "";
action_url = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=payOrder&orderSequence_no="
+ returnObj.orderId;
var audio;
if (window.Audio) {
audio = new Audio("http://www.w3school.com.cn/i/song.ogg");
audio.loop = true;
audio.play();
}
notify("恭喜,车票预订成!", null, true);
setTimeout(function () {
if (confirm("车票预订成,去付款?")) {
var form = document.getElementById("confirmPassenger");
form.action = action_url;
form.submit();
} else {
if (audio && !audio.paused) audio.pause();
}
}, 100);
//parent.closePopWin();
} else {
procFail(time, returnObj);
}
}
function erromessageFunc(erromsg) {
if (erromsg.indexOf("输入的验证码不正确") > -1) {
$("#img_rrand_code").click();
$("#rand").focus().select();
stop(erromsg);
return;
}
if (erromsg.indexOf('未处理的订单') > -1) {
notify("有未处理的订单!");
window.location.replace(userInfoUrl);
return;
}
setTimeout(reSubmitForm, freq || 50, erromsg);
}
function submitForm(){
var timer = null;
//更改提交列车日期参数
var wantDate = $("#startdatepicker").val();
$("#start_date").val(wantDate);
$("#_train_date_str").val(wantDate);
var url = 'https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=confirmSingleForQueueOrder';
var checkurl = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=checkOrderInfo&rand=" + $("#rand").val();
var t = jQuery("#confirmPassenger");
var tmp = $('#confirmPassenger').serialize();
tmp += "&tFlag=dc";
jQuery.ajax({
url: checkurl,
type: "POST",
data: tmp,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.errMsg != 'Y') {
erromessageFunc(data.errMsg);
//setTimeout(reSubmitForm, freq || 50,data.errMsg);
}
else {
jQuery.ajax(
{
url: url,
type: "POST",
data: tmp,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.errMsg != 'Y') {
erromessageFunc(data.errMsg);
//reSubmitForm();
//setTimeout(reSubmitForm, freq || 50,data.errMsg);
} else {
timer = new OrderQueueWaitTime('dc',
waitFunc, finishFun);
timer.start();
}
},
error: function (XMLHttpRequest, textStatus,
errorThrown) {
//dispMessage("下单失败!网络忙,请稍后再试。");
setTimeout(reSubmitForm, freq || 50, "网络忙");
//reSubmitForm("网络忙");
//return false;
}
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (errorThrown.concat('登陆')) {
alert("您离开页面的时间过长,请重新登录系统。");
}
else {
setTimeout(reSubmitForm, freq || 50,"网络忙");
}
}
});
//jQuery("#confirmPassenger").ajaxSubmit(
/*jQuery.ajax({
url: $("#confirmPassenger").attr('action'),
data: $('#confirmPassenger').serialize(),
beforeSend: function( xhr ) {
try{
xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
xhr.setRequestHeader('Cache-Control', 'max-age=0');
}catch(e){};
},
type: "POST",
timeout: 30000,
success: function( msg )
{
//Refresh token
var match = msg && msg.match(/org\.apache\.struts\.taglib\.html\.TOKEN['"]?\s*value=['"]?([^'">]+)/i);
var newToken = match && match[1];
if(newToken) {
$("input[name='org.apache.struts.taglib.html.TOKEN']").val(newToken);
}
if( msg.indexOf('payButton') > -1 ) {
//Success!
var audio;
if( window.Audio ) {
audio = new Audio("http://www.w3school.com.cn/i/song.ogg");
audio.loop = true;
audio.play();
}
notify("恭喜,车票预订成!", null, true);
setTimeout(function() {
if( confirm("车票预订成,去付款?") ){
window.location.replace(userInfoUrl);
} else {
if(audio && !audio.paused) audio.pause();
}
}, 100);
return;
}else if(msg.indexOf('未处理的订单') > -1){
notify("有未处理的订单!");
window.location.replace(userInfoUrl);
return;
}
var reTryMessage = [
'用户过多'
, '确认客票的状态后再尝试后续操作'
, '请不要重复提交'
, '没有足够的票!'
, '车次不开行'
];
for (var i = reTryMessage.length - 1; i >= 0; i--) {
if( msg.indexOf( reTryMessage[i] ) > -1 ) {
reSubmitForm( reTryMessage[i] );
return;
}
};
// 铁道部修改验证码规则后 update by 冯岩
if( msg.indexOf( "输入的验证码不正确" ) > -1 ) {
$("#img_rrand_code").click();
$("#rand").focus().select();
stop();
return;
}
//Parse error message
msg = msg.match(/var\s+message\s*=\s*"([^"]*)/);
stop(msg && msg[1] || '出错了。。。。 啥错? 我也不知道。。。。。');
},
error: function(msg){
reSubmitForm("网络错误");
}
});*/
};
function reSubmitForm(msg){
if( !doing )return;
count ++;
$msg.html("("+count+")次自动提交中... " + (msg || ""));
//timer = setTimeout( submitForm, freq || 50 );
submitForm();
}
function showmsg(msg)
{
$msg.html("(" + count + ")次自动提交中... " + (msg || ""));
}
function stop ( msg ) {
doing = false;
$msg.html("("+count+")次 已停止");
$('#refreshButton').html("自动提交订单");
//timer && clearTimeout( timer );
msg && alert( msg );
}
function reloadSeat(){
$("select[name$='_seat']").html('<option value="M" selected="">一等座</option><option value="O" selected="">二等座</option><option value="1">硬座</option><option value="3">硬卧</option><option value="4">软卧</option>');
}
//初始化
if($("#refreshButton").size()<1){
// //重置后加载所有席别
// $("select[name$='_seat']").each(function(){this.blur(function(){
// alert(this.attr("id") + "blur");
// })});
////初始化所有席别
//$(".qr_box :checkbox[name^='checkbox']").each(function(){$(this).click(reloadSeat)});
//reloadSeat();
//日期可选
//$("td.bluetext:first").html('<input type="text" name="orderRequest.train_date" value="' +$("#start_date").val()+'" id="startdatepicker" style="width: 150px;" class="input_20txt" onfocus="WdatePicker({firstDayOfWeek:1})" />');
//$("#start_date").remove();
var i = 0;
for (i = 1; i <= 5; i++)
{
$("#passenger_" + i + "_seat").after('<select name="passenger_1_seat_detail_select" id="passenger_' + i + '_seat_detail_select" onchange="setSeatDetail(\'' + i +'\')"> <option value="0">随机</option> <option value="3">上铺</option> <option value="2">中铺</option> <option value="1">下铺</option> </select>');
}
$(".tj_btn").append($("<a style='padding: 5px 10px; background: #2CC03E;border-color: #259A33;border-right-color: #2CC03E;border-bottom-color:#2CC03E;color: white;border-radius: 5px;text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);'></a>").attr("id", "refreshButton").html("自动提交订单").click(function() {
//alert('开始自动提交订单,请点确定后耐心等待!');
if( this.innerHTML.indexOf("自动提交订单") == -1 ){
//doing
stop();
} else {
if( window.submit_form_check && !window.submit_form_check("confirmPassenger") ) {
return;
}
count = 0;
doing = true;
this.innerHTML = "停止自动提交";
reSubmitForm();
}
return false;
}));
$(".tj_btn").append("自动提交频率:")
.append($("<select id='freq'><option value='50' >频繁</option><option value='500' selected='' >正常</option><option value='2000' >缓慢</option></select>").change(function() {
freq = parseInt( $(this).val() );
}))
.append($msg);
$("#rand").bind('keydown', function (e) {
var key = e.which;
if (key == 13) {
$("#refreshButton").click();
}
});
}
};
}, true);
| JavaScript |
/**
* Creates a new level control.
* @constructor
* @param {IoMap} iomap the IO map controller.
* @param {Array.<string>} levels the levels to create switchers for.
*/
function LevelControl(iomap, levels) {
var that = this;
this.iomap_ = iomap;
this.el_ = this.initDom_(levels);
google.maps.event.addListener(iomap, 'level_changed', function() {
that.changeLevel_(iomap.get('level'));
});
}
/**
* Gets the DOM element for the control.
* @return {Element}
*/
LevelControl.prototype.getElement = function() {
return this.el_;
};
/**
* Creates the necessary DOM for the control.
* @return {Element}
*/
LevelControl.prototype.initDom_ = function(levelDefinition) {
var controlDiv = document.createElement('DIV');
controlDiv.setAttribute('id', 'levels-wrapper');
var levels = document.createElement('DIV');
levels.setAttribute('id', 'levels');
controlDiv.appendChild(levels);
var levelSelect = this.levelSelect_ = document.createElement('DIV');
levelSelect.setAttribute('id', 'level-select');
levels.appendChild(levelSelect);
this.levelDivs_ = [];
var that = this;
for (var i = 0, level; level = levelDefinition[i]; i++) {
var div = document.createElement('DIV');
div.innerHTML = 'Level ' + level;
div.setAttribute('id', 'level-' + level);
div.className = 'level';
levels.appendChild(div);
this.levelDivs_.push(div);
google.maps.event.addDomListener(div, 'click', function(e) {
var id = e.currentTarget.getAttribute('id');
var level = parseInt(id.replace('level-', ''), 10);
that.iomap_.setHash('level' + level);
});
}
controlDiv.index = 1;
return controlDiv;
};
/**
* Changes the highlighted level in the control.
* @param {number} level the level number to select.
*/
LevelControl.prototype.changeLevel_ = function(level) {
if (this.currentLevelDiv_) {
this.currentLevelDiv_.className =
this.currentLevelDiv_.className.replace(' level-selected', '');
}
var h = 25;
if (window['ioEmbed']) {
h = (window.screen.availWidth > 600) ? 34 : 24;
}
this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px';
var div = this.levelDivs_[level - 1];
div.className += ' level-selected';
this.currentLevelDiv_ = div;
};
| JavaScript |
// Copyright 2011 Google
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The Google IO Map
* @constructor
*/
var IoMap = function() {
var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025);
/** @type {Node} */
this.mapDiv_ = document.getElementById(this.MAP_ID);
var ioStyle = [
{
'featureType': 'road',
stylers: [
{ hue: '#00aaff' },
{ gamma: 1.67 },
{ saturation: -24 },
{ lightness: -38 }
]
},{
'featureType': 'road',
'elementType': 'labels',
stylers: [
{ invert_lightness: true }
]
}];
/** @type {boolean} */
this.ready_ = false;
/** @type {google.maps.Map} */
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: moscone,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: 'io',
streetViewControl: false
});
var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle));
this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style));
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['onMapReady']();
}
});
/** @type {Array.<Floor>} */
this.floors_ = [];
for (var i = 0; i < this.LEVELS_.length; i++) {
this.floors_.push(new Floor(this.map_));
}
this.addLevelControl_();
this.addMapOverlay_();
this.loadMapContent_();
this.initLocationHashWatcher_();
if (!document.location.hash) {
this.showLevel(1, true);
}
}
IoMap.prototype = new google.maps.MVCObject;
/**
* The id of the Element to add the map to.
*
* @type {string}
* @const
*/
IoMap.prototype.MAP_ID = 'map-canvas';
/**
* The levels of the Moscone Center.
*
* @type {Array.<string>}
* @private
*/
IoMap.prototype.LEVELS_ = ['1', '2', '3'];
/**
* Location where the tiles are hosted.
*
* @type {string}
* @private
*/
IoMap.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/5/';
/**
* The minimum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MIN_ZOOM_ = 16;
/**
* The maximum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MAX_ZOOM_ = 20;
/**
* The template for loading tiles. Replace {L} with the level, {Z} with the
* zoom level, {X} and {Y} with respective tile coordinates.
*
* @type {string}
* @private
*/
IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* The extent of the overlay at certain zoom levels.
*
* @type {Object.<string, Array.<Array.<number>>>}
* @private
*/
IoMap.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* The previous hash to compare against.
*
* @type {string?}
* @private
*/
IoMap.prototype.prevHash_ = null;
/**
* Initialise the location hash watcher.
*
* @private
*/
IoMap.prototype.initLocationHashWatcher_ = function() {
var that = this;
if ('onhashchange' in window) {
window.addEventListener('hashchange', function() {
that.parseHash_();
}, true);
} else {
var that = this
window.setInterval(function() {
that.parseHash_();
}, 100);
}
this.parseHash_();
};
/**
* Called from Android.
*
* @param {Number} x A percentage to pan left by.
*/
IoMap.prototype.panLeft = function(x) {
var div = this.map_.getDiv();
var left = div.clientWidth * x;
this.map_.panBy(left, 0);
};
IoMap.prototype['panLeft'] = IoMap.prototype.panLeft;
/**
* Adds the level switcher to the top left of the map.
*
* @private
*/
IoMap.prototype.addLevelControl_ = function() {
var control = new LevelControl(this, this.LEVELS_).getElement();
this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control);
};
/**
* Shows a floor based on the content of location.hash.
*
* @private
*/
IoMap.prototype.parseHash_ = function() {
var hash = document.location.hash;
if (hash == this.prevHash_) {
return;
}
this.prevHash_ = hash;
var level = 1;
if (hash) {
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
level = parseInt(match[1], 10);
}
}
this.showLevel(level, true);
};
/**
* Updates location.hash based on the currently shown floor.
*
* @param {string?} opt_hash
*/
IoMap.prototype.setHash = function(opt_hash) {
var hash = document.location.hash.substring(1);
if (hash == opt_hash) {
return;
}
if (opt_hash) {
document.location.hash = opt_hash;
} else {
document.location.hash = 'level' + this.get('level');
}
};
IoMap.prototype['setHash'] = IoMap.prototype.setHash;
/**
* Called from spreadsheets.
*/
IoMap.prototype.loadSandboxCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.companyName = entry['gsx$companyname']['$t'];
item.companyUrl = entry['gsx$companyurl']['$t'];
var p = entry['gsx$companypod']['$t'];
item.pod = p;
p = p.toLowerCase().replace(/\s+/, '');
item.sessionRoom = p;
contentItems.push(item);
};
this.sandboxItems_ = contentItems;
this.ready_ = true;
this.addMapContent_();
};
/**
* Called from spreadsheets.
*
* @param {Object} json The json feed from the spreadsheet.
*/
IoMap.prototype.loadSessionsCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.sessionDate = entry['gsx$sessiondate']['$t'];
item.sessionAbstract = entry['gsx$sessionabstract']['$t'];
item.sessionHashtag = entry['gsx$sessionhashtag']['$t'];
item.sessionLevel = entry['gsx$sessionlevel']['$t'];
item.sessionTitle = entry['gsx$sessiontitle']['$t'];
item.sessionTrack = entry['gsx$sessiontrack']['$t'];
item.sessionUrl = entry['gsx$sessionurl']['$t'];
item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t'];
item.sessionTime = entry['gsx$sessiontime']['$t'];
item.sessionRoom = entry['gsx$sessionroom']['$t'];
item.sessionTags = entry['gsx$sessiontags']['$t'];
item.sessionSpeakers = entry['gsx$sessionspeakers']['$t'];
if (item.sessionDate.indexOf('10') != -1) {
item.sessionDay = 10;
} else {
item.sessionDay = 11;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.sessionItems_ = contentItems;
};
/**
* Converts the time in the spread sheet to 24 hour time.
*
* @param {string} time The time like 10:42am.
*/
IoMap.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* Loads the map content from Google Spreadsheets.
*
* @private
*/
IoMap.prototype.loadMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 'tmaLiaNqIWYYtuuhmIyG0uQ';
var worksheetIDs = {
sessions: 'od6',
sandbox: 'od4'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Called from Android.
*
* @param {string} roomId The id of the room to load.
*/
IoMap.prototype.showLocationById = function(roomId) {
var locations = this.LOCATIONS_;
for (var level in locations) {
var levelId = level.replace('LEVEL', '');
for (var loc in locations[level]) {
var room = locations[level][loc];
if (loc == roomId) {
var pos = new google.maps.LatLng(room.lat, room.lng);
this.map_.panTo(pos);
this.map_.setZoom(19);
this.showLevel(levelId);
if (room.marker_) {
room.marker_.setAnimation(google.maps.Animation.BOUNCE);
// Disable the animation after 5 seconds.
window.setTimeout(function() {
room.marker_.setAnimation();
}, 5000);
}
return;
}
}
}
};
IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById;
/**
* Called when the level is changed. Hides and shows floors.
*/
IoMap.prototype['level_changed'] = function() {
var level = this.get('level');
if (this.infoWindow_) {
this.infoWindow_.setMap(null);
}
for (var i = 1, floor; floor = this.floors_[i - 1]; i++) {
if (i == level) {
floor.show();
} else {
floor.hide();
}
}
this.setHash('level' + level);
};
/**
* Shows a particular floor.
*
* @param {string} level The level to show.
* @param {boolean=} opt_force if true, changes the floor even if it's already
* the current floor.
*/
IoMap.prototype.showLevel = function(level, opt_force) {
if (!opt_force && level == this.get('level')) {
return;
}
this.set('level', level);
};
IoMap.prototype['showLevel'] = IoMap.prototype.showLevel;
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
IoMap.prototype.createContentMarker_ = function(item) {
if (!item.icon) {
item.icon = 'generic';
}
var image;
var shadow;
switch(item.icon) {
case 'generic':
case 'info':
case 'media':
var image = new google.maps.MarkerImage(
'marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0,0),
new google.maps.Point(13, 26));
break;
case 'toilets':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(35, 35),
new google.maps.Point(0, 0),
new google.maps.Point(17, 17));
break;
case 'elevator':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(48, 26),
new google.maps.Point(0, 0),
new google.maps.Point(24, 13));
break;
}
var inactive = item.type == 'inactive';
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new SmartMarker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
minZoom: inactive ? 19 : 18,
clickable: !inactive
});
marker['type_'] = item.type;
if (!inactive) {
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo_(item);
});
}
return marker;
};
/**
* Create a label with the content item's title atribute, if it exists.
*
* @param {Object} item The content item for the marker.
* @return {MapLabel?} The new label.
* @private
*/
IoMap.prototype.createContentLabel_ = function(item) {
if (!item.title || item.suppressLabel) {
return null;
}
var latLng = new google.maps.LatLng(item.lat, item.lng);
return new MapLabel({
'text': item.title,
'position': latLng,
'minZoom': item.labelMinZoom || 18,
'align': item.labelAlign || 'center',
'fontColor': item.labelColor,
'fontSize': item.labelSize || 12
});
}
/**
* Open a info window a content item.
*
* @param {Object} item A content item with content and a marker.
*/
IoMap.prototype.openContentInfo_ = function(item) {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['openContentInfo'](item.room);
return;
}
var sessionBase = 'http://www.google.com/events/io/2011/sessions.html';
var now = new Date();
var may11 = new Date('May 11, 2011');
var day = now < may11 ? 10 : 11;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session') {
if (day == 10) {
content.push('<h3>' + title + ' - Tuesday May 10</h3>');
} else {
content.push('<h3>' + title + ' - Wednesday May 11</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.sessionRoom == item.room && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
session.sessionUrl + '">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox') {
var sandboxName;
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.sessionRoom == item.room) {
if (!sandboxName) {
sandboxName = sandbox.pod;
content.push('<h3>' + sandbox.pod + '</h3>');
content.push('<div class="sandbox">');
}
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
empty = false;
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
};
/**
* A custom sort function to sort the sessions by start time.
*
* @param {string} a SessionA<enter description here>.
* @param {string} b SessionB.
* @return {boolean} True if sessionA is after sessionB.
*/
IoMap.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return aStart > bStart;
};
/**
* Adds all overlays (markers, labels) to the map.
*/
IoMap.prototype.addMapContent_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var floor = this.floors_[i];
var locations = this.LOCATIONS_['LEVEL' + level];
for (var roomId in locations) {
var room = locations[roomId];
if (room.room == undefined) {
room.room = roomId;
}
if (room.type != 'label') {
var marker = this.createContentMarker_(room);
floor.addOverlay(marker);
room.marker_ = marker;
}
var label = this.createContentLabel_(room);
floor.addOverlay(label);
}
}
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
IoMap.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
return template
.replace('{L}', /** @type string */(this.get('level')))
.replace('{Z}', /** @type string */(zoom))
.replace('{X}', /** @type string */(coord.x))
.replace('{Y}', /** @type string */(coord.y));
};
/**
* Add the floor overlay to the map.
*
* @private
*/
IoMap.prototype.addMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256)
});
google.maps.event.addListener(this, 'level_changed', function() {
var overlays = that.map_.overlayMapTypes;
if (overlays.length) {
overlays.removeAt(0);
}
overlays.push(overlay);
});
};
/**
* All the features of the map.
* @type {Object.<string, Object.<string, Object.<string, *>>>}
*/
IoMap.prototype.LOCATIONS_ = {
'LEVEL1': {
'northentrance': {
lat: 37.78381535905965,
lng: -122.40362226963043,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'eastentrance': {
lat: 37.78328434094279,
lng: -122.40319311618805,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'lunchroom': {
lat: 37.783112633669575,
lng: -122.40407556295395,
title: 'Lunch Room'
},
'restroom1a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator1a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'gearpickup': {
lat: 37.78367863020862,
lng: -122.4037617444992,
title: 'Gear Pickup',
type: 'label'
},
'checkin': {
lat: 37.78334369645064,
lng: -122.40335404872894,
title: 'Check In',
type: 'label'
},
'escalators1': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
}
},
'LEVEL2': {
'escalators2': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left',
labelMinZoom: 19
},
'press': {
lat: 37.78316774962791,
lng: -122.40360751748085,
title: 'Press Room',
type: 'label'
},
'restroom2a': {
lat: 37.7835334217721,
lng: -122.40386635065079,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom2b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator2a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'1': {
lat: 37.78346240732338,
lng: -122.40415401756763,
icon: 'media',
title: 'Room 1',
type: 'session',
room: '1'
},
'2': {
lat: 37.78335005596647,
lng: -122.40431495010853,
icon: 'media',
title: 'Room 2',
type: 'session',
room: '2'
},
'3': {
lat: 37.783215446097124,
lng: -122.404490634799,
icon: 'media',
title: 'Room 3',
type: 'session',
room: '3'
},
'4': {
lat: 37.78332461789977,
lng: -122.40381203591824,
icon: 'media',
title: 'Room 4',
type: 'session',
room: '4'
},
'5': {
lat: 37.783186828219335,
lng: -122.4039850383997,
icon: 'media',
title: 'Room 5',
type: 'session',
room: '5'
},
'6': {
lat: 37.783013000871364,
lng: -122.40420497953892,
icon: 'media',
title: 'Room 6',
type: 'session',
room: '6'
},
'7': {
lat: 37.7828783903882,
lng: -122.40438133478165,
icon: 'media',
title: 'Room 7',
type: 'session',
room: '7'
},
'8': {
lat: 37.78305009820564,
lng: -122.40378588438034,
icon: 'media',
title: 'Room 8',
type: 'session',
room: '8'
},
'9': {
lat: 37.78286673120095,
lng: -122.40402393043041,
icon: 'media',
title: 'Room 9',
type: 'session',
room: '9'
},
'10': {
lat: 37.782719401312626,
lng: -122.40420028567314,
icon: 'media',
title: 'Room 10',
type: 'session',
room: '10'
},
'appengine': {
lat: 37.783362774996625,
lng: -122.40335941314697,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'App Engine'
},
'chrome': {
lat: 37.783730566003555,
lng: -122.40378990769386,
type: 'sandbox',
icon: 'generic',
title: 'Chrome'
},
'googleapps': {
lat: 37.783303419504094,
lng: -122.40320384502411,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Apps'
},
'geo': {
lat: 37.783365954753805,
lng: -122.40314483642578,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Geo'
},
'accessibility': {
lat: 37.783414711013485,
lng: -122.40342646837234,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Accessibility'
},
'developertools': {
lat: 37.783457107734876,
lng: -122.40347877144814,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Dev Tools'
},
'commerce': {
lat: 37.78349102509448,
lng: -122.40351900458336,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Commerce'
},
'youtube': {
lat: 37.783537661438515,
lng: -122.40358605980873,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'YouTube'
},
'officehoursfloor2a': {
lat: 37.78249045644304,
lng: -122.40410104393959,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2': {
lat: 37.78266852473624,
lng: -122.40387573838234,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2b': {
lat: 37.782844472747406,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
}
},
'LEVEL3': {
'escalators3': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
},
'restroom3a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom3b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator3a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote',
type: 'label'
},
'11': {
lat: 37.78283069370135,
lng: -122.40408763289452,
icon: 'media',
title: 'Room 11',
type: 'session',
room: '11'
},
'googletv': {
lat: 37.7837125474666,
lng: -122.40362092852592,
type: 'sandbox',
icon: 'generic',
title: 'Google TV'
},
'android': {
lat: 37.783530242022124,
lng: -122.40358874201775,
type: 'sandbox',
icon: 'generic',
title: 'Android'
},
'officehoursfloor3': {
lat: 37.782843412820846,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor3a': {
lat: 37.78267170452323,
lng: -122.40387842059135,
title: 'Office Hours',
type: 'label'
}
}
};
google.maps.event.addDomListener(window, 'load', function() {
window['IoMap'] = new IoMap();
});
| JavaScript |
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| JavaScript |
/**
* @license
*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
| JavaScript |
/**
* @preserve jQuery DateTimePicker plugin v2.2.8
* @homepage http://xdsoft.net/jqplugins/datetimepicker/
* (c) 2014, Chupurnov Valeriy.
*/
(function( $ ) {
'use strict';
var default_options = {
i18n:{
bg:{ // Bulgarian
months:[
"Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
],
dayOfWeek:[
"Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
]
},
fa:{ // Persian/Farsi
months:[
'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'
],
dayOfWeek:[
'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه'
]
},
ru:{ // Russian
months:[
'Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'
],
dayOfWeek:[
"Вск", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"
]
},
en:{ // English
months: [
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
],
dayOfWeek: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
]
},
el:{ // Ελληνικά
months: [
"Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"
],
dayOfWeek: [
"Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"
]
},
de:{ // German
months:[
'Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'
],
dayOfWeek:[
"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"
]
},
nl:{ // Dutch
months:[
"januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"
],
dayOfWeek:[
"zo", "ma", "di", "wo", "do", "vr", "za"
]
},
tr:{ // Turkish
months:[
"Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
],
dayOfWeek:[
"Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"
]
},
fr:{ //French
months:[
"Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
],
dayOfWeek:[
"Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"
]
},
es:{ // Spanish
months: [
"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
],
dayOfWeek: [
"Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"
]
},
th:{ // Thai
months:[
'มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฎาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'
],
dayOfWeek:[
'อา.','จ.','อ.','พ.','พฤ.','ศ.','ส.'
]
},
pl:{ // Polish
months: [
"styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"
],
dayOfWeek: [
"nd", "pn", "wt", "śr", "cz", "pt", "sb"
]
},
pt:{ // Portuguese
months: [
"Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
],
dayOfWeek: [
"Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"
]
},
ch:{ // Simplified Chinese
months: [
"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"
],
dayOfWeek: [
"日", "一","二","三","四","五","六"
]
},
se:{ // Swedish
months: [
"Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September","Oktober", "November", "December"
],
dayOfWeek: [
"Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"
]
},
kr:{ // Korean
months: [
"1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"
],
dayOfWeek: [
"일", "월", "화", "수", "목", "금", "토"
]
},
it:{ // Italian
months: [
"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"
],
dayOfWeek: [
"Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"
]
},
da:{ // Dansk
months: [
"January", "Februar", "Marts", "April", "Maj", "Juni", "July", "August", "September", "Oktober", "November", "December"
],
dayOfWeek: [
"Søn", "Man", "Tir", "ons", "Tor", "Fre", "lør"
]
},
ja:{ // Japanese
months: [
"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"
],
dayOfWeek: [
"日", "月", "火", "水", "木", "金", "土"
]
},
vi:{ // Vietnamese
months: [
"Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"
],
dayOfWeek: [
"CN", "T2", "T3", "T4", "T5", "T6", "T7"
]
},
sl:{ // Slovenščina
months: [
"Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"
],
dayOfWeek: [
"Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"
]
}
},
value:'',
lang:'en',
format: 'Y/m/d H:i',
formatTime: 'H:i',
formatDate: 'Y/m/d',
startDate: false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05',
step:60,
monthChangeSpinner:true,
closeOnDateSelect:false,
closeOnWithoutClick:true,
timepicker:true,
datepicker:true,
minDate:false,
maxDate:false,
minTime:false,
maxTime:false,
allowTimes:[],
opened:false,
initTime:true,
inline:false,
onSelectDate:function() {},
onSelectTime:function() {},
onChangeMonth:function() {},
onChangeDateTime:function() {},
onShow:function() {},
onClose:function() {},
onGenerate:function() {},
withoutCopyright:true,
inverseButton:false,
hours12:false,
next: 'xdsoft_next',
prev : 'xdsoft_prev',
dayOfWeekStart:0,
timeHeightInTimePicker:25,
timepickerScrollbar:true,
todayButton:true, // 2.1.0
defaultSelect:true, // 2.1.0
scrollMonth:true,
scrollTime:true,
scrollInput:true,
lazyInit:false,
mask:false,
validateOnBlur:true,
allowBlank:true,
yearStart:1950,
yearEnd:2050,
style:'',
id:'',
roundTime:'round', // ceil, floor
className:'',
weekends : [],
yearOffset:0
};
// fix for ie8
if ( !Array.prototype.indexOf ) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
};
Date.prototype.countDaysInMonth = function(){
return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate();
};
$.fn.xdsoftScroller = function( _percent ) {
return this.each(function() {
var timeboxparent = $(this);
if( !$(this).hasClass('xdsoft_scroller_box') ) {
var pointerEventToXY = function( e ) {
var out = {x:0, y:0};
if( e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel' ) {
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
out.x = touch.pageX;
out.y = touch.pageY;
}else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
out.x = e.pageX;
out.y = e.pageY;
}
return out;
},
move = 0,
timebox = timeboxparent.children().eq(0),
parentHeight = timeboxparent[0].clientHeight,
height = timebox[0].offsetHeight,
scrollbar = $('<div class="xdsoft_scrollbar"></div>'),
scroller = $('<div class="xdsoft_scroller"></div>'),
maximumOffset = 100,
start = false;
scrollbar.append(scroller);
timeboxparent.addClass('xdsoft_scroller_box').append(scrollbar);
scroller.on('mousedown.xdsoft_scroller',function ( event ) {
if( !parentHeight )
timeboxparent.trigger('resize_scroll.xdsoft_scroller',[_percent]);
var pageY = event.pageY,
top = parseInt(scroller.css('margin-top')),
h1 = scrollbar[0].offsetHeight;
$(document.body).addClass('xdsoft_noselect');
$([document.body,window]).on('mouseup.xdsoft_scroller',function arguments_callee() {
$([document.body,window]).off('mouseup.xdsoft_scroller',arguments_callee)
.off('mousemove.xdsoft_scroller',move)
.removeClass('xdsoft_noselect');
});
$(document.body).on('mousemove.xdsoft_scroller',move = function(event) {
var offset = event.pageY-pageY+top;
if( offset<0 )
offset = 0;
if( offset+scroller[0].offsetHeight>h1 )
offset = h1-scroller[0].offsetHeight;
timeboxparent.trigger('scroll_element.xdsoft_scroller',[maximumOffset?offset/maximumOffset:0]);
});
});
timeboxparent
.on('scroll_element.xdsoft_scroller',function( event,percent ) {
if( !parentHeight )
timeboxparent.trigger('resize_scroll.xdsoft_scroller',[percent,true]);
percent = percent>1?1:(percent<0||isNaN(percent))?0:percent;
scroller.css('margin-top',maximumOffset*percent);
timebox.css('marginTop',-parseInt((height-parentHeight)*percent))
})
.on('resize_scroll.xdsoft_scroller',function( event,_percent,noTriggerScroll ) {
parentHeight = timeboxparent[0].clientHeight;
height = timebox[0].offsetHeight;
var percent = parentHeight/height,
sh = percent*scrollbar[0].offsetHeight;
if( percent>1 )
scroller.hide();
else{
scroller.show();
scroller.css('height',parseInt(sh>10?sh:10));
maximumOffset = scrollbar[0].offsetHeight-scroller[0].offsetHeight;
if( noTriggerScroll!==true )
timeboxparent.trigger('scroll_element.xdsoft_scroller',[_percent?_percent:Math.abs(parseInt(timebox.css('marginTop')))/(height-parentHeight)]);
}
});
timeboxparent.mousewheel&&timeboxparent.mousewheel(function(event, delta, deltaX, deltaY) {
var top = Math.abs(parseInt(timebox.css('marginTop')));
timeboxparent.trigger('scroll_element.xdsoft_scroller',[(top-delta*20)/(height-parentHeight)]);
event.stopPropagation();
return false;
});
timeboxparent.on('touchstart',function( event ) {
start = pointerEventToXY(event);
});
timeboxparent.on('touchmove',function( event ) {
if( start ) {
var coord = pointerEventToXY(event), top = Math.abs(parseInt(timebox.css('marginTop')));
timeboxparent.trigger('scroll_element.xdsoft_scroller',[(top-(coord.y-start.y))/(height-parentHeight)]);
event.stopPropagation();
event.preventDefault();
};
});
timeboxparent.on('touchend touchcancel',function( event ) {
start = false;
});
}
timeboxparent.trigger('resize_scroll.xdsoft_scroller',[_percent]);
});
};
$.fn.datetimepicker = function( opt ) {
var KEY0 = 48,
KEY9 = 57,
_KEY0 = 96,
_KEY9 = 105,
CTRLKEY = 17,
DEL = 46,
ENTER = 13,
ESC = 27,
BACKSPACE = 8,
ARROWLEFT = 37,
ARROWUP = 38,
ARROWRIGHT = 39,
ARROWDOWN = 40,
TAB = 9,
F5 = 116,
AKEY = 65,
CKEY = 67,
VKEY = 86,
ZKEY = 90,
YKEY = 89,
ctrlDown = false,
options = ($.isPlainObject(opt)||!opt)?$.extend(true,{},default_options,opt):$.extend({},default_options),
lazyInitTimer = 0,
lazyInit = function( input ){
input
.on('open.xdsoft focusin.xdsoft mousedown.xdsoft',function initOnActionCallback(event) {
if( input.is(':disabled')||input.is(':hidden')||!input.is(':visible')||input.data( 'xdsoft_datetimepicker') )
return;
clearTimeout(lazyInitTimer);
lazyInitTimer = setTimeout(function() {
if( !input.data( 'xdsoft_datetimepicker') )
createDateTimePicker(input);
input
.off('open.xdsoft focusin.xdsoft mousedown.xdsoft',initOnActionCallback)
.trigger('open.xdsoft');
},100);
});
},
createDateTimePicker = function( input ) {
var datetimepicker = $('<div '+(options.id?'id="'+options.id+'"':'')+' '+(options.style?'style="'+options.style+'"':'')+' class="xdsoft_datetimepicker xdsoft_noselect '+options.className+'"></div>'),
xdsoft_copyright = $('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),
datepicker = $('<div class="xdsoft_datepicker active"></div>'),
mounth_picker = $('<div class="xdsoft_mounthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button><div class="xdsoft_label xdsoft_month"><span></span></div><div class="xdsoft_label xdsoft_year"><span></span></div><button type="button" class="xdsoft_next"></button></div>'),
calendar = $('<div class="xdsoft_calendar"></div>'),
timepicker = $('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),
timeboxparent = timepicker.find('.xdsoft_time_box').eq(0),
timebox = $('<div class="xdsoft_time_variant"></div>'),
scrollbar = $('<div class="xdsoft_scrollbar"></div>'),
scroller = $('<div class="xdsoft_scroller"></div>'),
monthselect =$('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>'),
yearselect =$('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>');
//constructor lego
mounth_picker
.find('.xdsoft_month span')
.after(monthselect);
mounth_picker
.find('.xdsoft_year span')
.after(yearselect);
mounth_picker
.find('.xdsoft_month,.xdsoft_year')
.on('mousedown.xdsoft',function(event) {
mounth_picker
.find('.xdsoft_select')
.hide();
var select = $(this).find('.xdsoft_select').eq(0),
val = 0,
top = 0;
if( _xdsoft_datetime.currentTime )
val = _xdsoft_datetime.currentTime[$(this).hasClass('xdsoft_month')?'getMonth':'getFullYear']();
select.show();
for(var items = select.find('div.xdsoft_option'),i = 0;i<items.length;i++) {
if( items.eq(i).data('value')==val ) {
break;
}else top+=items[0].offsetHeight;
}
select.xdsoftScroller(top/(select.children()[0].offsetHeight-(select[0].clientHeight)));
event.stopPropagation();
return false;
});
mounth_picker
.find('.xdsoft_select')
.xdsoftScroller()
.on('mousedown.xdsoft',function( event ) {
event.stopPropagation();
event.preventDefault();
})
.on('mousedown.xdsoft','.xdsoft_option',function( event ) {
if( _xdsoft_datetime&&_xdsoft_datetime.currentTime )
_xdsoft_datetime.currentTime[$(this).parent().parent().hasClass('xdsoft_monthselect')?'setMonth':'setFullYear']($(this).data('value'));
$(this).parent().parent().hide();
datetimepicker.trigger('xchange.xdsoft');
options.onChangeMonth&&options.onChangeMonth.call&&options.onChangeMonth.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
});
// set options
datetimepicker.setOptions = function( _options ) {
options = $.extend(true,{},options,_options);
if( _options.allowTimes && $.isArray(_options.allowTimes) && _options.allowTimes.length ){
options['allowTimes'] = $.extend(true,[],_options.allowTimes);
}
if( _options.weekends && $.isArray(_options.weekends) && _options.weekends.length ){
options['weekends'] = $.extend(true,[],_options.weekends);
}
if( (options.open||options.opened)&&(!options.inline) ) {
input.trigger('open.xdsoft');
}
if( options.inline ) {
triggerAfterOpen = true;
datetimepicker.addClass('xdsoft_inline');
input.after(datetimepicker).hide();
}
if( options.inverseButton ) {
options.next = 'xdsoft_prev';
options.prev = 'xdsoft_next';
}
if( options.datepicker )
datepicker.addClass('active');
else
datepicker.removeClass('active');
if( options.timepicker )
timepicker.addClass('active');
else
timepicker.removeClass('active');
if( options.value ){
input&&input.val&&input.val(options.value);
_xdsoft_datetime.setCurrentTime(options.value);
}
if( isNaN(options.dayOfWeekStart)||parseInt(options.dayOfWeekStart)<0||parseInt(options.dayOfWeekStart)>6 )
options.dayOfWeekStart = 0;
else
options.dayOfWeekStart = parseInt(options.dayOfWeekStart);
if( !options.timepickerScrollbar )
scrollbar.hide();
if( options.minDate && /^-(.*)$/.test(options.minDate) ){
options.minDate = _xdsoft_datetime.strToDateTime(options.minDate).dateFormat( options.formatDate );
}
if( options.maxDate && /^\+(.*)$/.test(options.maxDate) ) {
options.maxDate = _xdsoft_datetime.strToDateTime(options.maxDate).dateFormat( options.formatDate );
}
mounth_picker
.find('.xdsoft_today_button')
.css('visibility',!options.todayButton?'hidden':'visible');
if( options.mask ) {
var e,
getCaretPos = function ( input ) {
try{
if ( document.selection && document.selection.createRange ) {
var range = document.selection.createRange();
return range.getBookmark().charCodeAt(2) - 2;
}else
if ( input.setSelectionRange )
return input.selectionStart;
}catch(e) {
return 0;
}
},
setCaretPos = function ( node,pos ) {
var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
if(!node) {
return false;
}else if(node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
}else if(node.setSelectionRange) {
node.setSelectionRange(pos,pos);
return true;
}
return false;
},
isValidValue = function ( mask,value ) {
var reg = mask
.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g,'\\$1')
.replace(/_/g,'{digit+}')
.replace(/([0-9]{1})/g,'{digit$1}')
.replace(/\{digit([0-9]{1})\}/g,'[0-$1_]{1}')
.replace(/\{digit[\+]\}/g,'[0-9_]{1}');
return RegExp(reg).test(value);
};
input.off('keydown.xdsoft');
switch(true) {
case ( options.mask===true ):
options.mask = options.format
.replace(/Y/g,'9999')
.replace(/F/g,'9999')
.replace(/m/g,'19')
.replace(/d/g,'39')
.replace(/H/g,'29')
.replace(/i/g,'59')
.replace(/s/g,'59');
case ( $.type(options.mask) == 'string' ):
if( !isValidValue( options.mask,input.val() ) )
input.val(options.mask.replace(/[0-9]/g,'_'));
input.on('keydown.xdsoft',function( event ) {
var val = this.value,
key = event.which;
switch(true) {
case (( key>=KEY0&&key<=KEY9 )||( key>=_KEY0&&key<=_KEY9 ))||(key==BACKSPACE||key==DEL):
var pos = getCaretPos(this),
digit = ( key!=BACKSPACE&&key!=DEL )?String.fromCharCode((_KEY0 <= key && key <= _KEY9)? key-KEY0 : key):'_';
if( (key==BACKSPACE||key==DEL)&&pos ) {
pos--;
digit='_';
}
while( /[^0-9_]/.test(options.mask.substr(pos,1))&&pos<options.mask.length&&pos>0 )
pos+=( key==BACKSPACE||key==DEL )?-1:1;
val = val.substr(0,pos)+digit+val.substr(pos+1);
if( $.trim(val)=='' ){
val = options.mask.replace(/[0-9]/g,'_');
}else{
if( pos==options.mask.length )
break;
}
pos+=(key==BACKSPACE||key==DEL)?0:1;
while( /[^0-9_]/.test(options.mask.substr(pos,1))&&pos<options.mask.length&&pos>0 )
pos+=(key==BACKSPACE||key==DEL)?-1:1;
if( isValidValue( options.mask,val ) ) {
this.value = val;
setCaretPos(this,pos);
}else if( $.trim(val)=='' )
this.value = options.mask.replace(/[0-9]/g,'_');
else{
input.trigger('error_input.xdsoft');
}
break;
case ( !!~([AKEY,CKEY,VKEY,ZKEY,YKEY].indexOf(key))&&ctrlDown ):
case !!~([ESC,ARROWUP,ARROWDOWN,ARROWLEFT,ARROWRIGHT,F5,CTRLKEY,TAB,ENTER].indexOf(key)):
return true;
}
event.preventDefault();
return false;
});
break;
}
}
if( options.validateOnBlur ) {
input
.off('blur.xdsoft')
.on('blur.xdsoft', function() {
if( options.allowBlank && !$.trim($(this).val()).length ) {
$(this).val(null);
datetimepicker.data('xdsoft_datetime').empty();
}else if( !Date.parseDate( $(this).val(), options.format ) ) {
$(this).val((_xdsoft_datetime.now()).dateFormat( options.format ));
datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
}
else{
datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val());
}
datetimepicker.trigger('changedatetime.xdsoft');
});
}
options.dayOfWeekStartPrev = (options.dayOfWeekStart==0)?6:options.dayOfWeekStart-1;
datetimepicker
.trigger('xchange.xdsoft')
.trigger('afterOpen.xdsoft')
};
datetimepicker
.data('options',options)
.on('mousedown.xdsoft',function( event ) {
event.stopPropagation();
event.preventDefault();
yearselect.hide();
monthselect.hide();
return false;
});
var scroll_element = timepicker.find('.xdsoft_time_box');
scroll_element.append(timebox);
scroll_element.xdsoftScroller();
datetimepicker.on('afterOpen.xdsoft',function() {
scroll_element.xdsoftScroller();
});
datetimepicker
.append(datepicker)
.append(timepicker);
if( options.withoutCopyright!==true )
datetimepicker
.append(xdsoft_copyright);
datepicker
.append(mounth_picker)
.append(calendar);
$('body').append(datetimepicker);
var _xdsoft_datetime = new function() {
var _this = this;
_this.now = function() {
var d = new Date();
if( options.yearOffset )
d.setFullYear(d.getFullYear()+options.yearOffset);
return d;
};
_this.currentTime = this.now();
_this.isValidDate = function (d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
};
_this.setCurrentTime = function( dTime) {
_this.currentTime = (typeof dTime == 'string')? _this.strToDateTime(dTime) : _this.isValidDate(dTime) ? dTime: _this.now();
datetimepicker.trigger('xchange.xdsoft');
};
_this.empty = function() {
_this.currentTime = null;
};
_this.getCurrentTime = function( dTime) {
return _this.currentTime;
};
_this.nextMonth = function() {
var month = _this.currentTime.getMonth()+1;
if( month==12 ) {
_this.currentTime.setFullYear(_this.currentTime.getFullYear()+1);
month = 0;
}
_this.currentTime.setDate(
Math.min(
Date.daysInMonth[month],
_this.currentTime.getDate()
)
);
_this.currentTime.setMonth(month);
options.onChangeMonth&&options.onChangeMonth.call&&options.onChangeMonth.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
datetimepicker.trigger('xchange.xdsoft');
return month;
};
_this.prevMonth = function() {
var month = _this.currentTime.getMonth()-1;
if( month==-1 ) {
_this.currentTime.setFullYear(_this.currentTime.getFullYear()-1);
month = 11;
}
_this.currentTime.setDate(
Math.min(
Date.daysInMonth[month],
_this.currentTime.getDate()
)
);
_this.currentTime.setMonth(month);
options.onChangeMonth&&options.onChangeMonth.call&&options.onChangeMonth.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
datetimepicker.trigger('xchange.xdsoft');
return month;
};
_this.strToDateTime = function( sDateTime ) {
var tmpDate = [],timeOffset,currentTime;
if( ( tmpDate = /^(\+|\-)(.*)$/.exec(sDateTime) ) && ( tmpDate[2]=Date.parseDate(tmpDate[2], options.formatDate) ) ) {
timeOffset = tmpDate[2].getTime()-(tmpDate[2].getTimezoneOffset())*60000;
currentTime = new Date((_xdsoft_datetime.now()).getTime()+parseInt(tmpDate[1]+'1')*timeOffset);
}else
currentTime = sDateTime?Date.parseDate(sDateTime, options.format):_this.now();
if( !_this.isValidDate(currentTime) )
currentTime = _this.now();
return currentTime;
};
_this.strtodate = function( sDate ) {
var currentTime = sDate?Date.parseDate(sDate, options.formatDate):_this.now();
if( !_this.isValidDate(currentTime) )
currentTime = _this.now();
return currentTime;
};
_this.strtotime = function( sTime ) {
var currentTime = sTime?Date.parseDate(sTime, options.formatTime):_this.now();
if( !_this.isValidDate(currentTime) )
currentTime = _this.now();
return currentTime;
};
_this.str = function() {
return _this.currentTime.dateFormat(options.format);
};
};
mounth_picker
.find('.xdsoft_today_button')
.on('mousedown.xdsoft',function() {
datetimepicker.data('changed',true);
_xdsoft_datetime.setCurrentTime(0);
datetimepicker.trigger('afterOpen.xdsoft');
}).on('dblclick.xdsoft',function(){
input.val( _xdsoft_datetime.str() );
datetimepicker.trigger('close.xdsoft');
});
mounth_picker
.find('.xdsoft_prev,.xdsoft_next')
.on('mousedown.xdsoft',function() {
var $this = $(this),
timer = 0,
stop = false;
(function arguments_callee1(v) {
var month = _xdsoft_datetime.currentTime.getMonth();
if( $this.hasClass( options.next ) ) {
_xdsoft_datetime.nextMonth();
}else if( $this.hasClass( options.prev ) ) {
_xdsoft_datetime.prevMonth();
}
if (options.monthChangeSpinner) {
!stop&&(timer = setTimeout(arguments_callee1,v?v:100));
}
})(500);
$([document.body,window]).on('mouseup.xdsoft',function arguments_callee2() {
clearTimeout(timer);
stop = true;
$([document.body,window]).off('mouseup.xdsoft',arguments_callee2);
});
});
timepicker
.find('.xdsoft_prev,.xdsoft_next')
.on('mousedown.xdsoft',function() {
var $this = $(this),
timer = 0,
stop = false,
period = 110;
(function arguments_callee4(v) {
var pheight = timeboxparent[0].clientHeight,
height = timebox[0].offsetHeight,
top = Math.abs(parseInt(timebox.css('marginTop')));
if( $this.hasClass(options.next) && (height-pheight)- options.timeHeightInTimePicker>=top ) {
timebox.css('marginTop','-'+(top+options.timeHeightInTimePicker)+'px')
}else if( $this.hasClass(options.prev) && top-options.timeHeightInTimePicker>=0 ) {
timebox.css('marginTop','-'+(top-options.timeHeightInTimePicker)+'px')
}
timeboxparent.trigger('scroll_element.xdsoft_scroller',[Math.abs(parseInt(timebox.css('marginTop'))/(height-pheight))]);
period= ( period>10 )?10:period-10;
!stop&&(timer = setTimeout(arguments_callee4,v?v:period));
})(500);
$([document.body,window]).on('mouseup.xdsoft',function arguments_callee5() {
clearTimeout(timer);
stop = true;
$([document.body,window])
.off('mouseup.xdsoft',arguments_callee5);
});
});
var xchangeTimer = 0;
// base handler - generating a calendar and timepicker
datetimepicker
.on('xchange.xdsoft',function( event ) {
clearTimeout(xchangeTimer);
xchangeTimer = setTimeout(function(){
var table = '',
start = new Date(_xdsoft_datetime.currentTime.getFullYear(),_xdsoft_datetime.currentTime.getMonth(),1, 12, 0, 0),
i = 0,
today = _xdsoft_datetime.now();
while( start.getDay()!=options.dayOfWeekStart )
start.setDate(start.getDate()-1);
//generate calendar
table+='<table><thead><tr>';
// days
for(var j = 0; j<7; j++) {
table+='<th>'+options.i18n[options.lang].dayOfWeek[(j+options.dayOfWeekStart)>6?0:j+options.dayOfWeekStart]+'</th>';
}
table+='</tr></thead>';
table+='<tbody><tr>';
var maxDate = false, minDate = false;
if( options.maxDate!==false ) {
maxDate = _xdsoft_datetime.strtodate(options.maxDate);
maxDate = new Date(maxDate.getFullYear(),maxDate.getMonth(),maxDate.getDate(),23,59,59,999);
}
if( options.minDate!==false ) {
minDate = _xdsoft_datetime.strtodate(options.minDate);
minDate = new Date(minDate.getFullYear(),minDate.getMonth(),minDate.getDate());
}
var d,y,m,classes = [];
while( i<_xdsoft_datetime.currentTime.countDaysInMonth()||start.getDay()!=options.dayOfWeekStart||_xdsoft_datetime.currentTime.getMonth()==start.getMonth() ) {
classes = [];
i++;
d = start.getDate(); y = start.getFullYear(); m = start.getMonth();
classes.push('xdsoft_date');
if( ( maxDate!==false && start > maxDate )||( minDate!==false && start < minDate ) ){
classes.push('xdsoft_disabled');
}
if( _xdsoft_datetime.currentTime.getMonth()!=m ){
classes.push('xdsoft_other_month');
}
if( (options.defaultSelect||datetimepicker.data('changed')) && _xdsoft_datetime.currentTime.dateFormat( options.formatDate )==start.dateFormat( options.formatDate ) ) {
classes.push('xdsoft_current');
}
if( today.dateFormat( options.formatDate )==start.dateFormat( options.formatDate ) ) {
classes.push('xdsoft_today');
}
if( start.getDay()==0||start.getDay()==6||~options.weekends.indexOf(start.dateFormat( options.formatDate )) ) {
classes.push('xdsoft_weekend');
}
if(options.beforeShowDay && typeof options.beforeShowDay == 'function')
{
classes.push(options.beforeShowDay(start))
}
table+='<td data-date="'+d+'" data-month="'+m+'" data-year="'+y+'"'+' class="xdsoft_date xdsoft_day_of_week'+start.getDay()+' '+ classes.join(' ')+'">'+
'<div>'+d+'</div>'+
'</td>';
if( start.getDay()==options.dayOfWeekStartPrev ) {
table+='</tr>';
}
start.setDate(d+1);
}
table+='</tbody></table>';
calendar.html(table);
mounth_picker.find('.xdsoft_label span').eq(0).text(options.i18n[options.lang].months[_xdsoft_datetime.currentTime.getMonth()]);
mounth_picker.find('.xdsoft_label span').eq(1).text(_xdsoft_datetime.currentTime.getFullYear());
// generate timebox
var time = '',
h = '',
m ='',
line_time = function line_time( h,m ) {
var now = _xdsoft_datetime.now();
now.setHours(h);
h = parseInt(now.getHours());
now.setMinutes(m);
m = parseInt(now.getMinutes());
classes = [];
if( (options.maxTime!==false&&_xdsoft_datetime.strtotime(options.maxTime).getTime()<now.getTime())||(options.minTime!==false&&_xdsoft_datetime.strtotime(options.minTime).getTime()>now.getTime()))
classes.push('xdsoft_disabled');
if( (options.initTime||options.defaultSelect||datetimepicker.data('changed')) && parseInt(_xdsoft_datetime.currentTime.getHours())==parseInt(h)&&(options.step>59||Math[options.roundTime](_xdsoft_datetime.currentTime.getMinutes()/options.step)*options.step==parseInt(m))) {
if( options.defaultSelect||datetimepicker.data('changed')) {
classes.push('xdsoft_current');
} else if( options.initTime ) {
classes.push('xdsoft_init_time');
}
}
if( parseInt(today.getHours())==parseInt(h)&&parseInt(today.getMinutes())==parseInt(m))
classes.push('xdsoft_today');
time+= '<div class="xdsoft_time '+classes.join(' ')+'" data-hour="'+h+'" data-minute="'+m+'">'+now.dateFormat(options.formatTime)+'</div>';
};
if( !options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length ) {
for( var i=0,j=0;i<(options.hours12?12:24);i++ ) {
for( j=0;j<60;j+=options.step ) {
h = (i<10?'0':'')+i;
m = (j<10?'0':'')+j;
line_time( h,m );
}
}
}else{
for( var i=0;i<options.allowTimes.length;i++ ) {
h = _xdsoft_datetime.strtotime(options.allowTimes[i]).getHours();
m = _xdsoft_datetime.strtotime(options.allowTimes[i]).getMinutes();
line_time( h,m );
}
}
timebox.html(time);
var opt = '',
i = 0;
for( i = parseInt(options.yearStart,10)+options.yearOffset;i<= parseInt(options.yearEnd,10)+options.yearOffset;i++ ) {
opt+='<div class="xdsoft_option '+(_xdsoft_datetime.currentTime.getFullYear()==i?'xdsoft_current':'')+'" data-value="'+i+'">'+i+'</div>';
}
yearselect.children().eq(0)
.html(opt);
for( i = 0,opt = '';i<= 11;i++ ) {
opt+='<div class="xdsoft_option '+(_xdsoft_datetime.currentTime.getMonth()==i?'xdsoft_current':'')+'" data-value="'+i+'">'+options.i18n[options.lang].months[i]+'</div>';
}
monthselect.children().eq(0).html(opt);
$(datetimepicker)
.trigger('generate.xdsoft');
},10);
event.stopPropagation();
})
.on('afterOpen.xdsoft',function() {
if( options.timepicker ) {
var classType;
if( timebox.find('.xdsoft_current').length ) {
classType = '.xdsoft_current';
} else if( timebox.find('.xdsoft_init_time').length ) {
classType = '.xdsoft_init_time';
}
if( classType ) {
var pheight = timeboxparent[0].clientHeight,
height = timebox[0].offsetHeight,
top = timebox.find(classType).index()*options.timeHeightInTimePicker+1;
if( (height-pheight)<top )
top = height-pheight;
timeboxparent.trigger('scroll_element.xdsoft_scroller',[parseInt(top)/(height-pheight)]);
}else{
timeboxparent.trigger('scroll_element.xdsoft_scroller',[0]);
}
}
});
var timerclick = 0;
calendar
.on('click.xdsoft', 'td', function (xdevent) {
xdevent.stopPropagation(); // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
timerclick++;
var $this = $(this),
currentTime = _xdsoft_datetime.currentTime;
if( $this.hasClass('xdsoft_disabled') )
return false;
currentTime.setDate( 1 );
currentTime.setFullYear( $this.data('year') );
currentTime.setMonth( $this.data('month') );
currentTime.setDate( $this.data('date') );
datetimepicker.trigger('select.xdsoft',[currentTime]);
input.val( _xdsoft_datetime.str() );
if( (timerclick>1||(options.closeOnDateSelect===true||( options.closeOnDateSelect===0&&!options.timepicker )))&&!options.inline ) {
datetimepicker.trigger('close.xdsoft');
}
if( options.onSelectDate && options.onSelectDate.call ) {
options.onSelectDate.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
}
datetimepicker.data('changed',true);
datetimepicker.trigger('xchange.xdsoft');
datetimepicker.trigger('changedatetime.xdsoft');
setTimeout(function(){
timerclick = 0;
},200);
});
timebox
.on('click.xdsoft', 'div', function (xdevent) {
xdevent.stopPropagation(); // NAJ: Prevents closing of Pop-ups, Modals and Flyouts
var $this = $(this),
currentTime = _xdsoft_datetime.currentTime;
if( $this.hasClass('xdsoft_disabled') )
return false;
currentTime.setHours($this.data('hour'));
currentTime.setMinutes($this.data('minute'));
datetimepicker.trigger('select.xdsoft',[currentTime]);
datetimepicker.data('input').val( _xdsoft_datetime.str() );
!options.inline&&datetimepicker.trigger('close.xdsoft');
if( options.onSelectTime&&options.onSelectTime.call ) {
options.onSelectTime.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
}
datetimepicker.data('changed',true);
datetimepicker.trigger('xchange.xdsoft');
datetimepicker.trigger('changedatetime.xdsoft');
});
datetimepicker.mousewheel&&datepicker.mousewheel(function(event, delta, deltaX, deltaY) {
if( !options.scrollMonth )
return true;
if( delta<0 )
_xdsoft_datetime.nextMonth();
else
_xdsoft_datetime.prevMonth();
return false;
});
datetimepicker.mousewheel&&timeboxparent.unmousewheel().mousewheel(function(event, delta, deltaX, deltaY) {
if( !options.scrollTime )
return true;
var pheight = timeboxparent[0].clientHeight,
height = timebox[0].offsetHeight,
top = Math.abs(parseInt(timebox.css('marginTop'))),
fl = true;
if( delta<0 && (height-pheight)-options.timeHeightInTimePicker>=top ) {
timebox.css('marginTop','-'+(top+options.timeHeightInTimePicker)+'px');
fl = false;
}else if( delta>0&&top-options.timeHeightInTimePicker>=0 ) {
timebox.css('marginTop','-'+(top-options.timeHeightInTimePicker)+'px');
fl = false;
}
timeboxparent.trigger('scroll_element.xdsoft_scroller',[Math.abs(parseInt(timebox.css('marginTop'))/(height-pheight))]);
event.stopPropagation();
return fl;
});
var triggerAfterOpen = false;
datetimepicker
.on('changedatetime.xdsoft',function() {
if( options.onChangeDateTime&&options.onChangeDateTime.call ) {
var $input = datetimepicker.data('input');
options.onChangeDateTime.call(datetimepicker, _xdsoft_datetime.currentTime, $input);
$input.trigger('change');
}
})
.on('generate.xdsoft',function() {
if( options.onGenerate&&options.onGenerate.call )
options.onGenerate.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
if( triggerAfterOpen ){
datetimepicker.trigger('afterOpen.xdsoft');
triggerAfterOpen = false;
}
})
.on( 'click.xdsoft', function( xdevent )
{
xdevent.stopPropagation(); // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap
});
var current_time_index = 0;
input.mousewheel&&input.mousewheel(function( event, delta, deltaX, deltaY ) {
if( !options.scrollInput )
return true;
if( !options.datepicker && options.timepicker ) {
current_time_index = timebox.find('.xdsoft_current').length?timebox.find('.xdsoft_current').eq(0).index():0;
if( current_time_index+delta>=0&¤t_time_index+delta<timebox.children().length )
current_time_index+=delta;
timebox.children().eq(current_time_index).length&&timebox.children().eq(current_time_index).trigger('mousedown');
return false;
}else if( options.datepicker && !options.timepicker ) {
datepicker.trigger( event, [delta, deltaX, deltaY]);
input.val&&input.val( _xdsoft_datetime.str() );
datetimepicker.trigger('changedatetime.xdsoft');
return false;
}
});
var setPos = function() {
var offset = datetimepicker.data('input').offset(), top = offset.top+datetimepicker.data('input')[0].offsetHeight-1, left = offset.left;
if( top+datetimepicker[0].offsetHeight>$(window).height()+$(window).scrollTop() )
top = offset.top-datetimepicker[0].offsetHeight+1;
if (top < 0)
top = 0;
if( left+datetimepicker[0].offsetWidth>$(window).width() )
left = offset.left-datetimepicker[0].offsetWidth+datetimepicker.data('input')[0].offsetWidth;
datetimepicker.css({
left:left,
top:top
});
};
datetimepicker
.on('open.xdsoft', function() {
var onShow = true;
if( options.onShow&&options.onShow.call) {
onShow = options.onShow.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
}
if( onShow!==false ) {
datetimepicker.show();
setPos();
$(window)
.off('resize.xdsoft',setPos)
.on('resize.xdsoft',setPos);
if( options.closeOnWithoutClick ) {
$([document.body,window]).on('mousedown.xdsoft',function arguments_callee6() {
datetimepicker.trigger('close.xdsoft');
$([document.body,window]).off('mousedown.xdsoft',arguments_callee6);
});
}
}
})
.on('close.xdsoft', function( event ) {
var onClose = true;
if( options.onClose&&options.onClose.call ) {
onClose=options.onClose.call(datetimepicker,_xdsoft_datetime.currentTime,datetimepicker.data('input'));
}
if( onClose!==false&&!options.opened&&!options.inline ) {
datetimepicker.hide();
}
event.stopPropagation();
})
.data('input',input);
var timer = 0,
timer1 = 0;
datetimepicker.data('xdsoft_datetime',_xdsoft_datetime);
datetimepicker.setOptions(options);
function getCurrentValue(){
var ct = options.value?options.value:(input&&input.val&&input.val())?input.val():'';
if( ct && _xdsoft_datetime.isValidDate(ct = Date.parseDate(ct, options.format)) ) {
datetimepicker.data('changed',true);
}else
ct = '';
if( !ct && options.startDate!==false ){
ct = _xdsoft_datetime.strToDateTime(options.startDate);
}
return ct?ct:0;
}
_xdsoft_datetime.setCurrentTime( getCurrentValue() );
input
.data( 'xdsoft_datetimepicker',datetimepicker )
.on('open.xdsoft focusin.xdsoft mousedown.xdsoft',function(event) {
if( input.is(':disabled')||input.is(':hidden')||!input.is(':visible') )
return;
clearTimeout(timer);
timer = setTimeout(function() {
if( input.is(':disabled')||input.is(':hidden')||!input.is(':visible') )
return;
triggerAfterOpen = true;
_xdsoft_datetime.setCurrentTime(getCurrentValue());
datetimepicker.trigger('open.xdsoft');
},100);
})
.on('keydown.xdsoft',function( event ) {
var val = this.value,
key = event.which;
switch(true) {
case !!~([ENTER].indexOf(key)):
var elementSelector = $("input:visible,textarea:visible");
datetimepicker.trigger('close.xdsoft');
elementSelector.eq(elementSelector.index(this) + 1).focus();
return false;
case !!~[TAB].indexOf(key):
datetimepicker.trigger('close.xdsoft');
return true;
}
});
},
destroyDateTimePicker = function( input ) {
var datetimepicker = input.data('xdsoft_datetimepicker');
if( datetimepicker ) {
datetimepicker.data('xdsoft_datetime',null);
datetimepicker.remove();
input
.data( 'xdsoft_datetimepicker',null )
.off( 'open.xdsoft focusin.xdsoft focusout.xdsoft mousedown.xdsoft blur.xdsoft keydown.xdsoft' );
$(window).off('resize.xdsoft');
$([window,document.body]).off('mousedown.xdsoft');
input.unmousewheel&&input.unmousewheel();
}
};
$(document)
.off('keydown.xdsoftctrl keyup.xdsoftctrl')
.on('keydown.xdsoftctrl',function(e) {
if ( e.keyCode == CTRLKEY )
ctrlDown = true;
})
.on('keyup.xdsoftctrl',function(e) {
if ( e.keyCode == CTRLKEY )
ctrlDown = false;
});
return this.each(function() {
var datetimepicker;
if( datetimepicker = $(this).data('xdsoft_datetimepicker') ) {
if( $.type(opt) === 'string' ) {
switch(opt) {
case 'show':
$(this).select().focus();
datetimepicker.trigger( 'open.xdsoft' );
break;
case 'hide':
datetimepicker.trigger('close.xdsoft');
break;
case 'destroy':
destroyDateTimePicker($(this));
break;
case 'reset':
this.value = this.defaultValue;
if(!this.value || !datetimepicker.data('xdsoft_datetime').isValidDate(Date.parseDate(this.value, options.format)))
datetimepicker.data('changed',false);
datetimepicker.data('xdsoft_datetime').setCurrentTime(this.value);
break;
}
}else{
datetimepicker
.setOptions(opt);
}
return 0;
}else
if( ($.type(opt) !== 'string') ){
if( !options.lazyInit||options.open||options.inline ){
createDateTimePicker($(this));
}else
lazyInit($(this));
}
});
};
})( jQuery );
/*
* Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
*
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.1.3
*
* Requires: 1.2.2+
*/
(function(factory) {if(typeof define==='function'&&define.amd) {define(['jquery'],factory)}else if(typeof exports==='object') {module.exports=factory}else{factory(jQuery)}}(function($) {var toFix=['wheel','mousewheel','DOMMouseScroll','MozMousePixelScroll'];var toBind='onwheel'in document||document.documentMode>=9?['wheel']:['mousewheel','DomMouseScroll','MozMousePixelScroll'];var lowestDelta,lowestDeltaXY;if($.event.fixHooks) {for(var i=toFix.length;i;) {$.event.fixHooks[toFix[--i]]=$.event.mouseHooks}}$.event.special.mousewheel={setup:function() {if(this.addEventListener) {for(var i=toBind.length;i;) {this.addEventListener(toBind[--i],handler,false)}}else{this.onmousewheel=handler}},teardown:function() {if(this.removeEventListener) {for(var i=toBind.length;i;) {this.removeEventListener(toBind[--i],handler,false)}}else{this.onmousewheel=null}}};$.fn.extend({mousewheel:function(fn) {return fn?this.bind("mousewheel",fn):this.trigger("mousewheel")},unmousewheel:function(fn) {return this.unbind("mousewheel",fn)}});function handler(event) {var orgEvent=event||window.event,args=[].slice.call(arguments,1),delta=0,deltaX=0,deltaY=0,absDelta=0,absDeltaXY=0,fn;event=$.event.fix(orgEvent);event.type="mousewheel";if(orgEvent.wheelDelta) {delta=orgEvent.wheelDelta}if(orgEvent.detail) {delta=orgEvent.detail*-1}if(orgEvent.deltaY) {deltaY=orgEvent.deltaY*-1;delta=deltaY}if(orgEvent.deltaX) {deltaX=orgEvent.deltaX;delta=deltaX*-1}if(orgEvent.wheelDeltaY!==undefined) {deltaY=orgEvent.wheelDeltaY}if(orgEvent.wheelDeltaX!==undefined) {deltaX=orgEvent.wheelDeltaX*-1}absDelta=Math.abs(delta);if(!lowestDelta||absDelta<lowestDelta) {lowestDelta=absDelta}absDeltaXY=Math.max(Math.abs(deltaY),Math.abs(deltaX));if(!lowestDeltaXY||absDeltaXY<lowestDeltaXY) {lowestDeltaXY=absDeltaXY}fn=delta>0?'floor':'ceil';delta=Math[fn](delta/lowestDelta);deltaX=Math[fn](deltaX/lowestDeltaXY);deltaY=Math[fn](deltaY/lowestDeltaXY);args.unshift(event,delta,deltaX,deltaY);return($.event.dispatch||$.event.handle).apply(this,args)}}));
// Parse and Format Library
//http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
/*
* Copyright (C) 2004 Baron Schwartz <baron at sequent dot org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, version 2.1.
*
* 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 Lesser General Public License for more
* details.
*/
Date.parseFunctions={count:0};Date.parseRegexes=[];Date.formatFunctions={count:0};Date.prototype.dateFormat=function(b){if(b=="unixtime"){return parseInt(this.getTime()/1000);}if(Date.formatFunctions[b]==null){Date.createNewFormat(b);}var a=Date.formatFunctions[b];return this[a]();};Date.createNewFormat=function(format){var funcName="format"+Date.formatFunctions.count++;Date.formatFunctions[format]=funcName;var code="Date.prototype."+funcName+" = function() {return ";var special=false;var ch="";for(var i=0;i<format.length;++i){ch=format.charAt(i);if(!special&&ch=="\\"){special=true;}else{if(special){special=false;code+="'"+String.escape(ch)+"' + ";}else{code+=Date.getFormatCode(ch);}}}eval(code.substring(0,code.length-3)+";}");};Date.getFormatCode=function(a){switch(a){case"d":return"String.leftPad(this.getDate(), 2, '0') + ";case"D":return"Date.dayNames[this.getDay()].substring(0, 3) + ";case"j":return"this.getDate() + ";case"l":return"Date.dayNames[this.getDay()] + ";case"S":return"this.getSuffix() + ";case"w":return"this.getDay() + ";case"z":return"this.getDayOfYear() + ";case"W":return"this.getWeekOfYear() + ";case"F":return"Date.monthNames[this.getMonth()] + ";case"m":return"String.leftPad(this.getMonth() + 1, 2, '0') + ";case"M":return"Date.monthNames[this.getMonth()].substring(0, 3) + ";case"n":return"(this.getMonth() + 1) + ";case"t":return"this.getDaysInMonth() + ";case"L":return"(this.isLeapYear() ? 1 : 0) + ";case"Y":return"this.getFullYear() + ";case"y":return"('' + this.getFullYear()).substring(2, 4) + ";case"a":return"(this.getHours() < 12 ? 'am' : 'pm') + ";case"A":return"(this.getHours() < 12 ? 'AM' : 'PM') + ";case"g":return"((this.getHours() %12) ? this.getHours() % 12 : 12) + ";case"G":return"this.getHours() + ";case"h":return"String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + ";case"H":return"String.leftPad(this.getHours(), 2, '0') + ";case"i":return"String.leftPad(this.getMinutes(), 2, '0') + ";case"s":return"String.leftPad(this.getSeconds(), 2, '0') + ";case"O":return"this.getGMTOffset() + ";case"T":return"this.getTimezone() + ";case"Z":return"(this.getTimezoneOffset() * -60) + ";default:return"'"+String.escape(a)+"' + ";}};Date.parseDate=function(a,c){if(c=="unixtime"){return new Date(!isNaN(parseInt(a))?parseInt(a)*1000:0);}if(Date.parseFunctions[c]==null){Date.createParser(c);}var b=Date.parseFunctions[c];return Date[b](a);};Date.createParser=function(format){var funcName="parse"+Date.parseFunctions.count++;var regexNum=Date.parseRegexes.length;var currentGroup=1;Date.parseFunctions[format]=funcName;var code="Date."+funcName+" = function(input) {\nvar y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, z = -1;\nvar d = new Date();\ny = d.getFullYear();\nm = d.getMonth();\nd = d.getDate();\nvar results = input.match(Date.parseRegexes["+regexNum+"]);\nif (results && results.length > 0) {";var regex="";var special=false;var ch="";for(var i=0;i<format.length;++i){ch=format.charAt(i);if(!special&&ch=="\\"){special=true;}else{if(special){special=false;regex+=String.escape(ch);}else{obj=Date.formatCodeToRegex(ch,currentGroup);currentGroup+=obj.g;regex+=obj.s;if(obj.g&&obj.c){code+=obj.c;}}}}code+="if (y > 0 && z > 0){\nvar doyDate = new Date(y,0);\ndoyDate.setDate(z);\nm = doyDate.getMonth();\nd = doyDate.getDate();\n}";code+="if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n{return new Date(y, m, d, h, i, s);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n{return new Date(y, m, d, h, i);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0)\n{return new Date(y, m, d, h);}\nelse if (y > 0 && m >= 0 && d > 0)\n{return new Date(y, m, d);}\nelse if (y > 0 && m >= 0)\n{return new Date(y, m);}\nelse if (y > 0)\n{return new Date(y);}\n}return null;}";Date.parseRegexes[regexNum]=new RegExp("^"+regex+"$");eval(code);};Date.formatCodeToRegex=function(b,a){switch(b){case"D":return{g:0,c:null,s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};case"j":case"d":return{g:1,c:"d = parseInt(results["+a+"], 10);\n",s:"(\\d{1,2})"};case"l":return{g:0,c:null,s:"(?:"+Date.dayNames.join("|")+")"};case"S":return{g:0,c:null,s:"(?:st|nd|rd|th)"};case"w":return{g:0,c:null,s:"\\d"};case"z":return{g:1,c:"z = parseInt(results["+a+"], 10);\n",s:"(\\d{1,3})"};case"W":return{g:0,c:null,s:"(?:\\d{2})"};case"F":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+a+"].substring(0, 3)], 10);\n",s:"("+Date.monthNames.join("|")+")"};case"M":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+a+"]], 10);\n",s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};case"n":case"m":return{g:1,c:"m = parseInt(results["+a+"], 10) - 1;\n",s:"(\\d{1,2})"};case"t":return{g:0,c:null,s:"\\d{1,2}"};case"L":return{g:0,c:null,s:"(?:1|0)"};case"Y":return{g:1,c:"y = parseInt(results["+a+"], 10);\n",s:"(\\d{4})"};case"y":return{g:1,c:"var ty = parseInt(results["+a+"], 10);\ny = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",s:"(\\d{1,2})"};case"a":return{g:1,c:"if (results["+a+"] == 'am') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(am|pm)"};case"A":return{g:1,c:"if (results["+a+"] == 'AM') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(AM|PM)"};case"g":case"G":case"h":case"H":return{g:1,c:"h = parseInt(results["+a+"], 10);\n",s:"(\\d{1,2})"};case"i":return{g:1,c:"i = parseInt(results["+a+"], 10);\n",s:"(\\d{2})"};case"s":return{g:1,c:"s = parseInt(results["+a+"], 10);\n",s:"(\\d{2})"};case"O":return{g:0,c:null,s:"[+-]\\d{4}"};case"T":return{g:0,c:null,s:"[A-Z]{3}"};case"Z":return{g:0,c:null,s:"[+-]\\d{1,5}"};default:return{g:0,c:null,s:String.escape(b)};}};Date.prototype.getTimezone=function(){return this.toString().replace(/^.*? ([A-Z]{3}) [0-9]{4}.*$/,"$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/,"$1$2$3");};Date.prototype.getGMTOffset=function(){return(this.getTimezoneOffset()>0?"-":"+")+String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset())/60),2,"0")+String.leftPad(Math.abs(this.getTimezoneOffset())%60,2,"0");};Date.prototype.getDayOfYear=function(){var a=0;Date.daysInMonth[1]=this.isLeapYear()?29:28;for(var b=0;b<this.getMonth();++b){a+=Date.daysInMonth[b];}return a+this.getDate();};Date.prototype.getWeekOfYear=function(){var b=this.getDayOfYear()+(4-this.getDay());var a=new Date(this.getFullYear(),0,1);var c=(7-a.getDay()+4);return String.leftPad(Math.ceil((b-c)/7)+1,2,"0");};Date.prototype.isLeapYear=function(){var a=this.getFullYear();return((a&3)==0&&(a%100||(a%400==0&&a)));};Date.prototype.getFirstDayOfMonth=function(){var a=(this.getDay()-(this.getDate()-1))%7;return(a<0)?(a+7):a;};Date.prototype.getLastDayOfMonth=function(){var a=(this.getDay()+(Date.daysInMonth[this.getMonth()]-this.getDate()))%7;return(a<0)?(a+7):a;};Date.prototype.getDaysInMonth=function(){Date.daysInMonth[1]=this.isLeapYear()?29:28;return Date.daysInMonth[this.getMonth()];};Date.prototype.getSuffix=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};String.escape=function(a){return a.replace(/('|\\)/g,"\\$1");};String.leftPad=function(d,b,c){var a=new String(d);if(c==null){c=" ";}while(a.length<b){a=c+a;}return a;};Date.daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];Date.monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"];Date.dayNames=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];Date.y2kYear=50;Date.monthNumbers={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11};Date.patterns={ISO8601LongPattern:"Y-m-d H:i:s",ISO8601ShortPattern:"Y-m-d",ShortDatePattern:"n/j/Y",LongDatePattern:"l, F d, Y",FullDateTimePattern:"l, F d, Y g:i:s A",MonthDayPattern:"F d",ShortTimePattern:"g:i A",LongTimePattern:"g:i:s A",SortableDateTimePattern:"Y-m-d\\TH:i:s",UniversalSortableDateTimePattern:"Y-m-d H:i:sO",YearMonthPattern:"F, Y"};
| JavaScript |
/**
* @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time to build CKEditor again.
*
* If you would like to build CKEditor online again
* (for example to upgrade), visit one the following links:
*
* (1) http://ckeditor.com/builder
* Visit online builder to build CKEditor from scratch.
*
* (2) http://ckeditor.com/builder/0ebaeed5189874e28f9af28caed38f94
* Visit online builder to build CKEditor, starting with the same setup as before.
*
* (3) http://ckeditor.com/builder/download/0ebaeed5189874e28f9af28caed38f94
* Straight download link to the latest version of CKEditor (Optimized) with the same setup as before.
*
* NOTE:
* This file is not used by CKEditor, you may remove it.
* Changing this file will not change your CKEditor configuration.
*/
var CKBUILDER_CONFIG = {
skin: 'moonocolor',
preset: 'standard',
ignore: [
'dev',
'.gitignore',
'.gitattributes',
'README.md',
'.mailmap'
],
plugins : {
'basicstyles' : 1,
'blockquote' : 1,
'clipboard' : 1,
'contextmenu' : 1,
'elementspath' : 1,
'enterkey' : 1,
'entities' : 1,
'filebrowser' : 1,
'floatingspace' : 1,
'format' : 1,
'horizontalrule' : 1,
'htmlwriter' : 1,
'image' : 1,
'indentlist' : 1,
'link' : 1,
'list' : 1,
'magicline' : 1,
'maximize' : 1,
'pastefromword' : 1,
'pastetext' : 1,
'removeformat' : 1,
'resize' : 1,
'scayt' : 1,
'showborders' : 1,
'sourcearea' : 1,
'specialchar' : 1,
'stylescombo' : 1,
'tab' : 1,
'table' : 1,
'tabletools' : 1,
'toolbar' : 1,
'undo' : 1,
'wsc' : 1,
'wysiwygarea' : 1
},
languages : {
'en' : 1
}
}; | JavaScript |
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here.
// For complete reference see:
// http://docs.ckeditor.com/#!/api/CKEDITOR.config
// The toolbar groups arrangement, optimized for two toolbar rows.
config.toolbarGroups = [
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
{ name: 'links' },
{ name: 'insert' },
{ name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
{ name: 'styles' },
{ name: 'colors' },
{ name: 'about' }
];
// Remove some buttons provided by the standard plugins, which are
// not needed in the Standard(s) toolbar.
config.removeButtons = 'Underline,Subscript,Superscript';
// Set the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre';
// Simplify the dialog windows.
config.removeDialogTabs = 'image:advanced;link:advanced';
};
| JavaScript |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
| JavaScript |
/**
* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
// This file contains style definitions that can be used by CKEditor plugins.
//
// The most common use for it is the "stylescombo" plugin, which shows a combo
// in the editor toolbar, containing all styles. Other plugins instead, like
// the div plugin, use a subset of the styles on their feature.
//
// If you don't have plugins that depend on this file, you can simply ignore it.
// Otherwise it is strongly recommended to customize this file to match your
// website requirements and design properly.
CKEDITOR.stylesSet.add( 'default', [
/* Block Styles */
// These styles are already available in the "Format" combo ("format" plugin),
// so they are not needed here by default. You may enable them to avoid
// placing the "Format" combo in the toolbar, maintaining the same features.
/*
{ name: 'Paragraph', element: 'p' },
{ name: 'Heading 1', element: 'h1' },
{ name: 'Heading 2', element: 'h2' },
{ name: 'Heading 3', element: 'h3' },
{ name: 'Heading 4', element: 'h4' },
{ name: 'Heading 5', element: 'h5' },
{ name: 'Heading 6', element: 'h6' },
{ name: 'Preformatted Text',element: 'pre' },
{ name: 'Address', element: 'address' },
*/
{ name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } },
{ name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } },
{
name: 'Special Container',
element: 'div',
styles: {
padding: '5px 10px',
background: '#eee',
border: '1px solid #ccc'
}
},
/* Inline Styles */
// These are core styles available as toolbar buttons. You may opt enabling
// some of them in the Styles combo, removing them from the toolbar.
// (This requires the "stylescombo" plugin)
/*
{ name: 'Strong', element: 'strong', overrides: 'b' },
{ name: 'Emphasis', element: 'em' , overrides: 'i' },
{ name: 'Underline', element: 'u' },
{ name: 'Strikethrough', element: 'strike' },
{ name: 'Subscript', element: 'sub' },
{ name: 'Superscript', element: 'sup' },
*/
{ name: 'Marker', element: 'span', attributes: { 'class': 'marker' } },
{ name: 'Big', element: 'big' },
{ name: 'Small', element: 'small' },
{ name: 'Typewriter', element: 'tt' },
{ name: 'Computer Code', element: 'code' },
{ name: 'Keyboard Phrase', element: 'kbd' },
{ name: 'Sample Text', element: 'samp' },
{ name: 'Variable', element: 'var' },
{ name: 'Deleted Text', element: 'del' },
{ name: 'Inserted Text', element: 'ins' },
{ name: 'Cited Work', element: 'cite' },
{ name: 'Inline Quotation', element: 'q' },
{ name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } },
{ name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } },
/* Object Styles */
{
name: 'Styled image (left)',
element: 'img',
attributes: { 'class': 'left' }
},
{
name: 'Styled image (right)',
element: 'img',
attributes: { 'class': 'right' }
},
{
name: 'Compact table',
element: 'table',
attributes: {
cellpadding: '5',
cellspacing: '0',
border: '1',
bordercolor: '#ccc'
},
styles: {
'border-collapse': 'collapse'
}
},
{ name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } },
{ name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } }
] );
| JavaScript |
/**
* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'myDialog', function( editor ) {
return {
title: 'My Dialog',
minWidth: 400,
minHeight: 200,
contents: [
{
id: 'tab1',
label: 'First Tab',
title: 'First Tab',
elements: [
{
id: 'input1',
type: 'text',
label: 'Text Field'
},
{
id: 'select1',
type: 'select',
label: 'Select Field',
items: [
[ 'option1', 'value1' ],
[ 'option2', 'value2' ]
]
}
]
},
{
id: 'tab2',
label: 'Second Tab',
title: 'Second Tab',
elements: [
{
id: 'button1',
type: 'button',
label: 'Button Field'
}
]
}
]
};
} );
| JavaScript |
/**
* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
// Tool scripts for the sample pages.
// This file can be ignored and is not required to make use of CKEditor.
( function() {
CKEDITOR.on( 'instanceReady', function( ev ) {
// Check for sample compliance.
var editor = ev.editor,
meta = CKEDITOR.document.$.getElementsByName( 'ckeditor-sample-required-plugins' ),
requires = meta.length ? CKEDITOR.dom.element.get( meta[ 0 ] ).getAttribute( 'content' ).split( ',' ) : [],
missing = [],
i;
if ( requires.length ) {
for ( i = 0; i < requires.length; i++ ) {
if ( !editor.plugins[ requires[ i ] ] )
missing.push( '<code>' + requires[ i ] + '</code>' );
}
if ( missing.length ) {
var warn = CKEDITOR.dom.element.createFromHtml(
'<div class="warning">' +
'<span>To fully experience this demo, the ' + missing.join( ', ' ) + ' plugin' + ( missing.length > 1 ? 's are' : ' is' ) + ' required.</span>' +
'</div>'
);
warn.insertBefore( editor.container );
}
}
// Set icons.
var doc = new CKEDITOR.dom.document( document ),
icons = doc.find( '.button_icon' );
for ( i = 0; i < icons.count(); i++ ) {
var icon = icons.getItem( i ),
name = icon.getAttribute( 'data-icon' ),
style = CKEDITOR.skin.getIconStyle( name, ( CKEDITOR.lang.dir == 'rtl' ) );
icon.addClass( 'cke_button_icon' );
icon.addClass( 'cke_button__' + name + '_icon' );
icon.setAttribute( 'style', style );
icon.setStyle( 'float', 'none' );
}
} );
} )();
| JavaScript |
/*! SWFObject v2.1 <http://code.google.com/p/swfobject/>
Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject = function() {
var UNDEF = "undefined",
OBJECT = "object",
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
EXPRESS_INSTALL_ID = "SWFObjectExprInst",
win = window,
doc = document,
nav = navigator,
domLoadFnArr = [],
regObjArr = [],
objIdArr = [],
listenersArr = [],
script,
timer = null,
storedAltContent = null,
storedAltContentId = null,
isDomLoaded = false,
isExpressInstallActive = false;
/* Centralized function for browser feature detection
- Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
- User agent string detection is only used when no alternative is possible
- Is executed directly for optimal performance
*/
var ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
var a = null, fp6Crash = false;
try {
a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
}
catch(e) {
try {
a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
playerVersion = [6,0,21];
a.AllowScriptAccess = "always"; // Introduced in fp6.0.47
}
catch(e) {
if (playerVersion[0] == 6) {
fp6Crash = true;
}
}
if (!fp6Crash) {
try {
a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
}
catch(e) {}
}
}
if (!fp6Crash && a) { // a will return null when ActiveX is disabled
try {
d = a.GetVariable("$version"); // Will crash fp6.0.21/23/29
if (d) {
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
catch(e) {}
}
}
var u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = false,
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u);
/*@cc_on
ie = true;
@if (@_win32)
windows = true;
@elif (@_mac)
mac = true;
@end
@*/
return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
}();
/* Cross-browser onDomLoad
- Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/
- Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari)
*/
var onDomLoad = function() {
if (!ua.w3cdom) {
return;
}
addDomLoadEvent(main);
if (ua.ie && ua.win) {
try { // Avoid a possible Operation Aborted error
doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors
script = getElementById("__ie_ondomload");
if (script) {
addListener(script, "onreadystatechange", checkReadyState);
}
}
catch(e) {}
}
if (ua.webkit && typeof doc.readyState != UNDEF) {
timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10);
}
if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null);
}
addLoadEvent(callDomLoadFunctions);
}();
function checkReadyState() {
if (script.readyState == "complete") {
script.parentNode.removeChild(script);
callDomLoadFunctions();
}
}
function callDomLoadFunctions() {
if (isDomLoaded) {
return;
}
if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early
var s = createElement("span");
try { // Avoid a possible Operation Aborted error
var t = doc.getElementsByTagName("body")[0].appendChild(s);
t.parentNode.removeChild(t);
}
catch (e) {
return;
}
}
isDomLoaded = true;
if (timer) {
clearInterval(timer);
timer = null;
}
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Cross-browser onload
- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
- Will fire an event as soon as a web page including all of its assets are loaded
*/
function addLoadEvent(fn) {
if (typeof win.addEventListener != UNDEF) {
win.addEventListener("load", fn, false);
}
else if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("load", fn, false);
}
else if (typeof win.attachEvent != UNDEF) {
addListener(win, "onload", fn);
}
else if (typeof win.onload == "function") {
var fnOld = win.onload;
win.onload = function() {
fnOld();
fn();
};
}
else {
win.onload = fn;
}
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() { // Static publishing only
var rl = regObjArr.length;
for (var i = 0; i < rl; i++) { // For each registered object element
var id = regObjArr[i].id;
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0";
regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0";
if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match!
if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements
fixParams(obj);
}
setVisibility(id, true);
}
else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only)
showExpressInstall(regObjArr[i]);
}
else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content
displayAltContent(obj);
}
}
}
else { // If no fp is installed, we let the object element do its job (show alternative content)
setVisibility(id, true);
}
}
}
/* Fix nested param elements, which are ignored by older webkit engines
- This includes Safari up to and including version 1.2.2 on Mac OS 10.3
- Fall back to the proprietary embed element
*/
function fixParams(obj) {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var e = createElement("embed"), a = nestedObj.attributes;
if (a) {
var al = a.length;
for (var i = 0; i < al; i++) {
if (a[i].nodeName == "DATA") {
e.setAttribute("src", a[i].nodeValue);
}
else {
e.setAttribute(a[i].nodeName, a[i].nodeValue);
}
}
}
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var j = 0; j < cl; j++) {
if (c[j].nodeType == 1 && c[j].nodeName == "PARAM") {
e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value"));
}
}
}
obj.parentNode.replaceChild(e, obj);
}
}
/* Show the Adobe Express Install dialog
- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
*/
function showExpressInstall(regObj) {
isExpressInstallActive = true;
var obj = getElementById(regObj.id);
if (obj) {
if (regObj.altContentId) {
var ac = getElementById(regObj.altContentId);
if (ac) {
storedAltContent = ac;
storedAltContentId = regObj.altContentId;
}
}
else {
storedAltContent = abstractAltContent(obj);
}
if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) {
regObj.width = "310";
}
if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) {
regObj.height = "137";
}
doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
dt = doc.title,
fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt,
replaceId = regObj.id;
// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
if (ua.ie && ua.win && obj.readyState != 4) {
var newObj = createElement("div");
replaceId += "SWFObjectNew";
newObj.setAttribute("id", replaceId);
obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf
obj.style.display = "none";
var fn = function() {
obj.parentNode.removeChild(obj);
};
addListener(win, "onload", fn);
}
createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId);
}
}
/* Functions to abstract and display alternative content
*/
function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
var fn = function() {
obj.parentNode.removeChild(obj);
};
addListener(win, "onload", fn);
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
}
function abstractAltContent(obj) {
var ac = createElement("div");
if (ua.win && ua.ie) {
ac.innerHTML = obj.innerHTML;
}
else {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var i = 0; i < cl; i++) {
if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
ac.appendChild(c[i].cloneNode(true));
}
}
}
}
}
return ac;
}
/* Cross-browser dynamic SWF creation
*/
function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {}
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // Stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element
var e = createElement("embed");
e.setAttribute("type", FLASH_MIME_TYPE);
for (var k in attObj) {
if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
if (k.toLowerCase() == "data") {
e.setAttribute("src", attObj[k]);
}
else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
e.setAttribute("class", attObj[k]);
}
else if (k.toLowerCase() != "classid") { // Filter out IE specific attribute
e.setAttribute(k, attObj[k]);
}
}
}
for (var l in parObj) {
if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries
if (l.toLowerCase() != "movie") { // Filter out IE specific param element
e.setAttribute(l, parObj[l]);
}
}
}
el.parentNode.replaceChild(e, el);
r = e;
}
else { // Well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // Filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
}
function createObjParam(el, pName, pValue) {
var p = createElement("param");
p.setAttribute("name", pName);
p.setAttribute("value", pValue);
el.appendChild(p);
}
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
function removeSWF(id) {
var obj = getElementById(id);
if (obj && (obj.nodeName == "OBJECT" || obj.nodeName == "EMBED")) {
if (ua.ie && ua.win) {
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
win.attachEvent("onload", function() {
removeObjectInIE(id);
});
}
}
else {
obj.parentNode.removeChild(obj);
}
}
}
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
var el = null;
try {
el = doc.getElementById(id);
}
catch (e) {}
return el;
}
function createElement(el) {
return doc.createElement(el);
}
/* Updated attachEvent function for Internet Explorer
- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
*/
function addListener(target, eventType, fn) {
target.attachEvent(eventType, fn);
listenersArr[listenersArr.length] = [target, eventType, fn];
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
/* Cross-browser dynamic CSS creation
- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
*/
function createCSS(sel, decl) {
if (ua.ie && ua.mac) {
return;
}
var h = doc.getElementsByTagName("head")[0], s = createElement("style");
s.setAttribute("type", "text/css");
s.setAttribute("media", "screen");
if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) {
s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
}
h.appendChild(s);
if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
var ls = doc.styleSheets[doc.styleSheets.length - 1];
if (typeof ls.addRule == OBJECT) {
ls.addRule(sel, decl);
}
}
}
function setVisibility(id, isVisible) {
var v = isVisible ? "visible" : "hidden";
if (isDomLoaded && getElementById(id)) {
getElementById(id).style.visibility = v;
}
else {
createCSS("#" + id, "visibility:" + v);
}
}
/* Filter to avoid XSS attacks
*/
function urlEncodeIfNecessary(s) {
var regex = /[\\\"<>\.;]/;
var hasBadChars = regex.exec(s) != null;
return hasBadChars ? encodeURIComponent(s) : s;
}
/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
*/
var cleanup = function() {
if (ua.ie && ua.win) {
window.attachEvent("onunload", function() {
// remove listeners to avoid memory leaks
var ll = listenersArr.length;
for (var i = 0; i < ll; i++) {
listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
}
// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
var il = objIdArr.length;
for (var j = 0; j < il; j++) {
removeSWF(objIdArr[j]);
}
// cleanup library's main closures to avoid memory leaks
for (var k in ua) {
ua[k] = null;
}
ua = null;
for (var l in swfobject) {
swfobject[l] = null;
}
swfobject = null;
});
}
}();
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
*/
registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) {
if (!ua.w3cdom || !objectIdStr || !swfVersionStr) {
return;
}
var regObj = {};
regObj.id = objectIdStr;
regObj.swfVersion = swfVersionStr;
regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : false;
regObjArr[regObjArr.length] = regObj;
setVisibility(objectIdStr, false);
},
getObjectById: function(objectIdStr) {
var r = null;
if (ua.w3cdom) {
var o = getElementById(objectIdStr);
if (o) {
var n = o.getElementsByTagName(OBJECT)[0];
if (!n || (n && typeof o.SetVariable != UNDEF)) {
r = o;
}
else if (typeof n.SetVariable != UNDEF) {
r = n;
}
}
}
return r;
},
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {
if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) {
return;
}
widthStr += ""; // Auto-convert to string
heightStr += "";
if (hasPlayerVersion(swfVersionStr)) {
setVisibility(replaceElemIdStr, false);
var att = {};
if (attObj && typeof attObj === OBJECT) {
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries
att[i] = attObj[i];
}
}
}
att.data = swfUrlStr;
att.width = widthStr;
att.height = heightStr;
var par = {};
if (parObj && typeof parObj === OBJECT) {
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
par[j] = parObj[j];
}
}
}
if (flashvarsObj && typeof flashvarsObj === OBJECT) {
for (var k in flashvarsObj) {
if (flashvarsObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + k + "=" + flashvarsObj[k];
}
else {
par.flashvars = k + "=" + flashvarsObj[k];
}
}
}
}
addDomLoadEvent(function() {
createSWF(att, par, replaceElemIdStr);
if (att.id == replaceElemIdStr) {
setVisibility(replaceElemIdStr, true);
}
});
}
else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) {
isExpressInstallActive = true; // deferred execution
setVisibility(replaceElemIdStr, false);
addDomLoadEvent(function() {
var regObj = {};
regObj.id = regObj.altContentId = replaceElemIdStr;
regObj.width = widthStr;
regObj.height = heightStr;
regObj.expressInstall = xiSwfUrlStr;
showExpressInstall(regObj);
});
}
},
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3cdom) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
removeSWF: function(objElemIdStr) {
if (ua.w3cdom) {
removeSWF(objElemIdStr);
}
},
createCSS: function(sel, decl) {
if (ua.w3cdom) {
createCSS(sel, decl);
}
},
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: addLoadEvent,
getQueryParamValue: function(param) {
var q = doc.location.search || doc.location.hash;
if (param == null) {
return urlEncodeIfNecessary(q);
}
if (q) {
var pairs = q.substring(1).split("&");
for (var i = 0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
}
}
}
return "";
},
// For internal usage only
expressInstallCallback: function() {
if (isExpressInstallActive && storedAltContent) {
var obj = getElementById(EXPRESS_INSTALL_ID);
if (obj) {
obj.parentNode.replaceChild(storedAltContent, obj);
if (storedAltContentId) {
setVisibility(storedAltContentId, true);
if (ua.ie && ua.win) {
storedAltContent.style.display = "block";
}
}
storedAltContent = null;
storedAltContentId = null;
isExpressInstallActive = false;
}
}
}
};
}();
| JavaScript |
(function () {
"use strict";
var appView = Windows.UI.ViewManagement.ApplicationView;
var nav = WinJS.Navigation;
WinJS.Namespace.define("Application", {
PageControlNavigator: WinJS.Class.define(
// Define the constructor function for the PageControlNavigator.
function PageControlNavigator(element, options) {
this._element = element || document.createElement("div");
this._element.appendChild(this._createPageElement());
this.home = options.home;
this._lastViewstate = appView.value;
nav.onnavigated = this._navigated.bind(this);
window.onresize = this._resized.bind(this);
document.body.onkeyup = this._keyupHandler.bind(this);
document.body.onkeypress = this._keypressHandler.bind(this);
document.body.onmspointerup = this._mspointerupHandler.bind(this);
Application.navigator = this;
}, {
home: "",
/// <field domElement="true" />
_element: null,
_lastNavigationPromise: WinJS.Promise.as(),
_lastViewstate: 0,
// This is the currently loaded Page object.
pageControl: {
get: function () { return this.pageElement && this.pageElement.winControl; }
},
// This is the root element of the current page.
pageElement: {
get: function () { return this._element.firstElementChild; }
},
// Creates a container for a new page to be loaded into.
_createPageElement: function () {
var element = document.createElement("div");
element.setAttribute("dir", window.getComputedStyle(this._element, null).direction);
element.style.width = "100%";
element.style.height = "100%";
return element;
},
// Retrieves a list of animation elements for the current page.
// If the page does not define a list, animate the entire page.
_getAnimationElements: function () {
if (this.pageControl && this.pageControl.getAnimationElements) {
return this.pageControl.getAnimationElements();
}
return this.pageElement;
},
// Navigates back whenever the backspace key is pressed and
// not captured by an input field.
_keypressHandler: function (args) {
if (args.key === "Backspace") {
nav.back();
}
},
// Navigates back or forward when alt + left or alt + right
// key combinations are pressed.
_keyupHandler: function (args) {
if ((args.key === "Left" && args.altKey) || (args.key === "BrowserBack")) {
nav.back();
} else if ((args.key === "Right" && args.altKey) || (args.key === "BrowserForward")) {
nav.forward();
}
},
// This function responds to clicks to enable navigation using
// back and forward mouse buttons.
_mspointerupHandler: function (args) {
if (args.button === 3) {
nav.back();
} else if (args.button === 4) {
nav.forward();
}
},
// Responds to navigation by adding new pages to the DOM.
_navigated: function (args) {
var newElement = this._createPageElement();
var parentedComplete;
var parented = new WinJS.Promise(function (c) { parentedComplete = c; });
this._lastNavigationPromise.cancel();
this._lastNavigationPromise = WinJS.Promise.timeout().then(function () {
return WinJS.UI.Pages.render(args.detail.location, newElement, args.detail.state, parented);
}).then(function parentElement(control) {
var oldElement = this.pageElement;
if (oldElement.winControl && oldElement.winControl.unload) {
oldElement.winControl.unload();
}
this._element.appendChild(newElement);
this._element.removeChild(oldElement);
oldElement.innerText = "";
this._updateBackButton();
parentedComplete();
WinJS.UI.Animation.enterPage(this._getAnimationElements()).done();
}.bind(this));
args.detail.setPromise(this._lastNavigationPromise);
},
// Responds to resize events and call the updateLayout function
// on the currently loaded page.
_resized: function (args) {
if (this.pageControl && this.pageControl.updateLayout) {
this.pageControl.updateLayout.call(this.pageControl, this.pageElement, appView.value, this._lastViewstate);
}
this._lastViewstate = appView.value;
},
// Updates the back button state. Called after navigation has
// completed.
_updateBackButton: function () {
var backButton = this.pageElement.querySelector("header[role=banner] .win-backbutton");
if (backButton) {
backButton.onclick = function () { nav.back(); };
if (nav.canGoBack) {
backButton.removeAttribute("disabled");
} else {
backButton.setAttribute("disabled", "disabled");
}
}
},
}
)
});
})();
| JavaScript |
/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
var ui = WinJS.Namespace.define("UI", {
generateUI: function () {
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
var sessionKey = localSettings.values["sessionKey"];
if (sessionKey == null || sessionKey == "") {
var messageDialog = new Windows.UI.Popups.MessageDialog("Не сте влезли в профилът си.");
messageDialog.commands.append(new Windows.UI.Popups.UICommand("Вход", function () {
document.getElementById("loginForm").style.display = "block";
}));
messageDialog.commands.append(new Windows.UI.Popups.UICommand("Регистрация", function () {
document.getElementById("loginForm").style.display = "none";
document.getElementById("registerForm").style.display = "block";
}));
messageDialog.commands.append(new Windows.UI.Popups.UICommand("Продължи без логин", function () {
document.getElementById("loginForm").style.display = "none";
document.getElementById("registerForm").style.display = "none";
document.getElementById("placesContent").style.visibility = "visible";
}));
messageDialog.showAsync();
}
else {
document.getElementById("registerForm").style.display = "none";
document.getElementById("loginForm").style.display = "none";
document.getElementById("placesContent").style.visibility = "visible";
document.getElementById("appBarContainer").style.display = "block";
}
}
}); | JavaScript |
(function () {
"use strict";
var dataArray = [];
var itemList = new WinJS.Binding.List();
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
var sessionKey = localSettings.values["sessionKey"];
WinJS.xhr({
type: "GET",
url: "http://100nationalplaces.apphb.com/api/users/getPictures/"+sessionKey,
headers: { "Content-type": "application/json" },
}).done(
function (success) {
var pics = JSON.parse(success.responseText);
for (var i = 0; i < pics.length; i++) {
itemList.push({ picture: pics[i] });
}
},
function (error) {
console.log(error.responseText);
});
WinJS.Namespace.define("PicturesData", {
itemList: itemList
});
})(); | JavaScript |
(function () {
"use strict";
var list = new WinJS.Binding.List();
var groupedItems = list.createGrouped(
function groupKeySelector(item) { return item.group.key; },
function groupDataSelector(item) { return item.group; }
);
// TODO: Replace the data with your real data.
// You can add data from asynchronous sources whenever it becomes available.
generateSampleData().then(
function (items) {
for (var i = 0; i < items.length; i++) {
list.push(items[i]);
}
}, function (error) {
console.log(error);
});
WinJS.Namespace.define("Data", {
items: groupedItems,
groups: groupedItems.groups,
getItemReference: getItemReference,
getItemsFromGroup: getItemsFromGroup,
resolveGroupReference: resolveGroupReference,
resolveItemReference: resolveItemReference
});
// Get a reference for an item, using the group key and item title as a
// unique reference to the item that can be easily serialized.
function getItemReference(item) {
return [item.group.key, item.title];
}
// This function returns a WinJS.Binding.List containing only the items
// that belong to the provided group.
function getItemsFromGroup(group) {
return list.createFiltered(function (item) { return item.group.key === group.key; });
}
// Get the unique group corresponding to the provided group key.
function resolveGroupReference(key) {
for (var i = 0; i < groupedItems.groups.length; i++) {
if (groupedItems.groups.getAt(i).key === key) {
return groupedItems.groups.getAt(i);
}
}
}
// Get a unique item from the provided string array, which should contain a
// group key and an item title.
function resolveItemReference(reference) {
for (var i = 0; i < groupedItems.length; i++) {
var item = groupedItems.getAt(i);
if (item.group.key === reference[0] && item.title === reference[1]) {
return item;
}
}
}
// Returns an array of sample data that can be added to the application's
// data list.
function generateSampleData() {
// These three strings encode placeholder images. You will want to set the
// backgroundImage property in your real data to be URLs to images.
var darkGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY3B0cPoPAANMAcOba1BlAAAAAElFTkSuQmCC";
var lightGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY7h4+cp/AAhpA3h+ANDKAAAAAElFTkSuQmCC";
var mediumGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY5g8dcZ/AAY/AsAlWFQ+AAAAAElFTkSuQmCC";
// Each of these sample groups must have a unique key to be displayed
// separately.
//{ key: "group6", title: "Group Title: 6", subtitle: "Group Subtitle: 6", backgroundImage: darkGray, description: groupDescription }
//{ group: sampleGroups[0], title: "Item Title: 1", subtitle: "Item Subtitle: 1", description: itemDescription, content: itemContent, backgroundImage: lightGray }
return new WinJS.Promise(function(complete, err, prog) {
var sampleGroups = [];
WinJS.xhr({
type: "GET",
url: "http://100nationalplaces.apphb.com/api/towns/getTownsAndPlaces",
headers: { "Content-type": "application/json" },
}).done(
function(success) {
var allGroups = JSON.parse(success.responseText);
for (var k = 0; k < allGroups.length; k++) {
sampleGroups.push({ key: allGroups[k].Id, title: allGroups[k].TownName, subtitle: "", backgroundImage: darkGray, description: "" });
}
var sampleItems = [];
for (var i = 0; i < sampleGroups.length; i++) {
for (var j = 0; j < allGroups[i].Places.length; j++) {
sampleItems.push({ group: sampleGroups[i], title: allGroups[i].Places[j].Name, description: allGroups[i].Places[j].Description, backgroundImage: allGroups[i].Places[j].PictureUrl, subtitle: "", content: allGroups[i].Places[j].Description, });
}
}
complete(sampleItems);
},
function(error) {
err(error);
});
});
}
})();
| JavaScript |
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
var events = WinJS.Namespace.define("Events", {
attachEvents: function () {
var showRegister = document.getElementById("showRegister");
var showLogin = document.getElementById("showLogin");
var errors = document.getElementById("errorMessage");
var loginButton = document.getElementById("btnLogin");
loginButton.addEventListener("click", function () {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var escapedUsername = escapeSting(username);
var authCode = CryptoJS.SHA1(password).toString();
WinJS.xhr({
type: "POST",
url: "http://100NationalPlaces.apphb.com/api/users/login/",
headers: { "Content-type": "application/json" },
data: JSON.stringify({ Username: escapedUsername, AuthCode: authCode })
}).then(
function (success) {
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
var sessionKey = localSettings.values["sessionKey"] =
JSON.parse(success.responseText).SessionKey;
ui.generateUI();
},
function (error) {
var messageDialog = new Windows.UI.Popups.MessageDialog(error.responseText);
messageDialog.showAsync();
});
});
var registerButton = document.getElementById("btnRegister");
registerButton.addEventListener("click", function () {
var username = document.getElementById("regUsername").value;
var name = document.getElementById("fullName").value;
var password = document.getElementById("regPassword").value;
var picture = document.getElementById("profile-image-container").src;
var escapedUsername = escapeSting(username);
var escapedName = escapeSting(name);
var authCode = CryptoJS.SHA1(password).toString();
WinJS.xhr({
type: "POST",
url: "http://100NationalPlaces.apphb.com/api/users/register/",
headers: { "Content-type": "application/json" },
data: JSON.stringify({ Username: escapedUsername, AuthCode: authCode, Name: escapedName, ProfilePictureUrl: picture })
}).then(
function (success) {
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
var sessionKey = localSettings.values["sessionKey"] =
JSON.parse(success.responseText).SessionKey;
ui.generateUI();
},
function (error) {
var messageDialog = new Windows.UI.Popups.MessageDialog(error.responseText);
messageDialog.showAsync();
});
});
var logoutButton = document.getElementById("btnLogout");
logoutButton.addEventListener("click", function () {
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
var sessionKey = localSettings.values["sessionKey"];
WinJS.xhr({
type: "PUT",
url: "http://100NationalPlaces.apphb.com/api/users/logout/" + sessionKey,
headers: { "Content-type": "application/json" },
}).then(
function (success) {
var sessionKey = localSettings.values["sessionKey"] = "";
document.getElementById("placesContent").style.visibility = "hidden";
document.getElementById("appBarContainer").style.display = "none";
ui.generateUI();
},
function (error) {
var messageDialog = new Windows.UI.Popups.MessageDialog(error.responseText);
messageDialog.showAsync();
});
});
var fromCameraButton = document.getElementById("btnCamera");
fromCameraButton.addEventListener("click", function (ev) {
var captureUI = new Windows.Media.Capture.CameraCaptureUI();
captureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (capturedItem) {
if (capturedItem) {
var container = document.getElementById("profile-image-container");
container.style.display = "inline";
container.src = "images/loading.gif";
uploadImage(capturedItem).then(function (url) {
container.setAttribute("src", url);
});
}
});
});
var checkInButton = document.getElementById("btnCheckIn");
checkInButton.addEventListener("click", function () {
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
var sessionKey = localSettings.values["sessionKey"];
var loc = null;
if (loc == null) {
loc = new Windows.Devices.Geolocation.Geolocator();
}
if (loc != null) {
loc.getGeopositionAsync().then(getPositionHandler, errorHandler);
}
function getPositionHandler(pos) {
WinJS.xhr({
type: "POST",
url: "http://100nationalplaces.apphb.com/api/places/checkIn/" + sessionKey + "?longitude=" + pos.coordinate.longitude + "&latitude=" + pos.coordinate.latitude,
headers: { "Content-type": "application/json" },
}).then(
function (success) {
var messageDialog = new Windows.UI.Popups.MessageDialog(success.responseText);
messageDialog.showAsync();
},
function (error) {
var messageDialog = new Windows.UI.Popups.MessageDialog("Error!");
messageDialog.showAsync();
});
}
function errorHandler(e) {
var messageDialog = new Windows.UI.Popups.MessageDialog("Your location could not been reached!");
messageDialog.showAsync();
}
});
var profileButton = document.getElementById("myProfile");
profileButton.addEventListener("click", function () {
var menu = document.getElementById("menu-id").winControl;
menu.show();
});
WinJS.Utilities.id("btnUploadPicture").listen("click", function () {
var openPicker = Windows.Storage.Pickers.FileOpenPicker();
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
var sessionKey = localSettings.values["sessionKey"];
openPicker.fileTypeFilter.append(".jpg");
openPicker.pickMultipleFilesAsync().then(function (files) {
for (var i = 0; i < files.length; i++) {
uploadImage(files[i]).then(function (image) {
console.log(image);
WinJS.xhr({
type: "POST",
url: "http://100nationalplaces.apphb.com/api/users/addPicture/" + sessionKey + "?url=" + image,
headers: { "Content-type": "application/json" },
}).then(
function(success) {
var messageDialog = new Windows.UI.Popups.MessageDialog("Сминката е качена успешно");
messageDialog.showAsync();
//console.log(success.responseText);
},
function(error) {
var messageDialog = new Windows.UI.Popups.MessageDialog("Проблем при качването на снимка");
messageDialog.showAsync();
//console.log(error.responseText);
});
});
}
});
});
//var areShowed = false;
//document.getElementById("btnShowPictures").addEventListener("click", function() {
// if (!areShowed) {
// areShowed = true;
// document.getElementById("placesContent").style.visibility = "hidden";
// //var picturesContainer = document.getElementById("pictiresContainer");
// } else {
// areShowed = false;
// document.getElementById("placesContent").style.visibility = "visible";
// //var picturesContainer = document.getElementById("pictiresContainer");
// }
//});
}
});
var uploadImage = function (storageFile) {
return new WinJS.Promise(function (success) {
var file = MSApp.createFileFromStorageFile(storageFile);
if (!file || !file.type.match(/image.*/)) {
return;
}
var fd = new FormData();
fd.append("image", file);
fd.append("key", "6528448c258cff474ca9701c5bab6927");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://api.imgur.com/2/upload.json");
xhr.onload = function () {
var imgUrl = JSON.parse(xhr.responseText).upload.links.imgur_page + ".jpg";
success(imgUrl);
};
xhr.send(fd);
});
};
var escapeSting = (function () {
var chr = {
'"': '"', '&': '&', "'": ''',
'/': '/', '<': '<', '>': '>'
};
return function (text) {
return text.replace(/[\"&'\/<>]/g, function (a) { return chr[a]; });
};
}());
| JavaScript |
/// <reference path="events.js" />
/// <reference path="UI.js" />
// For an introduction to the Grid template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=232446
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var nav = WinJS.Navigation;
app.onsettings = function (e) {
e.detail.applicationcommands = {
"AppSettings": { title: "AppSettings", href: "/pages/settings/settings.html" },
"aboutUs": { title: "About Us", href: "/pages/aboutUs/aboutUs.html" },
};
WinJS.UI.SettingsFlyout.populateSettings(e);
}
app.addEventListener("activated", function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
if (app.sessionState.history) {
nav.history = app.sessionState.history;
}
args.setPromise(WinJS.UI.processAll().then(function () {
if (nav.location) {
nav.history.current.initialPlaceholder = true;
return nav.navigate(nav.location, nav.state);
} else {
return nav.navigate(Application.navigator.home);
}
}));
ui.generateUI();
events.attachEvents();
}
});
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. If you need to
// complete an asynchronous operation before your application is
// suspended, call args.setPromise().
app.sessionState.history = nav.history;
};
app.start();
})();
| JavaScript |
//(function () {
// "use strict";
// var list = new WinJS.Binding.List();
// var groupedItems = list.createGrouped(
// function groupKeySelector(item) { return item.group.key; },
// function groupDataSelector(item) { return item.group; }
// );
// // TODO: Replace the data with your real data.
// // You can add data from asynchronous sources whenever it becomes available.
// generateSampleData().then(
// function (items) {
// for (var i = 0; i < items.length; i++) {
// list.push(items[i]);
// }
// }, function (error) {
// console.log(error);
// });
// WinJS.Namespace.define("groupedItems", {
// items: groupedItems,
// groups: groupedItems.groups,
// getItemReference: getItemReference,
// getItemsFromGroup: getItemsFromGroup,
// resolveGroupReference: resolveGroupReference,
// resolveItemReference: resolveItemReference
// });
// // Get a reference for an item, using the group key and item title as a
// // unique reference to the item that can be easily serialized.
// function getItemReference(item) {
// return [item.group.key, item.title];
// }
// // This function returns a WinJS.Binding.List containing only the items
// // that belong to the provided group.
// function getItemsFromGroup(group) {
// return list.createFiltered(function (item) { return item.group.key === group.key; });
// }
// // Get the unique group corresponding to the provided group key.
// function resolveGroupReference(key) {
// for (var i = 0; i < groupedItems.groups.length; i++) {
// if (groupedItems.groups.getAt(i).key === key) {
// return groupedItems.groups.getAt(i);
// }
// }
// }
// // Get a unique item from the provided string array, which should contain a
// // group key and an item title.
// function resolveItemReference(reference) {
// for (var i = 0; i < groupedItems.length; i++) {
// var item = groupedItems.getAt(i);
// if (item.group.key === reference[0] && item.title === reference[1]) {
// return item;
// }
// }
// }
// // Returns an array of sample data that can be added to the application's
// // data list.
// function generateSampleData() {
// // These three strings encode placeholder images. You will want to set the
// // backgroundImage property in your real data to be URLs to images.
// var darkGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY3B0cPoPAANMAcOba1BlAAAAAElFTkSuQmCC";
// var lightGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY7h4+cp/AAhpA3h+ANDKAAAAAElFTkSuQmCC";
// var mediumGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY5g8dcZ/AAY/AsAlWFQ+AAAAAElFTkSuQmCC";
// // Each of these sample groups must have a unique key to be displayed
// // separately.
// //{ key: "group6", title: "Group Title: 6", subtitle: "Group Subtitle: 6", backgroundImage: darkGray, description: groupDescription }
// //{ group: sampleGroups[0], title: "Item Title: 1", subtitle: "Item Subtitle: 1", description: itemDescription, content: itemContent, backgroundImage: lightGray }
// return new WinJS.Promise(function (complete, err, prog) {
// var sampleGroups = [];
// WinJS.xhr({
// type: "GET",
// url: "http://100nationalplaces.apphb.com/api/towns/getTownsAndPlaces",
// headers: { "Content-type": "application/json" },
// }).done(
// function (success) {
// var allGroups = JSON.parse(success.responseText);
// for (var k = 0; k < allGroups.length; k++) {
// sampleGroups.push({ key: allGroups[k].Id, title: allGroups[k].TownName, subtitle: "", backgroundImage: darkGray, description: "" });
// }
// var sampleItems = [];
// for (var i = 0; i < sampleGroups.length; i++) {
// for (var j = 0; j < allGroups[i].Places.length; j++) {
// sampleItems.push({ group: sampleGroups[i], title: allGroups[i].Places[j].Name, description: allGroups[i].Places[j].Description, backgroundImage: allGroups[i].Places[j].PictureUrl, subtitle: "", content: allGroups[i].Places[j].Description, });
// }
// }
// complete(sampleItems);
// },
// function (error) {
// err(error);
// });
// });
// }
//})();
| JavaScript |
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/itemDetail/itemDetail.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var item = options && options.item ? Data.resolveItemReference(options.item) : Data.items.getAt(0);
element.querySelector(".titlearea .pagetitle").textContent = item.group.title;
element.querySelector("article .item-title").textContent = item.title;
element.querySelector("article .item-subtitle").textContent = item.subtitle;
element.querySelector("article .item-image").src = item.backgroundImage;
element.querySelector("article .item-image").alt = item.subtitle;
element.querySelector("article .item-content").innerHTML = item.content;
element.querySelector(".content").focus();
//SHARE CODE
//var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
//dataTransferManager.addEventListener("datarequested", shareTextHandler);
//function shareTextHandler(e) {
// var request = e.request;
// request.data.properties.title = item.title;
// request.data.properties.description = item.content;
// //request.data.setText(item.content);
//}
}
});
})();
| JavaScript |
(function () {
"use strict";
var appView = Windows.UI.ViewManagement.ApplicationView;
var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
var nav = WinJS.Navigation;
var ui = WinJS.UI;
ui.Pages.define("/pages/groupedItems/groupedItems.html", {
// Navigates to the groupHeaderPage. Called from the groupHeaders,
// keyboard shortcut and iteminvoked.
navigateToGroup: function (key) {
nav.navigate("/pages/groupDetail/groupDetail.html", { groupKey: key });
},
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var listView = element.querySelector(".groupeditemslist").winControl;
listView.groupHeaderTemplate = element.querySelector(".headertemplate");
listView.itemTemplate = element.querySelector(".itemtemplate");
listView.oniteminvoked = this._itemInvoked.bind(this);
// Set up a keyboard shortcut (ctrl + alt + g) to navigate to the
// current group when not in snapped mode.
listView.addEventListener("keydown", function (e) {
if (appView.value !== appViewState.snapped && e.ctrlKey && e.keyCode === WinJS.Utilities.Key.g && e.altKey) {
var data = listView.itemDataSource.list.getAt(listView.currentItem.index);
this.navigateToGroup(data.group.key);
e.preventDefault();
e.stopImmediatePropagation();
}
}.bind(this), true);
this._initializeLayout(listView, appView.value);
listView.element.focus();
sendTileLocalImageNotification();
},
// This function updates the page layout in response to viewState changes.
updateLayout: function (element, viewState, lastViewState) {
/// <param name="element" domElement="true" />
var listView = element.querySelector(".groupeditemslist").winControl;
if (lastViewState !== viewState) {
if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) {
var handler = function (e) {
listView.removeEventListener("contentanimating", handler, false);
e.preventDefault();
}
listView.addEventListener("contentanimating", handler, false);
this._initializeLayout(listView, viewState);
}
}
},
// This function updates the ListView with new layouts
_initializeLayout: function (listView, viewState) {
/// <param name="listView" value="WinJS.UI.ListView.prototype" />
if (viewState === appViewState.snapped) {
listView.itemDataSource = Data.groups.dataSource;
listView.groupDataSource = null;
listView.layout = new ui.ListLayout();
} else {
//trying to make promises!!!!
//
//Data.data(function (items) {
// listView.itemDataSource = items.items.dataSource;
// listView.groupDataSource = items.groups.dataSource;
// listView.layout = new ui.GridLayout({ groupHeaderPosition: "top" });
//});
listView.itemDataSource = Data.items.dataSource;
listView.groupDataSource = Data.groups.dataSource;
listView.layout = new ui.GridLayout({ groupHeaderPosition: "top" });
}
},
_itemInvoked: function (args) {
if (appView.value === appViewState.snapped) {
// If the page is snapped, the user invoked a group.
var group = Data.groups.getAt(args.detail.itemIndex);
this.navigateToGroup(group.key);
} else {
// If the page is not snapped, the user invoked an item.
var item = Data.items.getAt(args.detail.itemIndex);
nav.navigate("/pages/itemDetail/itemDetail.html", { item: Data.getItemReference(item) });
}
}
});
function sendTileLocalImageNotification() {
// Note: This sample contains an additional project, NotificationsExtensions.
// NotificationsExtensions exposes an object model for creating notifications, but you can also modify the xml
// of the notification directly. See the additional function sendTileLocalImageNotificationWithXml to see how
// to do it by modifying Xml directly, or sendLocalImageNotificationWithStringManipulation to see how to do it
// by modifying strings directly
//Clear Existing Notification
Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().clear();
var imgSource = "ms-appx:///images/BigLiveTile1.jpg";
var imgSmallSource = "ms-appx:///images/SmallLiveTile1.jpg";
var tileContent = Windows.UI.Notifications.TileTemplateType.tileWideImageAndText01;
var tileXml = Windows.UI.Notifications.TileUpdateManager.getTemplateContent(tileContent);
var tileImageAttributes = tileXml.getElementsByTagName("image");
var tileTextAttributes = tileXml.getElementsByTagName("text");
tileImageAttributes[0].setAttribute("src", imgSource);
tileImageAttributes[0].setAttribute("alt", "A Wide Live Tile.");
tileTextAttributes[0].innerText = "100 National Places";
var binding = tileXml.getElementsByTagName("binding");
// create the square template and attach it to the wide template
var template = Windows.UI.Notifications.TileTemplateType.tileSquareImage;
var squareTileXml = Windows.UI.Notifications.TileUpdateManager.getTemplateContent(template);
var squareTileImageElements = squareTileXml.getElementsByTagName("image");
squareTileImageElements[0].setAttribute("src", imgSmallSource);
squareTileImageElements[0].setAttribute("alt", "A Square Live Tile.");
var binding = squareTileXml.getElementsByTagName("binding").item(0);
var node = tileXml.importNode(binding, true);
tileXml.getElementsByTagName("visual").item(0).appendChild(node);
var tileNotification = new Windows.UI.Notifications.TileNotification(tileXml);
Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueue(true);
Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().update(tileNotification);
}
})();
| JavaScript |
// For an introduction to the Search Contract template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232512
// TODO: Add the following script tag to the start page's head to
// subscribe to search contract events.
//
// <script src="/searchResultPage.js"></script>
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var appModel = Windows.ApplicationModel;
var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
var nav = WinJS.Navigation;
var ui = WinJS.UI;
var utils = WinJS.Utilities;
var searchPageURI = "/pages/searchResultPage/searchResultPage.html";
ui.Pages.define(searchPageURI, {
_filters: [],
_lastSearch: "",
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var listView = element.querySelector(".resultslist").winControl;
listView.itemTemplate = element.querySelector(".itemtemplate");
listView.oniteminvoked = this._itemInvoked;
//this._handleQuery(element, options);
//listView.element.focus();
listView.addEventListener("keydown", function (e) {
if (Windows.UI.ViewManagement.ApplicationView.value !== appViewState.snapped && e.ctrlKey && e.keyCode === WinJS.Utilities.Key.g && e.altKey) {
var data = listView.itemDataSource.list.getAt(listView.currentItem.index);
this.navigateToGroup(data.group.key);
e.preventDefault();
e.stopImmediatePropagation();
}
}.bind(this), true);
document.querySelector(".titlearea .pagetitle").textContent = "Search Results " + "for '" + options.queryText + "'";
this._initializeLayout(element.querySelector(".resultslist").winControl, Windows.UI.ViewManagement.ApplicationView.value);
listView.element.focus();
},
// This function updates the page layout in response to viewState changes.
updateLayout: function (element, viewState, lastViewState) {
/// <param name="element" domElement="true" />
var listView = element.querySelector(".resultslist").winControl;
if (lastViewState !== viewState) {
if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) {
var handler = function (e) {
listView.removeEventListener("contentanimating", handler, false);
e.preventDefault();
}
listView.addEventListener("contentanimating", handler, false);
var firstVisible = listView.indexOfFirstVisible;
this._initializeLayout(listView, viewState);
if (firstVisible >= 0 && listView.itemDataSource.list.length > 0) {
listView.indexOfFirstVisible = firstVisible;
}
}
}
},
// This function updates the ListView with new layouts
_initializeLayout: function (listView, viewState) {
/// <param name="listView" value="WinJS.UI.ListView.prototype" />
if (viewState === appViewState.snapped) {
listView.itemDataSource = Data.items.dataSource;
listView.groupDataSource = null;
listView.layout = new ui.ListLayout();
//document.querySelector(".titlearea .pagetitle").textContent = '“' + this._lastSearch + '”';
document.querySelector(".titlearea .pagesubtitle").textContent = "";
} else {
listView.itemDataSource =Data.items.dataSource;
listView.layout = new ui.GridLayout();
// TODO: Change "App Name" to the name of your app.
//document.querySelector(".titlearea .pagetitle").textContent = "App Name";
//document.querySelector(".titlearea .pagesubtitle").textContent = "Results for “" + this._lastSearch + '”';
}
},
_itemInvoked: function (args) {
args.detail.itemPromise.done(function itemInvoked(item) {
// TODO: Navigate to the item that was invoked.
if (Windows.UI.ViewManagement.ApplicationView.value === appViewState.snapped) {
// If the page is snapped, the user invoked a group.
//var group = HubData.groups.getAt(args.detail.itemIndex);
//this.navigateToGroup(group.key);
var item = Data.items.getAt(args.detail.itemIndex);
nav.navigate("/pages/itemDetail/itemDetail.html", { item: Data.getItemReference(item) });
} else {
// If the page is not snapped, the user invoked an item.
var item = Data.items.getAt(args.detail.itemIndex);
if (item == null) {
var item1 = Data.items.getAt(0);
nav.navigate("/pages/itemDetail/itemDetail.html", { item: Data.getItemReference(item1) });
} else {
nav.navigate("/pages/itemDetail/itemDetail.html", { item: Data.getItemReference(item) });
}
}
});
},
// This function colors the search term. Referenced in /searchResultPage.html
// as part of the ListView item templates.
// This function generates the filter selection list.
// This function populates a WinJS.Binding.List with search results for the
// provided query.
});
WinJS.Application.addEventListener("activated", function (args) {
if (args.detail.kind === appModel.Activation.ActivationKind.search) {
args.setPromise(ui.processAll().then(function () {
if (!nav.location) {
nav.history.current = { location: Application.navigator.home, initialState: {} };
}
return nav.navigate(searchPageURI, { queryText: args.detail.queryText });
}));
}
});
appModel.Search.SearchPane.getForCurrentView().onquerysubmitted = function (args) { nav.navigate(searchPageURI, args); };
appModel.Search.SearchPane.getForCurrentView().onresultsuggestionchosen = function (eventObject) { onResultSuggestionChosen(item, eventObject); };
})();
| JavaScript |
// For an introduction to the Picker Contract template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232514
//
// TODO: Edit the manifest to enable use as a file open picker. The package
// manifest could not be automatically updated. Open the package manifest file
// and ensure that support for activation of the 'File Open Picker' is enabled.
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var pickerUI;
function fileRemovedFromPickerUI(args) {
// TODO: Respond to an item being deselected in the picker UI.
}
function getPickerDataSource() {
if (window.Data) {
return Data.items.dataSource;
} else {
return new WinJS.Binding.List().dataSource;
}
}
function updatePickerUI(args) {
// TODO: Respond to an item being selected or deselected on the page.
}
app.onactivated = function activated(args) {
if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.fileOpenPicker) {
pickerUI = args.detail.fileOpenPickerUI;
pickerUI.onfileremoved = fileRemovedFromPickerUI;
args.setPromise(WinJS.UI.processAll()
.then(function () {
var listView = document.querySelector(".pickerlist").winControl;
listView.itemDataSource = getPickerDataSource();
listView.itemTemplate = document.querySelector(".itemtemplate");
listView.onselectionchanged = updatePickerUI;
listView.element.focus();
}));
}
};
app.start();
})(); | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.