code
stringlengths
1
2.08M
language
stringclasses
1 value
(function($) { inlineEditPost = { init : function(){ var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit'); t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post'; t.what = '#post-'; // prepare the edit rows qeRow.keyup(function(e){ if (e.which == 27) return inlineEditPost.revert(); }); bulkRow.keyup(function(e){ if (e.which == 27) return inlineEditPost.revert(); }); $('a.cancel', qeRow).click(function(){ return inlineEditPost.revert(); }); $('a.save', qeRow).click(function(){ return inlineEditPost.save(this); }); $('td', qeRow).keydown(function(e){ if ( e.which == 13 ) return inlineEditPost.save(this); }); $('a.cancel', bulkRow).click(function(){ return inlineEditPost.revert(); }); $('#inline-edit .inline-edit-private input[value="private"]').click( function(){ var pw = $('input.inline-edit-password-input'); if ( $(this).prop('checked') ) { pw.val('').prop('disabled', true); } else { pw.prop('disabled', false); } }); // add events $('a.editinline').live('click', function(){ inlineEditPost.edit(this); return false; }); $('#bulk-title-div').parents('fieldset').after( $('#inline-edit fieldset.inline-edit-categories').clone() ).siblings( 'fieldset:last' ).prepend( $('#inline-edit label.inline-edit-tags').clone() ); // hiearchical taxonomies expandable? $('span.catshow').click(function(){ $(this).hide().next().show().parent().next().addClass("cat-hover"); }); $('span.cathide').click(function(){ $(this).hide().prev().show().parent().next().removeClass("cat-hover"); }); $('select[name="_status"] option[value="future"]', bulkRow).remove(); $('#doaction, #doaction2').click(function(e){ var n = $(this).attr('id').substr(2); if ( $('select[name="'+n+'"]').val() == 'edit' ) { e.preventDefault(); t.setBulk(); } else if ( $('form#posts-filter tr.inline-editor').length > 0 ) { t.revert(); } }); $('#post-query-submit').mousedown(function(e){ t.revert(); $('select[name^="action"]').val('-1'); }); }, toggle : function(el){ var t = this; $(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el); }, setBulk : function(){ var te = '', type = this.type, tax, c = true; this.revert(); $('#bulk-edit td').attr('colspan', $('.widefat:first thead th:visible').length); $('table.widefat tbody').prepend( $('#bulk-edit') ); $('#bulk-edit').addClass('inline-editor').show(); $('tbody th.check-column input[type="checkbox"]').each(function(i){ if ( $(this).prop('checked') ) { c = false; var id = $(this).val(), theTitle; theTitle = $('#inline_'+id+' .post_title').text() || inlineEditL10n.notitle; te += '<div id="ttle'+id+'"><a id="_'+id+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+theTitle+'</div>'; } }); if ( c ) return this.revert(); $('#bulk-titles').html(te); $('#bulk-titles a').click(function(){ var id = $(this).attr('id').substr(1); $('table.widefat input[value="' + id + '"]').prop('checked', false); $('#ttle'+id).remove(); }); // enable autocomplete for tags if ( 'post' == type ) { // support multi taxonomies? tax = 'post_tag'; $('tr.inline-editor textarea[name="tax_input['+tax+']"]').suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } ); } $('html, body').animate( { scrollTop: 0 }, 'fast' ); }, edit : function(id) { var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, cur_format, f; t.revert(); if ( typeof(id) == 'object' ) id = t.getId(id); fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order']; if ( t.type == 'page' ) fields.push('post_parent', 'page_template'); // add the new blank row editRow = $('#inline-edit').clone(true); $('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); // populate the data rowData = $('#inline_'+id); if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) { // author no longer has edit caps, so we need to add them to the list of authors $(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>'); } if ( $(':input[name="post_author"] option', editRow).length == 1 ) { $('label.inline-edit-author', editRow).hide(); } // hide unsupported formats, but leave the current format alone cur_format = $('.post_format', rowData).text(); $('option.unsupported', editRow).each(function() { var $this = $(this); if ( $this.val() != cur_format ) $this.remove(); }); for ( f = 0; f < fields.length; f++ ) { $(':input[name="' + fields[f] + '"]', editRow).val( $('.'+fields[f], rowData).text() ); } if ( $('.comment_status', rowData).text() == 'open' ) $('input[name="comment_status"]', editRow).prop("checked", true); if ( $('.ping_status', rowData).text() == 'open' ) $('input[name="ping_status"]', editRow).prop("checked", true); if ( $('.sticky', rowData).text() == 'sticky' ) $('input[name="sticky"]', editRow).prop("checked", true); // hierarchical taxonomies $('.post_category', rowData).each(function(){ var term_ids = $(this).text(); if ( term_ids ) { taxname = $(this).attr('id').replace('_'+id, ''); $('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(',')); } }); //flat taxonomies $('.tags_input', rowData).each(function(){ var terms = $(this).text(), taxname = $(this).attr('id').replace('_' + id, ''), textarea = $('textarea.tax_input_' + taxname, editRow), comma = inlineEditL10n.comma; if ( terms ) { if ( ',' !== comma ) terms = terms.replace(/,/g, comma); textarea.val(terms); } textarea.suggest( ajaxurl + '?action=ajax-tag-search&tax=' + taxname, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } ); }); // handle the post status status = $('._status', rowData).text(); if ( 'future' != status ) $('select[name="_status"] option[value="future"]', editRow).remove(); if ( 'private' == status ) { $('input[name="keep_private"]', editRow).prop("checked", true); $('input.inline-edit-password-input').val('').prop('disabled', true); } // remove the current page and children from the parent dropdown pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow); if ( pageOpt.length > 0 ) { pageLevel = pageOpt[0].className.split('-')[1]; nextPage = pageOpt; while ( pageLoop ) { nextPage = nextPage.next('option'); if (nextPage.length == 0) break; nextLevel = nextPage[0].className.split('-')[1]; if ( nextLevel <= pageLevel ) { pageLoop = false; } else { nextPage.remove(); nextPage = pageOpt; } } pageOpt.remove(); } $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show(); $('.ptitle', editRow).focus(); return false; }, save : function(id) { var params, fields, page = $('.post_status_page').val() || ''; if ( typeof(id) == 'object' ) id = this.getId(id); $('table.widefat .inline-edit-save .waiting').show(); params = { action: 'inline-save', post_type: typenow, post_ID: id, edit_date: 'true', post_status: page }; fields = $('#edit-'+id+' :input').serialize(); params = fields + '&' + $.param(params); // make ajax request $.post( ajaxurl, params, function(r) { $('table.widefat .inline-edit-save .waiting').hide(); if (r) { if ( -1 != r.indexOf('<tr') ) { $(inlineEditPost.what+id).remove(); $('#edit-'+id).before(r).remove(); $(inlineEditPost.what+id).hide().fadeIn(); } else { r = r.replace( /<.[^<>]*?>/g, '' ); $('#edit-'+id+' .inline-edit-save .error').html(r).show(); } } else { $('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show(); } } , 'html'); return false; }, revert : function(){ var id = $('table.widefat tr.inline-editor').attr('id'); if ( id ) { $('table.widefat .inline-edit-save .waiting').hide(); if ( 'bulk-edit' == id ) { $('table.widefat #bulk-edit').removeClass('inline-editor').hide(); $('#bulk-titles').html(''); $('#inlineedit').append( $('#bulk-edit') ); } else { $('#'+id).remove(); id = id.substr( id.lastIndexOf('-') + 1 ); $(this.what+id).show(); } } return false; }, getId : function(o) { var id = $(o).closest('tr').attr('id'), parts = id.split('-'); return parts[parts.length - 1]; } }; $(document).ready(function(){inlineEditPost.init();}); })(jQuery);
JavaScript
(function( exports, $ ){ var api = wp.customize; /* * @param options * - previewer - The Previewer instance to sync with. * - transport - The transport to use for previewing. Supports 'refresh' and 'postMessage'. */ api.Setting = api.Value.extend({ initialize: function( id, value, options ) { var element; api.Value.prototype.initialize.call( this, value, options ); this.id = id; this.transport = this.transport || 'refresh'; this.bind( this.preview ); }, preview: function() { switch ( this.transport ) { case 'refresh': return this.previewer.refresh(); case 'postMessage': return this.previewer.send( 'setting', [ this.id, this() ] ); } } }); api.Control = api.Class.extend({ initialize: function( id, options ) { var control = this, nodes, radios, settings; this.params = {}; $.extend( this, options || {} ); this.id = id; this.selector = '#customize-control-' + id.replace( ']', '' ).replace( '[', '-' ); this.container = $( this.selector ); settings = $.map( this.params.settings, function( value ) { return value; }); api.apply( api, settings.concat( function() { var key; control.settings = {}; for ( key in control.params.settings ) { control.settings[ key ] = api( control.params.settings[ key ] ); } control.setting = control.settings['default'] || null; control.ready(); }) ); control.elements = []; nodes = this.container.find('[data-customize-setting-link]'); radios = {}; nodes.each( function() { var node = $(this), name; if ( node.is(':radio') ) { name = node.prop('name'); if ( radios[ name ] ) return; radios[ name ] = true; node = nodes.filter( '[name="' + name + '"]' ); } api( node.data('customizeSettingLink'), function( setting ) { var element = new api.Element( node ); control.elements.push( element ); element.sync( setting ); element.set( setting() ); }); }); }, ready: function() {}, dropdownInit: function() { var control = this, statuses = this.container.find('.dropdown-status'), params = this.params, update = function( to ) { if ( typeof to === 'string' && params.statuses && params.statuses[ to ] ) statuses.html( params.statuses[ to ] ).show(); else statuses.hide(); }; // Support the .dropdown class to open/close complex elements this.container.on( 'click', '.dropdown', function( event ) { event.preventDefault(); control.container.toggleClass('open'); }); this.setting.bind( update ); update( this.setting() ); } }); api.ColorControl = api.Control.extend({ ready: function() { var control = this, rhex, spot, input, text, update; rhex = /^#([A-Fa-f0-9]{3}){0,2}$/; spot = this.container.find('.dropdown-content'); input = new api.Element( this.container.find('.color-picker-hex') ); update = function( color ) { spot.css( 'background', color ); control.farbtastic.setColor( color ); }; this.farbtastic = $.farbtastic( this.container.find('.farbtastic-placeholder'), control.setting.set ); // Only pass through values that are valid hexes/empty. input.sync( this.setting ).validate = function( to ) { return rhex.test( to ) ? to : null; }; this.setting.bind( update ); update( this.setting() ); this.dropdownInit(); } }); api.UploadControl = api.Control.extend({ ready: function() { var control = this; this.params.removed = this.params.removed || ''; this.success = $.proxy( this.success, this ); this.uploader = $.extend({ container: this.container, browser: this.container.find('.upload'), dropzone: this.container.find('.upload-dropzone'), success: this.success }, this.uploader || {} ); if ( this.uploader.supported ) { if ( control.params.context ) control.uploader.param( 'post_data[context]', this.params.context ); control.uploader.param( 'post_data[theme]', api.settings.theme.stylesheet ); } this.uploader = new wp.Uploader( this.uploader ); this.remover = this.container.find('.remove'); this.remover.click( function( event ) { control.setting.set( control.params.removed ); event.preventDefault(); }); this.removerVisibility = $.proxy( this.removerVisibility, this ); this.setting.bind( this.removerVisibility ); this.removerVisibility( this.setting.get() ); }, success: function( attachment ) { this.setting.set( attachment.url ); }, removerVisibility: function( to ) { this.remover.toggle( to != this.params.removed ); } }); api.ImageControl = api.UploadControl.extend({ ready: function() { var control = this, panels; this.uploader = { init: function( up ) { var fallback, button; if ( this.supports.dragdrop ) return; // Maintain references while wrapping the fallback button. fallback = control.container.find( '.upload-fallback' ); button = fallback.children().detach(); this.browser.detach().empty().append( button ); fallback.append( this.browser ).show(); } }; api.UploadControl.prototype.ready.call( this ); this.thumbnail = this.container.find('.preview-thumbnail img'); this.thumbnailSrc = $.proxy( this.thumbnailSrc, this ); this.setting.bind( this.thumbnailSrc ); this.library = this.container.find('.library'); // Generate tab objects this.tabs = {}; panels = this.library.find('.library-content'); this.library.children('ul').children('li').each( function() { var link = $(this), id = link.data('customizeTab'), panel = panels.filter('[data-customize-tab="' + id + '"]'); control.tabs[ id ] = { both: link.add( panel ), link: link, panel: panel }; }); // Bind tab switch events this.library.children('ul').on( 'click', 'li', function( event ) { var id = $(this).data('customizeTab'), tab = control.tabs[ id ]; event.preventDefault(); if ( tab.link.hasClass('library-selected') ) return; control.selected.both.removeClass('library-selected'); control.selected = tab; control.selected.both.addClass('library-selected'); }); // Bind events to switch image urls. this.library.on( 'click', 'a', function( event ) { var value = $(this).data('customizeImageValue'); if ( value ) { control.setting.set( value ); event.preventDefault(); } }); if ( this.tabs.uploaded ) { this.tabs.uploaded.target = this.library.find('.uploaded-target'); if ( ! this.tabs.uploaded.panel.find('.thumbnail').length ) this.tabs.uploaded.both.addClass('hidden'); } // Select a tab panels.each( function() { var tab = control.tabs[ $(this).data('customizeTab') ]; // Select the first visible tab. if ( ! tab.link.hasClass('hidden') ) { control.selected = tab; tab.both.addClass('library-selected'); return false; } }); this.dropdownInit(); }, success: function( attachment ) { api.UploadControl.prototype.success.call( this, attachment ); // Add the uploaded image to the uploaded tab. if ( this.tabs.uploaded && this.tabs.uploaded.target.length ) { this.tabs.uploaded.both.removeClass('hidden'); attachment.element = $( '<a href="#" class="thumbnail"></a>' ) .data( 'customizeImageValue', attachment.url ) .append( '<img src="' + attachment.url+ '" />' ) .appendTo( this.tabs.uploaded.target ); } }, thumbnailSrc: function( to ) { if ( /^(https?:)?\/\//.test( to ) ) this.thumbnail.prop( 'src', to ).show(); else this.thumbnail.hide(); } }); // Change objects contained within the main customize object to Settings. api.defaultConstructor = api.Setting; // Create the collection of Control objects. api.control = new api.Values({ defaultConstructor: api.Control }); api.PreviewFrame = api.Messenger.extend({ sensitivity: 2000, initialize: function( params, options ) { var deferred = $.Deferred(), self = this; // This is the promise object. deferred.promise( this ); this.container = params.container; this.signature = params.signature; $.extend( params, { channel: api.PreviewFrame.uuid() }); api.Messenger.prototype.initialize.call( this, params, options ); this.add( 'previewUrl', params.previewUrl ); this.query = $.extend( params.query || {}, { customize_messenger_channel: this.channel() }); this.run( deferred ); }, run: function( deferred ) { var self = this, loaded = false, ready = false; if ( this._ready ) this.unbind( 'ready', this._ready ); this._ready = function() { ready = true; if ( loaded ) deferred.resolveWith( self ); }; this.bind( 'ready', this._ready ); this.request = $.ajax( this.previewUrl(), { type: 'POST', data: this.query, xhrFields: { withCredentials: true } } ); this.request.fail( function() { deferred.rejectWith( self, [ 'request failure' ] ); }); this.request.done( function( response ) { var location = self.request.getResponseHeader('Location'), signature = self.signature, index; // Check if the location response header differs from the current URL. // If so, the request was redirected; try loading the requested page. if ( location && location != self.previewUrl() ) { deferred.rejectWith( self, [ 'redirect', location ] ); return; } // Check if the user is not logged in. if ( '0' === response ) { self.login( deferred ); return; } // Check for cheaters. if ( '-1' === response ) { deferred.rejectWith( self, [ 'cheatin' ] ); return; } // Check for a signature in the request. index = response.lastIndexOf( signature ); if ( -1 === index || index < response.lastIndexOf('</html>') ) { deferred.rejectWith( self, [ 'unsigned' ] ); return; } // Strip the signature from the request. response = response.slice( 0, index ) + response.slice( index + signature.length ); // Create the iframe and inject the html content. self.iframe = $('<iframe />').appendTo( self.container ); // Bind load event after the iframe has been added to the page; // otherwise it will fire when injected into the DOM. self.iframe.one( 'load', function() { loaded = true; if ( ready ) { deferred.resolveWith( self ); } else { setTimeout( function() { deferred.rejectWith( self, [ 'ready timeout' ] ); }, self.sensitivity ); } }); self.targetWindow( self.iframe[0].contentWindow ); self.targetWindow().document.open(); self.targetWindow().document.write( response ); self.targetWindow().document.close(); }); }, login: function( deferred ) { var self = this, reject; reject = function() { deferred.rejectWith( self, [ 'logged out' ] ); }; if ( this.triedLogin ) return reject(); // Check if we have an admin cookie. $.get( api.settings.url.ajax, { action: 'logged-in' }).fail( reject ).done( function( response ) { var iframe; if ( '1' !== response ) reject(); iframe = $('<iframe src="' + self.previewUrl() + '" />').hide(); iframe.appendTo( self.container ); iframe.load( function() { self.triedLogin = true; iframe.remove(); self.run( deferred ); }); }); }, destroy: function() { api.Messenger.prototype.destroy.call( this ); this.request.abort(); if ( this.iframe ) this.iframe.remove(); delete this.request; delete this.iframe; delete this.targetWindow; } }); (function(){ var uuid = 0; api.PreviewFrame.uuid = function() { return 'preview-' + uuid++; }; }()); api.Previewer = api.Messenger.extend({ refreshBuffer: 250, /** * Requires params: * - container - a selector or jQuery element * - previewUrl - the URL of preview frame */ initialize: function( params, options ) { var self = this, rscheme = /^https?/, url; $.extend( this, options || {} ); /* * Wrap this.refresh to prevent it from hammering the servers: * * If refresh is called once and no other refresh requests are * loading, trigger the request immediately. * * If refresh is called while another refresh request is loading, * debounce the refresh requests: * 1. Stop the loading request (as it is instantly outdated). * 2. Trigger the new request once refresh hasn't been called for * self.refreshBuffer milliseconds. */ this.refresh = (function( self ) { var refresh = self.refresh, callback = function() { timeout = null; refresh.call( self ); }, timeout; return function() { if ( typeof timeout !== 'number' ) { if ( self.loading ) { self.abort(); } else { return callback(); } } clearTimeout( timeout ); timeout = setTimeout( callback, self.refreshBuffer ); }; })( this ); this.container = api.ensure( params.container ); this.allowedUrls = params.allowedUrls; this.signature = params.signature; params.url = window.location.href; api.Messenger.prototype.initialize.call( this, params ); this.add( 'scheme', this.origin() ).link( this.origin ).setter( function( to ) { var match = to.match( rscheme ); return match ? match[0] : ''; }); // Limit the URL to internal, front-end links. // // If the frontend and the admin are served from the same domain, load the // preview over ssl if the customizer is being loaded over ssl. This avoids // insecure content warnings. This is not attempted if the admin and frontend // are on different domains to avoid the case where the frontend doesn't have // ssl certs. this.add( 'previewUrl', params.previewUrl ).setter( function( to ) { var result; // Check for URLs that include "/wp-admin/" or end in "/wp-admin". // Strip hashes and query strings before testing. if ( /\/wp-admin(\/|$)/.test( to.replace(/[#?].*$/, '') ) ) return null; // Attempt to match the URL to the control frame's scheme // and check if it's allowed. If not, try the original URL. $.each([ to.replace( rscheme, self.scheme() ), to ], function( i, url ) { $.each( self.allowedUrls, function( i, allowed ) { if ( 0 === url.indexOf( allowed ) ) { result = url; return false; } }); if ( result ) return false; }); // If we found a matching result, return it. If not, bail. return result ? result : null; }); // Refresh the preview when the URL is changed (but not yet). this.previewUrl.bind( this.refresh ); this.scroll = 0; this.bind( 'scroll', function( distance ) { this.scroll = distance; }); // Update the URL when the iframe sends a URL message. this.bind( 'url', this.previewUrl ); }, query: function() {}, abort: function() { if ( this.loading ) { this.loading.destroy(); delete this.loading; } }, refresh: function() { var self = this; this.abort(); this.loading = new api.PreviewFrame({ url: this.url(), previewUrl: this.previewUrl(), query: this.query() || {}, container: this.container, signature: this.signature }); this.loading.done( function() { // 'this' is the loading frame this.bind( 'synced', function() { if ( self.preview ) self.preview.destroy(); self.preview = this; delete self.loading; self.targetWindow( this.targetWindow() ); self.channel( this.channel() ); self.send( 'active' ); }); this.send( 'sync', { scroll: self.scroll, settings: api.get() }); }); this.loading.fail( function( reason, location ) { if ( 'redirect' === reason && location ) self.previewUrl( location ); if ( 'logged out' === reason ) { if ( self.preview ) { self.preview.destroy(); delete self.preview; } self.login().done( self.refresh ); } if ( 'cheatin' === reason ) self.cheatin(); }); }, login: function() { var previewer = this, deferred, messenger, iframe; if ( this._login ) return this._login; deferred = $.Deferred(); this._login = deferred.promise(); messenger = new api.Messenger({ channel: 'login', url: api.settings.url.login }); iframe = $('<iframe src="' + api.settings.url.login + '" />').appendTo( this.container ); messenger.targetWindow( iframe[0].contentWindow ); messenger.bind( 'login', function() { iframe.remove(); messenger.destroy(); delete previewer._login; deferred.resolve(); }); return this._login; }, cheatin: function() { $( document.body ).empty().addClass('cheatin').append( '<p>' + api.l10n.cheatin + '</p>' ); } }); /* ===================================================================== * Ready. * ===================================================================== */ api.controlConstructor = { color: api.ColorControl, upload: api.UploadControl, image: api.ImageControl }; $( function() { api.settings = window._wpCustomizeSettings; api.l10n = window._wpCustomizeControlsL10n; // Check if we can run the customizer. if ( ! api.settings ) return; // Redirect to the fallback preview if any incompatibilities are found. if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) ) return window.location = api.settings.url.fallback; var body = $( document.body ), overlay = body.children('.wp-full-overlay'), query, previewer, parent; // Prevent the form from saving when enter is pressed. $('#customize-controls').on( 'keydown', function( e ) { if ( $( e.target ).is('textarea') ) return; if ( 13 === e.which ) // Enter e.preventDefault(); }); // Initialize Previewer previewer = new api.Previewer({ container: '#customize-preview', form: '#customize-controls', previewUrl: api.settings.url.preview, allowedUrls: api.settings.url.allowed, signature: 'WP_CUSTOMIZER_SIGNATURE' }, { nonce: api.settings.nonce, query: function() { return { wp_customize: 'on', theme: api.settings.theme.stylesheet, customized: JSON.stringify( api.get() ), nonce: this.nonce.preview }; }, save: function() { var self = this, query = $.extend( this.query(), { action: 'customize_save', nonce: this.nonce.save }), request = $.post( api.settings.url.ajax, query ); api.trigger( 'save', request ); body.addClass('saving'); request.always( function() { body.removeClass('saving'); }); request.done( function( response ) { // Check if the user is logged out. if ( '0' === response ) { self.preview.iframe.hide(); self.login().done( function() { self.save(); self.preview.iframe.show(); }); return; } // Check for cheaters. if ( '-1' === response ) { self.cheatin(); return; } api.trigger( 'saved' ); }); } }); // Refresh the nonces if the preview sends updated nonces over. previewer.bind( 'nonce', function( nonce ) { $.extend( this.nonce, nonce ); }); $.each( api.settings.settings, function( id, data ) { api.create( id, id, data.value, { transport: data.transport, previewer: previewer } ); }); $.each( api.settings.controls, function( id, data ) { var constructor = api.controlConstructor[ data.type ] || api.Control, control; control = api.control.add( id, new constructor( id, { params: data, previewer: previewer } ) ); }); // Check if preview url is valid and load the preview frame. if ( previewer.previewUrl() ) previewer.refresh(); else previewer.previewUrl( api.settings.url.home ); // Save and activated states (function() { var state = new api.Values(), saved = state.create('saved'), activated = state.create('activated'); state.bind( 'change', function() { var save = $('#save'), back = $('.back'); if ( ! activated() ) { save.val( api.l10n.activate ).prop( 'disabled', false ); back.text( api.l10n.cancel ); } else if ( saved() ) { save.val( api.l10n.saved ).prop( 'disabled', true ); back.text( api.l10n.close ); } else { save.val( api.l10n.save ).prop( 'disabled', false ); back.text( api.l10n.cancel ); } }); // Set default states. saved( true ); activated( api.settings.theme.active ); api.bind( 'change', function() { state('saved').set( false ); }); api.bind( 'saved', function() { state('saved').set( true ); state('activated').set( true ); }); activated.bind( function( to ) { if ( to ) api.trigger( 'activated' ); }); // Expose states to the API. api.state = state; }()); // Temporary accordion code. $('.customize-section-title').click( function( event ) { var clicked = $( this ).parents( '.customize-section' ); if ( clicked.hasClass('cannot-expand') ) return; $( '.customize-section' ).not( clicked ).removeClass( 'open' ); clicked.toggleClass( 'open' ); event.preventDefault(); }); // Button bindings. $('#save').click( function( event ) { previewer.save(); event.preventDefault(); }); $('.collapse-sidebar').click( function( event ) { overlay.toggleClass( 'collapsed' ).toggleClass( 'expanded' ); event.preventDefault(); }); // Create a potential postMessage connection with the parent frame. parent = new api.Messenger({ url: api.settings.url.parent, channel: 'loader' }); // If we receive a 'back' event, we're inside an iframe. // Send any clicks to the 'Return' link to the parent page. parent.bind( 'back', function() { $('.back').on( 'click.back', function( event ) { event.preventDefault(); parent.send( 'close' ); }); }); // Pass events through to the parent. api.bind( 'saved', function() { parent.send( 'saved' ); }); // When activated, let the loader handle redirecting the page. // If no loader exists, redirect the page ourselves (if a url exists). api.bind( 'activated', function() { if ( parent.targetWindow() ) parent.send( 'activated', api.settings.url.activated ); else if ( api.settings.url.activated ) window.location = api.settings.url.activated; }); // Initialize the connection with the parent frame. parent.send( 'ready' ); // Control visibility for default controls $.each({ 'background_image': { controls: [ 'background_repeat', 'background_position_x', 'background_attachment' ], callback: function( to ) { return !! to } }, 'show_on_front': { controls: [ 'page_on_front', 'page_for_posts' ], callback: function( to ) { return 'page' === to } }, 'header_textcolor': { controls: [ 'header_textcolor' ], callback: function( to ) { return 'blank' !== to } } }, function( settingId, o ) { api( settingId, function( setting ) { $.each( o.controls, function( i, controlId ) { api.control( controlId, function( control ) { var visibility = function( to ) { control.container.toggle( o.callback( to ) ); }; visibility( setting.get() ); setting.bind( visibility ); }); }); }); }); // Juggle the two controls that use header_textcolor api.control( 'display_header_text', function( control ) { var last = ''; control.elements[0].unsync( api( 'header_textcolor' ) ); control.element = new api.Element( control.container.find('input') ); control.element.set( 'blank' !== control.setting() ); control.element.bind( function( to ) { if ( ! to ) last = api( 'header_textcolor' ).get(); control.setting.set( to ? last : 'blank' ); }); control.setting.bind( function( to ) { control.element.set( 'blank' !== to ); }); }); // Handle header image data api.control( 'header_image', function( control ) { control.setting.bind( function( to ) { if ( to === control.params.removed ) control.settings.data.set( false ); }); control.library.on( 'click', 'a', function( event ) { control.settings.data.set( $(this).data('customizeHeaderImageData') ); }); control.uploader.success = function( attachment ) { var data; api.ImageControl.prototype.success.call( control, attachment ); data = { attachment_id: attachment.id, url: attachment.url, thumbnail_url: attachment.url, height: attachment.meta.height, width: attachment.meta.width }; attachment.element.data( 'customizeHeaderImageData', data ); control.settings.data.set( data ); } }); api.trigger( 'ready' ); }); })( wp, jQuery );
JavaScript
/* * Superfish v1.4.8 - jQuery menu widget * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt */ ;(function($){ $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')), over = function(){ var $$ = $(this), menu = getMenu($$); clearTimeout(menu.sfTimer); $$.showSuperfishUl().siblings().hideSuperfishUl(); }, out = function(){ var $$ = $(this), menu = getMenu($$), o = sf.op; clearTimeout(menu.sfTimer); menu.sfTimer=setTimeout(function(){ o.retainPath=($.inArray($$[0],o.$path)>-1); $$.hideSuperfishUl(); if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);} },o.delay); }, getMenu = function($menu){ var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0]; sf.op = sf.o[menu.serial]; return menu; }, addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); }; return this.each(function() { var s = this.serial = sf.o.length; var o = $.extend({},sf.defaults,op); o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){ $(this).addClass([o.hoverClass,c.bcClass].join(' ')) .filter('li:has(ul)').removeClass(o.pathClass); }); sf.o[s] = sf.op = o; $('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() { if (o.autoArrows) addArrow( $('>a:first-child',this) ); }) .not('.'+c.bcClass) .hideSuperfishUl(); var $a = $('a',this); $a.each(function(i){ var $li = $a.eq(i).parents('li'); $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);}); }); o.onInit.call(this); }).each(function() { var menuClasses = [c.menuClass]; if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass); $(this).addClass(menuClasses.join(' ')); }); }; var sf = $.fn.superfish; sf.o = []; sf.op = {}; sf.IE7fix = function(){ var o = sf.op; if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined) this.toggleClass(sf.c.shadowClass+'-off'); }; sf.c = { bcClass : 'sf-breadcrumb', menuClass : 'sf-js-enabled', anchorClass : 'sf-with-ul', arrowClass : 'sf-sub-indicator', shadowClass : 'sf-shadow' }; sf.defaults = { hoverClass : 'sfHover', pathClass : 'overideThisToUse', pathLevels : 1, delay : 800, animation : {opacity:'show'}, speed : 'normal', autoArrows : true, dropShadows : true, disableHI : false, // true disables hoverIntent detection onInit : function(){}, // callback functions onBeforeShow: function(){}, onShow : function(){}, onHide : function(){} }; $.fn.extend({ hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass) .find('>ul').hide().css('visibility','hidden'); o.onHide.call($ul); return this; }, showSuperfishUl : function(){ var o = sf.op, sh = sf.c.shadowClass+'-off', $ul = this.addClass(o.hoverClass) .find('>ul:hidden').css('visibility','visible'); sf.IE7fix.call($ul); o.onBeforeShow.call($ul); $ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); }); return this; } }); })(jQuery);
JavaScript
/* * jQuery carouFredSel 4.5.2 * Demo's and documentation: * caroufredsel.frebsite.nl * * Copyright (c) 2011 Fred Heusschen * www.frebsite.nl * * Dual licensed under the MIT and GPL licenses. * http://en.wikipedia.org/wiki/MIT_License * http://en.wikipedia.org/wiki/GNU_General_Public_License */ (function($) { if ($.fn.carouFredSel) return; $.fn.carouFredSel = function(o) { if (this.length == 0) { debug(true, 'No element found for "'+this.selector+'".'); return this; } if (this.length > 1) { return this.each(function() { $(this).carouFredSel(o); }); } var $cfs = this, $tt0 = this[0]; $cfs.init = function(o, setOrig, start) { var obs = ['items', 'scroll', 'auto', 'prev', 'next', 'pagination']; o = getObject($tt0, o); for (var a = 0, l = obs.length; a < l; a++) { o[obs[a]] = getObject($tt0, o[obs[a]]); } if (typeof o.scroll == 'number') { if (o.scroll <= 50) o.scroll = { 'items' : o.scroll }; else o.scroll = { 'duration' : o.scroll }; } else { if (typeof o.scroll == 'string') o.scroll = { 'easing' : o.scroll }; } if (typeof o.items == 'number') o.items = { 'visible' : o.items }; else if ( o.items == 'variable') o.items = { 'visible' : o.items, 'width' : o.items, 'height' : o.items }; if (setOrig) opts_orig = $.extend(true, {}, $.fn.carouFredSel.defaults, o); opts = $.extend(true, {}, $.fn.carouFredSel.defaults, o); opts.d = {}; opts.variableVisible = false; opts.visibleAdjust = false; if (opts.items.start == 0 && typeof start == 'number') { opts.items.start = start; } conf.direction = (opts.direction == 'up' || opts.direction == 'left') ? 'next' : 'prev'; var dims = [ ['width' , 'innerWidth' , 'outerWidth' , 'height' , 'innerHeight' , 'outerHeight' , 'left', 'top' , 'marginRight' , 0, 1, 2, 3], ['height' , 'innerHeight' , 'outerHeight' , 'width' , 'innerWidth' , 'outerWidth' , 'top' , 'left', 'marginBottom', 3, 2, 1, 0] ]; var dn = dims[0].length, dx = (opts.direction == 'right' || opts.direction == 'left') ? 0 : 1; for (var d = 0; d < dn; d++) { opts.d[dims[0][d]] = dims[dx][d]; } var all_itm = $cfs.children(), lrgst_b = ms_getTrueLargestSize(all_itm, opts, 'outerHeight', false); // DEPRECATED if (opts.padding == 'auto') { debug(true, 'The option "padding: auto" is deprecated, use "align: center".'); opts.padding = false; opts.align = 'center'; } // /DEPRECATED // secondairy size set to auto -> measure largest size and set it if (opts[opts.d['height']] == 'auto') { opts[opts.d['height']] = lrgst_b; opts.items[opts.d['height']] = lrgst_b; } // primairy item-size not set -> measure it or set to "variable" if (!opts.items[opts.d['width']]) { opts.items[opts.d['width']] = (ms_hasVariableSizes(all_itm, opts, 'outerWidth')) ? 'variable' : all_itm[opts.d['outerWidth']](true); } // secondairy item-size not set -> measure it or set to "variable" if (!opts.items[opts.d['height']]) { opts.items[opts.d['height']] = (ms_hasVariableSizes(all_itm, opts, 'outerHeight')) ? 'variable' : all_itm[opts.d['outerHeight']](true); } // secondairy size not set -> set to secondairy item-size if (!opts[opts.d['height']]) { opts[opts.d['height']] = opts.items[opts.d['height']]; } switch (opts.items.visible) { case '+1': case '-1': case 'odd': case 'odd+': case 'even': case 'even+': opts.visibleAdjust = opts.items.visible; opts.items.visible = false; break; } // visible-items not set if (!opts.items.visible) { // primairy item-size variable -> set visible items variable if (opts.items[opts.d['width']] == 'variable') { opts.items.visible = 'variable'; } else { // primairy size is number -> calculate visible-items if (typeof opts[opts.d['width']] == 'number') { opts.items.visible = Math.floor(opts[opts.d['width']] / opts.items[opts.d['width']]); } else { // measure and calculate primairy size and visible-items var maxS = ms_getTrueInnerSize($wrp.parent(), opts, 'innerWidth'); opts.items.visible = Math.floor(maxS / opts.items[opts.d['width']]); opts[opts.d['width']] = opts.items.visible * opts.items[opts.d['width']]; if (!opts.visibleAdjust) opts.align = false; } if (opts.items.visible == 'Infinity' || opts.items.visible < 0) { debug(true, 'Not a valid number of visible items: Set to "1".'); opts.items.visible = 1; } opts.items.visible = cf_getVisibleItemsAdjust(opts.items.visible, opts); } } // primairy size not set -> calculate it or set to "variable" if (!opts[opts.d['width']]) { if (opts.items.visible != 'variable' && opts.items[opts.d['width']] != 'variable') { opts[opts.d['width']] = opts.items.visible * opts.items[opts.d['width']]; opts.align = false; } else { opts[opts.d['width']] = 'variable'; } } // variable primairy item-sizes with variabe visible-items if (opts.items.visible == 'variable') { opts.variableVisible = true; opts.maxDimention = (opts[opts.d['width']] == 'variable') ? ms_getTrueInnerSize($wrp.parent(), opts, 'innerWidth') : opts[opts.d['width']]; if (opts.align === false) { opts[opts.d['width']] = 'variable'; } opts.items.visible = getVisibleItemsNext(all_itm, opts, 0); if (opts.items.visible > conf.items.total) { opts.items.visible = conf.items.total; } } if (typeof opts.padding == 'undefined') { opts.padding = 0; } // align not set -> set to center if primairy size is number if (typeof opts.align == 'undefined') { opts.align = (opts[opts.d['width']] == 'variable') ? false : 'center'; } opts.items.oldVisible = opts.items.visible; opts.usePadding = false; opts.padding = cf_getPadding(opts.padding); if (opts.align == 'top') opts.align = 'left'; if (opts.align == 'bottom') opts.align = 'right'; switch (opts.align) { // align: center, left or right case 'center': case 'left': case 'right': if (opts[opts.d['width']] != 'variable') { var p = cf_getAlignPadding(getCurrentItems(all_itm, opts), opts); opts.usePadding = true; opts.padding[opts.d[1]] = p[1]; opts.padding[opts.d[3]] = p[0]; } break; // padding default: opts.align = false; opts.usePadding = ( opts.padding[0] == 0 && opts.padding[1] == 0 && opts.padding[2] == 0 && opts.padding[3] == 0 ) ? false : true; break; } if (typeof opts.items.minimum != 'number') opts.items.minimum = opts.items.visible; if (typeof opts.scroll.items != 'number') opts.scroll.items = (opts.variableVisible) ? 'variable' : opts.items.visible; if (typeof opts.scroll.duration != 'number') opts.scroll.duration = 500; opts.auto = getNaviObject($tt0, opts.auto, false, true); opts.prev = getNaviObject($tt0, opts.prev); opts.next = getNaviObject($tt0, opts.next); opts.pagination = getNaviObject($tt0, opts.pagination, true); opts.auto = $.extend(true, {}, opts.scroll, opts.auto); opts.prev = $.extend(true, {}, opts.scroll, opts.prev); opts.next = $.extend(true, {}, opts.scroll, opts.next); opts.pagination = $.extend(true, {}, opts.scroll, opts.pagination); if (typeof opts.pagination.keys != 'boolean') opts.pagination.keys = false; if (typeof opts.pagination.anchorBuilder != 'function') opts.pagination.anchorBuilder = $.fn.carouFredSel.pageAnchorBuilder; if (typeof opts.auto.play != 'boolean') opts.auto.play = true; if (typeof opts.auto.delay != 'number') opts.auto.delay = 0; if (typeof opts.auto.pauseDuration != 'number') opts.auto.pauseDuration = (opts.auto.duration < 10) ? 2500 : opts.auto.duration * 5; // DEPRECATED if (opts.auto.nap) { debug(true, 'jQuery.nap-plugin is no longer supported.'); } // /DEPRECATED if (opts.synchronise) { opts.synchronise = getSynchArr(opts.synchronise); } if (opts.debug) { debug(true, 'Carousel width: '+opts.width); debug(true, 'Carousel height: '+opts.height); if (opts[opts.d['width']] == 'variable') debug(true, 'Available '+opts.d['width']+': '+opts.maxDimention); debug(true, 'Item widths: '+opts.items.width); debug(true, 'Item heights: '+opts.items.height); debug(true, 'Number of items visible: '+opts.items.visible); if (opts.auto.play) debug(true, 'Number of items scrolled automatically: '+opts.auto.items); if (opts.prev.button) debug(true, 'Number of items scrolled backward: '+opts.prev.items); if (opts.next.button) debug(true, 'Number of items scrolled forward: '+opts.next.items); } }; // /init $cfs.build = function() { if ($cfs.css('position') == 'absolute' || $cfs.css('position') == 'fixed') { debug(opts.debug, 'Carousels CSS-attribute "position" should be "static" or "relative".'); } var orgCSS = { 'float' : $cfs.css('float'), 'position' : $cfs.css('position'), 'top' : $cfs.css('top'), 'right' : $cfs.css('right'), 'bottom' : $cfs.css('bottom'), 'left' : $cfs.css('left'), 'width' : $cfs.css('width'), 'height' : $cfs.css('height'), 'marginTop' : $cfs.css('marginTop'), 'marginRight' : $cfs.css('marginRight'), 'marginBottom' : $cfs.css('marginBottom'), 'marginLeft' : $cfs.css('marginLeft') }; $wrp.css(orgCSS).css({ 'overflow' : 'hidden', 'position' : (orgCSS.position == 'absolute') ? 'absolute' : 'relative' }); $cfs.data('cfs_origCss', orgCSS).css({ 'float' : 'none', 'position' : 'absolute', 'top' : 0, 'left' : 0, 'marginTop' : 0, 'marginRight' : 0, 'marginBottom' : 0, 'marginLeft' : 0 }); if (opts.usePadding) { $cfs.children().each(function() { var m = parseInt($(this).css(opts.d['marginRight'])); if (isNaN(m)) m = 0; $(this).data('cfs_origCssMargin', m); }); } }; // /build $cfs.bind_events = function() { $cfs.unbind_events(); $cfs.bind('stop.cfs'+serial, function(e) { e.stopPropagation(); $cfs.trigger('pause'); opts.auto.play = false; conf.isPaused = 'stopped'; }); $cfs.bind('finish.cfs'+serial, function(e) { }); $cfs.bind('pause.cfs'+serial, function(e, g) { e.stopPropagation(); // DEPRECATED if (typeof g == 'boolean') { debug(true, 'Pause a carousel globally is deprecated, use the "stop" custom event.'); $cfs.trigger('stop'); return; } // /DEPRECATED conf.isPaused = true; if (tmrs.timeouts.auto != null) clearTimeout(tmrs.timeouts.auto); if (tmrs.intervals.auto != null) clearInterval(tmrs.intervals.auto); if (tmrs.intervals.timer != null) clearInterval(tmrs.intervals.timer); var dur1 = opts.auto.pauseDuration - tmrs.pausePassed, perc = 100 - Math.ceil( dur1 * 100 / opts.auto.pauseDuration ); if (perc != 0) { if (opts.auto.onPausePause) opts.auto.onPausePause.call($tt0, perc, dur1); } }); $cfs.bind('play.cfs'+serial, function(e, dir, dla, sta) { e.stopPropagation(); $cfs.trigger('pause'); var v = [dir, dla, sta], t = ['string', 'number', 'boolean'], a = sortParams(v, t); var dir = a[0], dla = a[1], sta = a[2]; if (dir != 'prev' && dir != 'next') dir = conf.direction; if (typeof dla != 'number') dla = 0; if (sta) opts.auto.play = true; if (!opts.auto.play) { return e.stopImmediatePropagation(); } conf.isPaused = false; var dur1 = opts.auto.pauseDuration - tmrs.pausePassed, dur2 = dur1 + dla; perc = 100 - Math.ceil(dur1 * 100 / opts.auto.pauseDuration); tmrs.timeouts.auto = setTimeout(function() { if (conf.isAnimated) { $cfs.trigger('play', dir); } else { tmrs.pausePassed = 0; $cfs.trigger(dir, opts.auto); } }, dur2); if (opts.auto.pauseOnHover === 'resume') { tmrs.intervals.auto = setInterval(function() { tmrs.pausePassed += 50; }, 50); } if (opts.auto.onPauseEnd && perc == 0) { opts.auto.onPauseEnd.call($tt0, perc, dur1); } if (opts.auto.onPauseStart) { tmrs.intervals.timer = setTimeout(function() { opts.auto.onPauseStart.call($tt0, perc, dur1); }, dla); } }); $cfs.bind('prev.cfs'+serial+' next.cfs'+serial, function(e, obj, num, clb) { e.stopPropagation(); if (conf.isPaused == 'stopped' || $cfs.is(':hidden')) { e.stopImmediatePropagation(); return debug(opts.debug, 'Carousel stopped or hidden: Not scrolling.'); } var v = [obj, num, clb], t = ['object', 'number/string', 'function'], a = sortParams(v, t); var obj = a[0], num = a[1], clb = a[2]; if (typeof obj != 'object' || obj == null) obj = opts[e.type]; if (typeof clb == 'function') obj.onAfter = clb; if (typeof num != 'number') { if (num == 'visible') { if (!opts.variableVisible) num = opts.items.visible; } else { if (typeof obj.items == 'number') num = obj.items; else if (typeof opts[e.type].items == 'number') num = opts[e.type].items; else if (opts.variableVisible) num = 'visible'; else num = opts.items.visible; } } if (obj.duration > 0) { if (conf.isAnimated) { if (obj.queue) $cfs.trigger('queue', [e.type, [obj, num, clb]]); e.stopImmediatePropagation(); return debug(opts.debug, 'Carousel currently scrolling.'); } if (opts.items.minimum >= conf.items.total) { e.stopImmediatePropagation(); return debug(opts.debug, 'Not enough items ('+conf.items.total+', '+opts.items.minimum+' needed): Not scrolling.'); } } tmrs.pausePassed = 0; if (obj.conditions && !obj.conditions.call($tt0)) { e.stopImmediatePropagation(); return debug(opts.debug, 'Callback "conditions" returned false.'); } $cfs.trigger('slide_'+e.type, [obj, num]); if (opts.synchronise) { var s = opts.synchronise, c = [obj, num]; for (var j = 0, l = s.length; j < l; j++) { var d = e.type; if (!s[j][1]) c[0] = s[j][0].triggerHandler('configuration', e.type); if (!s[j][2]) d = (d == 'prev') ? 'next' : 'prev'; c[1] = num + s[j][3]; s[j][0].trigger('slide_'+d, c); } } }); $cfs.bind('slide_prev.cfs'+serial, function(e, sO, nI) { e.stopPropagation(); var a_itm = $cfs.children(); // non-circular at start, scroll to end if (!opts.circular) { if (conf.items.first == 0) { if (opts.infinite) { $cfs.trigger('next', conf.items.total-1); } return e.stopImmediatePropagation(); } } if (opts.usePadding) resetMargin(a_itm, opts); // find number of items to scroll if (opts.variableVisible) { if (typeof nI != 'number') { nI = getVisibleItemsPrev(a_itm, opts, conf.items.total-1); } } // prevent non-circular from scrolling to far if (!opts.circular) { if (conf.items.total - nI < conf.items.first) { nI = conf.items.total - conf.items.first; } } // set new number of visible items if (opts.variableVisible) { var vI = getVisibleItemsNext(a_itm, opts, conf.items.total-nI); opts.items.oldVisible = opts.items.visible; opts.items.visible = cf_getVisibleItemsAdjust(vI, opts); } if (opts.usePadding) resetMargin(a_itm, opts, true); // scroll 0, don't scroll if (nI == 0) { e.stopImmediatePropagation(); return debug(opts.debug, '0 items to scroll: Not scrolling.'); } debug(opts.debug, 'Scrolling '+nI+' items backward.'); // save new config conf.items.first += nI; while (conf.items.first >= conf.items.total) conf.items.first -= conf.items.total; // non-circular callback if (!opts.circular) { if (conf.items.first == 0 && sO.onEnd) sO.onEnd.call($tt0); if (!opts.infinite) nv_enableNavi(opts, conf.items.first); } // rearrange items $cfs.children().slice(conf.items.total-nI).prependTo($cfs); if (conf.items.total < opts.items.visible + nI) { $cfs.children().slice(0, (opts.items.visible+nI)-conf.items.total).clone(true).appendTo($cfs); } var a_itm = $cfs.children(), c_old = getOldItemsPrev(a_itm, opts, nI), c_new = getNewItemsPrev(a_itm, opts), l_cur = a_itm.eq(nI-1), l_old = c_old.last(), l_new = c_new.last(); if (opts.usePadding) resetMargin(a_itm, opts); if (opts.align) var p = cf_getAlignPadding(c_new, opts); if (sO.fx == 'directscroll' && opts.items.oldVisible < nI) { var hiddenitems = a_itm.slice(opts.items.oldVisible, nI).hide(), orgW = opts.items[opts.d['width']]; opts.items[opts.d['width']] = 'variable'; } else { var hiddenitems = false; } var i_siz = ms_getTotalSize(a_itm.slice(0, nI), opts, 'width'), w_siz = mapWrapperSizes(ms_getSizes(c_new, opts, true), opts, !opts.usePadding); if (hiddenitems) opts.items[opts.d['width']] = orgW; if (opts.usePadding) { resetMargin(a_itm, opts, true); resetMargin(l_old, opts, opts.padding[opts.d[1]]); resetMargin(l_cur, opts, opts.padding[opts.d[3]]); } if (opts.align) { opts.padding[opts.d[1]] = p[1]; opts.padding[opts.d[3]] = p[0]; } var a_cfs = {}, a_new = {}, a_cur = {}, a_old = {}, a_dur = sO.duration; if (sO.fx == 'none') a_dur = 0; else if (a_dur == 'auto') a_dur = opts.scroll.duration / opts.scroll.items * nI; else if (a_dur <= 0) a_dur = 0; else if (a_dur < 10) a_dur = i_siz / a_dur; var a_conf = { duration: a_dur, easing : sO.easing }; if (sO.onBefore) sO.onBefore.call($tt0, c_old, c_new, w_siz, a_dur); if (opts.usePadding) { var new_m = opts.padding[opts.d[3]]; a_cur[opts.d['marginRight']] = l_cur.data('cfs_origCssMargin'); a_new[opts.d['marginRight']] = l_new.data('cfs_origCssMargin') + opts.padding[opts.d[1]]; a_old[opts.d['marginRight']] = l_old.data('cfs_origCssMargin'); l_cur.stop().animate(a_cur, a_conf); l_old.stop().animate(a_old, a_conf); l_new.stop().animate(a_new, a_conf); } else { var new_m = 0; } a_cfs[opts.d['left']] = new_m; if (opts[opts.d['width']] == 'variable' || opts[opts.d['height']] == 'variable') { $wrp.stop().animate(w_siz, a_conf); } // alternative effects switch(sO.fx) { case 'crossfade': case 'cover': case 'uncover': var $cf2 = $cfs.clone().appendTo($wrp); break; } switch(sO.fx) { case 'uncover': $cf2.children().slice(0, nI).remove(); case 'crossfade': case 'cover': $cf2.children().slice(opts.items.visible).remove(); break; } switch(sO.fx) { case 'fade': fx_fade(sO, $cfs, 0, a_dur); break; case 'crossfade': $cf2.css({ 'opacity': 0 }); fx_fade(sO, $cf2, 1, a_dur); fx_fade(sO, $cfs, 1, a_dur, function() { $cf2.remove(); }); break; case 'cover': fx_cover(sO, $cfs, $cf2, opts, a_dur, true); break; case 'uncover': fx_uncover(sO, $cfs, $cf2, opts, a_dur, true, nI); break; } switch(sO.fx) { case 'fade': case 'crossfade': case 'cover': case 'uncover': f_dur = a_dur; a_dur = 0; break; } // /alternative effects conf.isAnimated = true; var c_nI = nI; $cfs.css(opts.d['left'], -i_siz); $cfs.animate(a_cfs, { duration: a_dur, easing : sO.easing, complete: function() { conf.isAnimated = false; var overFill = opts.items.visible+c_nI-conf.items.total; if (overFill > 0) { $cfs.children().slice(conf.items.total).remove(); c_old = $cfs.children().slice(conf.items.total-(c_nI-overFill)).get().concat( $cfs.children().slice(0, overFill).get() ); } if (hiddenitems) hiddenitems.show(); if (opts.usePadding) { var l_itm = $cfs.children().eq(opts.items.visible+c_nI-1); l_itm.css(opts.d['marginRight'], l_itm.data('cfs_origCssMargin')); } var fn = function() { if (sO.onAfter) { sO.onAfter.call($tt0, c_old, c_new, w_siz); } switch(sO.fx) { case 'fade': case 'crossfade': $cfs.css('filter', ''); break; } if (queue.length) { setTimeout(function() { $cfs.trigger(queue[0][0], queue[0][1]); queue.shift(); }, 1); } }; switch(sO.fx) { case 'fade': case 'uncover': fx_fade(sO, $cfs, 1, f_dur, fn); break; default: fn(); break; } } }); $cfs.trigger('updatePageStatus', [false, w_siz]).trigger('play', a_dur); }); $cfs.bind('slide_next.cfs'+serial, function(e, sO, nI) { e.stopPropagation(); var a_itm = $cfs.children(); // non-circular at end, scroll to start if (!opts.circular) { if (conf.items.first == opts.items.visible) { if (opts.infinite) { $cfs.trigger('prev', conf.items.total-1); } return e.stopImmediatePropagation(); } } if (opts.usePadding) resetMargin(a_itm, opts); // find number of items to scroll if (opts.variableVisible) { if (typeof nI != 'number') { nI = opts.items.visible; } } var lastItemNr = (conf.items.first == 0) ? conf.items.total : conf.items.first; // prevent non-circular from scrolling to far if (!opts.circular) { if (opts.variableVisible) { var vI = getVisibleItemsNext(a_itm, opts, nI), xI = getVisibleItemsPrev(a_itm, opts, lastItemNr-1); } else { var vI = opts.items.visible, xI = opts.items.visible; } if (nI + vI > lastItemNr) { nI = lastItemNr - xI; } } // set new number of visible items if (opts.variableVisible) { var vI = getVisibleItemsNextTestCircular(a_itm, opts, nI, lastItemNr); while (opts.items.visible - nI >= vI && nI < conf.items.total) { nI++; vI = getVisibleItemsNextTestCircular(a_itm, opts, nI, lastItemNr); } opts.items.oldVisible = opts.items.visible; opts.items.visible = cf_getVisibleItemsAdjust(vI, opts); } if (opts.usePadding) resetMargin(a_itm, opts, true); // scroll 0, don't scroll if (nI == 0) { e.stopImmediatePropagation(); return debug(opts.debug, '0 items to scroll: Not scrolling.'); } debug(opts.debug, 'Scrolling '+nI+' items forward.'); // save new config conf.items.first -= nI; while (conf.items.first < 0) conf.items.first += conf.items.total; // non-circular callback if (!opts.circular) { if (conf.items.first == opts.items.visible && sO.onEnd) sO.onEnd.call($tt0); if (!opts.infinite) nv_enableNavi(opts, conf.items.first); } // rearrange items if (conf.items.total < opts.items.visible + nI) { $cfs.children().slice(0, (opts.items.visible+nI)-conf.items.total).clone(true).appendTo($cfs); } var a_itm = $cfs.children(), c_old = getOldItemsNext(a_itm, opts), c_new = getNewItemsNext(a_itm, opts, nI), l_cur = a_itm.eq(nI-1), l_old = c_old.last(), l_new = c_new.last(); if (opts.usePadding) resetMargin(a_itm, opts); if (opts.align) var p = cf_getAlignPadding(c_new, opts); if (sO.fx == 'directscroll' && opts.items.oldVisible < nI) { var hiddenitems = a_itm.slice(opts.items.oldVisible, nI).hide(), orgW = opts.items[opts.d['width']]; opts.items[opts.d['width']] = 'variable'; } else { var hiddenitems = false; } var i_siz = ms_getTotalSize(a_itm.slice(0, nI), opts, 'width'), w_siz = mapWrapperSizes(ms_getSizes(c_new, opts, true), opts, !opts.usePadding); if (hiddenitems) opts.items[opts.d['width']] = orgW; if (opts.usePadding) { resetMargin(a_itm, opts, true); resetMargin(l_old, opts, opts.padding[opts.d[1]]); resetMargin(l_new, opts, opts.padding[opts.d[1]]); } if (opts.align) { opts.padding[opts.d[1]] = p[1]; opts.padding[opts.d[3]] = p[0]; } var a_cfs = {}, a_old = {}, a_cur = {}, a_dur = sO.duration; if (sO.fx == 'none') a_dur = 0; else if (a_dur == 'auto') a_dur = opts.scroll.duration / opts.scroll.items * nI; else if (a_dur <= 0) a_dur = 0; else if (a_dur < 10) a_dur = i_siz / a_dur; var a_conf = { duration: a_dur, easing : sO.easing }; if (sO.onBefore) sO.onBefore.call($tt0, c_old, c_new, w_siz, a_dur); if (opts.usePadding) { a_old[opts.d['marginRight']] = l_old.data('cfs_origCssMargin'); a_cur[opts.d['marginRight']] = l_cur.data('cfs_origCssMargin') + opts.padding[opts.d[3]]; l_new.css(opts.d['marginRight'], l_new.data('cfs_origCssMargin') + opts.padding[opts.d[1]]); l_old.stop().animate(a_old, a_conf); l_cur.stop().animate(a_cur, a_conf); } a_cfs[opts.d['left']] = -i_siz; if (opts[opts.d['width']] == 'variable' || opts[opts.d['height']] == 'variable') { $wrp.stop().animate(w_siz, a_conf); } // alternative effects switch(sO.fx) { case 'crossfade': case 'cover': case 'uncover': var $cf2 = $cfs.clone().appendTo($wrp); break; } switch(sO.fx) { case 'crossfade': case 'cover': $cf2.children().slice(0, nI).remove(); $cf2.children().slice(opts.items.visible).remove(); break; case 'uncover': $cf2.children().slice(opts.items.oldVisible).remove(); break; } switch(sO.fx) { case 'fade': fx_fade(sO, $cfs, 0, a_dur); break; case 'crossfade': $cf2.css({ 'opacity': 0 }); fx_fade(sO, $cf2, 1, a_dur); fx_fade(sO, $cfs, 1, a_dur, function() { $cf2.remove(); }); break; case 'cover': fx_cover(sO, $cfs, $cf2, opts, a_dur, false); break; case 'uncover': fx_uncover(sO, $cfs, $cf2, opts, a_dur, false, nI); break; } switch(sO.fx) { case 'fade': case 'crossfade': case 'cover': case 'uncover': f_dur = a_dur; a_dur = 0; break; } // /alternative effects conf.isAnimated = true; var c_nI = nI; $cfs.animate(a_cfs, { duration: a_dur, easing : sO.easing, complete: function() { conf.isAnimated = false; var overFill = opts.items.visible+c_nI-conf.items.total, new_m = (opts.usePadding) ? opts.padding[opts.d[3]] : 0; $cfs.css(opts.d['left'], new_m); if (overFill > 0) { $cfs.children().slice(conf.items.total).remove(); } var l_itm = $cfs.children().slice(0, c_nI).appendTo($cfs).last(); if (overFill > 0) { c_new = getCurrentItems(a_itm, opts); } if (hiddenitems) hiddenitems.show(); if (opts.usePadding) { if (conf.items.total < opts.items.visible+c_nI) { var l_cur = $cfs.children().eq(opts.items.visible-1); l_cur.css(opts.d['marginRight'], l_cur.data('cfs_origCssMargin') + opts.padding[opts.d[3]]); } l_itm.css(opts.d['marginRight'], l_itm.data('cfs_origCssMargin')); } var fn = function() { if (sO.onAfter) { sO.onAfter.call($tt0, c_old, c_new, w_siz); } switch(sO.fx) { case 'fade': case 'crossfade': $cfs.css('filter', ''); break; } if (queue.length) { setTimeout(function() { $cfs.trigger(queue[0][0], queue[0][1]); queue.shift(); }, 1); } }; switch(sO.fx) { case 'fade': case 'uncover': fx_fade(sO, $cfs, 1, f_dur, fn); break; default: fn(); break; } } }); $cfs.trigger('updatePageStatus', [false, w_siz]).trigger('play', a_dur); }); $cfs.bind('slideTo.cfs'+serial, function(e, num, dev, org, obj, dir) { e.stopPropagation(); var v = [num, dev, org, obj, dir], t = ['string/number/object', 'number', 'boolean', 'object', 'string'], a = sortParams(v, t); var obj = a[3], dir = a[4]; num = getItemIndex(a[0], a[1], a[2], conf.items, $cfs); if (num == 0) return; if (typeof obj != 'object') obj = false; if (conf.isAnimated) { if (typeof obj != 'object' || obj.duration > 0) return; } if (dir != 'prev' && dir != 'next') { if (opts.circular) { if (num <= conf.items.total / 2) dir = 'next'; else dir = 'prev'; } else { if (conf.items.first == 0 || conf.items.first > num) dir = 'next'; else dir = 'prev'; } } if (dir == 'prev') $cfs.trigger('prev', [obj, conf.items.total-num]); else $cfs.trigger('next', [obj, num]); }); $cfs.bind('jumpToStart.cfs'+serial, function(e) { if (conf.items.first > 0) { $cfs.prepend($cfs.children().slice(conf.items.first)); } }); $cfs.bind('synchronise.cfs'+serial, function(e, s) { if (s) s = getSynchArr(s); else if (opts.synchronise) s = opts.synchronise; else return debug(opts.debug, 'No carousel to synchronise.'); var n = $cfs.triggerHandler('currentPosition'); for (var j = 0, l = s.length; j < l; j++) { s[j][0].trigger('slideTo', [n, s[j][3], true]); } }); $cfs.bind('queue.cfs'+serial, function(e, dir, opt) { if (typeof dir == 'undefined') { return queue; } else if (typeof dir == 'function') { dir.call($tt0, queue); } else if (is_array(dir)) { queue = dir; } else { queue.push([dir, opt]); } }); $cfs.bind('insertItem.cfs'+serial, function(e, itm, num, org, dev) { e.stopPropagation(); var v = [itm, num, org, dev], t = ['string/object', 'string/number/object', 'boolean', 'number'], a = sortParams(v, t); var itm = a[0], num = a[1], org = a[2], dev = a[3]; if (typeof itm == 'object' && typeof itm.jquery == 'undefined') itm = $(itm); if (typeof itm == 'string') itm = $(itm); if (typeof itm != 'object' || typeof itm.jquery == 'undefined' || itm.length == 0) return debug(opts.debug, 'Not a valid object.'); if (typeof num == 'undefined') num = 'end'; if (opts.usePadding) { itm.each(function() { var m = parseInt($(this).css(opts.d['marginRight'])); if (isNaN(m)) m = 0; $(this).data('cfs_origCssMargin', m); }); } var orgNum = num, before = 'before'; if (num == 'end') { if (org) { if (conf.items.first == 0) { num = conf.items.total-1; before = 'after'; } else { num = conf.items.first; conf.items.first += itm.length } if (num < 0) num = 0; } else { num = conf.items.total-1; before = 'after'; } } else { num = getItemIndex(num, dev, org, conf.items, $cfs); } if (orgNum != 'end' && !org) { if (num < conf.items.first) conf.items.first += itm.length; } if (conf.items.first >= conf.items.total) conf.items.first -= conf.items.total; var $cit = $cfs.children().eq(num); if ($cit.length) { $cit[before](itm); } else { $cfs.append(itm); } conf.items.total = $cfs.children().length; $cfs.trigger('linkAnchors'); var sz = setSizes($cfs, opts); nv_showNavi(opts, conf.items.total); nv_enableNavi(opts, conf.items.first); $cfs.trigger('updatePageStatus', [true, sz]); }); $cfs.bind('removeItem.cfs'+serial, function(e, num, org, dev) { e.stopPropagation(); var v = [num, org, dev], t = ['string/number/object', 'boolean', 'number'], a = sortParams(v, t); var num = a[0], org = a[1], dev = a[2]; if (typeof num == 'undefined' || num == 'end') { $cfs.children().last().remove(); } else { num = getItemIndex(num, dev, org, conf.items, $cfs); var $cit = $cfs.children().eq(num); if ($cit.length){ if (num < conf.items.first) conf.items.first -= $cit.length; $cit.remove(); } } conf.items.total = $cfs.children().length; var sz = setSizes($cfs, opts); nv_showNavi(opts, conf.items.total); nv_enableNavi(opts, conf.items.first); $cfs.trigger('updatePageStatus', [true, sz]); }); $cfs.bind('currentPosition.cfs'+serial, function(e, fn) { e.stopPropagation(); if (conf.items.first == 0) var val = 0; else var val = conf.items.total - conf.items.first; if (typeof fn == 'function') fn.call($tt0, val); return val; }); $cfs.bind('currentPage.cfs'+serial, function(e, fn) { e.stopPropagation(); var max = Math.ceil(conf.items.total/opts.items.visible-1); if (conf.items.first == 0) var nr = 0; else if (conf.items.first < conf.items.total % opts.items.visible) var nr = 0; else if (conf.items.first == opts.items.visible && !opts.circular) var nr = max; else var nr = Math.round((conf.items.total-conf.items.first)/opts.items.visible); if (nr < 0) nr = 0; if (nr > max) nr = max; if (typeof fn == 'function') fn.call($tt0, nr); return nr; }); $cfs.bind('currentVisible.cfs'+serial, function(e, fn) { e.stopPropagation(); $i = getCurrentItems($cfs.children(), opts); if (typeof fn == 'function') fn.call($tt0, $i); return $i; }); $cfs.bind('isPaused.cfs'+serial, function(e, fn) { e.stopPropagation(); if (typeof fn == 'function') fn.call($tt0, conf.isPaused); return conf.isPaused; }); $cfs.bind('configuration.cfs'+serial, function(e, a, b, c) { e.stopPropagation(); var reInit = false; // return entire configuration-object if (typeof a == 'function') { a.call($tt0, opts); // set multiple options via object } else if (typeof a == 'object') { opts_orig = $.extend(true, {}, opts_orig, a); if (b !== false) reInit = true; else opts = $.extend(true, {}, opts, a); } else if (typeof a != 'undefined') { // callback function for specific option if (typeof b == 'function') { var val = eval('opts.'+a); if (typeof val == 'undefined') val = ''; b.call($tt0, val); // set individual option } else if (typeof b != 'undefined') { if (typeof c !== 'boolean') c = true; eval('opts_orig.'+a+' = b'); if (c !== false) reInit = true; else eval('opts.'+a+' = b'); // return value for specific option } else { return eval('opts.'+a); } } if (reInit) { resetMargin($cfs.children(), opts); $cfs.init(opts_orig); var siz = setSizes($cfs, opts); nv_showNavi(opts, conf.items.total); nv_enableNavi(opts, conf.items.first); $cfs.trigger('updatePageStatus', [true, siz]); } return opts; }); $cfs.bind('linkAnchors.cfs'+serial, function(e, $con, sel) { e.stopPropagation(); if (typeof $con == 'undefined' || $con.length == 0) $con = $('body'); else if (typeof $con == 'string') $con = $($con); if (typeof $con != 'object') return debug(opts.debug, 'Not a valid object.'); if (typeof sel != 'string' || sel.length == 0) sel = 'a.caroufredsel'; $con.find(sel).each(function() { var h = this.hash || ''; if (h.length > 0 && $cfs.children().index($(h)) != -1) { $(this).unbind('click').click(function(e) { e.preventDefault(); $cfs.trigger('slideTo', h); }); } }); }); $cfs.bind('updatePageStatus.cfs'+serial, function(e, build, sizes) { e.stopPropagation(); if (!opts.pagination.container) return; if (typeof build == 'boolean' && build) { opts.pagination.container.children().remove(); for (var a = 0, l = Math.ceil(conf.items.total/opts.items.visible); a < l; a++) { var i = $cfs.children().eq( getItemIndex(a*opts.items.visible, 0, true, conf.items, $cfs) ); opts.pagination.container.append(opts.pagination.anchorBuilder(a+1, i)); } opts.pagination.container.children().unbind(opts.pagination.event).each(function(a) { $(this).bind(opts.pagination.event, function(e) { e.preventDefault(); $cfs.trigger('slideTo', [a * opts.items.visible, 0, true, opts.pagination]); }); }); } var cnr = $cfs.triggerHandler('currentPage'); opts.pagination.container.children().removeClass('selected').eq(cnr).addClass('selected'); }); $cfs.bind('destroy.cfs'+serial, function(e, orgOrder) { e.stopPropagation(); if (orgOrder) { $cfs.trigger('jumpToStart'); } if (opts.usePadding) { resetMargin($cfs.children(), opts); } $cfs.trigger('pause').css($cfs.data('cfs_origCss')); $cfs.unbind_events(); $cfs.unbind_buttons(); $wrp.replaceWith($cfs); }); }; // /bind_events $cfs.unbind_events = function() { $cfs.unbind('.cfs'+serial); }; // /unbind_events $cfs.bind_buttons = function() { $cfs.unbind_buttons(); nv_showNavi(opts, conf.items.total); nv_enableNavi(opts, conf.items.first); if (opts.auto.pauseOnHover) { $wrp.bind('mouseenter.cfs'+serial, function() { $cfs.trigger('pause'); }) .bind('mouseleave.cfs'+serial, function() { $cfs.trigger('play'); }); } if (opts.prev.button) { opts.prev.button.bind(opts.prev.event+'.cfs'+serial, function(e) { e.preventDefault(); $cfs.trigger('prev'); }); if (opts.prev.pauseOnHover) { opts.prev.button.bind('mouseenter.cfs'+serial, function() { $cfs.trigger('pause'); }) .bind('mouseleave.cfs'+serial, function() { $cfs.trigger('play'); }); } } if (opts.next.button) { opts.next.button.bind(opts.next.event+'.cfs'+serial, function(e) { e.preventDefault(); $cfs.trigger('next'); }); if (opts.next.pauseOnHover) { opts.next.button.bind('mouseenter.cfs'+serial, function() { $cfs.trigger('pause'); }) .bind('mouseleave.cfs'+serial, function() { $cfs.trigger('play'); }); } } if ($.fn.mousewheel) { if (opts.prev.mousewheel) { $wrp.mousewheel(function(e, delta) { if (delta > 0) { e.preventDefault(); num = (typeof opts.prev.mousewheel == 'number') ? opts.prev.mousewheel : null; $cfs.trigger('prev', num); } }); } if (opts.next.mousewheel) { $wrp.mousewheel(function(e, delta) { if (delta < 0) { e.preventDefault(); num = (typeof opts.next.mousewheel == 'number') ? opts.next.mousewheel : null; $cfs.trigger('next', num); } }); } } if ($.fn.touchwipe) { var wP = (opts.prev.wipe) ? function() { $cfs.trigger('prev') } : null, wN = (opts.next.wipe) ? function() { $cfs.trigger('next') } : null; if (wN || wN) { var twOps = { 'min_move_x': 30, 'min_move_y': 30, 'preventDefaultEvents': true }; switch (opts.direction) { case 'up': case 'down': twOps.wipeUp = wN; twOps.wipeDown = wP; break; default: twOps.wipeLeft = wN; twOps.wipeRight = wP; } $wrp.touchwipe(twOps); } } if (opts.pagination.container) { if (opts.pagination.pauseOnHover) { opts.pagination.container.bind('mouseenter.cfs'+serial, function() { $cfs.trigger('pause'); }) .bind('mouseleave.cfs'+serial, function() { $cfs.trigger('play'); }); } } if (opts.prev.key || opts.next.key) { $(document).bind('keyup.cfs'+serial, function(e) { var k = e.keyCode; if (k == opts.next.key) { e.preventDefault(); $cfs.trigger('next'); } if (k == opts.prev.key) { e.preventDefault(); $cfs.trigger('prev'); } }); } if (opts.pagination.keys) { $(document).bind('keyup.cfs'+serial, function(e) { var k = e.keyCode; if (k >= 49 && k < 58) { k = (k-49) * opts.items.visible; if (k <= conf.items.total) { e.preventDefault(); $cfs.trigger('slideTo', [k, 0, true, opts.pagination]); } } }); } if (opts.auto.play) { $cfs.trigger('play', opts.auto.delay); } }; // /bind_buttons $cfs.unbind_buttons = function() { $(document).unbind('.cfs'+serial); $wrp.unbind('.cfs'+serial); if (opts.prev.button) opts.prev.button.unbind('.cfs'+serial); if (opts.next.button) opts.next.button.unbind('.cfs'+serial); if (opts.pagination.container) opts.pagination.container.unbind('.cfs'+serial); nv_showNavi(opts, 'hide'); nv_enableNavi(opts, 'removeClass'); if (opts.pagination.container) { opts.pagination.container.children().remove(); } }; // /unbind_buttons // DEPRECATED $cfs.configuration = function(a, b) { debug(true, 'The "configuration" public method is deprecated, use the "configuration" custom event.'); var cr = false; var fn = function(val) { cr = val; }; if (!a) a = fn; if (!b) b = fn; $cfs.trigger('configuration', [a, b]); return cr; }; $cfs.current_position = function() { debug(true, 'The "current_position" public method is deprecated, use the "currentPosition" custom event.'); return $cfs.triggerHandler('currentPosition'); }; $cfs.destroy = function() { debug(true, 'The "destroy" public method is deprecated, use the "destroy" custom event.'); $cfs.trigger('destroy'); return $cfs; }; $cfs.link_anchors = function($c, se) { debug(true, 'The "link_anchors" public method is deprecated, use the "linkAnchors" custom event.'); $cfs.trigger('linkAnchors', [$c, se]); return $cfs; }; // /DEPRECATED if ($cfs.parent().is('.caroufredsel_wrapper')) { var strt = $cfs.triggerHandler( 'currentPosition' ); $cfs.trigger('destroy', true); } else { var strt = false; } var $wrp = $cfs.wrap('<div class="caroufredsel_wrapper" />').parent(), conf = { 'direction' : 'next', 'isPaused' : true, 'isAnimated' : false, 'items' : { 'total' : $cfs.children().length, 'first' : 0 } }, tmrs = { 'pausePassed' : 0, 'intervals' : { 'auto' : null, 'timer' : null }, 'timeouts' : { 'auto' : null } }, opts = {}, opts_orig = o, queue = [], serial = $.fn.carouFredSel.serial++; $cfs.init(opts_orig, true, strt); $cfs.build(); $cfs.bind_events(); $cfs.bind_buttons(); if (opts.items.start != 0) { var s = opts.items.start; if (s === true) { s = window.location.hash; if (!s.length) s = 0; } else if (s === 'random') { s = Math.floor(Math.random() * conf.items.total); } $cfs.trigger('slideTo', [s, 0, true, { duration: 0 }, 'next']); } var siz = setSizes($cfs, opts, false), itm = getCurrentItems($cfs.children(), opts); if (opts.onCreate) { opts.onCreate.call($tt0, itm, siz); } $cfs.trigger('updatePageStatus', [true, siz]); $cfs.trigger('linkAnchors'); return this; }; // public $.fn.carouFredSel.serial = 0; $.fn.carouFredSel.defaults = { 'debug' : false, 'synchronise' : false, 'infinite' : true, 'circular' : true, 'direction' : 'left', 'items' : { 'start' : 0 }, 'scroll' : { 'easing' : 'swing', 'pauseOnHover' : false, 'mousewheel' : false, 'wipe' : false, 'event' : 'click', 'queue' : false } }; $.fn.carouFredSel.pageAnchorBuilder = function(nr, itm) { return '<a href="#"><span>'+nr+'</span></a>'; }; // private function fx_fade(sO, c, x, d, f) { var o = { 'duration' : d, 'easing' : sO.easing }; if (typeof f == 'function') o.complete = f; c.animate({ opacity: x }, o); } function fx_cover(sO, c1, c2, o, d, prev) { var old_w = ms_getSizes(getOldItemsNext(c1.children(), o), o, true)[0], new_w = ms_getSizes(c2.children(), o, true)[0], cur_l = (prev) ? -new_w : old_w, css_o = {}, ani_o = {}; css_o[o.d['width']] = new_w; css_o[o.d['left']] = cur_l; ani_o[o.d['left']] = 0; c1.animate({ opacity: '+=0' }, d); c2.css(css_o).animate(ani_o, { duration: d, easing: sO.easing, complete: function() { $(this).remove(); } }); } function fx_uncover(sO, c1, c2, o, d, prev, n) { var new_w = ms_getSizes(getNewItemsNext(c1.children(), o, n), o, true)[0], old_w = ms_getSizes(c2.children(), o, true)[0], cur_l = (prev) ? -old_w : new_w, css_o = {}, ani_o = {}; css_o[o.d['width']] = old_w; css_o[o.d['left']] = 0; ani_o[o.d['left']] = cur_l; c2.css(css_o).animate(ani_o, { duration: d, easing: sO.easing, complete: function() { $(this).remove(); } }); } function nv_showNavi(o, t) { if (t == 'show' || t == 'hide') { var f = t; } else if (o.items.minimum >= t) { debug(o.debug, 'Not enough items: hiding navigation ('+t+' items, '+o.items.minimum+' needed).'); var f = 'hide'; } else { var f = 'show'; } if (o.prev.button) o.prev.button[f](); if (o.next.button) o.next.button[f](); if (o.pagination.container) o.pagination.container[f](); } function nv_enableNavi(o, f) { if (o.circular || o.infinite) return; var fx = (f == 'removeClass' || f == 'addClass') ? f : false; if (o.next.button) { var fn = fx || (f == o.items.visible) ? 'addClass' : 'removeClass'; o.next.button[fn]('disabled'); } if (o.prev.button) { var fn = fx || (f == 0) ? 'addClass' : 'removeClass'; o.prev.button[fn]('disabled'); } } function sortParams(vals, typs) { var _arr = []; for (var a = 0, l1 = vals.length; a < l1; a++) { for (var b = 0, l2 = typs.length; b < l2; b++) { if (typs[b].indexOf(typeof vals[a]) > -1 && !_arr[b]) { _arr[b] = vals[a]; break; } } } return _arr; } function getSynchArr(s) { if (!is_array(s)) s = [[s]]; if (!is_array(s[0])) s = [s]; for (var j = 0, l = s.length; j < l; j++) { if (typeof s[j][0] == 'string') s[j][0] = $(s[j][0]); if (typeof s[j][1] != 'boolean') s[j][1] = true; if (typeof s[j][2] != 'boolean') s[j][2] = true; if (typeof s[j][3] != 'number') s[j][3] = 0; } return s; } function getKeyCode(k) { if (k == 'right') return 39; if (k == 'left') return 37; if (k == 'up') return 38; if (k == 'down') return 40; return -1; } function getObject($tt, obj) { if (typeof obj == 'function') obj = obj.call($tt); if (typeof obj == 'undefined') obj = {}; return obj; } function getNaviObject($tt, obj, pagi, auto) { if (typeof pagi != 'boolean') pagi = false; if (typeof auto != 'boolean') auto = false; obj = getObject($tt, obj); if (typeof obj == 'string') { var temp = getKeyCode(obj); if (temp == -1) obj = $(obj); else obj = temp; } // pagination if (pagi) { if (typeof obj == 'boolean') obj = { 'keys': obj }; if (typeof obj.jquery != 'undefined') obj = { 'container': obj }; if (typeof obj.container == 'function') obj.container = obj.container.call($tt); if (typeof obj.container == 'string') obj.container = $(obj.container); // auto } else if (auto) { if (typeof obj == 'boolean') obj = { 'play': obj }; if (typeof obj == 'number') obj = { 'pauseDuration': obj }; // prev + next } else { if (typeof obj.jquery != 'undefined') obj = { 'button': obj }; if (typeof obj == 'number') obj = { 'key': obj }; if (typeof obj.button == 'function') obj.button = obj.button.call($tt); if (typeof obj.button == 'string') obj.button = $(obj.button); if (typeof obj.key == 'string') obj.key = getKeyCode(obj.key); } return obj; } function getItemIndex(num, dev, org, items, $cfs) { if (typeof num == 'string') { if (isNaN(num)) num = $(num); else num = parseInt(num); } if (typeof num == 'object') { if (typeof num.jquery == 'undefined') num = $(num); num = $cfs.children().index(num); if (num == -1) num = 0; if (typeof org != 'boolean') org = false; } else { if (typeof org != 'boolean') org = true; } if (isNaN(num)) num = 0; else num = parseInt(num); if (isNaN(dev)) dev = 0; else dev = parseInt(dev); if (org) { num += items.first; } num += dev; if (items.total > 0) { while (num >= items.total) { num -= items.total; } while (num < 0) { num += items.total; } } return num; } function getCurrentItems(i, o) { return i.slice(0, o.items.visible); } function getOldItemsPrev(i, o, n) { return i.slice(n, o.items.oldVisible+n); } function getNewItemsPrev(i, o) { return i.slice(0, o.items.visible); } function getOldItemsNext(i, o) { return i.slice(0, o.items.oldVisible); } function getNewItemsNext(i, o, n) { return i.slice(n, o.items.visible+n); } function getVisibleItemsPrev(i, o, s) { var t = 0, x = 0; for (var a = s; a >= 0; a--) { t += i.eq(a)[o.d['outerWidth']](true); if (t > o.maxDimention) return x; if (a == 0) a = i.length; x++; } } function getVisibleItemsNext(i, o, s) { var t = 0, x = 0; for (var a = s, l = i.length-1; a <= l; a++) { t += i.eq(a)[o.d['outerWidth']](true); if (t > o.maxDimention) return x; if (a == l) a = -1; x++; } } function getVisibleItemsNextTestCircular(i, o, s, l) { var v = getVisibleItemsNext(i, o, s); if (!o.circular) { if (s + v > l) v = l - s; } return v; } function resetMargin(i, o, m) { var x = (typeof m == 'boolean') ? m : false; if (typeof m != 'number') m = 0; i.each(function() { var t = parseInt($(this).css(o.d['marginRight'])); if (isNaN(t)) t = 0; $(this).data('cfs_tempCssMargin', t); $(this).css(o.d['marginRight'], ((x) ? $(this).data('cfs_tempCssMargin') : m + $(this).data('cfs_origCssMargin'))); }); } function ms_getSizes(i, o, wrapper) { s1 = ms_getTotalSize(i, o, 'width', wrapper); s2 = ms_getLargestSize(i, o, 'height', wrapper); return [s1, s2]; } function ms_getLargestSize(i, o, dim, wrapper) { if (typeof wrapper != 'boolean') wrapper = false; if (typeof o[o.d[dim]] == 'number' && wrapper) return o[o.d[dim]]; if (typeof o.items[o.d[dim]] == 'number') return o.items[o.d[dim]]; var di2 = (dim.toLowerCase().indexOf('width') > -1) ? 'outerWidth' : 'outerHeight'; return ms_getTrueLargestSize(i, o, di2); } function ms_getTrueLargestSize(i, o, dim) { var s = 0; i.each(function() { var m = $(this)[o.d[dim]](true); if (s < m) s = m; }); return s; } function ms_getTrueInnerSize($el, o, dim) { var siz = $el[o.d[dim]](), arr = (o.d[dim].toLowerCase().indexOf('width') > -1) ? ['paddingLeft', 'paddingRight'] : ['paddingTop', 'paddingBottom']; for (a = 0, l = arr.length; a < l; a++) { var m = parseInt($el.css(arr[a])); if (isNaN(m)) m = 0; siz -= m; } return siz; } function ms_getTotalSize(i, o, dim, wrapper) { if (typeof wrapper != 'boolean') wrapper = false; if (typeof o[o.d[dim]] == 'number' && wrapper) return o[o.d[dim]]; if (typeof o.items[o.d[dim]] == 'number') return o.items[o.d[dim]] * i.length; var d = (dim.toLowerCase().indexOf('width') > -1) ? 'outerWidth' : 'outerHeight', s = 0; i.each(function() { var j = $(this); if (j.is(':visible')) { s += j[o.d[d]](true); } }); return s; } function ms_hasVariableSizes(i, o, dim) { var s = false, v = false; i.each(function() { c = $(this)[o.d[dim]](true); if (s === false) s = c; else if (s != c) v = true; if (s == 0) v = true; }); return v; } function mapWrapperSizes(ws, o, p) { if (typeof p != 'boolean') p = true; var pad = (o.usePadding && p) ? o.padding : [0, 0, 0, 0]; var wra = {}; wra[o.d['width']] = ws[0] + pad[1] + pad[3]; wra[o.d['height']] = ws[1] + pad[0] + pad[2]; return wra; } function setSizes($c, o, p) { var $w = $c.parent(), $i = $c.children(), $v = getCurrentItems($i, o), sz = mapWrapperSizes(ms_getSizes($v, o, true), o, p); $w.css(sz); if (o.usePadding) { var $l = $v.last(); $l.css(o.d['marginRight'], $l.data('cfs_origCssMargin') + o.padding[o.d[1]]); $c.css(o.d['top'], o.padding[o.d[0]]); $c.css(o.d['left'], o.padding[o.d[3]]); } $c.css(o.d['width'], sz[o.d['width']]+(ms_getTotalSize($i, o, 'width')*2)); $c.css(o.d['height'], ms_getLargestSize($i, o, 'height')); return sz; } function cf_getPadding(p) { if (typeof p == 'undefined') return [0, 0, 0, 0]; if (typeof p == 'number') return [p, p, p, p]; else if (typeof p == 'string') p = p.split('px').join('').split(' '); if (!is_array(p)) { return [0, 0, 0, 0]; } for (var i = 0; i < 4; i++) { p[i] = parseInt(p[i]); } switch (p.length) { case 0: return [0, 0, 0, 0]; case 1: return [p[0], p[0], p[0], p[0]]; case 2: return [p[0], p[1], p[0], p[1]]; case 3: return [p[0], p[1], p[2], p[1]]; default: return [p[0], p[1], p[2], p[3]]; } } function cf_getAlignPadding(itm, o) { var x = (typeof o[o.d['width']] == 'number') ? Math.ceil(o[o.d['width']] - ms_getTotalSize(itm, o, 'width')) : 0; switch (o.align) { case 'left': return [0, x]; break; case 'right': return [x, 0]; break; case 'center': default: var x1 = Math.ceil(x/2), x2 = Math.floor(x/2); return [x1, x2]; break; } } function cf_getVisibleItemsAdjust(x, o) { switch (o.visibleAdjust) { case '+1': return x + 1; break; case '-1': return x - 1; break; case 'odd': if (x % 2 == 0) return x - 1; break; case 'odd+': if (x % 2 == 0) return x + 1; break; case 'even': if (x % 2 == 1) return x - 1; break; case 'even+': if (x % 2 == 1) return x + 1; break; default: return x; break; } } function is_array(a) { return typeof(a) == 'object' && (a instanceof Array); } function debug(d, m) { if (!d) return false; if (typeof m == 'string') m = 'carouFredSel: ' + m; else m = ['carouFredSel:', m]; if (window.console && window.console.log) window.console.log(m); return false; } $.fn.caroufredsel = function(o) { return this.carouFredSel(o); }; })(jQuery);
JavaScript
/**************************************************************************** Copyright (c) 2011 The Wojo Group thewojogroup.com simplecartjs.com http://github.com/thewojogroup/simplecart-js/tree/master The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ var Custom="Custom",GoogleCheckout="GoogleCheckout",PayPal="PayPal",Email="Email",BrazilianReal="BRL",BRL="BRL",AustralianDollar="AUD",AUD="AUD",CanadianDollar="CAD",CAD="CAD",CzechKoruna="CZK",CZK="CZK",DanishKrone="DKK",DKK="DKK",Euro="EUR",EUR="EUR",HongKongDollar="HKD",HKD="HKD",HungarianForint="HUF",HUF="HUF",IsraeliNewSheqel="ILS",ILS="ILS",JapaneseYen="JPY",JPY="JPY",MexicanPeso="MXN",MXN="MXN",NorwegianKrone="NOK",NOK="NOK",NewZealandDollar="NZD",NZD="NZD",PolishZloty="PLN",PLN="PLN",PoundSterling="GBP",GBP="GBP",SingaporeDollar="SGD",SGD="SGD",SwedishKrona="SEK",SEK="SEK",SwissFranc="CHF",CHF="CHF",ThaiBaht="THB",THB="THB",USDollar="USD",USD="USD"; function Cart(){ var me = this; /* member variables */ me.nextId = 1; me.Version = '2.2.2'; me.Shelf = null; me.items = {}; me.isLoaded = false; me.pageIsReady = false; me.quantity = 0; me.total = 0; me.taxRate = 0; me.taxCost = 0; me.shippingFlatRate = 0; me.shippingTotalRate = 0; me.shippingQuantityRate = 0; me.shippingRate = 0; me.shippingCost = 0; me.currency = USD; me.checkoutTo = PayPal; me.email = ""; me.merchantId = ""; me.successUrl = null; me.cancelUrl = null; me.cookieDuration = 30; // default duration in days me.storagePrefix = "sc_"; me.MAX_COOKIE_SIZE = 4000; me.cartHeaders = ['Name','Price','Quantity','Total']; me.events = {}; me.sandbox = false; me.paypalHTTPMethod = "GET"; /* cart headers: you can set these to which ever order you would like, and the cart will display the appropriate headers and item info. any field you have for the items in the cart can be used, and 'Total' will automatically be price*quantity. there are keywords that can be used: 1) "_input" - the field will be a text input with the value set to the given field. when the user changes the value, it will update the cart. this can be useful for quantity. (ie "Quantity_input") 2) "increment" - a link with "+" that will increase the item quantity by 1 3) "decrement" - a link with "-" that will decrease the item quantity by 1 4) "remove" - a link that will remove the item from the cart 5) "_image" or "Image" - the field will be an img tag with the src set to the value. You can simply use "Image" if you set a field in the items called "Image". If you have a field named something else, like "Thumb", you can add the "_image" to create the image tag (ie "Thumb_image"). 6) "_noHeader" - this will skip the header for that field (ie "increment_noHeader") */ /****************************************************** add/remove items to cart ******************************************************/ me.add = function ( values ) { var me=this; /* load cart values if not already loaded */ if( !me.pageIsReady ) { me.initializeView(); me.update(); } if( !me.isLoaded ) { me.load(); me.update(); } var newItem = new CartItem(); /* check to ensure arguments have been passed in */ if( !arguments || arguments.length === 0 ){ error( 'No values passed for item.'); return null; } var argumentArray = arguments; if( values && typeof( values ) !== 'string' && typeof( values ) !== 'number' ){ argumentArray = values; } newItem.parseValuesFromArray( argumentArray ); newItem.checkQuantityAndPrice(); if( me.trigger('beforeAdd', [newItem] ) === false ){ return false; } var isNew = true; /* if the item already exists, update the quantity */ if( me.hasItem(newItem) ) { var foundItem=me.hasItem(newItem); foundItem.quantity= parseInt(foundItem.quantity,10) + parseInt(newItem.quantity,10); newItem = foundItem; isNew = false; } else { me.items[newItem.id] = newItem; } me.update(); me.trigger('afterAdd', [newItem,isNew] ); return newItem; }; me.remove = function( id ){ var tempArray = {}; me.each(function(item){ if( item.id !== id ){ tempArray[item.id] = item; } }); this.items = tempArray; }; me.empty = function () { me.items = {}; me.update(); }; /****************************************************** item accessor functions ******************************************************/ me.find = function (criteria) { if( !criteria ){ return null; } var results = []; me.each(function(item,x,next){ fits = true; me.each( criteria , function(value,j,name){ if( !item[name] || item[name] != value ){ fits = false; } }); if( fits ){ results.push( item ); } }); return (results.length === 0 ) ? null : results; }; me.each = function( array , callback ){ var next, x=0, result; if( typeof array === 'function' ){ var cb = array items = me.items; } else if( typeof callback === 'function' ){ var cb = callback, items = array; } else { return; } for( next in items ){ if( typeof items[next] !== "function" ){ result = cb.call( me , items[next] , x , next ); if( result === false ){ return; } x++; } } }; me.chunk = function(str, n) { if (typeof n==='undefined'){ n=2; } var result = str.match(RegExp('.{1,'+n+'}','g')); return result || []; }; /****************************************************** checkout management ******************************************************/ me.checkout = function() { if( me.quantity === 0 ){ error("Cart is empty"); return; } switch( me.checkoutTo ){ case PayPal: me.paypalCheckout(); break; case GoogleCheckout: me.googleCheckout(); break; case Email: me.emailCheckout(); break; default: me.customCheckout(); break; } }; me.paypalCheckout = function() { var form = document.createElement("form"), counter=1, current, item, descriptionString; form.style.display = "none"; form.method = me.paypalHTTPMethod =="GET" || me.paypalHTTPMethod == "POST" ? me.paypalHTTPMethod : "GET"; form.action = me.sandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr" : "https://www.paypal.com/cgi-bin/webscr"; form.acceptCharset = "utf-8"; // setup hidden fields form.appendChild(me.createHiddenElement("cmd", "_cart")); form.appendChild(me.createHiddenElement("rm", me.paypalHTTPMethod == "POST" ? "2" : "0" )); form.appendChild(me.createHiddenElement("upload", "1")); form.appendChild(me.createHiddenElement("business", me.email )); form.appendChild(me.createHiddenElement("currency_code", me.currency)); form.appendChild(me.createHiddenElement("charset", "utf-8")); if( me.taxRate ){ form.appendChild(me.createHiddenElement("tax_cart",me.taxCost )); } if( me.shipping() !== 0){ form.appendChild(me.createHiddenElement("handling_cart", me.shippingCost )); } if( me.successUrl ){ form.appendChild(me.createHiddenElement("return", me.successUrl )); } if( me.cancelUrl ){ form.appendChild(me.createHiddenElement("cancel_return", me.cancelUrl )); } me.each(function(item,iter){ counter = iter+1; form.appendChild( me.createHiddenElement( "item_name_" + counter, item.name ) ); form.appendChild( me.createHiddenElement( "quantity_" + counter, item.quantity ) ); form.appendChild( me.createHiddenElement( "amount_" + counter, item.price ) ); form.appendChild( me.createHiddenElement( "item_number_" + counter, counter ) ); var option_count = 0; me.each( item , function( value, x , field ){ if( field !== "id" && field !== "price" && field !== "quantity" && field !== "name" && field !== "shipping" && option_count < 10) { form.appendChild( me.createHiddenElement( "on" + option_count + "_" + counter, field ) ); form.appendChild( me.createHiddenElement( "os" + option_count + "_" + counter, value ) ); option_count++; } }); form.appendChild( me.createHiddenElement( "option_index_" + counter, option_count) ); }); document.body.appendChild( form ); form.submit(); document.body.removeChild( form ); }; me.googleCheckout = function() { var me = this; if( me.currency !== USD && me.currency !== GBP ){ error( "Google Checkout only allows the USD and GBP for currency."); return; } else if( me.merchantId === "" || me.merchantId === null || !me.merchantId ){ error( "No merchant Id for google checkout supplied."); return; } var form = document.createElement("form"), counter=1, current, item, descriptionString; form.style.display = "none"; form.method = "POST"; form.action = "https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/" + me.merchantId; form.acceptCharset = "utf-8"; me.each(function(item,iter){ counter = iter+1; form.appendChild( me.createHiddenElement( "item_name_" + counter, item.name ) ); form.appendChild( me.createHiddenElement( "item_quantity_" + counter, item.quantity ) ); form.appendChild( me.createHiddenElement( "item_price_" + counter, item.price ) ); form.appendChild( me.createHiddenElement( "item_currency_" + counter, me.currency ) ); form.appendChild( me.createHiddenElement( "item_tax_rate_" + counter, me.taxRate ) ); form.appendChild( me.createHiddenElement( "_charset_" , "" ) ); descriptionString = ""; me.each( item , function( value , x , field ){ if( field !== "id" && field !== "quantity" && field !== "price" ) { descriptionString = descriptionString + ", " + field + ": " + value; } }); descriptionString = descriptionString.substring( 1 ); form.appendChild( me.createHiddenElement( "item_description_" + counter, descriptionString) ); }); // hack for adding shipping if( me.shipping() !== 0){ form.appendChild(me.createHiddenElement("ship_method_name_1", "Shipping")); form.appendChild(me.createHiddenElement("ship_method_price_1", parseFloat(me.shippingCost).toFixed(2))); form.appendChild(me.createHiddenElement("ship_method_currency_1", me.currency)); } document.body.appendChild( form ); form.submit(); document.body.removeChild( form ); }; me.emailCheckout = function() { return; }; me.customCheckout = function() { return; }; /****************************************************** data storage and retrival ******************************************************/ /* load cart from cookie */ me.load = function () { var me = this, id; /* initialize variables and items array */ me.items = {}; me.total = 0.00; me.quantity = 0; /* retrieve item data from cookie */ if( readCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks") ){ var chunkCount = 1*readCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks"), dataArray = [], dataString = "", data = "", info, newItem, y=0; if(chunkCount>0) { for( y=0;y<chunkCount;y++){ dataArray.push( readCookie( simpleCart.storagePrefix + 'simpleCart_' + (1 + y ) ) ); } dataString = unescape( dataArray.join("") ); data = dataString.split("++"); } for(var x=0, xlen=data.length;x<xlen;x++){ info = data[x].split('||'); newItem = new CartItem(); if( newItem.parseValuesFromArray( info ) ){ newItem.checkQuantityAndPrice(); /* store the new item in the cart */ me.items[newItem.id] = newItem; } } } me.isLoaded = true; }; /* save cart to cookie */ me.save = function () { var dataString = "", dataArray = [], chunkCount = 0; chunkCount = 1*readCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks"); for( var j=0;j<chunkCount;j++){ eraseCookie(simpleCart.storagePrefix + 'simpleCart_'+ j); } eraseCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks"); me.each(function(item){ dataString = dataString + "++" + item.print(); }); dataArray = simpleCart.chunk( dataString.substring(2) , simpleCart.MAX_COOKIE_SIZE ); for( var x=0,xlen = dataArray.length;x<xlen;x++){ createCookie(simpleCart.storagePrefix + 'simpleCart_' + (1 + x ), dataArray[x], me.cookieDuration ); } createCookie( simpleCart.storagePrefix + 'simpleCart_' + "chunks", "" + dataArray.length , me.cookieDuration ); }; /****************************************************** view management ******************************************************/ me.initializeView = function() { var me = this; me.totalOutlets = getElementsByClassName('simpleCart_total'); me.quantityOutlets = getElementsByClassName('simpleCart_quantity'); me.cartDivs = getElementsByClassName('simpleCart_items'); me.taxCostOutlets = getElementsByClassName('simpleCart_taxCost'); me.taxRateOutlets = getElementsByClassName('simpleCart_taxRate'); me.shippingCostOutlets = getElementsByClassName('simpleCart_shippingCost'); me.finalTotalOutlets = getElementsByClassName('simpleCart_finalTotal'); me.addEventToArray( getElementsByClassName('simpleCart_checkout') , simpleCart.checkout , "click"); me.addEventToArray( getElementsByClassName('simpleCart_empty') , simpleCart.empty , "click" ); me.Shelf = new Shelf(); me.Shelf.readPage(); me.pageIsReady = true; }; me.updateView = function() { me.updateViewTotals(); if( me.cartDivs && me.cartDivs.length > 0 ){ me.updateCartView(); } }; me.updateViewTotals = function() { var outlets = [ ["quantity" , "none" ] , ["total" , "currency" ] , ["shippingCost" , "currency" ] , ["taxCost" , "currency" ] , ["taxRate" , "percentage" ] , ["finalTotal" , "currency" ] ]; for( var x=0,xlen=outlets.length; x<xlen;x++){ var arrayName = outlets[x][0] + "Outlets", outputString, element; for( var y = 0,ylen = me[ arrayName ].length; y<ylen; y++ ){ switch( outlets[x][1] ){ case "none": outputString = "" + me[outlets[x][0]]; break; case "currency": outputString = me.valueToCurrencyString( me[outlets[x][0]] ); break; case "percentage": outputString = me.valueToPercentageString( me[outlets[x][0]] ); break; default: outputString = "" + me[outlets[x][0]]; break; } me[arrayName][y].innerHTML = "" + outputString; } } }; me.updateCartView = function() { var newRows = [], y,newRow,current,header,newCell,info,outputValue,option,headerInfo; /* create headers row */ newRow = document.createElement('div'); for(var y=0,ylen = me.cartHeaders.length; y<ylen; y++ ){ newCell = document.createElement('div'); headerInfo = me.cartHeaders[y].split("_"); newCell.innerHTML = me.print( headerInfo[0] ); newCell.className = "item" + headerInfo[0]; for(var z=1,zlen=headerInfo.length;z<zlen;z++){ if( headerInfo[z].toLowerCase() == "noheader" ){ newCell.style.display = "none"; } } newRow.appendChild( newCell ); } newRow.className = "cartHeaders"; newRows[0] = newRow; /* create a row for each item in the cart */ me.each(function(item, x){ newRow = document.createElement('div'); for(var y=0,ylen = me.cartHeaders.length; y<ylen; y++ ){ newCell = document.createElement('div'); info = me.cartHeaders[y].split("_"); outputValue = me.createCartRow( info , item , outputValue ); newCell.innerHTML = outputValue; newCell.className = "item" + info[0]; newRow.appendChild( newCell ); } newRow.className = "itemContainer"; newRows[x+1] = newRow; }); for( var x=0,xlen=me.cartDivs.length; x<xlen; x++){ /* delete current rows in div */ var div = me.cartDivs[x]; if( div.childNodes && div.appendChild ){ while( div.childNodes[0] ){ div.removeChild( div.childNodes[0] ); } for(var j=0, jLen = newRows.length; j<jLen; j++){ div.appendChild( newRows[j] ); } } } }; me.createCartRow = function( info , item , outputValue ){ switch( info[0].toLowerCase() ){ case "total": outputValue = me.valueToCurrencyString(parseFloat(item.price)*parseInt(item.quantity,10) ); break; case "increment": outputValue = me.valueToLink( "+" , "javascript:;" , "onclick=\"simpleCart.items[\'" + item.id + "\'].increment();\"" ); break; case "decrement": outputValue = me.valueToLink( "-" , "javascript:;" , "onclick=\"simpleCart.items[\'" + item.id + "\'].decrement();\"" ); break; case "remove": outputValue = me.valueToLink( "Remove" , "javascript:;" , "onclick=\"simpleCart.items[\'" + item.id + "\'].remove();\"" ); break; case "price": outputValue = me.valueToCurrencyString( item[ info[0].toLowerCase() ] ? item[info[0].toLowerCase()] : " " ); break; default: outputValue = item[ info[0].toLowerCase() ] ? typeof item[info[0].toLowerCase()] === 'function' ? item[info[0].toLowerCase()].call(item) : item[info[0].toLowerCase()] : " "; break; } for( var y=1,ylen=info.length;y<ylen;y++){ option = info[y].toLowerCase(); switch( option ){ case "image": case "img": outputValue = me.valueToImageString( outputValue ); break; case "input": outputValue = me.valueToTextInput( outputValue , "onchange=\"simpleCart.items[\'" + item.id + "\'].set(\'" + info[0].toLowerCase() + "\' , this.value);\"" ); break; case "div": case "span": case "h1": case "h2": case "h3": case "h4": case "p": outputValue = me.valueToElement( option , outputValue , "" ); break; case "noheader": break; default: error( "unkown header option: " + option ); break; } } return outputValue; }; me.addEventToArray = function ( array , functionCall , theEvent ) { var outlet, element; for(var x=0,xlen=array.length; x<xlen; x++ ){ element = array[x]; if( element.addEventListener ) { element.addEventListener(theEvent, functionCall , false ); } else if( element.attachEvent ) { element.attachEvent( "on" + theEvent, functionCall ); } } }; me.createHiddenElement = function ( name , value ){ var element = document.createElement("input"); element.type = "hidden"; element.name = name; element.value = value; return element; }; /****************************************************** Event Management ******************************************************/ // bind a callback to a simpleCart event me.bind = function( name , callback ){ if( typeof callback !== 'function' ){ return me; } if (me.events[name] === true ){ callback.apply( me ); } else if( typeof me.events[name] !== 'undefined' ){ me.events[name].push( callback ); } else { me.events[name] = [ callback ]; } return me; }; // trigger event me.trigger = function( name , options ){ var returnval = true; if( typeof me.events[name] !== 'undefined' && typeof me.events[name][0] === 'function'){ for( var x=0,xlen=me.events[name].length; x<xlen; x++ ){ returnval = me.events[name][x].apply( me , (options ? options : [] ) ); } } if( returnval === false ){ return false; } else { return true; } }; // shortcut for ready function me.ready = function( callback ){ if( !callback ){ me.trigger( 'ready' ); me.events['ready'] = true; } else { me.bind( 'ready' , callback ); } return me; }; /****************************************************** Currency management ******************************************************/ me.currencySymbol = function() { switch(me.currency){ case CHF: return "CHF&nbsp;"; case CZK: return "CZK&nbsp;"; case DKK: return "DKK&nbsp;"; case HUF: return "HUF&nbsp;"; case NOK: return "NOK&nbsp;"; case PLN: return "PLN&nbsp;"; case SEK: return "SEK&nbsp;"; case JPY: return "&yen;"; case EUR: return "&euro;"; case GBP: return "&pound;"; case CHF: return "CHF&nbsp;"; case THB: return "&#3647;"; case USD: case CAD: case AUD: case NZD: case HKD: case SGD: return "&#36;"; default: return ""; } }; me.currencyStringForPaypalCheckout = function( value ){ if( me.currencySymbol() == "&#36;" ){ return "$" + parseFloat( value ).toFixed(2); } else { return "" + parseFloat(value ).toFixed(2); } }; /****************************************************** Formatting ******************************************************/ me.valueToCurrencyString = function( value ) { var val = parseFloat( value ); if( isNaN(val)) val = 0; return val.toCurrency( me.currencySymbol() ); }; me.valueToPercentageString = function( value ){ return parseFloat( 100*value ) + "%"; }; me.valueToImageString = function( value ){ if( value.match(/<\s*img.*src\=/) ){ return value; } else { return "<img src=\"" + value + "\" />"; } }; me.valueToTextInput = function( value , html ){ return "<input type=\"text\" value=\"" + value + "\" " + html + " />"; }; me.valueToLink = function( value, link, html){ return "<a href=\"" + link + "\" " + html + " >" + value + "</a>"; }; me.valueToElement = function( type , value , html ){ return "<" + type + " " + html + " > " + value + "</" + type + ">"; }; /****************************************************** Duplicate management ******************************************************/ me.hasItem = function ( item ) { var current, matches, field, match=false; me.each(function(testItem){ matches = true; me.each( item , function( value , x , field ){ if( field !== "quantity" && field !== "id" && item[field] !== testItem[field] ){ matches = false; } }); if( matches ){ match = testItem; } }); return match; }; /****************************************************** Language managment ******************************************************/ me.ln = { "en_us": { quantity: "Quantity" , price: "Price" , total: "Total" , decrement: "Decrement" , increment: "Increment" , remove: "Remove" , tax: "Tax" , shipping: "Shipping" , image: "Image" } }; me.language = "en_us"; me.print = function( input ) { var me = this; return me.ln[me.language] && me.ln[me.language][input.toLowerCase()] ? me.ln[me.language][input.toLowerCase()] : input; }; /****************************************************** Cart Update managment ******************************************************/ me.update = function() { if( !simpleCart.isLoaded ){ simpleCart.load(); } if( !simpleCart.pageIsReady ){ simpleCart.initializeView(); } me.updateTotals(); me.updateView(); me.save(); }; me.updateTotals = function() { me.total = 0 ; me.quantity = 0; me.each(function(item){ if( item.quantity < 1 ){ item.remove(); } else if( item.quantity !== null && item.quantity !== "undefined" ){ me.quantity = parseInt(me.quantity,10) + parseInt(item.quantity,10); } if( item.price ){ me.total = parseFloat(me.total) + parseInt(item.quantity,10)*parseFloat(item.price); } }); me.shippingCost = me.shipping(); me.taxCost = parseFloat(me.total)*me.taxRate; me.finalTotal = me.shippingCost + me.taxCost + me.total; }; me.shipping = function(){ if( parseInt(me.quantity,10)===0 ) return 0; var shipping = parseFloat(me.shippingFlatRate) + parseFloat(me.shippingTotalRate)*parseFloat(me.total) + parseFloat(me.shippingQuantityRate)*parseInt(me.quantity,10), next; me.each(function(nextItem){ if( nextItem.shipping ){ if( typeof nextItem.shipping == 'function' ){ shipping += parseFloat(nextItem.shipping()); } else { shipping += parseFloat(nextItem.shipping); } } }); return shipping; } me.initialize = function() { me.initializeView(); me.load(); me.update(); me.ready(); }; } /******************************************************************************************************** * Cart Item Object ********************************************************************************************************/ function CartItem() { while( simpleCart.items["c" + simpleCart.nextId] ) simpleCart.nextId++; this.id = "c" + simpleCart.nextId; } CartItem.prototype = { set : function ( field , value ){ field = field.toLowerCase(); if( typeof( this[field] ) !== "function" && field !== "id" ){ value = "" + value; if( field == "quantity"){ value = value.replace( /[^(\d|\.)]*/gi , "" ); value = value.replace(/,*/gi, ""); value = parseInt(value,10); } else if( field == "price" ){ value = value.replace( /[^(\d|\.)]*/gi, ""); value = value.replace(/,*/gi , ""); value = parseFloat( value ); } if( typeof(value) == "number" && isNaN( value ) ){ error( "Improperly formatted input."); } else { if( typeof( value ) === "string" ){ if( value.match(/\~|\=/) ){ error("Special character ~ or = not allowed: " + value); } value = value.replace(/\~|\=/g, ""); } this[field] = value; this.checkQuantityAndPrice(); } } else { error( "Cannot change " + field + ", this is a reserved field."); } simpleCart.update(); }, increment : function(){ this.quantity = parseInt(this.quantity,10) + 1; simpleCart.update(); }, decrement : function(){ if( parseInt(this.quantity,10) < 2 ){ this.remove(); } else { this.quantity = parseInt(this.quantity,10) - 1; simpleCart.update(); } }, print : function () { var returnString = '', field; simpleCart.each(this ,function(item,x,name){ returnString+= escape(name) + "=" + escape(item) + "||"; }); return returnString.substring(0,returnString.length-2); }, checkQuantityAndPrice : function() { if( !this.quantity || this.quantity == null || this.quantity == 'undefined'){ this.quantity = 1; error('No quantity for item.'); } else { this.quantity = ("" + this.quantity).replace(/,*/gi, "" ); this.quantity = parseInt( ("" + this.quantity).replace( /[^(\d|\.)]*/gi, "") , 10); if( isNaN(this.quantity) ){ error('Quantity is not a number.'); this.quantity = 1; } } if( !this.price || this.price == null || this.price == 'undefined'){ this.price=0.00; error('No price for item or price not properly formatted.'); } else { this.price = ("" + this.price).replace(/,*/gi, "" ); this.price = parseFloat( ("" + this.price).replace( /[^(\d|\.)]*/gi, "") ); if( isNaN(this.price) ){ error('Price is not a number.'); this.price = 0.00; } } }, parseValuesFromArray : function( array ) { if( array && array.length && array.length > 0) { for(var x=0, xlen=array.length; x<xlen;x++ ){ /* ensure the pair does not have key delimeters */ array[x] = array[x].replace(/\|\|/g, "| |"); array[x] = array[x].replace(/\+\+/g, "+ +"); if( array[x].match(/\~/) ){ error("Special character ~ not allowed: " + array[x]); } array[x] = array[x].replace(/\~/g, ""); /* split the pair and save the unescaped values to the item */ var value = array[x].split('='); if( value.length>1 ){ if( value.length>2 ){ for(var j=2, jlen=value.length;j<jlen;j++){ value[1] = value[1] + "=" + value[j]; } } this[ unescape(value[0]).toLowerCase() ] = unescape(value[1]); } } return true; } else { return false; } }, remove : function() { simpleCart.remove(this.id); simpleCart.update(); } }; /******************************************************************************************************** * Shelf Object for managing items on shelf that can be added to cart ********************************************************************************************************/ function Shelf(){ this.items = {}; } Shelf.prototype = { readPage : function () { this.items = {}; var newItems = getElementsByClassName( "simpleCart_shelfItem" ), newItem; me = this; for( var x = 0, xlen = newItems.length; x<xlen; x++){ newItem = new ShelfItem(); me.checkChildren( newItems[x] , newItem ); me.items[newItem.id] = newItem; } }, checkChildren : function ( item , newItem) { if( !item.childNodes ) return; for(var x=0;item.childNodes[x];x++){ var node = item.childNodes[x]; if( node.className && node.className.match(/item_[^ ]+/) ){ var data = /item_[^ ]+/.exec(node.className)[0].split("_"); if( data[1] == "add" || data[1] == "Add" ){ var tempArray = []; tempArray.push( node ); var addFunction = simpleCart.Shelf.addToCart(newItem.id); simpleCart.addEventToArray( tempArray , addFunction , "click"); node.id = newItem.id; } else { newItem[data[1]] = node; } } if( node.childNodes[0] ){ this.checkChildren( node , newItem ); } } }, empty : function () { this.items = {}; }, addToCart : function ( id ) { return function(){ if( simpleCart.Shelf.items[id]){ simpleCart.Shelf.items[id].addToCart(); } else { error( "Shelf item with id of " + id + " does not exist."); } }; } }; /******************************************************************************************************** * Shelf Item Object ********************************************************************************************************/ function ShelfItem(){ this.id = "s" + simpleCart.nextId++; } ShelfItem.prototype = { remove : function () { simpleCart.Shelf.items[this.id] = null; }, addToCart : function () { var outStrings = [], valueString, field; for( field in this ){ if( typeof( this[field] ) !== "function" && field !== "id" ){ valueString = ""; switch(field){ case "price": if( this[field].value ){ valueString = this[field].value; } else if( this[field].innerHTML ) { valueString = this[field].innerHTML; } /* remove all characters from price except digits and a period */ valueString = valueString.replace( /[^(\d|\.)]*/gi , "" ); valueString = valueString.replace( /,*/ , "" ); break; case "image": valueString = this[field].src; break; default: if( this[field].value ){ valueString = this[field].value; } else if( this[field].innerHTML ) { valueString = this[field].innerHTML; } else if( this[field].src ){ valueString = this[field].src; } else { valueString = this[field]; } break; } outStrings.push( field + "=" + valueString ); } } simpleCart.add( outStrings ); } }; /******************************************************************************************************** * Thanks to Peter-Paul Koch for these cookie functions (http://www.quirksmode.org/js/cookies.html) ********************************************************************************************************/ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; value = value.replace(/\=/g, '~'); document.cookie = name + "=" + escape(value) + expires + "; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) === 0){ var value = unescape(c.substring(nameEQ.length, c.length)); return value.replace(/\~/g, '='); } } return null; } function eraseCookie(name) { createCookie(name,"",-1); } //************************************************************************************************* /* Developed by Robert Nyman, http://www.robertnyman.com Code/licensing: http://code.google.com/p/getelementsbyclassname/ */ var getElementsByClassName = function (className, tag, elm){ if (document.getElementsByClassName) { getElementsByClassName = function (className, tag, elm) { elm = elm || document; var elements = elm.getElementsByClassName(className), nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null, returnElements = [], current; for(var i=0, il=elements.length; i<il; i+=1){ current = elements[i]; if(!nodeName || nodeName.test(current.nodeName)) { returnElements.push(current); } } return returnElements; }; } else if (document.evaluate) { getElementsByClassName = function (className, tag, elm) { tag = tag || "*"; elm = elm || document; var classes = className.split(" "), classesToCheck = "", xhtmlNamespace = "http://www.w3.org/1999/xhtml", namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null, returnElements = [], elements, node; for(var j=0, jl=classes.length; j<jl; j+=1){ classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]"; } try { elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null); } catch (e) { elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null); } while ((node = elements.iterateNext())) { returnElements.push(node); } return returnElements; }; } else { getElementsByClassName = function (className, tag, elm) { tag = tag || "*"; elm = elm || document; var classes = className.split(" "), classesToCheck = [], elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag), current, returnElements = [], match; for(var k=0, kl=classes.length; k<kl; k+=1){ classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)")); } for(var l=0, ll=elements.length; l<ll; l+=1){ current = elements[l]; match = false; for(var m=0, ml=classesToCheck.length; m<ml; m+=1){ match = classesToCheck[m].test(current.className); if (!match) { break; } } if (match) { returnElements.push(current); } } return returnElements; }; } return getElementsByClassName(className, tag, elm); }; /******************************************************************************************************** * Helpers ********************************************************************************************************/ String.prototype.reverse=function(){return this.split("").reverse().join("");}; Number.prototype.withCommas=function(){var x=6,y=parseFloat(this).toFixed(2).toString().reverse();while(x<y.length){y=y.substring(0,x)+","+y.substring(x);x+=4;}return y.reverse();}; Number.prototype.toCurrency=function(){return(arguments[0]?arguments[0]:"$")+this.withCommas();}; /******************************************************************************************************** * error management ********************************************************************************************************/ function error( message ){ try{ console.log( message ); }catch(err){ // alert( message ); } } var simpleCart = new Cart(); if( typeof jQuery !== 'undefined' ) $(document).ready(function(){simpleCart.initialize();}); else if( typeof Prototype !== 'undefined') Event.observe( window, 'load', function(){simpleCart.initialize();}); else window.onload = simpleCart.initialize;
JavaScript
/**************************************************************************** Copyright (c) 2011 The Wojo Group thewojogroup.com simplecartjs.com http://github.com/thewojogroup/simplecart-js/tree/master The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ var Custom="Custom",GoogleCheckout="GoogleCheckout",PayPal="PayPal",Email="Email",BrazilianReal="BRL",BRL="BRL",AustralianDollar="AUD",AUD="AUD",CanadianDollar="CAD",CAD="CAD",CzechKoruna="CZK",CZK="CZK",DanishKrone="DKK",DKK="DKK",Euro="EUR",EUR="EUR",HongKongDollar="HKD",HKD="HKD",HungarianForint="HUF",HUF="HUF",IsraeliNewSheqel="ILS",ILS="ILS",JapaneseYen="JPY",JPY="JPY",MexicanPeso="MXN",MXN="MXN",NorwegianKrone="NOK",NOK="NOK",NewZealandDollar="NZD",NZD="NZD",PolishZloty="PLN",PLN="PLN",PoundSterling="GBP",GBP="GBP",SingaporeDollar="SGD",SGD="SGD",SwedishKrona="SEK",SEK="SEK",SwissFranc="CHF",CHF="CHF",ThaiBaht="THB",THB="THB",USDollar="USD",USD="USD"; function Cart(){ var me = this; /* member variables */ me.nextId = 1; me.Version = '2.2.2'; me.Shelf = null; me.items = {}; me.isLoaded = false; me.invoice = null; me.pageIsReady = false; me.quantity = 0; me.total = 0; me.taxRate = 0; me.taxCost = 0; me.shippingFlatRate = 0; me.shippingTotalRate = 0; me.shippingQuantityRate = 0; me.shippingRate = 0; me.shippingCost = 0; me.currency = USD; me.checkoutTo = PayPal; me.email = ""; me.merchantId = ""; me.successUrl = null; me.cancelUrl = null; me.cookieDuration = 30; // default duration in days me.storagePrefix = "sc_"; me.MAX_COOKIE_SIZE = 4000; me.cartHeaders = ['Name','Price','Quantity','Total']; me.events = {}; me.sandbox = false; me.paypalHTTPMethod = "GET"; /* cart headers: you can set these to which ever order you would like, and the cart will display the appropriate headers and item info. any field you have for the items in the cart can be used, and 'Total' will automatically be price*quantity. there are keywords that can be used: 1) "_input" - the field will be a text input with the value set to the given field. when the user changes the value, it will update the cart. this can be useful for quantity. (ie "Quantity_input") 2) "increment" - a link with "+" that will increase the item quantity by 1 3) "decrement" - a link with "-" that will decrease the item quantity by 1 4) "remove" - a link that will remove the item from the cart 5) "_image" or "Image" - the field will be an img tag with the src set to the value. You can simply use "Image" if you set a field in the items called "Image". If you have a field named something else, like "Thumb", you can add the "_image" to create the image tag (ie "Thumb_image"). 6) "_noHeader" - this will skip the header for that field (ie "increment_noHeader") */ /****************************************************** function for setting options ******************************************************/ me.options = function( values ){ me.each(values, function( value , x , name ){ me[name]=value; }); }; /****************************************************** add/remove items to cart ******************************************************/ me.add = function ( values ) { var me=this; /* load cart values if not already loaded */ if( !me.pageIsReady ) { me.initializeView(); me.update(); } if( !me.isLoaded ) { me.load(); me.update(); } var newItem = new CartItem(); /* check to ensure arguments have been passed in */ if( !arguments || arguments.length === 0 ){ error( 'No values passed for item.'); return null; } var argumentArray = arguments; if( values && typeof( values ) !== 'string' && typeof( values ) !== 'number' ){ argumentArray = values; } newItem.parseValuesFromArray( argumentArray ); newItem.checkQuantityAndPrice(); if( me.trigger('beforeAdd', [newItem] ) === false ){ return false; } var isNew = true; /* if the item already exists, update the quantity */ if( me.hasItem(newItem) ) { var foundItem=me.hasItem(newItem); foundItem.quantity= parseInt(foundItem.quantity,10) + parseInt(newItem.quantity,10); newItem = foundItem; isNew = false; } else { me.items[newItem.id] = newItem; } me.update(); me.trigger('afterAdd', [newItem,isNew] ); return newItem; }; me.remove = function( id ){ var tempArray = {}; me.each(function(item){ if( item.id !== id ){ tempArray[item.id] = item; } }); this.items = tempArray; }; me.empty = function () { me.items = {}; me.update(); }; /****************************************************** item accessor functions ******************************************************/ me.find = function (criteria) { if( !criteria ){ return null; } var results = []; me.each(function(item,x,next){ fits = true; me.each( criteria , function(value,j,name){ if( !item[name] || item[name] != value ){ fits = false; } }); if( fits ){ results.push( item ); } }); return (results.length === 0 ) ? null : results; }; me.each = function( array , callback ){ var next, x=0, result; if( typeof array === 'function' ){ var cb = array items = me.items; } else if( typeof callback === 'function' ){ var cb = callback, items = array; } else { return; } for( next in items ){ if( typeof items[next] !== "function" ){ result = cb.call( me , items[next] , x , next ); if( result === false ){ return; } x++; } } }; me.chunk = function(str, n) { if (typeof n==='undefined'){ n=2; } var result = str.match(RegExp('.{1,'+n+'}','g')); return result || []; }; /****************************************************** checkout management ******************************************************/ me.checkout = function() { if( me.quantity === 0 ){ error("Cart is empty"); return; } switch( me.checkoutTo ){ case PayPal: me.paypalCheckout(); break; case GoogleCheckout: me.googleCheckout(); break; case Email: me.emailCheckout(); break; default: me.customCheckout(); break; } }; me.paypalCheckout = function() { var form = document.createElement("form"), counter=1, current, item, descriptionString; form.style.display = "none"; form.method = me.paypalHTTPMethod =="GET" || me.paypalHTTPMethod == "POST" ? me.paypalHTTPMethod : "GET"; form.action = me.sandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr" : "https://www.paypal.com/cgi-bin/webscr"; form.acceptCharset = "utf-8"; // setup hidden fields form.appendChild(me.createHiddenElement("cmd", "_cart")); form.appendChild(me.createHiddenElement("rm", me.paypalHTTPMethod == "POST" ? "2" : "0" )); form.appendChild(me.createHiddenElement("upload", "1")); form.appendChild(me.createHiddenElement("business", me.email )); form.appendChild(me.createHiddenElement("currency_code", me.currency)); form.appendChild(me.createHiddenElement("charset", "utf-8")); if (me.invoice) { form.appendChild(me.createHiddenElement("invoice", me.invoice)); } if( me.taxRate ){ form.appendChild(me.createHiddenElement("tax_cart", parseFloat(me.taxCost).toFixed(2))); } if( me.shipping() !== 0){ form.appendChild(me.createHiddenElement("handling_cart", me.shippingCost )); } if( me.successUrl ){ form.appendChild(me.createHiddenElement("return", me.successUrl )); } if( me.cancelUrl ){ form.appendChild(me.createHiddenElement("cancel_return", me.cancelUrl )); } me.each(function(item,iter){ counter = iter+1; form.appendChild( me.createHiddenElement( "item_name_" + counter, item.name ) ); form.appendChild( me.createHiddenElement( "quantity_" + counter, item.quantity ) ); form.appendChild( me.createHiddenElement( "amount_" + counter, item.price ) ); form.appendChild( me.createHiddenElement( "item_number_" + counter, counter ) ); var option_count = 0; me.each( item , function( value, x , field ){ if( field !== "id" && field !== "price" && field !== "quantity" && field !== "name" && field !== "shipping" && option_count < 10) { form.appendChild( me.createHiddenElement( "on" + option_count + "_" + counter, field ) ); form.appendChild( me.createHiddenElement( "os" + option_count + "_" + counter, value ) ); option_count++; } }); form.appendChild( me.createHiddenElement( "option_index_" + counter, option_count) ); }); document.body.appendChild( form ); form.submit(); document.body.removeChild( form ); }; me.googleCheckout = function() { var me = this; if( me.currency !== USD && me.currency !== GBP ){ error( "Google Checkout only allows the USD and GBP for currency."); return; } else if( me.merchantId === "" || me.merchantId === null || !me.merchantId ){ error( "No merchant Id for google checkout supplied."); return; } var form = document.createElement("form"), counter=1, current, item, descriptionString; form.style.display = "none"; form.method = "POST"; form.action = "https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/" + me.merchantId; form.acceptCharset = "utf-8"; me.each(function(item,iter){ counter = iter+1; form.appendChild( me.createHiddenElement( "item_name_" + counter, item.name ) ); form.appendChild( me.createHiddenElement( "item_quantity_" + counter, item.quantity ) ); form.appendChild( me.createHiddenElement( "item_price_" + counter, item.price ) ); form.appendChild( me.createHiddenElement( "item_currency_" + counter, me.currency ) ); form.appendChild( me.createHiddenElement( "item_tax_rate_" + counter, me.taxRate ) ); form.appendChild( me.createHiddenElement( "_charset_" , "" ) ); descriptionString = ""; me.each( item , function( value , x , field ){ if( field !== "id" && field !== "quantity" && field !== "price" ) { descriptionString = descriptionString + ", " + field + ": " + value; } }); descriptionString = descriptionString.substring( 1 ); form.appendChild( me.createHiddenElement( "item_description_" + counter, descriptionString) ); }); // hack for adding shipping if( me.shipping() !== 0){ form.appendChild(me.createHiddenElement("ship_method_name_1", "Shipping")); form.appendChild(me.createHiddenElement("ship_method_price_1", parseFloat(me.shippingCost).toFixed(2))); form.appendChild(me.createHiddenElement("ship_method_currency_1", me.currency)); } document.body.appendChild( form ); form.submit(); document.body.removeChild( form ); }; me.emailCheckout = function() { var remite = prompt("Introduzca correo de contacto: "); if (remite != '' && remite != null) { itemsString = ""; esubtotal = 0; egastos = 0; etotal = 0; for( var current in this.items ){ var item = this.items[current]; esubtotal = item.quantity * item.price; itemsString += item.name; if (item.size) itemsString += "Talla " + item.size + "\n"; if (item.color) itemsString += "Color " + item.color + "\n"; itemsString += item.quantity + " x " + item.price + " = " + String(esubtotal) + me.currency + "\n"; etotal += esubtotal; }; if (me.shippingCost){ itemsString += "\nSubtotal = " + etotal + "\n"; itemsString += "Gastos de envio = " + me.shippingCost + "\n"; etotal += me.shippingCost; }; itemsString +="\nTotal: " + String(etotal) + me.currency + "\n" + "Remitente: " + remite; var form = document.createElement("form"); form.style.display = "none"; form.method = "POST"; form.action = "http://www.luisruiz.byethost11.com/email.php"; form.acceptCharset = "utf-8"; form.appendChild(this.createHiddenElement("jcitems", itemsString)); form.appendChild(this.createHiddenElement("jcremite", remite)); document.body.appendChild(form); me.empty(); form.submit(); document.body.removeChild(form); if (p == null || p==''); } return; }; me.customCheckout = function() { return; }; /****************************************************** data storage and retrival ******************************************************/ /* load cart from cookie */ me.load = function () { var me = this, id; /* initialize variables and items array */ me.items = {}; me.total = 0.00; me.quantity = 0; /* retrieve item data from cookie */ if( readCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks") ){ var chunkCount = 1*readCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks"), dataArray = [], dataString = "", data = "", info, newItem, y=0; if(chunkCount>0) { for( y=0;y<chunkCount;y++){ dataArray.push( readCookie( simpleCart.storagePrefix + 'simpleCart_' + (1 + y ) ) ); } dataString = unescape( dataArray.join("") ); data = dataString.split("++"); } for(var x=0, xlen=data.length;x<xlen;x++){ info = data[x].split('||'); newItem = new CartItem(); if( newItem.parseValuesFromArray( info ) ){ newItem.checkQuantityAndPrice(); /* store the new item in the cart */ me.items[newItem.id] = newItem; } } } me.isLoaded = true; }; /* save cart to cookie */ me.save = function () { var dataString = "", dataArray = [], chunkCount = 0; chunkCount = 1*readCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks"); for( var j=0;j<chunkCount;j++){ eraseCookie(simpleCart.storagePrefix + 'simpleCart_'+ j); } eraseCookie(simpleCart.storagePrefix + 'simpleCart_' + "chunks"); me.each(function(item){ dataString = dataString + "++" + item.print(); }); dataArray = simpleCart.chunk( dataString.substring(2) , simpleCart.MAX_COOKIE_SIZE ); for( var x=0,xlen = dataArray.length;x<xlen;x++){ createCookie(simpleCart.storagePrefix + 'simpleCart_' + (1 + x ), dataArray[x], me.cookieDuration ); } createCookie( simpleCart.storagePrefix + 'simpleCart_' + "chunks", "" + dataArray.length , me.cookieDuration ); }; /****************************************************** view management ******************************************************/ me.initializeView = function() { var me = this; me.totalOutlets = getElementsByClassName('simpleCart_total'); me.quantityOutlets = getElementsByClassName('simpleCart_quantity'); me.cartDivs = getElementsByClassName('simpleCart_items'); me.taxCostOutlets = getElementsByClassName('simpleCart_taxCost'); me.taxRateOutlets = getElementsByClassName('simpleCart_taxRate'); me.shippingCostOutlets = getElementsByClassName('simpleCart_shippingCost'); me.finalTotalOutlets = getElementsByClassName('simpleCart_finalTotal'); me.addEventToArray( getElementsByClassName('simpleCart_checkout') , simpleCart.checkout , "click"); me.addEventToArray( getElementsByClassName('simpleCart_empty') , simpleCart.empty , "click" ); me.Shelf = new Shelf(); me.Shelf.readPage(); me.pageIsReady = true; }; me.updateView = function() { me.updateViewTotals(); if( me.cartDivs && me.cartDivs.length > 0 ){ me.updateCartView(); } }; me.updateViewTotals = function() { var outlets = [ ["quantity" , "none" ] , ["total" , "currency" ] , ["shippingCost" , "currency" ] , ["taxCost" , "currency" ] , ["taxRate" , "percentage" ] , ["finalTotal" , "currency" ] ]; for( var x=0,xlen=outlets.length; x<xlen;x++){ var arrayName = outlets[x][0] + "Outlets", outputString, element; for( var y = 0,ylen = me[ arrayName ].length; y<ylen; y++ ){ switch( outlets[x][1] ){ case "none": outputString = "" + me[outlets[x][0]]; break; case "currency": outputString = me.valueToCurrencyString( me[outlets[x][0]] ); break; case "percentage": outputString = me.valueToPercentageString( me[outlets[x][0]] ); break; default: outputString = "" + me[outlets[x][0]]; break; } me[arrayName][y].innerHTML = "" + outputString; } } }; me.updateCartView = function() { var newRows = [], y,newRow,current,header,newCell,info,outputValue,option,headerInfo; /* create headers row */ newRow = document.createElement('div'); for(var y=0,ylen = me.cartHeaders.length; y<ylen; y++ ){ newCell = document.createElement('div'); headerInfo = me.cartHeaders[y].split("_"); newCell.innerHTML = me.print( headerInfo[0] ); newCell.className = "item" + headerInfo[0]; for(var z=1,zlen=headerInfo.length;z<zlen;z++){ if( headerInfo[z].toLowerCase() == "noheader" ){ newCell.style.display = "none"; } } newRow.appendChild( newCell ); } newRow.className = "cartHeaders"; newRows[0] = newRow; /* create a row for each item in the cart */ me.each(function(item, x){ newRow = document.createElement('div'); for(var y=0,ylen = me.cartHeaders.length; y<ylen; y++ ){ newCell = document.createElement('div'); info = me.cartHeaders[y].split("_"); outputValue = me.createCartRow( info , item , outputValue ); newCell.innerHTML = outputValue; newCell.className = "item" + info[0]; newRow.appendChild( newCell ); } newRow.className = "itemContainer"; newRows[x+1] = newRow; }); for( var x=0,xlen=me.cartDivs.length; x<xlen; x++){ /* delete current rows in div */ var div = me.cartDivs[x]; if( div.childNodes && div.appendChild ){ while( div.childNodes[0] ){ div.removeChild( div.childNodes[0] ); } for(var j=0, jLen = newRows.length; j<jLen; j++){ div.appendChild( newRows[j] ); } } } }; me.createCartRow = function( info , item , outputValue ){ switch( info[0].toLowerCase() ){ case "total": outputValue = me.valueToCurrencyString(parseFloat(item.price)*parseInt(item.quantity,10) ); break; case "increment": outputValue = me.valueToLink( "+" , "javascript:;" , "onclick=\"simpleCart.items[\'" + item.id + "\'].increment();\"" ); break; case "decrement": outputValue = me.valueToLink( "-" , "javascript:;" , "onclick=\"simpleCart.items[\'" + item.id + "\'].decrement();\"" ); break; case "remove": outputValue = me.valueToLink( "Remove" , "javascript:;" , "onclick=\"simpleCart.items[\'" + item.id + "\'].remove();\"" ); break; case "price": outputValue = me.valueToCurrencyString( item[ info[0].toLowerCase() ] ? item[info[0].toLowerCase()] : " " ); break; default: outputValue = item[ info[0].toLowerCase() ] ? typeof item[info[0].toLowerCase()] === 'function' ? item[info[0].toLowerCase()].call(item) : item[info[0].toLowerCase()] : " "; break; } for( var y=1,ylen=info.length;y<ylen;y++){ option = info[y].toLowerCase(); switch( option ){ case "image": case "img": outputValue = me.valueToImageString( outputValue ); break; case "input": outputValue = me.valueToTextInput( outputValue , "onchange=\"simpleCart.items[\'" + item.id + "\'].set(\'" + info[0].toLowerCase() + "\' , this.value);\"" ); break; case "div": case "span": case "h1": case "h2": case "h3": case "h4": case "p": outputValue = me.valueToElement( option , outputValue , "" ); break; case "noheader": break; default: error( "unkown header option: " + option ); break; } } return outputValue; }; me.addEventToArray = function ( array , functionCall , theEvent ) { var outlet, element; for(var x=0,xlen=array.length; x<xlen; x++ ){ element = array[x]; if( element.addEventListener ) { element.addEventListener(theEvent, functionCall , false ); } else if( element.attachEvent ) { element.attachEvent( "on" + theEvent, functionCall ); } } }; me.createHiddenElement = function ( name , value ){ var element = document.createElement("input"); element.type = "hidden"; element.name = name; element.value = value; return element; }; /****************************************************** Event Management ******************************************************/ // bind a callback to a simpleCart event me.bind = function( name , callback ){ if( typeof callback !== 'function' ){ return me; } if (me.events[name] === true ){ callback.apply( me ); } else if( typeof me.events[name] !== 'undefined' ){ me.events[name].push( callback ); } else { me.events[name] = [ callback ]; } return me; }; // trigger event me.trigger = function( name , options ){ var returnval = true; if( typeof me.events[name] !== 'undefined' && typeof me.events[name][0] === 'function'){ for( var x=0,xlen=me.events[name].length; x<xlen; x++ ){ returnval = me.events[name][x].apply( me , (options ? options : [] ) ); } } if( returnval === false ){ return false; } else { return true; } }; // shortcut for ready function me.ready = function( callback ){ if( !callback ){ me.trigger( 'ready' ); me.events['ready'] = true; } else { me.bind( 'ready' , callback ); } return me; }; /****************************************************** Currency management ******************************************************/ me.currencySymbol = function() { switch(me.currency){ case CHF: return "CHF&nbsp;"; case CZK: return "CZK&nbsp;"; case DKK: return "DKK&nbsp;"; case HUF: return "HUF&nbsp;"; case NOK: return "NOK&nbsp;"; case PLN: return "PLN&nbsp;"; case SEK: return "SEK&nbsp;"; case JPY: return "&yen;"; case EUR: return "&euro;"; case GBP: return "&pound;"; case CHF: return "CHF&nbsp;"; case THB: return "&#3647;"; case USD: case CAD: case AUD: case NZD: case HKD: case SGD: return "&#36;"; default: return ""; } }; me.currencyStringForPaypalCheckout = function( value ){ if( me.currencySymbol() == "&#36;" ){ return "$" + parseFloat( value ).toFixed(2); } else { return "" + parseFloat(value ).toFixed(2); } }; /****************************************************** Formatting ******************************************************/ me.valueToCurrencyString = function( value ) { var val = parseFloat( value ); if( isNaN(val)) val = 0; return val.toCurrency( me.currencySymbol() ); }; me.valueToPercentageString = function( value ){ return parseFloat( 100*value ) + "%"; }; me.valueToImageString = function( value ){ if( value.match(/<\s*img.*src\=/) ){ return value; } else { return "<img src=\"" + value + "\" />"; } }; me.valueToTextInput = function( value , html ){ return "<input type=\"text\" value=\"" + value + "\" " + html + " />"; }; me.valueToLink = function( value, link, html){ return "<a href=\"" + link + "\" " + html + " >" + value + "</a>"; }; me.valueToElement = function( type , value , html ){ return "<" + type + " " + html + " > " + value + "</" + type + ">"; }; /****************************************************** Duplicate management ******************************************************/ me.hasItem = function ( item ) { var current, matches, field, match=false; me.each(function(testItem){ matches = true; me.each( item , function( value , x , field ){ if( field !== "quantity" && field !== "id" && item[field] !== testItem[field] ){ matches = false; } }); if( matches ){ match = testItem; } }); return match; }; /****************************************************** Language managment ******************************************************/ me.ln = { "en_us": { quantity: "Quantity" , price: "Price" , total: "Total" , decrement: "Decrement" , increment: "Increment" , remove: "Remove" , tax: "Tax" , shipping: "Shipping" , image: "Image" } }; me.language = "en_us"; me.print = function( input ) { var me = this; return me.ln[me.language] && me.ln[me.language][input.toLowerCase()] ? me.ln[me.language][input.toLowerCase()] : input; }; /****************************************************** Cart Update managment ******************************************************/ me.update = function() { if( !simpleCart.isLoaded ){ simpleCart.load(); } if( !simpleCart.pageIsReady ){ simpleCart.initializeView(); } me.updateTotals(); me.updateView(); me.save(); }; me.updateTotals = function() { me.total = 0 ; me.quantity = 0; me.each(function(item){ if( item.quantity < 1 ){ item.remove(); } else if( item.quantity !== null && item.quantity !== "undefined" ){ me.quantity = parseInt(me.quantity,10) + parseInt(item.quantity,10); } if( item.price ){ me.total = parseFloat(me.total) + parseInt(item.quantity,10)*parseFloat(item.price); } }); me.shippingCost = me.shipping(); me.taxCost = parseFloat(me.total)*me.taxRate; me.finalTotal = me.shippingCost + me.taxCost + me.total; }; me.shipping = function(){ if( parseInt(me.quantity,10)===0 ) return 0; var shipping = parseFloat(me.shippingFlatRate) + parseFloat(me.shippingTotalRate)*parseFloat(me.total) + parseFloat(me.shippingQuantityRate)*parseInt(me.quantity,10), next; me.each(function(nextItem){ if( nextItem.shipping ){ if( typeof nextItem.shipping == 'function' ){ shipping += parseFloat(nextItem.shipping()); } else { shipping += parseFloat(nextItem.shipping); } } }); return shipping; } me.initialize = function() { me.initializeView(); me.load(); me.update(); me.ready(); }; } /******************************************************************************************************** * Cart Item Object ********************************************************************************************************/ function CartItem() { while( simpleCart.items["c" + simpleCart.nextId] ) simpleCart.nextId++; this.id = "c" + simpleCart.nextId; } CartItem.prototype = { set : function ( field , value ){ field = field.toLowerCase(); if( typeof( this[field] ) !== "function" && field !== "id" ){ value = "" + value; if( field == "quantity"){ value = value.replace( /[^(\d|\.)]*/gi , "" ); value = value.replace(/,*/gi, ""); value = parseInt(value,10); } else if( field == "price" ){ value = value.replace( /[^(\d|\.)]*/gi, ""); value = value.replace(/,*/gi , ""); value = parseFloat( value ); } if( typeof(value) == "number" && isNaN( value ) ){ error( "Improperly formatted input."); } else { if( typeof( value ) === "string" ){ if( value.match(/\~|\=/) ){ error("Special character ~ or = not allowed: " + value); } value = value.replace(/\~|\=/g, ""); } this[field] = value; this.checkQuantityAndPrice(); } } else { error( "Cannot change " + field + ", this is a reserved field."); } simpleCart.update(); }, increment : function(){ this.quantity = parseInt(this.quantity,10) + 1; simpleCart.update(); }, decrement : function(){ if( parseInt(this.quantity,10) < 2 ){ this.remove(); } else { this.quantity = parseInt(this.quantity,10) - 1; simpleCart.update(); } }, print : function () { var returnString = '', field; simpleCart.each(this ,function(item,x,name){ returnString+= escape(name) + "=" + escape(item) + "||"; }); return returnString.substring(0,returnString.length-2); }, checkQuantityAndPrice : function() { if( !this.quantity || this.quantity == null || this.quantity == 'undefined'){ this.quantity = 1; error('No quantity for item.'); } else { this.quantity = ("" + this.quantity).replace(/,*/gi, "" ); this.quantity = parseInt( ("" + this.quantity).replace( /[^(\d|\.)]*/gi, "") , 10); if( isNaN(this.quantity) ){ error('Quantity is not a number.'); this.quantity = 1; } } if( !this.price || this.price == null || this.price == 'undefined'){ this.price=0.00; error('No price for item or price not properly formatted.'); } else { this.price = ("" + this.price).replace(/,*/gi, "" ); this.price = parseFloat( ("" + this.price).replace( /[^(\d|\.)]*/gi, "") ); if( isNaN(this.price) ){ error('Price is not a number.'); this.price = 0.00; } } }, parseValuesFromArray : function( array ) { if( array && array.length && array.length > 0) { for(var x=0, xlen=array.length; x<xlen;x++ ){ /* ensure the pair does not have key delimeters */ array[x] = array[x].replace(/\|\|/g, "| |"); array[x] = array[x].replace(/\+\+/g, "+ +"); if( array[x].match(/\~/) ){ error("Special character ~ not allowed: " + array[x]); } array[x] = array[x].replace(/\~/g, ""); /* split the pair and save the unescaped values to the item */ var value = array[x].split('='); if( value.length>1 ){ if( value.length>2 ){ for(var j=2, jlen=value.length;j<jlen;j++){ value[1] = value[1] + "=" + value[j]; } } this[ unescape(value[0]).toLowerCase() ] = unescape(value[1]); } } return true; } else { return false; } }, remove : function() { simpleCart.remove(this.id); simpleCart.update(); } }; /******************************************************************************************************** * Shelf Object for managing items on shelf that can be added to cart ********************************************************************************************************/ function Shelf(){ this.items = {}; } Shelf.prototype = { readPage : function () { this.items = {}; var newItems = getElementsByClassName( "simpleCart_shelfItem" ), newItem; me = this; for( var x = 0, xlen = newItems.length; x<xlen; x++){ newItem = new ShelfItem(); me.checkChildren( newItems[x] , newItem ); me.items[newItem.id] = newItem; } }, checkChildren : function ( item , newItem) { if( !item.childNodes ) return; for(var x=0;item.childNodes[x];x++){ var node = item.childNodes[x]; if( node.className && node.className.match(/item_[^ ]+/) ){ var data = /item_[^ ]+/.exec(node.className)[0].split("_"); if( data[1] == "add" || data[1] == "Add" ){ var tempArray = []; tempArray.push( node ); var addFunction = simpleCart.Shelf.addToCart(newItem.id); simpleCart.addEventToArray( tempArray , addFunction , "click"); node.id = newItem.id; } else { newItem[data[1]] = node; } } if( node.childNodes[0] ){ this.checkChildren( node , newItem ); } } }, empty : function () { this.items = {}; }, addToCart : function ( id ) { return function(){ if( simpleCart.Shelf.items[id]){ simpleCart.Shelf.items[id].addToCart(); } else { error( "Shelf item with id of " + id + " does not exist."); } }; } }; /******************************************************************************************************** * Shelf Item Object ********************************************************************************************************/ function ShelfItem(){ this.id = "s" + simpleCart.nextId++; } ShelfItem.prototype = { remove : function () { simpleCart.Shelf.items[this.id] = null; }, addToCart : function () { var outStrings = [], valueString, field; for( field in this ){ if( typeof( this[field] ) !== "function" && field !== "id" ){ valueString = ""; switch(field){ case "price": if( this[field].value ){ valueString = this[field].value; } else if( this[field].innerHTML ) { valueString = this[field].innerHTML; } /* remove all characters from price except digits and a period */ valueString = valueString.replace( /[^(\d|\.)]*/gi , "" ); valueString = valueString.replace( /,*/ , "" ); break; case "image": valueString = this[field].src; break; default: if( this[field].value ){ valueString = this[field].value; } else if( this[field].innerHTML ) { valueString = this[field].innerHTML; } else if( this[field].src ){ valueString = this[field].src; } else { valueString = this[field]; } break; } outStrings.push( field + "=" + valueString ); } } simpleCart.add( outStrings ); } }; /******************************************************************************************************** * Thanks to Peter-Paul Koch for these cookie functions (http://www.quirksmode.org/js/cookies.html) ********************************************************************************************************/ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; value = value.replace(/\=/g, '~'); document.cookie = name + "=" + escape(value) + expires + "; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) === 0){ var value = unescape(c.substring(nameEQ.length, c.length)); return value.replace(/\~/g, '='); } } return null; } function eraseCookie(name) { createCookie(name,"",-1); } //************************************************************************************************* /* Developed by Robert Nyman, http://www.robertnyman.com Code/licensing: http://code.google.com/p/getelementsbyclassname/ */ var getElementsByClassName = function (className, tag, elm){ if (document.getElementsByClassName) { getElementsByClassName = function (className, tag, elm) { elm = elm || document; var elements = elm.getElementsByClassName(className), nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null, returnElements = [], current; for(var i=0, il=elements.length; i<il; i+=1){ current = elements[i]; if(!nodeName || nodeName.test(current.nodeName)) { returnElements.push(current); } } return returnElements; }; } else if (document.evaluate) { getElementsByClassName = function (className, tag, elm) { tag = tag || "*"; elm = elm || document; var classes = className.split(" "), classesToCheck = "", xhtmlNamespace = "http://www.w3.org/1999/xhtml", namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null, returnElements = [], elements, node; for(var j=0, jl=classes.length; j<jl; j+=1){ classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]"; } try { elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null); } catch (e) { elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null); } while ((node = elements.iterateNext())) { returnElements.push(node); } return returnElements; }; } else { getElementsByClassName = function (className, tag, elm) { tag = tag || "*"; elm = elm || document; var classes = className.split(" "), classesToCheck = [], elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag), current, returnElements = [], match; for(var k=0, kl=classes.length; k<kl; k+=1){ classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)")); } for(var l=0, ll=elements.length; l<ll; l+=1){ current = elements[l]; match = false; for(var m=0, ml=classesToCheck.length; m<ml; m+=1){ match = classesToCheck[m].test(current.className); if (!match) { break; } } if (match) { returnElements.push(current); } } return returnElements; }; } return getElementsByClassName(className, tag, elm); }; /******************************************************************************************************** * Helpers ********************************************************************************************************/ String.prototype.reverse=function(){return this.split("").reverse().join("");}; Number.prototype.withCommas=function(){var x=6,y=parseFloat(this).toFixed(2).toString().reverse();while(x<y.length){y=y.substring(0,x)+","+y.substring(x);x+=4;}return y.reverse();}; Number.prototype.toCurrency=function(){return(arguments[0]?arguments[0]:"$")+this.withCommas();}; /******************************************************************************************************** * error management ********************************************************************************************************/ function error( message ){ try{ console.log( message ); }catch(err){ // alert( message ); } } var simpleCart = new Cart(); if( typeof jQuery !== 'undefined' ) $(document).ready(function(){simpleCart.initialize();}); else if( typeof Prototype !== 'undefined') Event.observe( window, 'load', function(){simpleCart.initialize();}); else window.onload = simpleCart.initialize;
JavaScript
/*jslint browser: true */ /*global jQuery: true */ /** * jQuery Cookie plugin * * Copyright (c) 2010 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ // TODO JsDoc /** * Create a cookie with the given key and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String key The key of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given key. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String key The key of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function (key, value, options) { // key and at least value given, set cookie... if (arguments.length > 1 && String(value) !== "[object Object]") { options = jQuery.extend({}, options); if (value === null || value === undefined) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = String(value); return (document.cookie = [ encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // key and possibly options given, get cookie... options = value || {}; var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent; return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null; };
JavaScript
function WebSocketTest() { if ("WebSocket" in window) { alert("WebSocket supported here! :)\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } else { // Browser doesn't support WebSocket alert("WebSocket NOT supported here! :(\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } }
JavaScript
function WebSocketTest2() { if ("WebSocket" in window) { var ws = new WebSocket("%%WEBSOCKET_URL%%"); ws.onopen = function() { // Web Socket is connected alert("websocket is open"); // You can send data now ws.send("Hey man, you got the time?"); }; ws.onmessage = function(evt) { alert("received: " + evt.data); }; ws.onclose = function() { alert("websocket is closed"); }; } else { alert("Browser doesn't support WebSocket!"); } }
JavaScript
function WebSocketTest() { if ("WebSocket" in window) { alert("WebSocket supported here! :)\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } else { // Browser doesn't support WebSocket alert("WebSocket NOT supported here! :(\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } }
JavaScript
var ws; var t; function init() { document.getElementById('updateme').innerHTML = "connecting to websocket"; OpenWebSocket(); } function OpenWebSocket() { if ("WebSocket" in window) { ws = new WebSocket("%%WEBSOCKET_URL%%"); ws.onopen = function() { // Web Socket is connected document.getElementById('updateme').innerHTML = "websocket is open"; t=setTimeout("SendMessage()",1000); }; ws.onmessage = function(evt) { document.getElementById('updateme').innerHTML = evt.data; }; ws.onclose = function() { document.getElementById('updateme').innerHTML = "websocket is closed"; OpenWebSocket(); }; ws.onerror = function(evt) { alert("onerror: " + evt); }; } else { alert("Browser doesn't support WebSocket!"); } } function SendMessage() { if ("WebSocket" in window) { ws.send("time"); t=setTimeout("SendMessage()",1000); } else { alert("Browser doesn't support WebSocket!"); } }
JavaScript
// Place your application-specific JavaScript functions and classes here // This file is automatically included by javascript_include_tag :defaults
JavaScript
// Import the needed java packages and classes importPackage(java.util); importClass(javax.swing.JOptionPane) function putDate() { TARGET.replaceSelection("This is a dummy proc that inserts the Current Date:\n" + new Date()); TARGET.replaceSelection("\nTab Size of doc = " + AU.getTabSize(TARGET)); }
JavaScript
/** * @license * * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview SmartMarker. * * @author Chris Broadfoot (cbro@google.com) */ /** * A google.maps.Marker that has some smarts about the zoom levels it should be * shown. * * Options are the same as google.maps.Marker, with the addition of minZoom and * maxZoom. These zoom levels are inclusive. That is, a SmartMarker with * a minZoom and maxZoom of 13 will only be shown at zoom level 13. * @constructor * @extends google.maps.Marker * @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom. */ function SmartMarker(opts) { var marker = new google.maps.Marker; // default min/max Zoom - shows the marker all the time. marker.setValues({ 'minZoom': 0, 'maxZoom': Infinity }); // the current listener (if any), triggered on map zoom_changed var mapZoomListener; google.maps.event.addListener(marker, 'map_changed', function() { if (mapZoomListener) { google.maps.event.removeListener(mapZoomListener); } var map = marker.getMap(); if (map) { var listener = SmartMarker.newZoomListener_(marker); mapZoomListener = google.maps.event.addListener(map, 'zoom_changed', listener); // Call the listener straight away. The map may already be initialized, // so it will take user input for zoom_changed to be fired. listener(); } }); marker.setValues(opts); return marker; } window['SmartMarker'] = SmartMarker; /** * Creates a new listener to be triggered on 'zoom_changed' event. * Hides and shows the target Marker based on the map's zoom level. * @param {google.maps.Marker} marker The target marker. * @return Function */ SmartMarker.newZoomListener_ = function(marker) { var map = marker.getMap(); return function() { var zoom = map.getZoom(); var minZoom = Number(marker.get('minZoom')); var maxZoom = Number(marker.get('maxZoom')); marker.setVisible(zoom >= minZoom && zoom <= maxZoom); }; };
JavaScript
/** * Creates a new level control. * @constructor * @param {IoMap} iomap the IO map controller. * @param {Array.<string>} levels the levels to create switchers for. */ function LevelControl(iomap, levels) { var that = this; this.iomap_ = iomap; this.el_ = this.initDom_(levels); google.maps.event.addListener(iomap, 'level_changed', function() { that.changeLevel_(iomap.get('level')); }); } /** * Gets the DOM element for the control. * @return {Element} */ LevelControl.prototype.getElement = function() { return this.el_; }; /** * Creates the necessary DOM for the control. * @return {Element} */ LevelControl.prototype.initDom_ = function(levelDefinition) { var controlDiv = document.createElement('DIV'); controlDiv.setAttribute('id', 'levels-wrapper'); var levels = document.createElement('DIV'); levels.setAttribute('id', 'levels'); controlDiv.appendChild(levels); var levelSelect = this.levelSelect_ = document.createElement('DIV'); levelSelect.setAttribute('id', 'level-select'); levels.appendChild(levelSelect); this.levelDivs_ = []; var that = this; for (var i = 0, level; level = levelDefinition[i]; i++) { var div = document.createElement('DIV'); div.innerHTML = 'Level ' + level; div.setAttribute('id', 'level-' + level); div.className = 'level'; levels.appendChild(div); this.levelDivs_.push(div); google.maps.event.addDomListener(div, 'click', function(e) { var id = e.currentTarget.getAttribute('id'); var level = parseInt(id.replace('level-', ''), 10); that.iomap_.setHash('level' + level); }); } controlDiv.index = 1; return controlDiv; }; /** * Changes the highlighted level in the control. * @param {number} level the level number to select. */ LevelControl.prototype.changeLevel_ = function(level) { if (this.currentLevelDiv_) { this.currentLevelDiv_.className = this.currentLevelDiv_.className.replace(' level-selected', ''); } var h = 25; if (window['ioEmbed']) { h = (window.screen.availWidth > 600) ? 34 : 24; } this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px'; var div = this.levelDivs_[level - 1]; div.className += ' level-selected'; this.currentLevelDiv_ = div; };
JavaScript
/** * Creates a new Floor. * @constructor * @param {google.maps.Map=} opt_map */ function Floor(opt_map) { /** * @type Array.<google.maps.MVCObject> */ this.overlays_ = []; /** * @type boolean */ this.shown_ = true; if (opt_map) { this.setMap(opt_map); } } /** * @param {google.maps.Map} map */ Floor.prototype.setMap = function(map) { this.map_ = map; }; /** * @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel. * Requires a setMap method. */ Floor.prototype.addOverlay = function(overlay) { if (!overlay) return; this.overlays_.push(overlay); overlay.setMap(this.shown_ ? this.map_ : null); }; /** * Sets the map on all the overlays * @param {google.maps.Map} map The map to set. */ Floor.prototype.setMapAll_ = function(map) { this.shown_ = !!map; for (var i = 0, overlay; overlay = this.overlays_[i]; i++) { overlay.setMap(map); } }; /** * Hides the floor and all associated overlays. */ Floor.prototype.hide = function() { this.setMapAll_(null); }; /** * Shows the floor and all associated overlays. */ Floor.prototype.show = function() { this.setMapAll_(this.map_); };
JavaScript
// Copyright 2011 Google /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The Google IO Map * @constructor */ var IoMap = function() { var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025); /** @type {Node} */ this.mapDiv_ = document.getElementById(this.MAP_ID); var ioStyle = [ { 'featureType': 'road', stylers: [ { hue: '#00aaff' }, { gamma: 1.67 }, { saturation: -24 }, { lightness: -38 } ] },{ 'featureType': 'road', 'elementType': 'labels', stylers: [ { invert_lightness: true } ] }]; /** @type {boolean} */ this.ready_ = false; /** @type {google.maps.Map} */ this.map_ = new google.maps.Map(this.mapDiv_, { zoom: 18, center: moscone, navigationControl: true, mapTypeControl: false, scaleControl: true, mapTypeId: 'io', streetViewControl: false }); var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle)); this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style)); google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['onMapReady'](); } }); /** @type {Array.<Floor>} */ this.floors_ = []; for (var i = 0; i < this.LEVELS_.length; i++) { this.floors_.push(new Floor(this.map_)); } this.addLevelControl_(); this.addMapOverlay_(); this.loadMapContent_(); this.initLocationHashWatcher_(); if (!document.location.hash) { this.showLevel(1, true); } } IoMap.prototype = new google.maps.MVCObject; /** * The id of the Element to add the map to. * * @type {string} * @const */ IoMap.prototype.MAP_ID = 'map-canvas'; /** * The levels of the Moscone Center. * * @type {Array.<string>} * @private */ IoMap.prototype.LEVELS_ = ['1', '2', '3']; /** * Location where the tiles are hosted. * * @type {string} * @private */ IoMap.prototype.BASE_TILE_URL_ = 'http://www.gstatic.com/io2010maps/tiles/5/'; /** * The minimum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MIN_ZOOM_ = 16; /** * The maximum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MAX_ZOOM_ = 20; /** * The template for loading tiles. Replace {L} with the level, {Z} with the * zoom level, {X} and {Y} with respective tile coordinates. * * @type {string} * @private */ IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + 'L{L}_{Z}_{X}_{Y}.png'; /** * @type {string} * @private */ IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png'; /** * The extent of the overlay at certain zoom levels. * * @type {Object.<string, Array.<Array.<number>>>} * @private */ IoMap.prototype.RESOLUTION_BOUNDS_ = { 16: [[10484, 10485], [25328, 25329]], 17: [[20969, 20970], [50657, 50658]], 18: [[41939, 41940], [101315, 101317]], 19: [[83878, 83881], [202631, 202634]], 20: [[167757, 167763], [405263, 405269]] }; /** * The previous hash to compare against. * * @type {string?} * @private */ IoMap.prototype.prevHash_ = null; /** * Initialise the location hash watcher. * * @private */ IoMap.prototype.initLocationHashWatcher_ = function() { var that = this; if ('onhashchange' in window) { window.addEventListener('hashchange', function() { that.parseHash_(); }, true); } else { var that = this window.setInterval(function() { that.parseHash_(); }, 100); } this.parseHash_(); }; /** * Called from Android. * * @param {Number} x A percentage to pan left by. */ IoMap.prototype.panLeft = function(x) { var div = this.map_.getDiv(); var left = div.clientWidth * x; this.map_.panBy(left, 0); }; IoMap.prototype['panLeft'] = IoMap.prototype.panLeft; /** * Adds the level switcher to the top left of the map. * * @private */ IoMap.prototype.addLevelControl_ = function() { var control = new LevelControl(this, this.LEVELS_).getElement(); this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control); }; /** * Shows a floor based on the content of location.hash. * * @private */ IoMap.prototype.parseHash_ = function() { var hash = document.location.hash; if (hash == this.prevHash_) { return; } this.prevHash_ = hash; var level = 1; if (hash) { var match = hash.match(/level(\d)(?:\:([\w-]+))?/); if (match && match[1]) { level = parseInt(match[1], 10); } } this.showLevel(level, true); }; /** * Updates location.hash based on the currently shown floor. * * @param {string?} opt_hash */ IoMap.prototype.setHash = function(opt_hash) { var hash = document.location.hash.substring(1); if (hash == opt_hash) { return; } if (opt_hash) { document.location.hash = opt_hash; } else { document.location.hash = 'level' + this.get('level'); } }; IoMap.prototype['setHash'] = IoMap.prototype.setHash; /** * Called from spreadsheets. */ IoMap.prototype.loadSandboxCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.companyName = entry['gsx$companyname']['$t']; item.companyUrl = entry['gsx$companyurl']['$t']; var p = entry['gsx$companypod']['$t']; item.pod = p; p = p.toLowerCase().replace(/\s+/, ''); item.sessionRoom = p; contentItems.push(item); }; this.sandboxItems_ = contentItems; this.ready_ = true; this.addMapContent_(); }; /** * Called from spreadsheets. * * @param {Object} json The json feed from the spreadsheet. */ IoMap.prototype.loadSessionsCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.sessionDate = entry['gsx$sessiondate']['$t']; item.sessionAbstract = entry['gsx$sessionabstract']['$t']; item.sessionHashtag = entry['gsx$sessionhashtag']['$t']; item.sessionLevel = entry['gsx$sessionlevel']['$t']; item.sessionTitle = entry['gsx$sessiontitle']['$t']; item.sessionTrack = entry['gsx$sessiontrack']['$t']; item.sessionUrl = entry['gsx$sessionurl']['$t']; item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t']; item.sessionTime = entry['gsx$sessiontime']['$t']; item.sessionRoom = entry['gsx$sessionroom']['$t']; item.sessionTags = entry['gsx$sessiontags']['$t']; item.sessionSpeakers = entry['gsx$sessionspeakers']['$t']; if (item.sessionDate.indexOf('10') != -1) { item.sessionDay = 10; } else { item.sessionDay = 11; } var timeParts = item.sessionTime.split('-'); item.sessionStart = this.convertTo24Hour_(timeParts[0]); item.sessionEnd = this.convertTo24Hour_(timeParts[1]); contentItems.push(item); } this.sessionItems_ = contentItems; }; /** * Converts the time in the spread sheet to 24 hour time. * * @param {string} time The time like 10:42am. */ IoMap.prototype.convertTo24Hour_ = function(time) { var pm = time.indexOf('pm') != -1; time = time.replace(/[am|pm]/ig, ''); if (pm) { var bits = time.split(':'); var hr = parseInt(bits[0], 10); if (hr < 12) { time = (hr + 12) + ':' + bits[1]; } } return time; }; /** * Loads the map content from Google Spreadsheets. * * @private */ IoMap.prototype.loadMapContent_ = function() { // Initiate a JSONP request. var that = this; // Add a exposed call back function window['loadSessionsCallback'] = function(json) { that.loadSessionsCallback(json); } // Add a exposed call back function window['loadSandboxCallback'] = function(json) { that.loadSandboxCallback(json); } var key = 'tmaLiaNqIWYYtuuhmIyG0uQ'; var worksheetIDs = { sessions: 'od6', sandbox: 'od4' }; var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sessions + '/public/values' + '?alt=json-in-script&callback=loadSessionsCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sandbox + '/public/values' + '?alt=json-in-script&callback=loadSandboxCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); }; /** * Called from Android. * * @param {string} roomId The id of the room to load. */ IoMap.prototype.showLocationById = function(roomId) { var locations = this.LOCATIONS_; for (var level in locations) { var levelId = level.replace('LEVEL', ''); for (var loc in locations[level]) { var room = locations[level][loc]; if (loc == roomId) { var pos = new google.maps.LatLng(room.lat, room.lng); this.map_.panTo(pos); this.map_.setZoom(19); this.showLevel(levelId); if (room.marker_) { room.marker_.setAnimation(google.maps.Animation.BOUNCE); // Disable the animation after 5 seconds. window.setTimeout(function() { room.marker_.setAnimation(); }, 5000); } return; } } } }; IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById; /** * Called when the level is changed. Hides and shows floors. */ IoMap.prototype['level_changed'] = function() { var level = this.get('level'); if (this.infoWindow_) { this.infoWindow_.setMap(null); } for (var i = 1, floor; floor = this.floors_[i - 1]; i++) { if (i == level) { floor.show(); } else { floor.hide(); } } this.setHash('level' + level); }; /** * Shows a particular floor. * * @param {string} level The level to show. * @param {boolean=} opt_force if true, changes the floor even if it's already * the current floor. */ IoMap.prototype.showLevel = function(level, opt_force) { if (!opt_force && level == this.get('level')) { return; } this.set('level', level); }; IoMap.prototype['showLevel'] = IoMap.prototype.showLevel; /** * Create a marker with the content item's correct icon. * * @param {Object} item The content item for the marker. * @return {google.maps.Marker} The new marker. * @private */ IoMap.prototype.createContentMarker_ = function(item) { if (!item.icon) { item.icon = 'generic'; } var image; var shadow; switch(item.icon) { case 'generic': case 'info': case 'media': var image = new google.maps.MarkerImage( 'marker-' + item.icon + '.png', new google.maps.Size(30, 28), new google.maps.Point(0, 0), new google.maps.Point(13, 26)); var shadow = new google.maps.MarkerImage( 'marker-shadow.png', new google.maps.Size(30, 28), new google.maps.Point(0,0), new google.maps.Point(13, 26)); break; case 'toilets': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(35, 35), new google.maps.Point(0, 0), new google.maps.Point(17, 17)); break; case 'elevator': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(48, 26), new google.maps.Point(0, 0), new google.maps.Point(24, 13)); break; } var inactive = item.type == 'inactive'; var latLng = new google.maps.LatLng(item.lat, item.lng); var marker = new SmartMarker({ position: latLng, shadow: shadow, icon: image, title: item.title, minZoom: inactive ? 19 : 18, clickable: !inactive }); marker['type_'] = item.type; if (!inactive) { var that = this; google.maps.event.addListener(marker, 'click', function() { that.openContentInfo_(item); }); } return marker; }; /** * Create a label with the content item's title atribute, if it exists. * * @param {Object} item The content item for the marker. * @return {MapLabel?} The new label. * @private */ IoMap.prototype.createContentLabel_ = function(item) { if (!item.title || item.suppressLabel) { return null; } var latLng = new google.maps.LatLng(item.lat, item.lng); return new MapLabel({ 'text': item.title, 'position': latLng, 'minZoom': item.labelMinZoom || 18, 'align': item.labelAlign || 'center', 'fontColor': item.labelColor, 'fontSize': item.labelSize || 12 }); } /** * Open a info window a content item. * * @param {Object} item A content item with content and a marker. */ IoMap.prototype.openContentInfo_ = function(item) { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['openContentInfo'](item.room); return; } var sessionBase = 'http://www.google.com/events/io/2011/sessions.html'; var now = new Date(); var may11 = new Date('May 11, 2011'); var day = now < may11 ? 10 : 11; var type = item.type; var id = item.id; var title = item.title; var content = ['<div class="infowindow">']; var sessions = []; var empty = true; if (item.type == 'session') { if (day == 10) { content.push('<h3>' + title + ' - Tuesday May 10</h3>'); } else { content.push('<h3>' + title + ' - Wednesday May 11</h3>'); } for (var i = 0, session; session = this.sessionItems_[i]; i++) { if (session.sessionRoom == item.room && session.sessionDay == day) { sessions.push(session); empty = false; } } sessions.sort(this.sortSessions_); for (var i = 0, session; session = sessions[i]; i++) { content.push('<div class="session"><div class="session-time">' + session.sessionTime + '</div><div class="session-title"><a href="' + session.sessionUrl + '">' + session.sessionTitle + '</a></div></div>'); } } if (item.type == 'sandbox') { var sandboxName; for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) { if (sandbox.sessionRoom == item.room) { if (!sandboxName) { sandboxName = sandbox.pod; content.push('<h3>' + sandbox.pod + '</h3>'); content.push('<div class="sandbox">'); } content.push('<div class="sandbox-items"><a href="http://' + sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>'); empty = false; } } content.push('</div>'); empty = false; } if (empty) { return; } content.push('</div>'); var pos = new google.maps.LatLng(item.lat, item.lng); if (!this.infoWindow_) { this.infoWindow_ = new google.maps.InfoWindow(); } this.infoWindow_.setContent(content.join('')); this.infoWindow_.setPosition(pos); this.infoWindow_.open(this.map_); }; /** * A custom sort function to sort the sessions by start time. * * @param {string} a SessionA<enter description here>. * @param {string} b SessionB. * @return {boolean} True if sessionA is after sessionB. */ IoMap.prototype.sortSessions_ = function(a, b) { var aStart = parseInt(a.sessionStart.replace(':', ''), 10); var bStart = parseInt(b.sessionStart.replace(':', ''), 10); return aStart > bStart; }; /** * Adds all overlays (markers, labels) to the map. */ IoMap.prototype.addMapContent_ = function() { if (!this.ready_) { return; } for (var i = 0, level; level = this.LEVELS_[i]; i++) { var floor = this.floors_[i]; var locations = this.LOCATIONS_['LEVEL' + level]; for (var roomId in locations) { var room = locations[roomId]; if (room.room == undefined) { room.room = roomId; } if (room.type != 'label') { var marker = this.createContentMarker_(room); floor.addOverlay(marker); room.marker_ = marker; } var label = this.createContentLabel_(room); floor.addOverlay(label); } } }; /** * Gets the correct tile url for the coordinates and zoom. * * @param {google.maps.Point} coord The coordinate of the tile. * @param {Number} zoom The current zoom level. * @return {string} The url to the tile. */ IoMap.prototype.getTileUrl = function(coord, zoom) { // Ensure that the requested resolution exists for this tile layer. if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) { return ''; } // Ensure that the requested tile x,y exists. if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x || coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) || (this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y || coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) { return ''; } var template = this.TILE_TEMPLATE_URL_; if (16 <= zoom && zoom <= 17) { template = this.SIMPLE_TILE_TEMPLATE_URL_; } return template .replace('{L}', /** @type string */(this.get('level'))) .replace('{Z}', /** @type string */(zoom)) .replace('{X}', /** @type string */(coord.x)) .replace('{Y}', /** @type string */(coord.y)); }; /** * Add the floor overlay to the map. * * @private */ IoMap.prototype.addMapOverlay_ = function() { var that = this; var overlay = new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return that.getTileUrl(coord, zoom); }, tileSize: new google.maps.Size(256, 256) }); google.maps.event.addListener(this, 'level_changed', function() { var overlays = that.map_.overlayMapTypes; if (overlays.length) { overlays.removeAt(0); } overlays.push(overlay); }); }; /** * All the features of the map. * @type {Object.<string, Object.<string, Object.<string, *>>>} */ IoMap.prototype.LOCATIONS_ = { 'LEVEL1': { 'northentrance': { lat: 37.78381535905965, lng: -122.40362226963043, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'eastentrance': { lat: 37.78328434094279, lng: -122.40319311618805, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'lunchroom': { lat: 37.783112633669575, lng: -122.40407556295395, title: 'Lunch Room' }, 'restroom1a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator1a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'gearpickup': { lat: 37.78367863020862, lng: -122.4037617444992, title: 'Gear Pickup', type: 'label' }, 'checkin': { lat: 37.78334369645064, lng: -122.40335404872894, title: 'Check In', type: 'label' }, 'escalators1': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' } }, 'LEVEL2': { 'escalators2': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left', labelMinZoom: 19 }, 'press': { lat: 37.78316774962791, lng: -122.40360751748085, title: 'Press Room', type: 'label' }, 'restroom2a': { lat: 37.7835334217721, lng: -122.40386635065079, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom2b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator2a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, '1': { lat: 37.78346240732338, lng: -122.40415401756763, icon: 'media', title: 'Room 1', type: 'session', room: '1' }, '2': { lat: 37.78335005596647, lng: -122.40431495010853, icon: 'media', title: 'Room 2', type: 'session', room: '2' }, '3': { lat: 37.783215446097124, lng: -122.404490634799, icon: 'media', title: 'Room 3', type: 'session', room: '3' }, '4': { lat: 37.78332461789977, lng: -122.40381203591824, icon: 'media', title: 'Room 4', type: 'session', room: '4' }, '5': { lat: 37.783186828219335, lng: -122.4039850383997, icon: 'media', title: 'Room 5', type: 'session', room: '5' }, '6': { lat: 37.783013000871364, lng: -122.40420497953892, icon: 'media', title: 'Room 6', type: 'session', room: '6' }, '7': { lat: 37.7828783903882, lng: -122.40438133478165, icon: 'media', title: 'Room 7', type: 'session', room: '7' }, '8': { lat: 37.78305009820564, lng: -122.40378588438034, icon: 'media', title: 'Room 8', type: 'session', room: '8' }, '9': { lat: 37.78286673120095, lng: -122.40402393043041, icon: 'media', title: 'Room 9', type: 'session', room: '9' }, '10': { lat: 37.782719401312626, lng: -122.40420028567314, icon: 'media', title: 'Room 10', type: 'session', room: '10' }, 'appengine': { lat: 37.783362774996625, lng: -122.40335941314697, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'App Engine' }, 'chrome': { lat: 37.783730566003555, lng: -122.40378990769386, type: 'sandbox', icon: 'generic', title: 'Chrome' }, 'googleapps': { lat: 37.783303419504094, lng: -122.40320384502411, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Apps' }, 'geo': { lat: 37.783365954753805, lng: -122.40314483642578, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Geo' }, 'accessibility': { lat: 37.783414711013485, lng: -122.40342646837234, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Accessibility' }, 'developertools': { lat: 37.783457107734876, lng: -122.40347877144814, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Dev Tools' }, 'commerce': { lat: 37.78349102509448, lng: -122.40351900458336, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Commerce' }, 'youtube': { lat: 37.783537661438515, lng: -122.40358605980873, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'YouTube' }, 'officehoursfloor2a': { lat: 37.78249045644304, lng: -122.40410104393959, title: 'Office Hours', type: 'label' }, 'officehoursfloor2': { lat: 37.78266852473624, lng: -122.40387573838234, title: 'Office Hours', type: 'label' }, 'officehoursfloor2b': { lat: 37.782844472747406, lng: -122.40365579724312, title: 'Office Hours', type: 'label' } }, 'LEVEL3': { 'escalators3': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' }, 'restroom3a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom3b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator3a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'keynote': { lat: 37.783250423488326, lng: -122.40417748689651, icon: 'media', title: 'Keynote', type: 'label' }, '11': { lat: 37.78283069370135, lng: -122.40408763289452, icon: 'media', title: 'Room 11', type: 'session', room: '11' }, 'googletv': { lat: 37.7837125474666, lng: -122.40362092852592, type: 'sandbox', icon: 'generic', title: 'Google TV' }, 'android': { lat: 37.783530242022124, lng: -122.40358874201775, type: 'sandbox', icon: 'generic', title: 'Android' }, 'officehoursfloor3': { lat: 37.782843412820846, lng: -122.40365579724312, title: 'Office Hours', type: 'label' }, 'officehoursfloor3a': { lat: 37.78267170452323, lng: -122.40387842059135, title: 'Office Hours', type: 'label' } } }; google.maps.event.addDomListener(window, 'load', function() { window['IoMap'] = new IoMap(); });
JavaScript
/* Copyright 2010 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 Bookmark bubble library. This is meant to be included in the * main JavaScript binary of a mobile web application. * * Supported browsers: iPhone / iPod / iPad Safari 3.0+ */ var google = google || {}; google.bookmarkbubble = google.bookmarkbubble || {}; /** * Binds a context object to the function. * @param {Function} fn The function to bind to. * @param {Object} context The "this" object to use when the function is run. * @return {Function} A partially-applied form of fn. */ google.bind = function(fn, context) { return function() { return fn.apply(context, arguments); }; }; /** * Function used to define an abstract method in a base class. If a subclass * fails to override the abstract method, then an error will be thrown whenever * that method is invoked. */ google.abstractMethod = function() { throw Error('Unimplemented abstract method.'); }; /** * The bubble constructor. Instantiating an object does not cause anything to * be rendered yet, so if necessary you can set instance properties before * showing the bubble. * @constructor */ google.bookmarkbubble.Bubble = function() { /** * Handler for the scroll event. Keep a reference to it here, so it can be * unregistered when the bubble is destroyed. * @type {function()} * @private */ this.boundScrollHandler_ = google.bind(this.setPosition, this); /** * The bubble element. * @type {Element} * @private */ this.element_ = null; /** * Whether the bubble has been destroyed. * @type {boolean} * @private */ this.hasBeenDestroyed_ = false; }; /** * Shows the bubble if allowed. It is not allowed if: * - The browser is not Mobile Safari, or * - The user has dismissed it too often already, or * - The hash parameter is present in the location hash, or * - The application is in fullscreen mode, which means it was already loaded * from a homescreen bookmark. * @return {boolean} True if the bubble is being shown, false if it is not * allowed to show for one of the aforementioned reasons. */ google.bookmarkbubble.Bubble.prototype.showIfAllowed = function() { if (!this.isAllowedToShow_()) { return false; } this.show_(); return true; }; /** * Shows the bubble if allowed after loading the icon image. This method creates * an image element to load the image into the browser's cache before showing * the bubble to ensure that the image isn't blank. Use this instead of * showIfAllowed if the image url is http and cacheable. * This hack is necessary because Mobile Safari does not properly render * image elements with border-radius CSS. * @param {function()} opt_callback Closure to be called if and when the bubble * actually shows. * @return {boolean} True if the bubble is allowed to show. */ google.bookmarkbubble.Bubble.prototype.showIfAllowedWhenLoaded = function(opt_callback) { if (!this.isAllowedToShow_()) { return false; } var self = this; // Attach to self to avoid garbage collection. var img = self.loadImg_ = document.createElement('img'); img.src = self.getIconUrl_(); img.onload = function() { if (img.complete) { delete self.loadImg_; img.onload = null; // Break the circular reference. self.show_(); opt_callback && opt_callback(); } }; img.onload(); return true; }; /** * Sets the parameter in the location hash. As it is * unpredictable what hash scheme is to be used, this method must be * implemented by the host application. * * This gets called automatically when the bubble is shown. The idea is that if * the user then creates a bookmark, we can later recognize on application * startup whether it was from a bookmark suggested with this bubble. * * NOTE: Using a hash parameter to track whether the bubble has been shown * conflicts with the navigation system in jQuery Mobile. If you are using that * library, you should implement this function to track the bubble's status in * a different way, e.g. using window.localStorage in HTML5. */ google.bookmarkbubble.Bubble.prototype.setHashParameter = google.abstractMethod; /** * Whether the parameter is present in the location hash. As it is * unpredictable what hash scheme is to be used, this method must be * implemented by the host application. * * Call this method during application startup if you want to log whether the * application was loaded from a bookmark with the bookmark bubble promotion * parameter in it. * * @return {boolean} Whether the bookmark bubble parameter is present in the * location hash. */ google.bookmarkbubble.Bubble.prototype.hasHashParameter = google.abstractMethod; /** * The number of times the user must dismiss the bubble before we stop showing * it. This is a public property and can be changed by the host application if * necessary. * @type {number} */ google.bookmarkbubble.Bubble.prototype.NUMBER_OF_TIMES_TO_DISMISS = 2; /** * Time in milliseconds. If the user does not dismiss the bubble, it will auto * destruct after this amount of time. * @type {number} */ google.bookmarkbubble.Bubble.prototype.TIME_UNTIL_AUTO_DESTRUCT = 15000; /** * The prefix for keys in local storage. This is a public property and can be * changed by the host application if necessary. * @type {string} */ google.bookmarkbubble.Bubble.prototype.LOCAL_STORAGE_PREFIX = 'BOOKMARK_'; /** * The key name for the dismissed state. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.DISMISSED_ = 'DISMISSED_COUNT'; /** * The arrow image in base64 data url format. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.IMAGE_ARROW_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAMAAABSrFY3AAABKVBMVEUAAAD///8AAAAAAAAAAAAAAAAAAADf398AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD09PQAAAAAAAAAAAC9vb0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD19fUAAAAAAAAAAAAAAADq6uoAAAAAAAAAAAC8vLzU1NTT09MAAADg4OAAAADs7OwAAAAAAAAAAAD///+cueenwerA0vC1y+3a5fb5+/3t8vr4+v3w9PuwyOy3zO3h6vfh6vjq8Pqkv+mat+fE1fHB0/Cduuifu+iuxuuivemrxOvC1PDz9vzJ2fKpwuqmwOrb5vapw+q/0vDf6ffK2vLN3PPprJISAAAAQHRSTlMAAAEGExES7FM+JhUoQSxIRwMbNfkJUgXXBE4kDQIMHSA0Tw4xIToeTSc4Chz4OyIjPfI3QD/X5OZR6zzwLSUPrm1y3gAAAQZJREFUeF5lzsVyw0AURNE3IMsgmZmZgszQZoeZOf//EYlG5Yrhbs+im4Dj7slM5wBJ4OJ+undAUr68gK/Hyb6Bcp5yBR/w8jreNeAr5Eg2XE7g6e2/0z6cGw1JQhpmHP3u5aiPPnTTkIK48Hj9Op7bD3btAXTfgUdwYjwSDCVXMbizO0O4uDY/x4kYC5SWFnfC6N1a9RCO7i2XEmQJj2mHK1Hgp9Vq3QBRl9shuBLGhcNtHexcdQCnDUoUGetxDD+H2DQNG2xh6uAWgG2/17o1EmLqYH0Xej0UjHAaFxZIV6rJ/WK1kg7QZH8HU02zmdJinKZJaDV3TVMjM5Q9yiqYpUwiMwa/1apDXTNESjsAAAAASUVORK5CYII='; /** * The close image in base64 data url format. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.IMAGE_CLOSE_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAALVBMVEXM3fm+1Pfb5/rF2fjw9f23z/aavPOhwfTp8PyTt/L3+v7T4vqMs/K7zP////+qRWzhAAAAXElEQVQIW2O4CwUM996BwVskxtOqd++2rwMyPI+ve31GD8h4Madqz2mwms5jZ/aBGS/mHIDoen3m+DowY8/hOVUgxusz+zqPg7SvPA1UxQfSvu/du0YUK2AMmDMA5H1qhVX33T8AAAAASUVORK5CYII='; /** * The link used to locate the application's home screen icon to display inside * the bubble. The default link used here is for an iPhone home screen icon * without gloss. If your application uses a glossy icon, change this to * 'apple-touch-icon'. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.REL_ICON_ = 'apple-touch-icon-precomposed'; /** * Regular expression for detecting an iPhone or iPod or iPad. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.MOBILE_SAFARI_USERAGENT_REGEX_ = /iPhone|iPod|iPad/; /** * Regular expression for detecting an iPad. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.IPAD_USERAGENT_REGEX_ = /iPad/; /** * Regular expression for extracting the iOS version. Only matches 2.0 and up. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.IOS_VERSION_USERAGENT_REGEX_ = /OS (\d)_(\d)(?:_(\d))?/; /** * Determines whether the bubble should be shown or not. * @return {boolean} Whether the bubble should be shown or not. * @private */ google.bookmarkbubble.Bubble.prototype.isAllowedToShow_ = function() { return this.isMobileSafari_() && !this.hasBeenDismissedTooManyTimes_() && !this.isFullscreen_() && !this.hasHashParameter(); }; /** * Builds and shows the bubble. * @private */ google.bookmarkbubble.Bubble.prototype.show_ = function() { this.element_ = this.build_(); document.body.appendChild(this.element_); this.element_.style.WebkitTransform = 'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)'; this.setHashParameter(); window.setTimeout(this.boundScrollHandler_, 1); window.addEventListener('scroll', this.boundScrollHandler_, false); // If the user does not dismiss the bubble, slide out and destroy it after // some time. window.setTimeout(google.bind(this.autoDestruct_, this), this.TIME_UNTIL_AUTO_DESTRUCT); }; /** * Destroys the bubble by removing its DOM nodes from the document. */ google.bookmarkbubble.Bubble.prototype.destroy = function() { if (this.hasBeenDestroyed_) { return; } window.removeEventListener('scroll', this.boundScrollHandler_, false); if (this.element_ && this.element_.parentNode == document.body) { document.body.removeChild(this.element_); this.element_ = null; } this.hasBeenDestroyed_ = true; }; /** * Remember that the user has dismissed the bubble once more. * @private */ google.bookmarkbubble.Bubble.prototype.rememberDismissal_ = function() { if (window.localStorage) { try { var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_; var value = Number(window.localStorage[key]) || 0; window.localStorage[key] = String(value + 1); } catch (ex) { // Looks like we've hit the storage size limit. Currently we have no // fallback for this scenario, but we could use cookie storage instead. // This would increase the code bloat though. } } }; /** * Whether the user has dismissed the bubble often enough that we will not * show it again. * @return {boolean} Whether the user has dismissed the bubble often enough * that we will not show it again. * @private */ google.bookmarkbubble.Bubble.prototype.hasBeenDismissedTooManyTimes_ = function() { if (!window.localStorage) { // If we can not use localStorage to remember how many times the user has // dismissed the bubble, assume he has dismissed it. Otherwise we might end // up showing it every time the host application loads, into eternity. return true; } try { var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_; // If the key has never been set, localStorage yields undefined, which // Number() turns into NaN. In that case we'll fall back to zero for // clarity's sake. var value = Number(window.localStorage[key]) || 0; return value >= this.NUMBER_OF_TIMES_TO_DISMISS; } catch (ex) { // If we got here, something is wrong with the localStorage. Make the same // assumption as when it does not exist at all. Exceptions should only // occur when setting a value (due to storage limitations) but let's be // extra careful. return true; } }; /** * Whether the application is running in fullscreen mode. * @return {boolean} Whether the application is running in fullscreen mode. * @private */ google.bookmarkbubble.Bubble.prototype.isFullscreen_ = function() { return !!window.navigator.standalone; }; /** * Whether the application is running inside Mobile Safari. * @return {boolean} True if the current user agent looks like Mobile Safari. * @private */ google.bookmarkbubble.Bubble.prototype.isMobileSafari_ = function() { return this.MOBILE_SAFARI_USERAGENT_REGEX_.test(window.navigator.userAgent); }; /** * Whether the application is running on an iPad. * @return {boolean} True if the current user agent looks like an iPad. * @private */ google.bookmarkbubble.Bubble.prototype.isIpad_ = function() { return this.IPAD_USERAGENT_REGEX_.test(window.navigator.userAgent); }; /** * Creates a version number from 4 integer pieces between 0 and 127 (inclusive). * @param {*=} opt_a The major version. * @param {*=} opt_b The minor version. * @param {*=} opt_c The revision number. * @param {*=} opt_d The build number. * @return {number} A representation of the version. * @private */ google.bookmarkbubble.Bubble.prototype.getVersion_ = function(opt_a, opt_b, opt_c, opt_d) { // We want to allow implicit conversion of any type to number while avoiding // compiler warnings about the type. return /** @type {number} */ (opt_a) << 21 | /** @type {number} */ (opt_b) << 14 | /** @type {number} */ (opt_c) << 7 | /** @type {number} */ (opt_d); }; /** * Gets the iOS version of the device. Only works for 2.0+. * @return {number} The iOS version. * @private */ google.bookmarkbubble.Bubble.prototype.getIosVersion_ = function() { var groups = this.IOS_VERSION_USERAGENT_REGEX_.exec( window.navigator.userAgent) || []; groups.shift(); return this.getVersion_.apply(this, groups); }; /** * Positions the bubble at the bottom of the viewport using an animated * transition. */ google.bookmarkbubble.Bubble.prototype.setPosition = function() { this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-out'; this.element_.style.WebkitTransform = 'translate3d(0,' + this.getVisibleYPosition_() + 'px,0)'; }; /** * Destroys the bubble by removing its DOM nodes from the document, and * remembers that it was dismissed. * @private */ google.bookmarkbubble.Bubble.prototype.closeClickHandler_ = function() { this.destroy(); this.rememberDismissal_(); }; /** * Gets called after a while if the user ignores the bubble. * @private */ google.bookmarkbubble.Bubble.prototype.autoDestruct_ = function() { if (this.hasBeenDestroyed_) { return; } this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-in'; this.element_.style.WebkitTransform = 'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)'; window.setTimeout(google.bind(this.destroy, this), 700); }; /** * Gets the y offset used to show the bubble (i.e., position it on-screen). * @return {number} The y offset. * @private */ google.bookmarkbubble.Bubble.prototype.getVisibleYPosition_ = function() { return this.isIpad_() ? window.pageYOffset + 17 : window.pageYOffset - this.element_.offsetHeight + window.innerHeight - 17; }; /** * Gets the y offset used to hide the bubble (i.e., position it off-screen). * @return {number} The y offset. * @private */ google.bookmarkbubble.Bubble.prototype.getHiddenYPosition_ = function() { return this.isIpad_() ? window.pageYOffset - this.element_.offsetHeight : window.pageYOffset + window.innerHeight; }; /** * The url of the app's bookmark icon. * @type {string|undefined} * @private */ google.bookmarkbubble.Bubble.prototype.iconUrl_; /** * Scrapes the document for a link element that specifies an Apple favicon and * returns the icon url. Returns an empty data url if nothing can be found. * @return {string} A url string. * @private */ google.bookmarkbubble.Bubble.prototype.getIconUrl_ = function() { if (!this.iconUrl_) { var link = this.getLink(this.REL_ICON_); if (!link || !(this.iconUrl_ = link.href)) { this.iconUrl_ = 'data:image/png;base64,'; } } return this.iconUrl_; }; /** * Gets the requested link tag if it exists. * @param {string} rel The rel attribute of the link tag to get. * @return {Element} The requested link tag or null. */ google.bookmarkbubble.Bubble.prototype.getLink = function(rel) { rel = rel.toLowerCase(); var links = document.getElementsByTagName('link'); for (var i = 0; i < links.length; ++i) { var currLink = /** @type {Element} */ (links[i]); if (currLink.getAttribute('rel').toLowerCase() == rel) { return currLink; } } return null; }; /** * Creates the bubble and appends it to the document. * @return {Element} The bubble element. * @private */ google.bookmarkbubble.Bubble.prototype.build_ = function() { var bubble = document.createElement('div'); var isIpad = this.isIpad_(); bubble.style.position = 'absolute'; bubble.style.zIndex = 1000; bubble.style.width = '100%'; bubble.style.left = '0'; bubble.style.top = '0'; var bubbleInner = document.createElement('div'); bubbleInner.style.position = 'relative'; bubbleInner.style.width = '214px'; bubbleInner.style.margin = isIpad ? '0 0 0 82px' : '0 auto'; bubbleInner.style.border = '2px solid #fff'; bubbleInner.style.padding = '20px 20px 20px 10px'; bubbleInner.style.WebkitBorderRadius = '8px'; bubbleInner.style.WebkitBoxShadow = '0 0 8px rgba(0, 0, 0, 0.7)'; bubbleInner.style.WebkitBackgroundSize = '100% 8px'; bubbleInner.style.backgroundColor = '#b0c8ec'; bubbleInner.style.background = '#cddcf3 -webkit-gradient(linear, ' + 'left bottom, left top, ' + isIpad ? 'from(#cddcf3), to(#b3caed)) no-repeat top' : 'from(#b3caed), to(#cddcf3)) no-repeat bottom'; bubbleInner.style.font = '13px/17px sans-serif'; bubble.appendChild(bubbleInner); // The "Add to Home Screen" text is intended to be the exact same text // that is displayed in the menu of Mobile Safari. if (this.getIosVersion_() >= this.getVersion_(4, 2)) { bubbleInner.innerHTML = 'Install this web app on your phone: ' + 'tap on the arrow and then <b>\'Add to Home Screen\'</b>'; } else { bubbleInner.innerHTML = 'Install this web app on your phone: ' + 'tap <b style="font-size:15px">+</b> and then ' + '<b>\'Add to Home Screen\'</b>'; } var icon = document.createElement('div'); icon.style['float'] = 'left'; icon.style.width = '55px'; icon.style.height = '55px'; icon.style.margin = '-2px 7px 3px 5px'; icon.style.background = '#fff url(' + this.getIconUrl_() + ') no-repeat -1px -1px'; icon.style.WebkitBackgroundSize = '57px'; icon.style.WebkitBorderRadius = '10px'; icon.style.WebkitBoxShadow = '0 2px 5px rgba(0, 0, 0, 0.4)'; bubbleInner.insertBefore(icon, bubbleInner.firstChild); var arrow = document.createElement('div'); arrow.style.backgroundImage = 'url(' + this.IMAGE_ARROW_DATA_URL_ + ')'; arrow.style.width = '25px'; arrow.style.height = '19px'; arrow.style.position = 'absolute'; arrow.style.left = '111px'; if (isIpad) { arrow.style.WebkitTransform = 'rotate(180deg)'; arrow.style.top = '-19px'; } else { arrow.style.bottom = '-19px'; } bubbleInner.appendChild(arrow); var close = document.createElement('a'); close.onclick = google.bind(this.closeClickHandler_, this); close.style.position = 'absolute'; close.style.display = 'block'; close.style.top = '-3px'; close.style.right = '-3px'; close.style.width = '16px'; close.style.height = '16px'; close.style.border = '10px solid transparent'; close.style.background = 'url(' + this.IMAGE_CLOSE_DATA_URL_ + ') no-repeat'; bubbleInner.appendChild(close); return bubble; };
JavaScript
/* Copyright 2010 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 Example of how to use the bookmark bubble. */ window.addEventListener('load', function() { window.setTimeout(function() { var bubble = new google.bookmarkbubble.Bubble(); var parameter = 'bmb=1'; bubble.hasHashParameter = function() { return window.location.hash.indexOf(parameter) != -1; }; bubble.setHashParameter = function() { if (!this.hasHashParameter()) { window.location.hash += parameter; } }; bubble.getViewportHeight = function() { window.console.log('Example of how to override getViewportHeight.'); return window.innerHeight; }; bubble.getViewportScrollY = function() { window.console.log('Example of how to override getViewportScrollY.'); return window.pageYOffset; }; bubble.registerScrollHandler = function(handler) { window.console.log('Example of how to override registerScrollHandler.'); window.addEventListener('scroll', handler, false); }; bubble.deregisterScrollHandler = function(handler) { window.console.log('Example of how to override deregisterScrollHandler.'); window.removeEventListener('scroll', handler, false); }; bubble.showIfAllowed(); }, 1000); }, false);
JavaScript
/* Copyright Cobalys.com (c) 2011 This file is part of 365Video. 365Video 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. 365Video is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with 365Video. If not, see <http://www.gnu.org/licenses/>. */ $(function(){ $('.date-sidebar-year').click(function() { $(this).next().slideToggle(); $(this).toggleClass("date-sidebar-year-collapsed").toggleClass("date-sidebar-year-expanded"); return false; }).next().hide(); }); $(function(){ $('.sidebar-module-title').click(function() { $(this).next().slideToggle('slow'); return false; }) });
JavaScript
$(function(){ function split(val){ return val.split(/,\s*/); } function extractLast(term){ return split(term).pop(); } $("#id_tags").bind("keydown", function(event){ if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { event.preventDefault(); } }).autocomplete({ minLength: 0, source: function(request, response){ response($.ui.autocomplete.filter(availableTags, extractLast(request.term))); }, focus: function(){ return false; }, select: function(event, ui){ var terms = split(this.value); terms.pop(); terms.push(ui.item.value); terms.push(""); this.value = terms.join(", "); return false; } }); });
JavaScript
/* Main function, that handles request and responses in background. * Response functions are handled if response code equals to OK 200. */ function updateMultiple(formUpd, callBack, userName, userPassword) { xmlHttp = GetXmlHttpObject(); if(xmlHttp == null) { alert("XmlHttp not initialized!"); return 0; } xmlHttp.onreadystatechange = responseHandler; xmlHttp.open("GET", formUpd.url, true, userName, userPassword); xmlHttp.send(null); function responseHandler(){ if(xmlHttp.readyState == 4) { //response ready if(xmlHttp.status == 200) { //handle received data var xmlDoc = xmlHttp.responseXML; if(xmlDoc == null) return 0; try { //catching IE bug processResponse(xmlDoc); } catch(e) { return 0; } /* Callback function for custom update. */ if (callBack != undefined) callBack(); } else if(xmlHttp.status == 401) alert("Error code 401: Unauthorized"); else if(xmlHttp.status == 403) alert("Error code 403: Forbidden"); else if(xmlHttp.status == 404) alert("Error code 404: URL not found!"); } } } function processResponse(xmlDoc) { textElementArr = xmlDoc.getElementsByTagName("text"); for(var i = 0; i < textElementArr.length; i++) { try { elId = textElementArr[i].childNodes[0].childNodes[0].nodeValue; elValue = textElementArr[i].childNodes[1].childNodes[0].nodeValue; document.getElementById(elId).value = elValue; } catch(error) { if(elId == undefined){ continue; } else if(elValue == undefined) { elValue = ""; document.getElementById(elId).value = elValue; } } } checkboxElementArr = xmlDoc.getElementsByTagName("checkbox"); for(var i = 0; i < checkboxElementArr.length; i++) { try { elId = checkboxElementArr[i].childNodes[0].childNodes[0].nodeValue; elValue = checkboxElementArr[i].childNodes[1].childNodes[0].nodeValue; if(elValue.match("true")) document.getElementById(elId).checked = true; else document.getElementById(elId).checked = false; } catch(error) { if(elId == undefined) { continue; } else if(elValue == undefined) //we leave current state continue; } } selectElementArr = xmlDoc.getElementsByTagName("select"); for(var i = 0; i < selectElementArr.length; i++) { try { elId = selectElementArr[i].childNodes[0].childNodes[0].nodeValue; elValue = selectElementArr[i].childNodes[1].childNodes[0].nodeValue; document.getElementById(elId).value = elValue; if(elValue.match("true")) document.getElementById(elId).selected = true; else document.getElementById(elId).selected = false; } catch(error) { if(elId == undefined) { continue; } else if(elValue == undefined) { elValue = ""; document.getElementById(elId).value = elValue; } } } radioElementArr = xmlDoc.getElementsByTagName("radio"); for(var i = 0; i < radioElementArr.length; i++) { try { elId = radioElementArr[i].childNodes[0].childNodes[0].nodeValue; elValue = radioElementArr[i].childNodes[1].childNodes[0].nodeValue; if(elValue.match("true")) document.getElementById(elId).checked = true; else document.getElementById(elId).checked = false; } catch(error) { if(elId == undefined) { continue; } else if(elValue == undefined) //we leave current state continue; } } } /* XMLHttpRequest object specific functions */ function GetXmlHttpObject() { //init XMLHttp object var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari } catch (e) { try { // Internet Explorer xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } /* Objects templates */ function periodicObj(url, period) { this.url = url; this.period = (typeof period == "undefined") ? 0 : period; }
JavaScript
// needs Markdown.Converter.js at the moment (function () { var util = {}, position = {}, ui = {}, doc = window.document, re = window.RegExp, nav = window.navigator, SETTINGS = { lineLength: 72 }, // Used to work around some browser bugs where we can't use feature testing. uaSniffed = { isIE: /msie/.test(nav.userAgent.toLowerCase()), isIE_5or6: /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase()), isOpera: /opera/.test(nav.userAgent.toLowerCase()) }; var defaultsStrings = { bold: "Strong <strong> Ctrl+B", boldexample: "strong text", italic: "Emphasis <em> Ctrl+I", italicexample: "emphasized text", link: "Hyperlink <a> Ctrl+L", linkdescription: "enter link description here", linkdialog: "<p><b>Insert Hyperlink</b></p><p>http://example.com/ \"optional title\"</p>", quote: "Blockquote <blockquote> Ctrl+Q", quoteexample: "Blockquote", code: "Code Sample <pre><code> Ctrl+K", codeexample: "enter code here", image: "Image <img> Ctrl+G", imagedescription: "enter image description here", imagedialog: "<p><b>Insert Image</b></p><p>http://example.com/images/diagram.jpg \"optional title\"<br><br>Need <a href='http://www.google.com/search?q=free+image+hosting' target='_blank'>free image hosting?</a></p>", olist: "Numbered List <ol> Ctrl+O", ulist: "Bulleted List <ul> Ctrl+U", litem: "List item", heading: "Heading <h1>/<h2> Ctrl+H", headingexample: "Heading", hr: "Horizontal Rule <hr> Ctrl+R", undo: "Undo - Ctrl+Z", redo: "Redo - Ctrl+Y", redomac: "Redo - Ctrl+Shift+Z", help: "Markdown Editing Help" }; // ------------------------------------------------------------------- // YOUR CHANGES GO HERE // // I've tried to localize the things you are likely to change to // this area. // ------------------------------------------------------------------- // The default text that appears in the dialog input box when entering // links. var imageDefaultText = "http://"; var linkDefaultText = "http://"; // ------------------------------------------------------------------- // END OF YOUR CHANGES // ------------------------------------------------------------------- // options, if given, can have the following properties: // options.helpButton = { handler: yourEventHandler } // options.strings = { italicexample: "slanted text" } // `yourEventHandler` is the click handler for the help button. // If `options.helpButton` isn't given, not help button is created. // `options.strings` can have any or all of the same properties as // `defaultStrings` above, so you can just override some string displayed // to the user on a case-by-case basis, or translate all strings to // a different language. // // For backwards compatibility reasons, the `options` argument can also // be just the `helpButton` object, and `strings.help` can also be set via // `helpButton.title`. This should be considered legacy. // // The constructed editor object has the methods: // - getConverter() returns the markdown converter object that was passed to the constructor // - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op. // - refreshPreview() forces the preview to be updated. This method is only available after run() was called. Markdown.Editor = function (markdownConverter, idPostfix, options) { options = options || {}; if (typeof options.handler === "function") { //backwards compatible behavior options = { helpButton: options }; } options.strings = options.strings || {}; if (options.helpButton) { options.strings.help = options.strings.help || options.helpButton.title; } var getString = function (identifier) { return options.strings[identifier] || defaultsStrings[identifier]; } idPostfix = idPostfix || ""; var hooks = this.hooks = new Markdown.HookCollection(); hooks.addNoop("onPreviewRefresh"); // called with no arguments after the preview has been refreshed hooks.addNoop("postBlockquoteCreation"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates * its own image insertion dialog, this hook should return true, and the callback should be called with the chosen * image url (or null if the user cancelled). If this hook returns false, the default dialog will be used. */ this.getConverter = function () { return markdownConverter; } var that = this, panels; this.run = function () { if (panels) return; // already initialized panels = new PanelCollection(idPostfix); var commandManager = new CommandManager(hooks, getString); var previewManager = new PreviewManager(markdownConverter, panels, function () { hooks.onPreviewRefresh(); }); var undoManager, uiManager; if (!/\?noundo/.test(doc.location.href)) { undoManager = new UndoManager(function () { previewManager.refresh(); if (uiManager) // not available on the first call uiManager.setUndoRedoButtonStates(); }, panels); this.textOperation = function (f) { undoManager.setCommandMode(); f(); that.refreshPreview(); } } uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, options.helpButton, getString); uiManager.setUndoRedoButtonStates(); var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); }; forceRefresh(); }; } // before: contains all the text in the input box BEFORE the selection. // after: contains all the text in the input box AFTER the selection. function Chunks() { } // startRegex: a regular expression to find the start tag // endRegex: a regular expresssion to find the end tag Chunks.prototype.findTags = function (startRegex, endRegex) { var chunkObj = this; var regex; if (startRegex) { regex = util.extendRegExp(startRegex, "", "$"); this.before = this.before.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); regex = util.extendRegExp(startRegex, "^", ""); this.selection = this.selection.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); } if (endRegex) { regex = util.extendRegExp(endRegex, "", "$"); this.selection = this.selection.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); regex = util.extendRegExp(endRegex, "^", ""); this.after = this.after.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); } }; // If remove is false, the whitespace is transferred // to the before/after regions. // // If remove is true, the whitespace disappears. Chunks.prototype.trimWhitespace = function (remove) { var beforeReplacer, afterReplacer, that = this; if (remove) { beforeReplacer = afterReplacer = ""; } else { beforeReplacer = function (s) { that.before += s; return ""; } afterReplacer = function (s) { that.after = s + that.after; return ""; } } this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer); }; Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) { if (nLinesBefore === undefined) { nLinesBefore = 1; } if (nLinesAfter === undefined) { nLinesAfter = 1; } nLinesBefore++; nLinesAfter++; var regexText; var replacementText; // chrome bug ... documented at: http://meta.stackexchange.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985 if (navigator.userAgent.match(/Chrome/)) { "X".match(/()./); } this.selection = this.selection.replace(/(^\n*)/, ""); this.startTag = this.startTag + re.$1; this.selection = this.selection.replace(/(\n*$)/, ""); this.endTag = this.endTag + re.$1; this.startTag = this.startTag.replace(/(^\n*)/, ""); this.before = this.before + re.$1; this.endTag = this.endTag.replace(/(\n*$)/, ""); this.after = this.after + re.$1; if (this.before) { regexText = replacementText = ""; while (nLinesBefore--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.before = this.before.replace(new re(regexText + "$", ""), replacementText); } if (this.after) { regexText = replacementText = ""; while (nLinesAfter--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.after = this.after.replace(new re(regexText, ""), replacementText); } }; // end of Chunks // A collection of the important regions on the page. // Cached so we don't have to keep traversing the DOM. // Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around // this issue: // Internet explorer has problems with CSS sprite buttons that use HTML // lists. When you click on the background image "button", IE will // select the non-existent link text and discard the selection in the // textarea. The solution to this is to cache the textarea selection // on the button's mousedown event and set a flag. In the part of the // code where we need to grab the selection, we check for the flag // and, if it's set, use the cached area instead of querying the // textarea. // // This ONLY affects Internet Explorer (tested on versions 6, 7 // and 8) and ONLY on button clicks. Keyboard shortcuts work // normally since the focus never leaves the textarea. function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); this.preview = doc.getElementById("wmd-preview" + postfix); this.input = doc.getElementById("wmd-input" + postfix); }; // Returns true if the DOM element is visible, false if it's hidden. // Checks if display is anything other than none. util.isVisible = function (elem) { if (window.getComputedStyle) { // Most browsers return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none"; } else if (elem.currentStyle) { // IE return elem.currentStyle["display"] !== "none"; } }; // Adds a listener callback to a DOM element which is fired on a specified // event. util.addEvent = function (elem, event, listener) { if (elem.attachEvent) { // IE only. The "on" is mandatory. elem.attachEvent("on" + event, listener); } else { // Other browsers. elem.addEventListener(event, listener, false); } }; // Removes a listener callback from a DOM element which is fired on a specified // event. util.removeEvent = function (elem, event, listener) { if (elem.detachEvent) { // IE only. The "on" is mandatory. elem.detachEvent("on" + event, listener); } else { // Other browsers. elem.removeEventListener(event, listener, false); } }; // Converts \r\n and \r to \n. util.fixEolChars = function (text) { text = text.replace(/\r\n/g, "\n"); text = text.replace(/\r/g, "\n"); return text; }; // Extends a regular expression. Returns a new RegExp // using pre + regex + post as the expression. // Used in a few functions where we have a base // expression and we want to pre- or append some // conditions to it (e.g. adding "$" to the end). // The flags are unchanged. // // regex is a RegExp, pre and post are strings. util.extendRegExp = function (regex, pre, post) { if (pre === null || pre === undefined) { pre = ""; } if (post === null || post === undefined) { post = ""; } var pattern = regex.toString(); var flags; // Replace the flags with empty space and store them. pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) { flags = flagsPart; return ""; }); // Remove the slash delimiters on the regular expression. pattern = pattern.replace(/(^\/|\/$)/g, ""); pattern = pre + pattern + post; return new re(pattern, flags); } // UNFINISHED // The assignment in the while loop makes jslint cranky. // I'll change it to a better loop later. position.getTop = function (elem, isInner) { var result = elem.offsetTop; if (!isInner) { while (elem = elem.offsetParent) { result += elem.offsetTop; } } return result; }; position.getHeight = function (elem) { return elem.offsetHeight || elem.scrollHeight; }; position.getWidth = function (elem) { return elem.offsetWidth || elem.scrollWidth; }; position.getPageSize = function () { var scrollWidth, scrollHeight; var innerWidth, innerHeight; // It's not very clear which blocks work with which browsers. if (self.innerHeight && self.scrollMaxY) { scrollWidth = doc.body.scrollWidth; scrollHeight = self.innerHeight + self.scrollMaxY; } else if (doc.body.scrollHeight > doc.body.offsetHeight) { scrollWidth = doc.body.scrollWidth; scrollHeight = doc.body.scrollHeight; } else { scrollWidth = doc.body.offsetWidth; scrollHeight = doc.body.offsetHeight; } if (self.innerHeight) { // Non-IE browser innerWidth = self.innerWidth; innerHeight = self.innerHeight; } else if (doc.documentElement && doc.documentElement.clientHeight) { // Some versions of IE (IE 6 w/ a DOCTYPE declaration) innerWidth = doc.documentElement.clientWidth; innerHeight = doc.documentElement.clientHeight; } else if (doc.body) { // Other versions of IE innerWidth = doc.body.clientWidth; innerHeight = doc.body.clientHeight; } var maxWidth = Math.max(scrollWidth, innerWidth); var maxHeight = Math.max(scrollHeight, innerHeight); return [maxWidth, maxHeight, innerWidth, innerHeight]; }; // Handles pushing and popping TextareaStates for undo/redo commands. // I should rename the stack variables to list. function UndoManager(callback, panels) { var undoObj = this; var undoStack = []; // A stack of undo states var stackPtr = 0; // The index of the current state var mode = "none"; var lastState; // The last state var timer; // The setTimeout handle for cancelling the timer var inputStateObj; // Set the mode for later logic steps. var setMode = function (newMode, noSave) { if (mode != newMode) { mode = newMode; if (!noSave) { saveState(); } } if (!uaSniffed.isIE || mode != "moving") { timer = setTimeout(refreshState, 1); } else { inputStateObj = null; } }; var refreshState = function (isInitialState) { inputStateObj = new TextareaState(panels, isInitialState); timer = undefined; }; this.setCommandMode = function () { mode = "command"; saveState(); timer = setTimeout(refreshState, 0); }; this.canUndo = function () { return stackPtr > 1; }; this.canRedo = function () { if (undoStack[stackPtr + 1]) { return true; } return false; }; // Removes the last state and restores it. this.undo = function () { if (undoObj.canUndo()) { if (lastState) { // What about setting state -1 to null or checking for undefined? lastState.restore(); lastState = null; } else { undoStack[stackPtr] = new TextareaState(panels); undoStack[--stackPtr].restore(); if (callback) { callback(); } } } mode = "none"; panels.input.focus(); refreshState(); }; // Redo an action. this.redo = function () { if (undoObj.canRedo()) { undoStack[++stackPtr].restore(); if (callback) { callback(); } } mode = "none"; panels.input.focus(); refreshState(); }; // Push the input area state to the stack. var saveState = function () { var currState = inputStateObj || new TextareaState(panels); if (!currState) { return false; } if (mode == "moving") { if (!lastState) { lastState = currState; } return; } if (lastState) { if (undoStack[stackPtr - 1].text != lastState.text) { undoStack[stackPtr++] = lastState; } lastState = null; } undoStack[stackPtr++] = currState; undoStack[stackPtr + 1] = null; if (callback) { callback(); } }; var handleCtrlYZ = function (event) { var handled = false; if ((event.ctrlKey || event.metaKey) && !event.altKey) { // IE and Opera do not support charCode. var keyCode = event.charCode || event.keyCode; var keyCodeChar = String.fromCharCode(keyCode); switch (keyCodeChar.toLowerCase()) { case "y": undoObj.redo(); handled = true; break; case "z": if (!event.shiftKey) { undoObj.undo(); } else { undoObj.redo(); } handled = true; break; } } if (handled) { if (event.preventDefault) { event.preventDefault(); } if (window.event) { window.event.returnValue = false; } return; } }; // Set the mode depending on what is going on in the input area. var handleModeChange = function (event) { if (!event.ctrlKey && !event.metaKey) { var keyCode = event.keyCode; if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) { // 33 - 40: page up/dn and arrow keys // 63232 - 63235: page up/dn and arrow keys on safari setMode("moving"); } else if (keyCode == 8 || keyCode == 46 || keyCode == 127) { // 8: backspace // 46: delete // 127: delete setMode("deleting"); } else if (keyCode == 13) { // 13: Enter setMode("newlines"); } else if (keyCode == 27) { // 27: escape setMode("escape"); } else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) { // 16-20 are shift, etc. // 91: left window key // I think this might be a little messed up since there are // a lot of nonprinting keys above 20. setMode("typing"); } } }; var setEventHandlers = function () { util.addEvent(panels.input, "keypress", function (event) { // keyCode 89: y // keyCode 90: z if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.keyCode == 89 || event.keyCode == 90)) { event.preventDefault(); } }); var handlePaste = function () { if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) { if (timer == undefined) { mode = "paste"; saveState(); refreshState(); } } }; util.addEvent(panels.input, "keydown", handleCtrlYZ); util.addEvent(panels.input, "keydown", handleModeChange); util.addEvent(panels.input, "mousedown", function () { setMode("moving"); }); panels.input.onpaste = handlePaste; panels.input.ondrop = handlePaste; }; var init = function () { setEventHandlers(); refreshState(true); saveState(); }; init(); } // end of UndoManager // The input textarea state/contents. // This is used to implement undo/redo by the undo manager. function TextareaState(panels, isInitialState) { // Aliases var stateObj = this; var inputArea = panels.input; this.init = function () { if (!util.isVisible(inputArea)) { return; } if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box return; } this.setInputAreaSelectionStartEnd(); this.scrollTop = inputArea.scrollTop; if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) { this.text = inputArea.value; } } // Sets the selected text in the input box after we've performed an // operation. this.setInputAreaSelection = function () { if (!util.isVisible(inputArea)) { return; } if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) { inputArea.focus(); inputArea.selectionStart = stateObj.start; inputArea.selectionEnd = stateObj.end; inputArea.scrollTop = stateObj.scrollTop; } else if (doc.selection) { if (doc.activeElement && doc.activeElement !== inputArea) { return; } inputArea.focus(); var range = inputArea.createTextRange(); range.moveStart("character", -inputArea.value.length); range.moveEnd("character", -inputArea.value.length); range.moveEnd("character", stateObj.end); range.moveStart("character", stateObj.start); range.select(); } }; this.setInputAreaSelectionStartEnd = function () { if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) { stateObj.start = inputArea.selectionStart; stateObj.end = inputArea.selectionEnd; } else if (doc.selection) { stateObj.text = util.fixEolChars(inputArea.value); // IE loses the selection in the textarea when buttons are // clicked. On IE we cache the selection. Here, if something is cached, // we take it. var range = panels.ieCachedRange || doc.selection.createRange(); var fixedRange = util.fixEolChars(range.text); var marker = "\x07"; var markedRange = marker + fixedRange + marker; range.text = markedRange; var inputText = util.fixEolChars(inputArea.value); range.moveStart("character", -markedRange.length); range.text = fixedRange; stateObj.start = inputText.indexOf(marker); stateObj.end = inputText.lastIndexOf(marker) - marker.length; var len = stateObj.text.length - util.fixEolChars(inputArea.value).length; if (len) { range.moveStart("character", -fixedRange.length); while (len--) { fixedRange += "\n"; stateObj.end += 1; } range.text = fixedRange; } if (panels.ieCachedRange) stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange panels.ieCachedRange = null; this.setInputAreaSelection(); } }; // Restore this state into the input area. this.restore = function () { if (stateObj.text != undefined && stateObj.text != inputArea.value) { inputArea.value = stateObj.text; } this.setInputAreaSelection(); inputArea.scrollTop = stateObj.scrollTop; }; // Gets a collection of HTML chunks from the inptut textarea. this.getChunks = function () { var chunk = new Chunks(); chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start)); chunk.startTag = ""; chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end)); chunk.endTag = ""; chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end)); chunk.scrollTop = stateObj.scrollTop; return chunk; }; // Sets the TextareaState properties given a chunk of markdown. this.setChunks = function (chunk) { chunk.before = chunk.before + chunk.startTag; chunk.after = chunk.endTag + chunk.after; this.start = chunk.before.length; this.end = chunk.before.length + chunk.selection.length; this.text = chunk.before + chunk.selection + chunk.after; this.scrollTop = chunk.scrollTop; }; this.init(); }; function PreviewManager(converter, panels, previewRefreshCallback) { var managerObj = this; var timeout; var elapsedTime; var oldInputText; var maxDelay = 3000; var startType = "delayed"; // The other legal value is "manual" // Adds event listeners to elements var setupEvents = function (inputElem, listener) { util.addEvent(inputElem, "input", listener); inputElem.onpaste = listener; inputElem.ondrop = listener; util.addEvent(inputElem, "keypress", listener); util.addEvent(inputElem, "keydown", listener); }; var getDocScrollTop = function () { var result = 0; if (window.innerHeight) { result = window.pageYOffset; } else if (doc.documentElement && doc.documentElement.scrollTop) { result = doc.documentElement.scrollTop; } else if (doc.body) { result = doc.body.scrollTop; } return result; }; var makePreviewHtml = function () { // If there is no registered preview panel // there is nothing to do. if (!panels.preview) return; var text = panels.input.value; if (text && text == oldInputText) { return; // Input text hasn't changed. } else { oldInputText = text; } var prevTime = new Date().getTime(); text = converter.makeHtml(text); // Calculate the processing time of the HTML creation. // It's used as the delay time in the event listener. var currTime = new Date().getTime(); elapsedTime = currTime - prevTime; pushPreviewHtml(text); }; // setTimeout is already used. Used as an event listener. var applyTimeout = function () { if (timeout) { clearTimeout(timeout); timeout = undefined; } if (startType !== "manual") { var delay = 0; if (startType === "delayed") { delay = elapsedTime; } if (delay > maxDelay) { delay = maxDelay; } timeout = setTimeout(makePreviewHtml, delay); } }; var getScaleFactor = function (panel) { if (panel.scrollHeight <= panel.clientHeight) { return 1; } return panel.scrollTop / (panel.scrollHeight - panel.clientHeight); }; var setPanelScrollTops = function () { if (panels.preview) { panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview); } }; this.refresh = function (requiresRefresh) { if (requiresRefresh) { oldInputText = ""; makePreviewHtml(); } else { applyTimeout(); } }; this.processingTime = function () { return elapsedTime; }; var isFirstTimeFilled = true; // IE doesn't let you use innerHTML if the element is contained somewhere in a table // (which is the case for inline editing) -- in that case, detach the element, set the // value, and reattach. Yes, that *is* ridiculous. var ieSafePreviewSet = function (text) { var preview = panels.preview; var parent = preview.parentNode; var sibling = preview.nextSibling; parent.removeChild(preview); preview.innerHTML = text; if (!sibling) parent.appendChild(preview); else parent.insertBefore(preview, sibling); } var nonSuckyBrowserPreviewSet = function (text) { panels.preview.innerHTML = text; } var previewSetter; var previewSet = function (text) { if (previewSetter) return previewSetter(text); try { nonSuckyBrowserPreviewSet(text); previewSetter = nonSuckyBrowserPreviewSet; } catch (e) { previewSetter = ieSafePreviewSet; previewSetter(text); } }; var pushPreviewHtml = function (text) { var emptyTop = position.getTop(panels.input) - getDocScrollTop(); if (panels.preview) { previewSet(text); previewRefreshCallback(); } setPanelScrollTops(); if (isFirstTimeFilled) { isFirstTimeFilled = false; return; } var fullTop = position.getTop(panels.input) - getDocScrollTop(); if (uaSniffed.isIE) { setTimeout(function () { window.scrollBy(0, fullTop - emptyTop); }, 0); } else { window.scrollBy(0, fullTop - emptyTop); } }; var init = function () { setupEvents(panels.input, applyTimeout); makePreviewHtml(); if (panels.preview) { panels.preview.scrollTop = 0; } }; init(); }; // Creates the background behind the hyperlink text entry box. // And download dialog // Most of this has been moved to CSS but the div creation and // browser-specific hacks remain here. ui.createBackground = function () { var background = doc.createElement("div"), style = background.style; background.className = "wmd-prompt-background"; style.position = "absolute"; style.top = "0"; style.zIndex = "1000"; if (uaSniffed.isIE) { style.filter = "alpha(opacity=50)"; } else { style.opacity = "0.5"; } var pageSize = position.getPageSize(); style.height = pageSize[1] + "px"; if (uaSniffed.isIE) { style.left = doc.documentElement.scrollLeft; style.width = doc.documentElement.clientWidth; } else { style.left = "0"; style.width = "100%"; } doc.body.appendChild(background); return background; }; // This simulates a modal dialog box and asks for the URL when you // click the hyperlink or image buttons. // // text: The html for the input box. // defaultInputText: The default value that appears in the input box. // callback: The function which is executed when the prompt is dismissed, either via OK or Cancel. // It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel // was chosen). ui.prompt = function (text, defaultInputText, callback) { // These variables need to be declared at this level since they are used // in multiple functions. var dialog; // The dialog box. var input; // The text box where you enter the hyperlink. if (defaultInputText === undefined) { defaultInputText = ""; } // Used as a keydown event handler. Esc dismisses the prompt. // Key code 27 is ESC. var checkEscape = function (key) { var code = (key.charCode || key.keyCode); if (code === 27) { if (key.stopPropagation) key.stopPropagation(); close(true); return false; } }; // Dismisses the hyperlink input box. // isCancel is true if we don't care about the input text. // isCancel is false if we are going to keep the text. var close = function (isCancel) { util.removeEvent(doc.body, "keyup", checkEscape); var text = input.value; if (isCancel) { text = null; } else { // Fixes common pasting errors. text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://'); if (!/^(?:https?|ftp):\/\//.test(text)) text = 'http://' + text; } dialog.parentNode.removeChild(dialog); callback(text); return false; }; // Create the text input box form/window. var createDialog = function () { // The main dialog box. dialog = doc.createElement("div"); dialog.className = "wmd-prompt-dialog"; dialog.style.padding = "10px;"; dialog.style.position = "fixed"; dialog.style.width = "400px"; dialog.style.zIndex = "1001"; // The dialog text. var question = doc.createElement("div"); question.innerHTML = text; question.style.padding = "5px"; dialog.appendChild(question); // The web form container for the text box and buttons. var form = doc.createElement("form"), style = form.style; form.onsubmit = function () { return close(false); }; style.padding = "0"; style.margin = "0"; style.cssFloat = "left"; style.width = "100%"; style.textAlign = "center"; style.position = "relative"; dialog.appendChild(form); // The input text box input = doc.createElement("input"); input.type = "text"; input.value = defaultInputText; style = input.style; style.display = "block"; style.width = "80%"; style.marginLeft = style.marginRight = "auto"; form.appendChild(input); // The ok button var okButton = doc.createElement("input"); okButton.type = "button"; okButton.onclick = function () { return close(false); }; okButton.value = "OK"; style = okButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; // The cancel button var cancelButton = doc.createElement("input"); cancelButton.type = "button"; cancelButton.onclick = function () { return close(true); }; cancelButton.value = "Cancel"; style = cancelButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; form.appendChild(okButton); form.appendChild(cancelButton); util.addEvent(doc.body, "keyup", checkEscape); dialog.style.top = "50%"; dialog.style.left = "50%"; dialog.style.display = "block"; if (uaSniffed.isIE_5or6) { dialog.style.position = "absolute"; dialog.style.top = doc.documentElement.scrollTop + 200 + "px"; dialog.style.left = "50%"; } doc.body.appendChild(dialog); // This has to be done AFTER adding the dialog to the form if you // want it to be centered. dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px"; dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px"; }; // Why is this in a zero-length timeout? // Is it working around a browser bug? setTimeout(function () { createDialog(); var defTextLen = defaultInputText.length; if (input.selectionStart !== undefined) { input.selectionStart = 0; input.selectionEnd = defTextLen; } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(false); range.moveStart("character", -defTextLen); range.moveEnd("character", defTextLen); range.select(); } input.focus(); }, 0); }; function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions, getString) { var inputBox = panels.input, buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements. makeSpritedButtonRow(); var keyEvent = "keydown"; if (uaSniffed.isOpera) { keyEvent = "keypress"; } util.addEvent(inputBox, keyEvent, function (key) { // Check to see if we have a button key and, if so execute the callback. if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) { var keyCode = key.charCode || key.keyCode; var keyCodeStr = String.fromCharCode(keyCode).toLowerCase(); switch (keyCodeStr) { case "b": doClick(buttons.bold); break; case "i": doClick(buttons.italic); break; case "l": doClick(buttons.link); break; case "q": doClick(buttons.quote); break; case "k": doClick(buttons.code); break; case "g": doClick(buttons.image); break; case "o": doClick(buttons.olist); break; case "u": doClick(buttons.ulist); break; case "h": doClick(buttons.heading); break; case "r": doClick(buttons.hr); break; case "y": doClick(buttons.redo); break; case "z": if (key.shiftKey) { doClick(buttons.redo); } else { doClick(buttons.undo); } break; default: return; } if (key.preventDefault) { key.preventDefault(); } if (window.event) { window.event.returnValue = false; } } }); // Auto-indent on shift-enter util.addEvent(inputBox, "keyup", function (key) { if (key.shiftKey && !key.ctrlKey && !key.metaKey) { var keyCode = key.charCode || key.keyCode; // Character 13 is Enter if (keyCode === 13) { var fakeButton = {}; fakeButton.textOp = bindCommand("doAutoindent"); doClick(fakeButton); } } }); // special handler because IE clears the context of the textbox on ESC if (uaSniffed.isIE) { util.addEvent(inputBox, "keydown", function (key) { var code = key.keyCode; if (code === 27) { return false; } }); } // Perform the button's action. function doClick(button) { inputBox.focus(); if (button.textOp) { if (undoManager) { undoManager.setCommandMode(); } var state = new TextareaState(panels); if (!state) { return; } var chunks = state.getChunks(); // Some commands launch a "modal" prompt dialog. Javascript // can't really make a modal dialog box and the WMD code // will continue to execute while the dialog is displayed. // This prevents the dialog pattern I'm used to and means // I can't do something like this: // // var link = CreateLinkDialog(); // makeMarkdownLink(link); // // Instead of this straightforward method of handling a // dialog I have to pass any code which would execute // after the dialog is dismissed (e.g. link creation) // in a function parameter. // // Yes this is awkward and I think it sucks, but there's // no real workaround. Only the image and link code // create dialogs and require the function pointers. var fixupInputArea = function () { inputBox.focus(); if (chunks) { state.setChunks(chunks); } state.restore(); previewManager.refresh(); }; var noCleanup = button.textOp(chunks, fixupInputArea); if (!noCleanup) { fixupInputArea(); } } if (button.execute) { button.execute(undoManager); } }; function setupButton(button, isEnabled) { var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var image = button.getElementsByTagName("span")[0]; if (isEnabled) { image.style.backgroundPosition = button.XShift + " " + normalYShift; button.onmouseover = function () { image.style.backgroundPosition = this.XShift + " " + highlightYShift; }; button.onmouseout = function () { image.style.backgroundPosition = this.XShift + " " + normalYShift; }; // IE tries to select the background image "button" text (it's // implemented in a list item) so we have to cache the selection // on mousedown. if (uaSniffed.isIE) { button.onmousedown = function () { if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection return; } panels.ieCachedRange = document.selection.createRange(); panels.ieCachedScrollTop = panels.input.scrollTop; }; } if (!button.isHelp) { button.onclick = function () { if (this.onmouseout) { this.onmouseout(); } doClick(this); return false; } } } else { image.style.backgroundPosition = button.XShift + " " + disabledYShift; button.onmouseover = button.onmouseout = button.onclick = function () { }; } } function bindCommand(method) { if (typeof method === "string") method = commandManager[method]; return function () { method.apply(commandManager, arguments); } } function makeSpritedButtonRow() { var buttonBar = panels.buttonBar; var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var buttonRow = document.createElement("ul"); buttonRow.id = "wmd-button-row" + postfix; buttonRow.className = 'wmd-button-row'; buttonRow = buttonBar.appendChild(buttonRow); var xPosition = 0; var makeButton = function (id, title, XShift, textOp) { var button = document.createElement("li"); button.className = "wmd-button"; button.style.left = xPosition + "px"; xPosition += 25; var buttonImage = document.createElement("span"); button.id = id + postfix; button.appendChild(buttonImage); button.title = title; button.XShift = XShift; if (textOp) button.textOp = textOp; setupButton(button, true); buttonRow.appendChild(button); return button; }; var makeSpacer = function (num) { var spacer = document.createElement("li"); spacer.className = "wmd-spacer wmd-spacer" + num; spacer.id = "wmd-spacer" + num + postfix; buttonRow.appendChild(spacer); xPosition += 25; } buttons.bold = makeButton("wmd-bold-button", getString("bold"), "0px", bindCommand("doBold")); buttons.italic = makeButton("wmd-italic-button", getString("italic"), "-20px", bindCommand("doItalic")); makeSpacer(1); buttons.link = makeButton("wmd-link-button", getString("link"), "-40px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, false); })); buttons.quote = makeButton("wmd-quote-button", getString("quote"), "-60px", bindCommand("doBlockquote")); buttons.code = makeButton("wmd-code-button", getString("code"), "-80px", bindCommand("doCode")); buttons.image = makeButton("wmd-image-button", getString("image"), "-100px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, true); })); makeSpacer(2); buttons.olist = makeButton("wmd-olist-button", getString("olist"), "-120px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, true); })); buttons.ulist = makeButton("wmd-ulist-button", getString("ulist"), "-140px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, false); })); buttons.heading = makeButton("wmd-heading-button", getString("heading"), "-160px", bindCommand("doHeading")); buttons.hr = makeButton("wmd-hr-button", getString("hr"), "-180px", bindCommand("doHorizontalRule")); makeSpacer(3); buttons.undo = makeButton("wmd-undo-button", getString("undo"), "-200px", null); buttons.undo.execute = function (manager) { if (manager) manager.undo(); }; var redoTitle = /win/.test(nav.platform.toLowerCase()) ? getString("redo") : getString("redomac"); // mac and other non-Windows platforms buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null); buttons.redo.execute = function (manager) { if (manager) manager.redo(); }; if (helpOptions) { var helpButton = document.createElement("li"); var helpButtonImage = document.createElement("span"); helpButton.appendChild(helpButtonImage); helpButton.className = "wmd-button wmd-help-button"; helpButton.id = "wmd-help-button" + postfix; helpButton.XShift = "-240px"; helpButton.isHelp = true; helpButton.style.right = "0px"; helpButton.title = getString("help"); helpButton.onclick = helpOptions.handler; setupButton(helpButton, true); buttonRow.appendChild(helpButton); buttons.help = helpButton; } setUndoRedoButtonStates(); } function setUndoRedoButtonStates() { if (undoManager) { setupButton(buttons.undo, undoManager.canUndo()); setupButton(buttons.redo, undoManager.canRedo()); } }; this.setUndoRedoButtonStates = setUndoRedoButtonStates; } function CommandManager(pluginHooks, getString) { this.hooks = pluginHooks; this.getString = getString; } var commandProto = CommandManager.prototype; // The markdown symbols - 4 spaces = code, > = blockquote, etc. commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)"; // Remove markdown symbols from the chunk selection. commandProto.unwrap = function (chunk) { var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g"); chunk.selection = chunk.selection.replace(txt, "$1 $2"); }; commandProto.wrap = function (chunk, len) { this.unwrap(chunk); var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"), that = this; chunk.selection = chunk.selection.replace(regex, function (line, marked) { if (new re("^" + that.prefixes, "").test(line)) { return line; } return marked + "\n"; }); chunk.selection = chunk.selection.replace(/\s+$/, ""); }; commandProto.doBold = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 2, this.getString("boldexample")); }; commandProto.doItalic = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 1, this.getString("italicexample")); }; // chunk: The selected region that will be enclosed with */** // nStars: 1 for italics, 2 for bold // insertText: If you just click the button without highlighting text, this gets inserted commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) { // Get rid of whitespace and fixup newlines. chunk.trimWhitespace(); chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n"); // Look for stars before and after. Is the chunk already marked up? // note that these regex matches cannot fail var starsBefore = /(\**$)/.exec(chunk.before)[0]; var starsAfter = /(^\**)/.exec(chunk.after)[0]; var prevStars = Math.min(starsBefore.length, starsAfter.length); // Remove stars if we have to since the button acts as a toggle. if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) { chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), ""); chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), ""); } else if (!chunk.selection && starsAfter) { // It's not really clear why this code is necessary. It just moves // some arbitrary stuff around. chunk.after = chunk.after.replace(/^([*_]*)/, ""); chunk.before = chunk.before.replace(/(\s?)$/, ""); var whitespace = re.$1; chunk.before = chunk.before + starsAfter + whitespace; } else { // In most cases, if you don't have any selected text and click the button // you'll get a selected, marked up region with the default text inserted. if (!chunk.selection && !starsAfter) { chunk.selection = insertText; } // Add the true markup. var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ? chunk.before = chunk.before + markup; chunk.after = markup + chunk.after; } return; }; commandProto.stripLinkDefs = function (text, defsToAdd) { text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm, function (totalMatch, id, link, newlines, title) { defsToAdd[id] = totalMatch.replace(/\s*$/, ""); if (newlines) { // Strip the title and return that separately. defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, ""); return newlines + title; } return ""; }); return text; }; commandProto.addLinkDef = function (chunk, linkDef) { var refNumber = 0; // The current reference number var defsToAdd = {}; // // Start with a clean slate by removing all previous link definitions. chunk.before = this.stripLinkDefs(chunk.before, defsToAdd); chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd); chunk.after = this.stripLinkDefs(chunk.after, defsToAdd); var defs = ""; var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g; var addDefNumber = function (def) { refNumber++; def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:"); defs += "\n" + def; }; // note that // a) the recursive call to getLink cannot go infinite, because by definition // of regex, inner is always a proper substring of wholeMatch, and // b) more than one level of nesting is neither supported by the regex // nor making a lot of sense (the only use case for nesting is a linked image) var getLink = function (wholeMatch, before, inner, afterInner, id, end) { inner = inner.replace(regex, getLink); if (defsToAdd[id]) { addDefNumber(defsToAdd[id]); return before + inner + afterInner + refNumber + end; } return wholeMatch; }; chunk.before = chunk.before.replace(regex, getLink); if (linkDef) { addDefNumber(linkDef); } else { chunk.selection = chunk.selection.replace(regex, getLink); } var refOut = refNumber; chunk.after = chunk.after.replace(regex, getLink); if (chunk.after) { chunk.after = chunk.after.replace(/\n*$/, ""); } if (!chunk.after) { chunk.selection = chunk.selection.replace(/\n*$/, ""); } chunk.after += "\n\n" + defs; return refOut; }; // takes the line as entered into the add link/as image dialog and makes // sure the URL and the optinal title are "nice". function properlyEncoded(linkdef) { return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) { var inQueryString = false; // Having `[^\w\d-./]` in there is just a shortcut that lets us skip // the most common characters in URLs. Replacing that it with `.` would not change // the result, because encodeURI returns those characters unchanged, but it // would mean lots of unnecessary replacement calls. Having `[` and `]` in that // section as well means we do *not* enocde square brackets. These characters are // a strange beast in URLs, but if anything, this causes URLs to be more readable, // and we leave it to the browser to make sure that these links are handled without // problems. link = link.replace(/%(?:[\da-fA-F]{2})|\?|\+|[^\w\d-./[\]]/g, function (match) { // Valid percent encoding. Could just return it as is, but we follow RFC3986 // Section 2.1 which says "For consistency, URI producers and normalizers // should use uppercase hexadecimal digits for all percent-encodings." // Note that we also handle (illegal) stand-alone percent characters by // replacing them with "%25" if (match.length === 3 && match.charAt(0) == "%") { return match.toUpperCase(); } switch (match) { case "?": inQueryString = true; return "?"; break; // In the query string, a plus and a space are identical -- normalize. // Not strictly necessary, but identical behavior to the previous version // of this function. case "+": if (inQueryString) return "%20"; break; } return encodeURI(match); }) if (title) { title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, ""); title = title.replace(/"/g, "quot;").replace(/\(/g, "&#40;").replace(/\)/g, "&#41;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); } return title ? link + ' "' + title + '"' : link; }); } commandProto.doLinkOrImage = function (chunk, postProcessing, isImage) { chunk.trimWhitespace(); chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/); var background; if (chunk.endTag.length > 1 && chunk.startTag.length > 0) { chunk.startTag = chunk.startTag.replace(/!?\[/, ""); chunk.endTag = ""; this.addLinkDef(chunk, null); } else { // We're moving start and end tag back into the selection, since (as we're in the else block) we're not // *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the // link text. linkEnteredCallback takes care of escaping any brackets. chunk.selection = chunk.startTag + chunk.selection + chunk.endTag; chunk.startTag = chunk.endTag = ""; if (/\n\n/.test(chunk.selection)) { this.addLinkDef(chunk, null); return; } var that = this; // The function to be executed when you enter a link and press OK or Cancel. // Marks up the link and adds the ref. var linkEnteredCallback = function (link) { background.parentNode.removeChild(background); if (link !== null) { // ( $1 // [^\\] anything that's not a backslash // (?:\\\\)* an even number (this includes zero) of backslashes // ) // (?= followed by // [[\]] an opening or closing bracket // ) // // In other words, a non-escaped bracket. These have to be escaped now to make sure they // don't count as the end of the link or similar. // Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets), // the bracket in one match may be the "not a backslash" character in the next match, so it // should not be consumed by the first match. // The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the // start of the string, so this also works if the selection begins with a bracket. We cannot solve // this by anchoring with ^, because in the case that the selection starts with two brackets, this // would mean a zero-width match at the start. Since zero-width matches advance the string position, // the first bracket could then not act as the "not a backslash" for the second. chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1); var linkDef = " [999]: " + properlyEncoded(link); var num = that.addLinkDef(chunk, linkDef); chunk.startTag = isImage ? "![" : "["; chunk.endTag = "][" + num + "]"; if (!chunk.selection) { if (isImage) { chunk.selection = that.getString("imagedescription"); } else { chunk.selection = that.getString("linkdescription"); } } } postProcessing(); }; background = ui.createBackground(); if (isImage) { if (!this.hooks.insertImageDialog(linkEnteredCallback)) ui.prompt(this.getString("imagedialog"), imageDefaultText, linkEnteredCallback); } else { ui.prompt(this.getString("linkdialog"), linkDefaultText, linkEnteredCallback); } return true; } }; // When making a list, hitting shift-enter will put your cursor on the next line // at the current indent level. commandProto.doAutoindent = function (chunk, postProcessing) { var commandMgr = this, fakeSelection = false; chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n"); // There's no selection, end the cursor wasn't at the end of the line: // The user wants to split the current list item / code line / blockquote line // (for the latter it doesn't really matter) in two. Temporarily select the // (rest of the) line to achieve this. if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) { chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) { chunk.selection = wholeMatch; return ""; }); fakeSelection = true; } if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doList) { commandMgr.doList(chunk); } } if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doBlockquote) { commandMgr.doBlockquote(chunk); } } if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { if (commandMgr.doCode) { commandMgr.doCode(chunk); } } if (fakeSelection) { chunk.after = chunk.selection + chunk.after; chunk.selection = ""; } }; commandProto.doBlockquote = function (chunk, postProcessing) { chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/, function (totalMatch, newlinesBefore, text, newlinesAfter) { chunk.before += newlinesBefore; chunk.after = newlinesAfter + chunk.after; return text; }); chunk.before = chunk.before.replace(/(>[ \t]*)$/, function (totalMatch, blankLine) { chunk.selection = blankLine + chunk.selection; return ""; }); chunk.selection = chunk.selection.replace(/^(\s|>)+$/, ""); chunk.selection = chunk.selection || this.getString("quoteexample"); // The original code uses a regular expression to find out how much of the // text *directly before* the selection already was a blockquote: /* if (chunk.before) { chunk.before = chunk.before.replace(/\n?$/, "\n"); } chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/, function (totalMatch) { chunk.startTag = totalMatch; return ""; }); */ // This comes down to: // Go backwards as many lines a possible, such that each line // a) starts with ">", or // b) is almost empty, except for whitespace, or // c) is preceeded by an unbroken chain of non-empty lines // leading up to a line that starts with ">" and at least one more character // and in addition // d) at least one line fulfills a) // // Since this is essentially a backwards-moving regex, it's susceptible to // catstrophic backtracking and can cause the browser to hang; // see e.g. http://meta.stackexchange.com/questions/9807. // // Hence we replaced this by a simple state machine that just goes through the // lines and checks for a), b), and c). var match = "", leftOver = "", line; if (chunk.before) { var lines = chunk.before.replace(/\n$/, "").split("\n"); var inChain = false; for (var i = 0; i < lines.length; i++) { var good = false; line = lines[i]; inChain = inChain && line.length > 0; // c) any non-empty line continues the chain if (/^>/.test(line)) { // a) good = true; if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain inChain = true; } else if (/^[ \t]*$/.test(line)) { // b) good = true; } else { good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain } if (good) { match += line + "\n"; } else { leftOver += match + line; match = "\n"; } } if (!/(^|\n)>/.test(match)) { // d) leftOver += match; match = ""; } } chunk.startTag = match; chunk.before = leftOver; // end of change if (chunk.after) { chunk.after = chunk.after.replace(/^\n?/, "\n"); } chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/, function (totalMatch) { chunk.endTag = totalMatch; return ""; } ); var replaceBlanksInTags = function (useBracket) { var replacement = useBracket ? "> " : ""; if (chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } if (chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } }; if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) { this.wrap(chunk, SETTINGS.lineLength - 2); chunk.selection = chunk.selection.replace(/^/gm, "> "); replaceBlanksInTags(true); chunk.skipLines(); } else { chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, ""); this.unwrap(chunk); replaceBlanksInTags(false); if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n"); } if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n"); } } chunk.selection = this.hooks.postBlockquoteCreation(chunk.selection); if (!/\n/.test(chunk.selection)) { chunk.selection = chunk.selection.replace(/^(> *)/, function (wholeMatch, blanks) { chunk.startTag += blanks; return ""; }); } }; commandProto.doCode = function (chunk, postProcessing) { var hasTextBefore = /\S[ ]*$/.test(chunk.before); var hasTextAfter = /^[ ]*\S/.test(chunk.after); // Use 'four space' markdown if the selection is on its own // line or is multiline. if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) { chunk.before = chunk.before.replace(/[ ]{4}$/, function (totalMatch) { chunk.selection = totalMatch + chunk.selection; return ""; }); var nLinesBack = 1; var nLinesForward = 1; if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { nLinesBack = 0; } if (/^\n(\t|[ ]{4,})/.test(chunk.after)) { nLinesForward = 0; } chunk.skipLines(nLinesBack, nLinesForward); if (!chunk.selection) { chunk.startTag = " "; chunk.selection = this.getString("codeexample"); } else { if (/^[ ]{0,3}\S/m.test(chunk.selection)) { if (/\n/.test(chunk.selection)) chunk.selection = chunk.selection.replace(/^/gm, " "); else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior chunk.before += " "; } else { chunk.selection = chunk.selection.replace(/^(?:[ ]{4}|[ ]{0,3}\t)/gm, ""); } } } else { // Use backticks (`) to delimit the code block. chunk.trimWhitespace(); chunk.findTags(/`/, /`/); if (!chunk.startTag && !chunk.endTag) { chunk.startTag = chunk.endTag = "`"; if (!chunk.selection) { chunk.selection = this.getString("codeexample"); } } else if (chunk.endTag && !chunk.startTag) { chunk.before += chunk.endTag; chunk.endTag = ""; } else { chunk.startTag = chunk.endTag = ""; } } }; commandProto.doList = function (chunk, postProcessing, isNumberedList) { // These are identical except at the very beginning and end. // Should probably use the regex extension function to make this clearer. var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/; var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/; // The default bullet is a dash but others are possible. // This has nothing to do with the particular HTML bullet, // it's just a markdown bullet. var bullet = "-"; // The number in a numbered list. var num = 1; // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list. var getItemPrefix = function () { var prefix; if (isNumberedList) { prefix = " " + num + ". "; num++; } else { prefix = " " + bullet + " "; } return prefix; }; // Fixes the prefixes of the other list items. var getPrefixedItem = function (itemText) { // The numbering flag is unset when called by autoindent. if (isNumberedList === undefined) { isNumberedList = /^\s*\d/.test(itemText); } // Renumber/bullet the list element. itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm, function (_) { return getItemPrefix(); }); return itemText; }; chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null); if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) { chunk.before += chunk.startTag; chunk.startTag = ""; } if (chunk.startTag) { var hasDigits = /\d+[.]/.test(chunk.startTag); chunk.startTag = ""; chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n"); this.unwrap(chunk); chunk.skipLines(); if (hasDigits) { // Have to renumber the bullet points if this is a numbered list. chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem); } if (isNumberedList == hasDigits) { return; } } var nLinesUp = 1; chunk.before = chunk.before.replace(previousItemsRegex, function (itemText) { if (/^\s*([*+-])/.test(itemText)) { bullet = re.$1; } nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); if (!chunk.selection) { chunk.selection = this.getString("litem"); } var prefix = getItemPrefix(); var nLinesDown = 1; chunk.after = chunk.after.replace(nextItemsRegex, function (itemText) { nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); chunk.trimWhitespace(true); chunk.skipLines(nLinesUp, nLinesDown, true); chunk.startTag = prefix; var spaces = prefix.replace(/./g, " "); this.wrap(chunk, SETTINGS.lineLength - spaces.length); chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces); }; commandProto.doHeading = function (chunk, postProcessing) { // Remove leading/trailing whitespace and reduce internal spaces to single spaces. chunk.selection = chunk.selection.replace(/\s+/g, " "); chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, ""); // If we clicked the button with no selected text, we just // make a level 2 hash header around some default text. if (!chunk.selection) { chunk.startTag = "## "; chunk.selection = this.getString("headingexample"); chunk.endTag = " ##"; return; } var headerLevel = 0; // The existing header level of the selected text. // Remove any existing hash heading markdown and save the header level. chunk.findTags(/#+[ ]*/, /[ ]*#+/); if (/#+/.test(chunk.startTag)) { headerLevel = re.lastMatch.length; } chunk.startTag = chunk.endTag = ""; // Try to get the current header level by looking for - and = in the line // below the selection. chunk.findTags(null, /\s?(-+|=+)/); if (/=+/.test(chunk.endTag)) { headerLevel = 1; } if (/-+/.test(chunk.endTag)) { headerLevel = 2; } // Skip to the next line so we can create the header markdown. chunk.startTag = chunk.endTag = ""; chunk.skipLines(1, 1); // We make a level 2 header if there is no current header. // If there is a header level, we substract one from the header level. // If it's already a level 1 header, it's removed. var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1; if (headerLevelToCreate > 0) { // The button only creates level 1 and 2 underline headers. // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner? var headerChar = headerLevelToCreate >= 2 ? "-" : "="; var len = chunk.selection.length; if (len > SETTINGS.lineLength) { len = SETTINGS.lineLength; } chunk.endTag = "\n"; while (len--) { chunk.endTag += headerChar; } } }; commandProto.doHorizontalRule = function (chunk, postProcessing) { chunk.startTag = "----------\n"; chunk.selection = ""; chunk.skipLines(2, 1, true); } })();
JavaScript
(function () { var output, Converter; if (typeof exports === "object" && typeof require === "function") { // we're in a CommonJS (e.g. Node.js) module output = exports; Converter = require("./Markdown.Converter").Converter; } else { output = window.Markdown; Converter = output.Converter; } output.getSanitizingConverter = function () { var converter = new Converter(); converter.hooks.chain("postConversion", sanitizeHtml); converter.hooks.chain("postConversion", balanceTags); return converter; } function sanitizeHtml(html) { return html.replace(/<[^>]*>?/gi, sanitizeTag); } // (tags that can be opened/closed) | (tags that stand alone) var basic_tag_whitelist = /^(<\/?(b|blockquote|code|del|dd|dl|dt|em|h1|h2|h3|i|kbd|li|ol(?: start="\d+")?|p|pre|s|sup|sub|strong|strike|ul)>|<(br|hr)\s?\/?>)$/i; // <a href="url..." optional title>|</a> var a_white = /^(<a\shref="((https?|ftp):\/\/|\/)[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)*[\]$]+"(\stitle="[^"<>]+")?\s?>|<\/a>)$/i; // <img src="url..." optional width optional height optional alt optional title var img_white = /^(<img\ssrc="(https?:\/\/|\/)[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)*[\]$]+"(\swidth="\d{1,3}")?(\sheight="\d{1,3}")?(\salt="[^"<>]*")?(\stitle="[^"<>]*")?\s?\/?>)$/i; function sanitizeTag(tag) { if (tag.match(basic_tag_whitelist) || tag.match(a_white) || tag.match(img_white)) return tag; else return ""; } /// <summary> /// attempt to balance HTML tags in the html string /// by removing any unmatched opening or closing tags /// IMPORTANT: we *assume* HTML has *already* been /// sanitized and is safe/sane before balancing! /// /// adapted from CODESNIPPET: A8591DBA-D1D3-11DE-947C-BA5556D89593 /// </summary> function balanceTags(html) { if (html == "") return ""; var re = /<\/?\w+[^>]*(\s|$|>)/g; // convert everything to lower case; this makes // our case insensitive comparisons easier var tags = html.toLowerCase().match(re); // no HTML tags present? nothing to do; exit now var tagcount = (tags || []).length; if (tagcount == 0) return html; var tagname, tag; var ignoredtags = "<p><img><br><li><hr>"; var match; var tagpaired = []; var tagremove = []; var needsRemoval = false; // loop through matched tags in forward order for (var ctag = 0; ctag < tagcount; ctag++) { tagname = tags[ctag].replace(/<\/?(\w+).*/, "$1"); // skip any already paired tags // and skip tags in our ignore list; assume they're self-closed if (tagpaired[ctag] || ignoredtags.search("<" + tagname + ">") > -1) continue; tag = tags[ctag]; match = -1; if (!/^<\//.test(tag)) { // this is an opening tag // search forwards (next tags), look for closing tags for (var ntag = ctag + 1; ntag < tagcount; ntag++) { if (!tagpaired[ntag] && tags[ntag] == "</" + tagname + ">") { match = ntag; break; } } } if (match == -1) needsRemoval = tagremove[ctag] = true; // mark for removal else tagpaired[match] = true; // mark paired } if (!needsRemoval) return html; // delete all orphaned tags from the string var ctag = 0; html = html.replace(re, function (match) { var res = tagremove[ctag] ? "" : match; ctag++; return res; }); return html; } })();
JavaScript
exports.Converter = require("./Markdown.Converter").Converter; exports.getSanitizingConverter = require("./Markdown.Sanitizer").getSanitizingConverter;
JavaScript
"use strict"; var Markdown; if (typeof exports === "object" && typeof require === "function") // we're in a CommonJS (e.g. Node.js) module Markdown = exports; else Markdown = {}; // The following text is included for historical reasons, but should // be taken with a pinch of salt; it's not all true anymore. // // Wherever possible, Showdown is a straight, line-by-line port // of the Perl version of Markdown. // // This is not a normal parser design; it's basically just a // series of string substitutions. It's hard to read and // maintain this way, but keeping Showdown close to the original // design makes it easier to port new features. // // More importantly, Showdown behaves like markdown.pl in most // edge cases. So web applications can do client-side preview // in Javascript, and then build identical HTML on the server. // // This port needs the new RegExp functionality of ECMA 262, // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers // should do fine. Even with the new regular expression features, // We do a lot of work to emulate Perl's regex functionality. // The tricky changes in this file mostly have the "attacklab:" // label. Major or self-explanatory changes don't. // // Smart diff tools like Araxis Merge will be able to match up // this file with markdown.pl in a useful way. A little tweaking // helps: in a copy of markdown.pl, replace "#" with "//" and // replace "$text" with "text". Be sure to ignore whitespace // and line endings. // // // Usage: // // var text = "Markdown *rocks*."; // // var converter = new Markdown.Converter(); // var html = converter.makeHtml(text); // // alert(html); // // Note: move the sample code to the bottom of this // file before uncommenting it. // (function () { function identity(x) { return x; } function returnFalse(x) { return false; } function HookCollection() { } HookCollection.prototype = { chain: function (hookname, func) { var original = this[hookname]; if (!original) throw new Error("unknown hook " + hookname); if (original === identity) this[hookname] = func; else this[hookname] = function (text) { var args = Array.prototype.slice.call(arguments, 0); args[0] = original.apply(null, args); return func.apply(null, args); }; }, set: function (hookname, func) { if (!this[hookname]) throw new Error("unknown hook " + hookname); this[hookname] = func; }, addNoop: function (hookname) { this[hookname] = identity; }, addFalse: function (hookname) { this[hookname] = returnFalse; } }; Markdown.HookCollection = HookCollection; // g_urls and g_titles allow arbitrary user-entered strings as keys. This // caused an exception (and hence stopped the rendering) when the user entered // e.g. [push] or [__proto__]. Adding a prefix to the actual key prevents this // (since no builtin property starts with "s_"). See // http://meta.stackexchange.com/questions/64655/strange-wmd-bug // (granted, switching from Array() to Object() alone would have left only __proto__ // to be a problem) function SaveHash() { } SaveHash.prototype = { set: function (key, value) { this["s_" + key] = value; }, get: function (key) { return this["s_" + key]; } }; Markdown.Converter = function (OPTIONS) { var pluginHooks = this.hooks = new HookCollection(); // given a URL that was encountered by itself (without markup), should return the link text that's to be given to this link pluginHooks.addNoop("plainLinkText"); // called with the orignal text as given to makeHtml. The result of this plugin hook is the actual markdown source that will be cooked pluginHooks.addNoop("preConversion"); // called with the text once all normalizations have been completed (tabs to spaces, line endings, etc.), but before any conversions have pluginHooks.addNoop("postNormalization"); // Called with the text before / after creating block elements like code blocks and lists. Note that this is called recursively // with inner content, e.g. it's called with the full text, and then only with the content of a blockquote. The inner // call will receive outdented text. pluginHooks.addNoop("preBlockGamut"); pluginHooks.addNoop("postBlockGamut"); // called with the text of a single block element before / after the span-level conversions (bold, code spans, etc.) have been made pluginHooks.addNoop("preSpanGamut"); pluginHooks.addNoop("postSpanGamut"); // called with the final cooked HTML code. The result of this plugin hook is the actual output of makeHtml pluginHooks.addNoop("postConversion"); // // Private state of the converter instance: // // Global hashes, used by various utility routines var g_urls; var g_titles; var g_html_blocks; // Used to track when we're inside an ordered or unordered list // (see _ProcessListItems() for details): var g_list_level; OPTIONS = OPTIONS || {}; var asciify = identity, deasciify = identity; if (OPTIONS.nonAsciiLetters) { /* In JavaScript regular expressions, \w only denotes [a-zA-Z0-9_]. * That's why there's inconsistent handling e.g. with intra-word bolding * of Japanese words. That's why we do the following if OPTIONS.nonAsciiLetters * is true: * * Before doing bold and italics, we find every instance * of a unicode word character in the Markdown source that is not * matched by \w, and the letter "Q". We take the character's code point * and encode it in base 51, using the "digits" * * A, B, ..., P, R, ..., Y, Z, a, b, ..., y, z * * delimiting it with "Q" on both sides. For example, the source * * > In Chinese, the smurfs are called 藍精靈, meaning "blue spirits". * * turns into * * > In Chinese, the smurfs are called QNIhQQMOIQQOuUQ, meaning "blue spirits". * * Since everything that is a letter in Unicode is now a letter (or * several letters) in ASCII, \w and \b should always do the right thing. * * After the bold/italic conversion, we decode again; since "Q" was encoded * alongside all non-ascii characters (as "QBfQ"), and the conversion * will not generate "Q", the only instances of that letter should be our * encoded characters. And since the conversion will not break words, the * "Q...Q" should all still be in one piece. * * We're using "Q" as the delimiter because it's probably one of the * rarest characters, and also because I can't think of any special behavior * that would ever be triggered by this letter (to use a silly example, if we * delimited with "H" on the left and "P" on the right, then "Ψ" would be * encoded as "HTTP", which may cause special behavior). The latter would not * actually be a huge issue for bold/italic, but may be if we later use it * in other places as well. * */ (function () { var lettersThatJavaScriptDoesNotKnowAndQ = /[Q\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376-\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0523\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0621-\u064a\u0660-\u0669\u066e-\u066f\u0671-\u06d3\u06d5\u06e5-\u06e6\u06ee-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07c0-\u07ea\u07f4-\u07f5\u07fa\u0904-\u0939\u093d\u0950\u0958-\u0961\u0966-\u096f\u0971-\u0972\u097b-\u097f\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc-\u09dd\u09df-\u09e1\u09e6-\u09f1\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a66-\u0a6f\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0-\u0ae1\u0ae6-\u0aef\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b66-\u0b6f\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0be6-\u0bef\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58-\u0c59\u0c60-\u0c61\u0c66-\u0c6f\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0-\u0ce1\u0ce6-\u0cef\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d3d\u0d60-\u0d61\u0d66-\u0d6f\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32-\u0e33\u0e40-\u0e46\u0e50-\u0e59\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0ed0-\u0ed9\u0edc-\u0edd\u0f00\u0f20-\u0f29\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8b\u1000-\u102a\u103f-\u1049\u1050-\u1055\u105a-\u105d\u1061\u1065-\u1066\u106e-\u1070\u1075-\u1081\u108e\u1090-\u1099\u10a0-\u10c5\u10d0-\u10fa\u10fc\u1100-\u1159\u115f-\u11a2\u11a8-\u11f9\u1200-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u1676\u1681-\u169a\u16a0-\u16ea\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u17e0-\u17e9\u1810-\u1819\u1820-\u1877\u1880-\u18a8\u18aa\u1900-\u191c\u1946-\u196d\u1970-\u1974\u1980-\u19a9\u19c1-\u19c7\u19d0-\u19d9\u1a00-\u1a16\u1b05-\u1b33\u1b45-\u1b4b\u1b50-\u1b59\u1b83-\u1ba0\u1bae-\u1bb9\u1c00-\u1c23\u1c40-\u1c49\u1c4d-\u1c7d\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u203f-\u2040\u2054\u2071\u207f\u2090-\u2094\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2183-\u2184\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2c6f\u2c71-\u2c7d\u2c80-\u2ce4\u2d00-\u2d25\u2d30-\u2d65\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3006\u3031-\u3035\u303b-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31b7\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fc3\ua000-\ua48c\ua500-\ua60c\ua610-\ua62b\ua640-\ua65f\ua662-\ua66e\ua67f-\ua697\ua717-\ua71f\ua722-\ua788\ua78b-\ua78c\ua7fb-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8d0-\ua8d9\ua900-\ua925\ua930-\ua946\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa50-\uaa59\uac00-\ud7a3\uf900-\ufa2d\ufa30-\ufa6a\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe33-\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]/g; var cp_Q = "Q".charCodeAt(0); var cp_A = "A".charCodeAt(0); var cp_Z = "Z".charCodeAt(0); var dist_Za = "a".charCodeAt(0) - cp_Z - 1; asciify = function(text) { return text.replace(lettersThatJavaScriptDoesNotKnowAndQ, function (m) { var c = m.charCodeAt(0); var s = ""; var v; while (c > 0) { v = (c % 51) + cp_A; if (v >= cp_Q) v++; if (v > cp_Z) v += dist_Za; s = String.fromCharCode(v) + s; c = c / 51 | 0; } return "Q" + s + "Q"; }) }; deasciify = function(text) { return text.replace(/Q([A-PR-Za-z]{1,3})Q/g, function (m, s) { var c = 0; var v; for (var i = 0; i < s.length; i++) { v = s.charCodeAt(i); if (v > cp_Z) v -= dist_Za; if (v > cp_Q) v--; v -= cp_A; c = (c * 51) + v; } return String.fromCharCode(c); }) } })(); } var _DoItalicsAndBold = OPTIONS.asteriskIntraWordEmphasis ? _DoItalicsAndBold_AllowIntrawordWithAsterisk : _DoItalicsAndBoldStrict; this.makeHtml = function (text) { // // Main function. The order in which other subs are called here is // essential. Link and image substitutions need to happen before // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a> // and <img> tags get encoded. // // This will only happen if makeHtml on the same converter instance is called from a plugin hook. // Don't do that. if (g_urls) throw new Error("Recursive call to converter.makeHtml"); // Create the private state objects. g_urls = new SaveHash(); g_titles = new SaveHash(); g_html_blocks = []; g_list_level = 0; text = pluginHooks.preConversion(text); // attacklab: Replace ~ with ~T // This lets us use tilde as an escape char to avoid md5 hashes // The choice of character is arbitray; anything that isn't // magic in Markdown will work. text = text.replace(/~/g, "~T"); // attacklab: Replace $ with ~D // RegExp interprets $ as a special character // when it's in a replacement string text = text.replace(/\$/g, "~D"); // Standardize line endings text = text.replace(/\r\n/g, "\n"); // DOS to Unix text = text.replace(/\r/g, "\n"); // Mac to Unix // Make sure text begins and ends with a couple of newlines: text = "\n\n" + text + "\n\n"; // Convert all tabs to spaces. text = _Detab(text); // Strip any lines consisting only of spaces and tabs. // This makes subsequent regexen easier to write, because we can // match consecutive blank lines with /\n+/ instead of something // contorted like /[ \t]*\n+/ . text = text.replace(/^[ \t]+$/mg, ""); text = pluginHooks.postNormalization(text); // Turn block-level HTML blocks into hash entries text = _HashHTMLBlocks(text); // Strip link definitions, store in hashes. text = _StripLinkDefinitions(text); text = _RunBlockGamut(text); text = _UnescapeSpecialChars(text); // attacklab: Restore dollar signs text = text.replace(/~D/g, "$$"); // attacklab: Restore tildes text = text.replace(/~T/g, "~"); text = pluginHooks.postConversion(text); g_html_blocks = g_titles = g_urls = null; return text; }; function _StripLinkDefinitions(text) { // // Strips link definitions from text, stores the URLs and titles in // hash references. // // Link defs are in the form: ^[id]: url "optional title" /* text = text.replace(/ ^[ ]{0,3}\[([^\[\]]+)\]: // id = $1 attacklab: g_tab_width - 1 [ \t]* \n? // maybe *one* newline [ \t]* <?(\S+?)>? // url = $2 (?=\s|$) // lookahead for whitespace instead of the lookbehind removed below [ \t]* \n? // maybe one newline [ \t]* ( // (potential) title = $3 (\n*) // any lines skipped = $4 attacklab: lookbehind removed [ \t]+ ["(] (.+?) // title = $5 [")] [ \t]* )? // title is optional (?:\n+|$) /gm, function(){...}); */ text = text.replace(/^[ ]{0,3}\[([^\[\]]+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?(?=\s|$)[ \t]*\n?[ \t]*((\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm, function (wholeMatch, m1, m2, m3, m4, m5) { m1 = m1.toLowerCase(); g_urls.set(m1, _EncodeAmpsAndAngles(m2)); // Link IDs are case-insensitive if (m4) { // Oops, found blank lines, so it's not a title. // Put back the parenthetical statement we stole. return m3; } else if (m5) { g_titles.set(m1, m5.replace(/"/g, "&quot;")); } // Completely remove the definition from the text return ""; } ); return text; } function _HashHTMLBlocks(text) { // Hashify HTML blocks: // We only want to do this for block-level HTML tags, such as headers, // lists, and tables. That's because we still want to wrap <p>s around // "paragraphs" that are wrapped in non-block-level tags, such as anchors, // phrase emphasis, and spans. The list of tags we're looking for is // hard-coded: var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del" var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math" // First, look for nested blocks, e.g.: // <div> // <div> // tags for inner block must be indented. // </div> // </div> // // The outermost tags must start at the left margin for this to match, and // the inner nested divs must be indented. // We need to do this before the next, more liberal match, because the next // match will start at the first `<div>` and stop at the first `</div>`. // attacklab: This regex can be expensive when it fails. /* text = text.replace(/ ( // save in $1 ^ // start of line (with /m) <($block_tags_a) // start tag = $2 \b // word break // attacklab: hack around khtml/pcre bug... [^\r]*?\n // any number of lines, minimally matching </\2> // the matching end tag [ \t]* // trailing spaces/tabs (?=\n+) // followed by a newline ) // attacklab: there are sentinel newlines at end of document /gm,function(){...}}; */ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm, hashMatch); // // Now match more liberally, simply from `\n<tag>` to `</tag>\n` // /* text = text.replace(/ ( // save in $1 ^ // start of line (with /m) <($block_tags_b) // start tag = $2 \b // word break // attacklab: hack around khtml/pcre bug... [^\r]*? // any number of lines, minimally matching .*</\2> // the matching end tag [ \t]* // trailing spaces/tabs (?=\n+) // followed by a newline ) // attacklab: there are sentinel newlines at end of document /gm,function(){...}}; */ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm, hashMatch); // Special case just for <hr />. It was easier to make a special case than // to make the other regex more complicated. /* text = text.replace(/ \n // Starting after a blank line [ ]{0,3} ( // save in $1 (<(hr) // start tag = $2 \b // word break ([^<>])*? \/?>) // the matching end tag [ \t]* (?=\n{2,}) // followed by a blank line ) /g,hashMatch); */ text = text.replace(/\n[ ]{0,3}((<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g, hashMatch); // Special case for standalone HTML comments: /* text = text.replace(/ \n\n // Starting after a blank line [ ]{0,3} // attacklab: g_tab_width - 1 ( // save in $1 <! (--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--) // see http://www.w3.org/TR/html-markup/syntax.html#comments and http://meta.stackexchange.com/q/95256 > [ \t]* (?=\n{2,}) // followed by a blank line ) /g,hashMatch); */ text = text.replace(/\n\n[ ]{0,3}(<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>[ \t]*(?=\n{2,}))/g, hashMatch); // PHP and ASP-style processor instructions (<?...?> and <%...%>) /* text = text.replace(/ (?: \n\n // Starting after a blank line ) ( // save in $1 [ ]{0,3} // attacklab: g_tab_width - 1 (?: <([?%]) // $2 [^\r]*? \2> ) [ \t]* (?=\n{2,}) // followed by a blank line ) /g,hashMatch); */ text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g, hashMatch); return text; } function hashBlock(text) { text = text.replace(/(^\n+|\n+$)/g, ""); // Replace the element text with a marker ("~KxK" where x is its key) return "\n\n~K" + (g_html_blocks.push(text) - 1) + "K\n\n"; } function hashMatch(wholeMatch, m1) { return hashBlock(m1); } var blockGamutHookCallback = function (t) { return _RunBlockGamut(t); } function _RunBlockGamut(text, doNotUnhash) { // // These are all the transformations that form block-level // tags like paragraphs, headers, and list items. // text = pluginHooks.preBlockGamut(text, blockGamutHookCallback); text = _DoHeaders(text); // Do Horizontal Rules: var replacement = "<hr />\n"; text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, replacement); text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm, replacement); text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, replacement); text = _DoLists(text); text = _DoCodeBlocks(text); text = _DoBlockQuotes(text); text = pluginHooks.postBlockGamut(text, blockGamutHookCallback); // We already ran _HashHTMLBlocks() before, in Markdown(), but that // was to escape raw HTML in the original Markdown source. This time, // we're escaping the markup we've just created, so that we don't wrap // <p> tags around block-level tags. text = _HashHTMLBlocks(text); text = _FormParagraphs(text, doNotUnhash); return text; } function _RunSpanGamut(text) { // // These are all the transformations that occur *within* block-level // tags like paragraphs, headers, and list items. // text = pluginHooks.preSpanGamut(text); text = _DoCodeSpans(text); text = _EscapeSpecialCharsWithinTagAttributes(text); text = _EncodeBackslashEscapes(text); // Process anchor and image tags. Images must come first, // because ![foo][f] looks like an anchor. text = _DoImages(text); text = _DoAnchors(text); // Make links out of things like `<http://example.com/>` // Must come after _DoAnchors(), because you can use < and > // delimiters in inline links like [this](<url>). text = _DoAutoLinks(text); text = text.replace(/~P/g, "://"); // put in place to prevent autolinking; reset now text = _EncodeAmpsAndAngles(text); text = _DoItalicsAndBold(text); // Do hard breaks: text = text.replace(/ +\n/g, " <br>\n"); text = pluginHooks.postSpanGamut(text); return text; } function _EscapeSpecialCharsWithinTagAttributes(text) { // // Within tags -- meaning between < and > -- encode [\ ` * _] so they // don't conflict with their use in Markdown for code, italics and strong. // // Build a regex to find HTML tags and comments. See Friedl's // "Mastering Regular Expressions", 2nd Ed., pp. 200-201. // SE: changed the comment part of the regex var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>)/gi; text = text.replace(regex, function (wholeMatch) { var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, "$1`"); tag = escapeCharacters(tag, wholeMatch.charAt(1) == "!" ? "\\`*_/" : "\\`*_"); // also escape slashes in comments to prevent autolinking there -- http://meta.stackexchange.com/questions/95987 return tag; }); return text; } function _DoAnchors(text) { if (text.indexOf("[") === -1) return text; // // Turn Markdown link shortcuts into XHTML <a> tags. // // // First, handle reference-style links: [link text] [id] // /* text = text.replace(/ ( // wrap whole match in $1 \[ ( (?: \[[^\]]*\] // allow brackets nested one level | [^\[] // or anything else )* ) \] [ ]? // one optional space (?:\n[ ]*)? // one optional newline followed by spaces \[ (.*?) // id = $3 \] ) ()()()() // pad remaining backreferences /g, writeAnchorTag); */ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeAnchorTag); // // Next, inline-style links: [link text](url "optional title") // /* text = text.replace(/ ( // wrap whole match in $1 \[ ( (?: \[[^\]]*\] // allow brackets nested one level | [^\[\]] // or anything else )* ) \] \( // literal paren [ \t]* () // no id, so leave $3 empty <?( // href = $4 (?: \([^)]*\) // allow one level of (correctly nested) parens (think MSDN) | [^()\s] )*? )>? [ \t]* ( // $5 (['"]) // quote char = $6 (.*?) // Title = $7 \6 // matching quote [ \t]* // ignore any spaces/tabs between closing quote and ) )? // title is optional \) ) /g, writeAnchorTag); */ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((?:\([^)]*\)|[^()\s])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeAnchorTag); // // Last, handle reference-style shortcuts: [link text] // These must come last in case you've also got [link test][1] // or [link test](/foo) // /* text = text.replace(/ ( // wrap whole match in $1 \[ ([^\[\]]+) // link text = $2; can't contain '[' or ']' \] ) ()()()()() // pad rest of backreferences /g, writeAnchorTag); */ text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag); return text; } function writeAnchorTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) { if (m7 == undefined) m7 = ""; var whole_match = m1; var link_text = m2.replace(/:\/\//g, "~P"); // to prevent auto-linking withing the link. will be converted back after the auto-linker runs var link_id = m3.toLowerCase(); var url = m4; var title = m7; if (url == "") { if (link_id == "") { // lower-case and turn embedded newlines into spaces link_id = link_text.toLowerCase().replace(/ ?\n/g, " "); } url = "#" + link_id; if (g_urls.get(link_id) != undefined) { url = g_urls.get(link_id); if (g_titles.get(link_id) != undefined) { title = g_titles.get(link_id); } } else { if (whole_match.search(/\(\s*\)$/m) > -1) { // Special case for explicit empty url url = ""; } else { return whole_match; } } } url = attributeSafeUrl(url); var result = "<a href=\"" + url + "\""; if (title != "") { title = attributeEncode(title); title = escapeCharacters(title, "*_"); result += " title=\"" + title + "\""; } result += ">" + link_text + "</a>"; return result; } function _DoImages(text) { if (text.indexOf("![") === -1) return text; // // Turn Markdown image shortcuts into <img> tags. // // // First, handle reference-style labeled images: ![alt text][id] // /* text = text.replace(/ ( // wrap whole match in $1 !\[ (.*?) // alt text = $2 \] [ ]? // one optional space (?:\n[ ]*)? // one optional newline followed by spaces \[ (.*?) // id = $3 \] ) ()()()() // pad rest of backreferences /g, writeImageTag); */ text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag); // // Next, handle inline images: ![alt text](url "optional title") // Don't forget: encode * and _ /* text = text.replace(/ ( // wrap whole match in $1 !\[ (.*?) // alt text = $2 \] \s? // One optional whitespace character \( // literal paren [ \t]* () // no id, so leave $3 empty <?(\S+?)>? // src url = $4 [ \t]* ( // $5 (['"]) // quote char = $6 (.*?) // title = $7 \6 // matching quote [ \t]* )? // title is optional \) ) /g, writeImageTag); */ text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeImageTag); return text; } function attributeEncode(text) { // unconditionally replace angle brackets here -- what ends up in an attribute (e.g. alt or title) // never makes sense to have verbatim HTML in it (and the sanitizer would totally break it) return text.replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;"); } function writeImageTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) { var whole_match = m1; var alt_text = m2; var link_id = m3.toLowerCase(); var url = m4; var title = m7; if (!title) title = ""; if (url == "") { if (link_id == "") { // lower-case and turn embedded newlines into spaces link_id = alt_text.toLowerCase().replace(/ ?\n/g, " "); } url = "#" + link_id; if (g_urls.get(link_id) != undefined) { url = g_urls.get(link_id); if (g_titles.get(link_id) != undefined) { title = g_titles.get(link_id); } } else { return whole_match; } } alt_text = escapeCharacters(attributeEncode(alt_text), "*_[]()"); url = escapeCharacters(url, "*_"); var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\""; // attacklab: Markdown.pl adds empty title attributes to images. // Replicate this bug. //if (title != "") { title = attributeEncode(title); title = escapeCharacters(title, "*_"); result += " title=\"" + title + "\""; //} result += " />"; return result; } function _DoHeaders(text) { // Setext-style headers: // Header 1 // ======== // // Header 2 // -------- // text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm, function (wholeMatch, m1) { return "<h1>" + _RunSpanGamut(m1) + "</h1>\n\n"; } ); text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm, function (matchFound, m1) { return "<h2>" + _RunSpanGamut(m1) + "</h2>\n\n"; } ); // atx-style headers: // # Header 1 // ## Header 2 // ## Header 2 with closing hashes ## // ... // ###### Header 6 // /* text = text.replace(/ ^(\#{1,6}) // $1 = string of #'s [ \t]* (.+?) // $2 = Header text [ \t]* \#* // optional closing #'s (not counted) \n+ /gm, function() {...}); */ text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm, function (wholeMatch, m1, m2) { var h_level = m1.length; return "<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">\n\n"; } ); return text; } function _DoLists(text, isInsideParagraphlessListItem) { // // Form HTML ordered (numbered) and unordered (bulleted) lists. // // attacklab: add sentinel to hack around khtml/safari bug: // http://bugs.webkit.org/show_bug.cgi?id=11231 text += "~0"; // Re-usable pattern to match any entirel ul or ol list: /* var whole_list = / ( // $1 = whole list ( // $2 [ ]{0,3} // attacklab: g_tab_width - 1 ([*+-]|\d+[.]) // $3 = first list item marker [ \t]+ ) [^\r]+? ( // $4 ~0 // sentinel for workaround; should be $ | \n{2,} (?=\S) (?! // Negative lookahead for another list item marker [ \t]* (?:[*+-]|\d+[.])[ \t]+ ) ) ) /g */ var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm; if (g_list_level) { text = text.replace(whole_list, function (wholeMatch, m1, m2) { var list = m1; var list_type = (m2.search(/[*+-]/g) > -1) ? "ul" : "ol"; var first_number; if (list_type === "ol") first_number = parseInt(m2, 10) var result = _ProcessListItems(list, list_type, isInsideParagraphlessListItem); // Trim any trailing whitespace, to put the closing `</$list_type>` // up on the preceding line, to get it past the current stupid // HTML block parser. This is a hack to work around the terrible // hack that is the HTML block parser. result = result.replace(/\s+$/, ""); var opening = "<" + list_type; if (first_number && first_number !== 1) opening += " start=\"" + first_number + "\""; result = opening + ">" + result + "</" + list_type + ">\n"; return result; }); } else { whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g; text = text.replace(whole_list, function (wholeMatch, m1, m2, m3) { var runup = m1; var list = m2; var list_type = (m3.search(/[*+-]/g) > -1) ? "ul" : "ol"; var first_number; if (list_type === "ol") first_number = parseInt(m3, 10) var result = _ProcessListItems(list, list_type); var opening = "<" + list_type; if (first_number && first_number !== 1) opening += " start=\"" + first_number + "\""; result = runup + opening + ">\n" + result + "</" + list_type + ">\n"; return result; }); } // attacklab: strip sentinel text = text.replace(/~0/, ""); return text; } var _listItemMarkers = { ol: "\\d+[.]", ul: "[*+-]" }; function _ProcessListItems(list_str, list_type, isInsideParagraphlessListItem) { // // Process the contents of a single ordered or unordered list, splitting it // into individual list items. // // list_type is either "ul" or "ol". // The $g_list_level global keeps track of when we're inside a list. // Each time we enter a list, we increment it; when we leave a list, // we decrement. If it's zero, we're not in a list anymore. // // We do this because when we're not inside a list, we want to treat // something like this: // // I recommend upgrading to version // 8. Oops, now this line is treated // as a sub-list. // // As a single paragraph, despite the fact that the second line starts // with a digit-period-space sequence. // // Whereas when we're inside a list (or sub-list), that line will be // treated as the start of a sub-list. What a kludge, huh? This is // an aspect of Markdown's syntax that's hard to parse perfectly // without resorting to mind-reading. Perhaps the solution is to // change the syntax rules such that sub-lists must start with a // starting cardinal number; e.g. "1." or "a.". g_list_level++; // trim trailing blank lines: list_str = list_str.replace(/\n{2,}$/, "\n"); // attacklab: add sentinel to emulate \z list_str += "~0"; // In the original attacklab showdown, list_type was not given to this function, and anything // that matched /[*+-]|\d+[.]/ would just create the next <li>, causing this mismatch: // // Markdown rendered by WMD rendered by MarkdownSharp // ------------------------------------------------------------------ // 1. first 1. first 1. first // 2. second 2. second 2. second // - third 3. third * third // // We changed this to behave identical to MarkdownSharp. This is the constructed RegEx, // with {MARKER} being one of \d+[.] or [*+-], depending on list_type: /* list_str = list_str.replace(/ (^[ \t]*) // leading whitespace = $1 ({MARKER}) [ \t]+ // list marker = $2 ([^\r]+? // list item text = $3 (\n+) ) (?= (~0 | \2 ({MARKER}) [ \t]+) ) /gm, function(){...}); */ var marker = _listItemMarkers[list_type]; var re = new RegExp("(^[ \\t]*)(" + marker + ")[ \\t]+([^\\r]+?(\\n+))(?=(~0|\\1(" + marker + ")[ \\t]+))", "gm"); var last_item_had_a_double_newline = false; list_str = list_str.replace(re, function (wholeMatch, m1, m2, m3) { var item = m3; var leading_space = m1; var ends_with_double_newline = /\n\n$/.test(item); var contains_double_newline = ends_with_double_newline || item.search(/\n{2,}/) > -1; if (contains_double_newline || last_item_had_a_double_newline) { item = _RunBlockGamut(_Outdent(item), /* doNotUnhash = */true); } else { // Recursion for sub-lists: item = _DoLists(_Outdent(item), /* isInsideParagraphlessListItem= */ true); item = item.replace(/\n$/, ""); // chomp(item) if (!isInsideParagraphlessListItem) // only the outer-most item should run this, otherwise it's run multiple times for the inner ones item = _RunSpanGamut(item); } last_item_had_a_double_newline = ends_with_double_newline; return "<li>" + item + "</li>\n"; } ); // attacklab: strip sentinel list_str = list_str.replace(/~0/g, ""); g_list_level--; return list_str; } function _DoCodeBlocks(text) { // // Process Markdown `<pre><code>` blocks. // /* text = text.replace(/ (?:\n\n|^) ( // $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width .*\n+ )+ ) (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width /g ,function(){...}); */ // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug text += "~0"; text = text.replace(/(?:\n\n|^\n?)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g, function (wholeMatch, m1, m2) { var codeblock = m1; var nextChar = m2; codeblock = _EncodeCode(_Outdent(codeblock)); codeblock = _Detab(codeblock); codeblock = codeblock.replace(/^\n+/g, ""); // trim leading newlines codeblock = codeblock.replace(/\n+$/g, ""); // trim trailing whitespace codeblock = "<pre><code>" + codeblock + "\n</code></pre>"; return "\n\n" + codeblock + "\n\n" + nextChar; } ); // attacklab: strip sentinel text = text.replace(/~0/, ""); return text; } function _DoCodeSpans(text) { // // * Backtick quotes are used for <code></code> spans. // // * You can use multiple backticks as the delimiters if you want to // include literal backticks in the code span. So, this input: // // Just type ``foo `bar` baz`` at the prompt. // // Will translate to: // // <p>Just type <code>foo `bar` baz</code> at the prompt.</p> // // There's no arbitrary limit to the number of backticks you // can use as delimters. If you need three consecutive backticks // in your code, use four for delimiters, etc. // // * You can use spaces to get literal backticks at the edges: // // ... type `` `bar` `` ... // // Turns to: // // ... type <code>`bar`</code> ... // /* text = text.replace(/ (^|[^\\`]) // Character before opening ` can't be a backslash or backtick (`+) // $2 = Opening run of ` (?!`) // and no more backticks -- match the full run ( // $3 = The code block [^\r]*? [^`] // attacklab: work around lack of lookbehind ) \2 // Matching closer (?!`) /gm, function(){...}); */ text = text.replace(/(^|[^\\`])(`+)(?!`)([^\r]*?[^`])\2(?!`)/gm, function (wholeMatch, m1, m2, m3, m4) { var c = m3; c = c.replace(/^([ \t]*)/g, ""); // leading whitespace c = c.replace(/[ \t]*$/g, ""); // trailing whitespace c = _EncodeCode(c); c = c.replace(/:\/\//g, "~P"); // to prevent auto-linking. Not necessary in code *blocks*, but in code spans. Will be converted back after the auto-linker runs. return m1 + "<code>" + c + "</code>"; } ); return text; } function _EncodeCode(text) { // // Encode/escape certain characters inside Markdown code runs. // The point is that in code, these characters are literals, // and lose their special Markdown meanings. // // Encode all ampersands; HTML entities are not // entities within a Markdown code span. text = text.replace(/&/g, "&amp;"); // Do the angle bracket song and dance: text = text.replace(/</g, "&lt;"); text = text.replace(/>/g, "&gt;"); // Now, escape characters that are magic in Markdown: text = escapeCharacters(text, "\*_{}[]\\", false); // jj the line above breaks this: //--- //* Item // 1. Subitem // special char: * //--- return text; } function _DoItalicsAndBoldStrict(text) { if (text.indexOf("*") === -1 && text.indexOf("_") === - 1) return text; text = asciify(text); // <strong> must go first: // (^|[\W_]) Start with a non-letter or beginning of string. Store in \1. // (?:(?!\1)|(?=^)) Either the next character is *not* the same as the previous, // or we started at the end of the string (in which case the previous // group had zero width, so we're still there). Because the next // character is the marker, this means that if there are e.g. multiple // underscores in a row, we can only match the left-most ones (which // prevents foo___bar__ from getting bolded) // (\*|_) The marker character itself, asterisk or underscore. Store in \2. // \2 The marker again, since bold needs two. // (?=\S) The first bolded character cannot be a space. // ([^\r]*?\S) The actual bolded string. At least one character, and it cannot *end* // with a space either. Note that like in many other places, [^\r] is // just a workaround for JS' lack of single-line regexes; it's equivalent // to a . in an /s regex, because the string cannot contain any \r (they // are removed in the normalizing step). // \2\2 The marker character, twice -- end of bold. // (?!\2) Not followed by another marker character (ensuring that we match the // rightmost two in a longer row)... // (?=[\W_]|$) ...but by any other non-word character or the end of string. text = text.replace(/(^|[\W_])(?:(?!\1)|(?=^))(\*|_)\2(?=\S)([^\r]*?\S)\2\2(?!\2)(?=[\W_]|$)/g, "$1<strong>$3</strong>"); // This is almost identical to the <strong> regex, except 1) there's obviously just one marker // character, and 2) the italicized string cannot contain the marker character. text = text.replace(/(^|[\W_])(?:(?!\1)|(?=^))(\*|_)(?=\S)((?:(?!\2)[^\r])*?\S)\2(?!\2)(?=[\W_]|$)/g, "$1<em>$3</em>"); return deasciify(text); } function _DoItalicsAndBold_AllowIntrawordWithAsterisk(text) { if (text.indexOf("*") === -1 && text.indexOf("_") === - 1) return text; text = asciify(text); // <strong> must go first: // (?=[^\r][*_]|[*_]) Optimization only, to find potentially relevant text portions faster. Minimally slower in Chrome, but much faster in IE. // ( Store in \1. This is the last character before the delimiter // ^ Either we're at the start of the string (i.e. there is no last character)... // | ... or we allow one of the following: // (?= (lookahead; we're not capturing this, just listing legal possibilities) // \W__ If the delimiter is __, then this last character must be non-word non-underscore (extra-word emphasis only) // | // (?!\*)[\W_]\*\* If the delimiter is **, then this last character can be non-word non-asterisk (extra-word emphasis)... // | // \w\*\*\w ...or it can be word/underscore, but only if the first bolded character is such a character as well (intra-word emphasis) // ) // [^\r] actually capture the character (can't use `.` since it could be \n) // ) // (\*\*|__) Store in \2: the actual delimiter // (?!\2) not followed by the delimiter again (at most one more asterisk/underscore is allowed) // (?=\S) the first bolded character can't be a space // ( Store in \3: the bolded string // // (?:| Look at all bolded characters except for the last one. Either that's empty, meaning only a single character was bolded... // [^\r]*? ... otherwise take arbitrary characters, minimally matching; that's all bolded characters except for the last *two* // (?!\2) the last two characters cannot be the delimiter itself (because that would mean four underscores/asterisks in a row) // [^\r] capture the next-to-last bolded character // ) // (?= lookahead at the very last bolded char and what comes after // \S_ for underscore-bolding, it can be any non-space // | // \w for asterisk-bolding (otherwise the previous alternative would've matched, since \w implies \S), either the last char is word/underscore... // | // \S\*\*(?:[\W_]|$) ... or it's any other non-space, but in that case the character *after* the delimiter may not be a word character // ) // . actually capture the last character (can use `.` this time because the lookahead ensures \S in all cases) // ) // (?= lookahead; list the legal possibilities for the closing delimiter and its following character // __(?:\W|$) for underscore-bolding, the following character (if any) must be non-word non-underscore // | // \*\*(?:[^*]|$) for asterisk-bolding, any non-asterisk is allowed (note we already ensured above that it's not a word character if the last bolded character wasn't one) // ) // \2 actually capture the closing delimiter (and make sure that it matches the opening one) text = text.replace(/(?=[^\r][*_]|[*_])(^|(?=\W__|(?!\*)[\W_]\*\*|\w\*\*\w)[^\r])(\*\*|__)(?!\2)(?=\S)((?:|[^\r]*?(?!\2)[^\r])(?=\S_|\w|\S\*\*(?:[\W_]|$)).)(?=__(?:\W|$)|\*\*(?:[^*]|$))\2/g, "$1<strong>$3</strong>"); // now <em>: // (?=[^\r][*_]|[*_]) Optimization, see above. // ( Store in \1. This is the last character before the delimiter // ^ Either we're at the start of the string (i.e. there is no last character)... // | ... or we allow one of the following: // (?= (lookahead; we're not capturing this, just listing legal possibilities) // \W_ If the delimiter is _, then this last character must be non-word non-underscore (extra-word emphasis only) // | // (?!\*) otherwise, we list two possiblities for * as the delimiter; in either case, the last characters cannot be an asterisk itself // (?: // [\W_]\* this last character can be non-word (extra-word emphasis)... // | // \D\*(?=\w)\D ...or it can be word (otherwise the first alternative would've matched), but only if // a) the first italicized character is such a character as well (intra-word emphasis), and // b) neither character on either side of the asterisk is a digit // ) // ) // [^\r] actually capture the character (can't use `.` since it could be \n) // ) // (\*|_) Store in \2: the actual delimiter // (?!\2\2\2) not followed by more than two more instances of the delimiter // (?=\S) the first italicized character can't be a space // ( Store in \3: the italicized string // (?:(?!\2)[^\r])*? arbitrary characters except for the delimiter itself, minimally matching // (?= lookahead at the very last italicized char and what comes after // [^\s_]_ for underscore-italicizing, it can be any non-space non-underscore // | // (?=\w)\D\*\D for asterisk-italicizing, either the last char is word/underscore *and* neither character on either side of the asterisk is a digit... // | // [^\s*]\*(?:[\W_]|$) ... or that last char is any other non-space non-asterisk, but then the character after the delimiter (if any) must be non-word // ) // . actually capture the last character (can use `.` this time because the lookahead ensures \S in all cases) // ) // (?= lookahead; list the legal possibilities for the closing delimiter and its following character // _(?:\W|$) for underscore-italicizing, the following character (if any) must be non-word non-underscore // | // \*(?:[^*]|$) for asterisk-italicizing, any non-asterisk is allowed; all other restrictions have already been ensured in the previous lookahead // ) // \2 actually capture the closing delimiter (and make sure that it matches the opening one) text = text.replace(/(?=[^\r][*_]|[*_])(^|(?=\W_|(?!\*)(?:[\W_]\*|\D\*(?=\w)\D))[^\r])(\*|_)(?!\2\2\2)(?=\S)((?:(?!\2)[^\r])*?(?=[^\s_]_|(?=\w)\D\*\D|[^\s*]\*(?:[\W_]|$)).)(?=_(?:\W|$)|\*(?:[^*]|$))\2/g, "$1<em>$3</em>"); return deasciify(text); } function _DoBlockQuotes(text) { /* text = text.replace(/ ( // Wrap whole match in $1 ( ^[ \t]*>[ \t]? // '>' at the start of a line .+\n // rest of the first line (.+\n)* // subsequent consecutive lines \n* // blanks )+ ) /gm, function(){...}); */ text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm, function (wholeMatch, m1) { var bq = m1; // attacklab: hack around Konqueror 3.5.4 bug: // "----------bug".replace(/^-/g,"") == "bug" bq = bq.replace(/^[ \t]*>[ \t]?/gm, "~0"); // trim one level of quoting // attacklab: clean up hack bq = bq.replace(/~0/g, ""); bq = bq.replace(/^[ \t]+$/gm, ""); // trim whitespace-only lines bq = _RunBlockGamut(bq); // recurse bq = bq.replace(/(^|\n)/g, "$1 "); // These leading spaces screw with <pre> content, so we need to fix that: bq = bq.replace( /(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) { var pre = m1; // attacklab: hack around Konqueror 3.5.4 bug: pre = pre.replace(/^ /mg, "~0"); pre = pre.replace(/~0/g, ""); return pre; }); return hashBlock("<blockquote>\n" + bq + "\n</blockquote>"); } ); return text; } function _FormParagraphs(text, doNotUnhash) { // // Params: // $text - string to process with html <p> tags // // Strip leading and trailing lines: text = text.replace(/^\n+/g, ""); text = text.replace(/\n+$/g, ""); var grafs = text.split(/\n{2,}/g); var grafsOut = []; var markerRe = /~K(\d+)K/; // // Wrap <p> tags. // var end = grafs.length; for (var i = 0; i < end; i++) { var str = grafs[i]; // if this is an HTML marker, copy it if (markerRe.test(str)) { grafsOut.push(str); } else if (/\S/.test(str)) { str = _RunSpanGamut(str); str = str.replace(/^([ \t]*)/g, "<p>"); str += "</p>" grafsOut.push(str); } } // // Unhashify HTML blocks // if (!doNotUnhash) { end = grafsOut.length; for (var i = 0; i < end; i++) { var foundAny = true; while (foundAny) { // we may need several runs, since the data may be nested foundAny = false; grafsOut[i] = grafsOut[i].replace(/~K(\d+)K/g, function (wholeMatch, id) { foundAny = true; return g_html_blocks[id]; }); } } } return grafsOut.join("\n\n"); } function _EncodeAmpsAndAngles(text) { // Smart processing for ampersands and angle brackets that need to be encoded. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: // http://bumppo.net/projects/amputator/ text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, "&amp;"); // Encode naked <'s text = text.replace(/<(?![a-z\/?!]|~D)/gi, "&lt;"); return text; } function _EncodeBackslashEscapes(text) { // // Parameter: String. // Returns: The string, with after processing the following backslash // escape sequences. // // attacklab: The polite way to do this is with the new // escapeCharacters() function: // // text = escapeCharacters(text,"\\",true); // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true); // // ...but we're sidestepping its use of the (slow) RegExp constructor // as an optimization for Firefox. This function gets called a LOT. text = text.replace(/\\(\\)/g, escapeCharacters_callback); text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, escapeCharacters_callback); return text; } var charInsideUrl = "[-A-Z0-9+&@#/%?=~_|[\\]()!:,.;]", charEndingUrl = "[-A-Z0-9+&@#/%=~_|[\\])]", autoLinkRegex = new RegExp("(=\"|<)?\\b(https?|ftp)(://" + charInsideUrl + "*" + charEndingUrl + ")(?=$|\\W)", "gi"), endCharRegex = new RegExp(charEndingUrl, "i"); function handleTrailingParens(wholeMatch, lookbehind, protocol, link) { if (lookbehind) return wholeMatch; if (link.charAt(link.length - 1) !== ")") return "<" + protocol + link + ">"; var parens = link.match(/[()]/g); var level = 0; for (var i = 0; i < parens.length; i++) { if (parens[i] === "(") { if (level <= 0) level = 1; else level++; } else { level--; } } var tail = ""; if (level < 0) { var re = new RegExp("\\){1," + (-level) + "}$"); link = link.replace(re, function (trailingParens) { tail = trailingParens; return ""; }); } if (tail) { var lastChar = link.charAt(link.length - 1); if (!endCharRegex.test(lastChar)) { tail = lastChar + tail; link = link.substr(0, link.length - 1); } } return "<" + protocol + link + ">" + tail; } function _DoAutoLinks(text) { // note that at this point, all other URL in the text are already hyperlinked as <a href=""></a> // *except* for the <http://www.foo.com> case // automatically add < and > around unadorned raw hyperlinks // must be preceded by a non-word character (and not by =" or <) and followed by non-word/EOF character // simulating the lookbehind in a consuming way is okay here, since a URL can neither and with a " nor // with a <, so there is no risk of overlapping matches. text = text.replace(autoLinkRegex, handleTrailingParens); // autolink anything like <http://example.com> var replacer = function (wholematch, m1) { var url = attributeSafeUrl(m1); return "<a href=\"" + url + "\">" + pluginHooks.plainLinkText(m1) + "</a>"; }; text = text.replace(/<((https?|ftp):[^'">\s]+)>/gi, replacer); // Email addresses: <address@domain.foo> /* text = text.replace(/ < (?:mailto:)? ( [-.\w]+ \@ [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+ ) > /gi, _DoAutoLinks_callback()); */ /* disabling email autolinking, since we don't do that on the server, either text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi, function(wholeMatch,m1) { return _EncodeEmailAddress( _UnescapeSpecialChars(m1) ); } ); */ return text; } function _UnescapeSpecialChars(text) { // // Swap back in all the special characters we've hidden. // text = text.replace(/~E(\d+)E/g, function (wholeMatch, m1) { var charCodeToReplace = parseInt(m1); return String.fromCharCode(charCodeToReplace); } ); return text; } function _Outdent(text) { // // Remove one level of line-leading tabs or spaces // // attacklab: hack around Konqueror 3.5.4 bug: // "----------bug".replace(/^-/g,"") == "bug" text = text.replace(/^(\t|[ ]{1,4})/gm, "~0"); // attacklab: g_tab_width // attacklab: clean up hack text = text.replace(/~0/g, "") return text; } function _Detab(text) { if (!/\t/.test(text)) return text; var spaces = [" ", " ", " ", " "], skew = 0, v; return text.replace(/[\n\t]/g, function (match, offset) { if (match === "\n") { skew = offset + 1; return match; } v = (offset - skew) % 4; skew = offset + 1; return spaces[v]; }); } // // attacklab: Utility functions // function attributeSafeUrl(url) { url = attributeEncode(url); url = escapeCharacters(url, "*_:()[]") return url; } function escapeCharacters(text, charsToEscape, afterBackslash) { // First we have to escape the escape characters so that // we can build a character class out of them var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g, "\\$1") + "])"; if (afterBackslash) { regexString = "\\\\" + regexString; } var regex = new RegExp(regexString, "g"); text = text.replace(regex, escapeCharacters_callback); return text; } function escapeCharacters_callback(wholeMatch, m1) { var charCodeToEscape = m1.charCodeAt(0); return "~E" + charCodeToEscape + "E"; } }; // end of the Markdown.Converter constructor })();
JavaScript
// Usage: // // var myConverter = new Markdown.Editor(myConverter, null, { strings: Markdown.local.fr }); (function () { Markdown.local = Markdown.local || {}; Markdown.local.fr = { bold: "Gras <strong> Ctrl+B", boldexample: "texte en gras", italic: "Italique <em> Ctrl+I", italicexample: "texte en italique", link: "Hyperlien <a> Ctrl+L", linkdescription: "description de l'hyperlien", linkdialog: "<p><b>Insérer un hyperlien</b></p><p>http://example.com/ \"titre optionnel\"</p>", quote: "Citation <blockquote> Ctrl+Q", quoteexample: "Citation", code: "Extrait de code <pre><code> Ctrl+K", codeexample: "votre extrait de code", image: "Image <img> Ctrl+G", imagedescription: "description de l'image", imagedialog: "<p><b>Insérer une image</b></p><p>http://example.com/images/diagram.jpg \"titre optionnel\"<br><br><a href='http://www.google.com/search?q=free+image+hosting' target='_blank'>Vous chercher un hébergement d'image grauit ?</a></p>", olist: "Liste numérotée <ol> Ctrl+O", ulist: "Liste à point <ul> Ctrl+U", litem: "Elément de liste", heading: "Titre <h1>/<h2> Ctrl+H", headingexample: "Titre", hr: "Trait horizontal <hr> Ctrl+R", undo: "Annuler - Ctrl+Z", redo: "Refaire - Ctrl+Y", redomac: "Refaire - Ctrl+Shift+Z", help: "Aide sur Markdown" }; })();
JavaScript
// NOTE: This is just a demo -- in a production environment, // be sure to spend a few more thoughts on sanitizing user input. // (also, you probably wouldn't use a get request) var http = require("http"), url = require("url"), querystring = require("querystring"), Converter = require("../../Markdown.Converter").Converter, getSanitizingConverter = require("../../Markdown.Sanitizer").getSanitizingConverter, conv = new Converter(), saneConv = getSanitizingConverter(); http.createServer(function (req, res) { var route = url.parse(req.url); if (route.pathname !== "/") { res.writeHead(404); res.end("Page not found"); return; } var query = querystring.parse(route.query); res.writeHead(200, { "Content-type": "text/html" }); res.write("<html><body>"); var markdown = query.md || "## Hello!\n\n<marquee>I'm walking</marquee>\n\nVisit [Stack Overflow](http://stackoverflow.com)\n\n<b><i>This is never closed!"; res.write("<h1>Your output, sanitized:</h1>\n" + saneConv.makeHtml(markdown)) res.write("<h1>Your output, unsanitized:</h1>\n" + conv.makeHtml(markdown)) res.write( "<h1>Enter Markdown</h1>\n" + "<form method='get' action='/'>" + "<textarea cols=50 rows=10 name='md'>" + markdown.replace(/</g, "&lt;") + "</textarea><br>" + "<input type='submit' value='Convert!'>" + "</form>" ); res.end("</body></html>"); }).listen(8000);
JavaScript
/* Author: Robert Hashemian http://www.hashemian.com/ You can use this code in any manner so long as the author's name, Web address and this disclaimer is kept intact. */ function calcage(secs, num1, num2) { s = ((Math.floor(secs/num1))%num2).toString(); if (LeadingZero && s.length < 2) s = "0" + s; return "<b>" + s + "</b>"; } function CountBack(secs) { if (secs < 0) { document.getElementById("cntdwn").innerHTML = FinishMessage; return; } DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000)); DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24)); DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60)); DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60)); document.getElementById("cntdwn").innerHTML = DisplayStr; if (CountActive) setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod); } function putspan(backcolor, forecolor) { document.write("<span id='cntdwn'></span>"); } if (typeof(BackColor)=="undefined") BackColor = "transparent"; if (typeof(ForeColor)=="undefined") ForeColor= "#414141"; if (typeof(TargetDate)=="undefined") TargetDate = "03/03/2014 0:00 AM"; if (typeof(DisplayFormat)=="undefined") DisplayFormat = "<ul><li><span id=\"days\"> %%D%% </span><span class=\"timeDescription\">Days</span></li> <li><span id=\"hours\"> %%H%% </span><span class=\"timeDescription\">Hours</span></li> <li><span id=\"minutes\"> %%M%% </span><span class=\"timeDescription\">Minutes</span></li> <li><span id=\"sec-number\">%%S%%</span> <span class=\"timeDescription\">Seconds</span></li></ul>"; if (typeof(CountActive)=="undefined") CountActive = true; if (typeof(FinishMessage)=="undefined") FinishMessage = "Page should be online soon! Please be patient. You can try pressing F5."; if (typeof(CountStepper)!="number") CountStepper = -1; if (typeof(LeadingZero)=="undefined") LeadingZero = true; CountStepper = Math.ceil(CountStepper); if (CountStepper == 0) CountActive = false; var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990; putspan(BackColor, ForeColor); var dthen = new Date(TargetDate); var dnow = new Date(); if(CountStepper>0) ddiff = new Date(dnow-dthen); else ddiff = new Date(dthen-dnow); gsecs = Math.floor(ddiff.valueOf()/1000); CountBack(gsecs);
JavaScript
var xmlDocSchool; try {//IE xmlDocSchool = new ActiveXObject("Microsoft.XMLDOM"); } catch (e) {//Firefox,Mozilla,Opera,etc. try { xmlDocSchool = document.implementation.createDocument("", "", null); } catch (e) { alert(e.message); } } xmlDocSchool.async = false; xmlDocSchool.load("../xml/Schools.xml"); var controlName; function showSchool(obj) { controlName = obj; var msgw, msgh, bordercolor; msgw = 700; //提示窗口的宽度 msgh = 400; //提示窗口的高度 titleheight = 25; //提示窗口标题高度 bordercolor = "#336699"; //提示窗口的边框颜色 titlecolor = "#99CCFF"; //提示窗口的标题颜色 var sWidth, sHeight; sWidth = document.body.offsetWidth; //浏览器工作区域内页面宽度 sHeight = screen.height; //屏幕高度(垂直分辨率) var msgObj = document.createElement("div"); //创建一个div对象(提示框层) //定义div属性,即相当于 //<div id="msgDiv" align="center" style="background-color:white; border:1px solid #336699; position:absolute; left:50%; top:50%; font:12px/1.6em Verdana,Geneva,Arial,Helvetica,sans-serif; margin-left:-225px; margin-top:npx; width:400px; height:100px; text-align:center; line-height:25px; z-index:100001;"></div> msgObj.setAttribute("id", "msgDiv"); msgObj.setAttribute("align", "center"); msgObj.style.background = "white"; msgObj.style.border = "1px solid " + bordercolor; msgObj.style.position = "absolute"; msgObj.style.left = "50%"; msgObj.style.top = "50%"; msgObj.style.font = "12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif"; msgObj.style.marginLeft = "-320px"; if (screen.width == 1024) { msgObj.style.marginTop = -125 + document.documentElement.scrollTop + "px"; } if (screen.width == 1280) { msgObj.style.marginTop = -155 + document.documentElement.scrollTop + "px"; } msgObj.style.width = msgw + "px"; msgObj.style.height = msgh + "px"; msgObj.style.textAlign = "left"; msgObj.style.lineHeight = "25px"; msgObj.style.zIndex = "10001"; //msgObj.style.overflow = "auto"; msgObj.style.overflowy = "visible"; var title = document.createElement("h4"); //创建一个h4对象(提示框标题栏) //定义h4的属性,即相当于 //<h4 id="msgTitle" align="right" style="margin:0; padding:3px; background-color:#336699; filter:progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100); opacity:0.75; border:1px solid #336699; height:18px; font:12px Verdana,Geneva,Arial,Helvetica,sans-serif; color:white; cursor:pointer;" onclick="">关闭</h4> title.setAttribute("id", "msgTitle"); title.setAttribute("align", "right"); title.style.margin = "0"; title.style.padding = "3px"; title.style.background = bordercolor; title.style.filter = "progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100);"; title.style.opacity = "0.75"; title.style.border = "1px solid " + bordercolor; title.style.height = "18px"; title.style.font = "12px Verdana, Geneva, Arial, Helvetica, sans-serif"; title.style.color = "white"; title.style.cursor = "pointer"; title.innerHTML = " <table style='width:100%;font-size:14px; font-weight:bold'> <tr> <td align='left'> 选择学校&nbsp;</td> <td align='right'>关闭 &nbsp;</td> </tr> </table>"; title.onclick = removeObj; var proObj = document.createElement("div"); //创建一个div对象(显示省份) proObj.setAttribute("id", "proDiv"); proObj.setAttribute("align", "center"); proObj.style.background = "white"; proObj.style.border = "1px solid " + bordercolor; proObj.style.position = "relative"; proObj.style.font = "12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif"; proObj.style.marginLeft = "10px"; if (screen.width == 1024) { proObj.style.marginTop = 10 + document.documentElement.scrollTop + "px"; } if (screen.width == 1280) { proObj.style.marginTop = 10 + document.documentElement.scrollTop + "px"; } proObj.style.width = msgw - 30 + "px"; proObj.style.height = "50px"; proObj.style.textAlign = "left"; proObj.style.lineHeight = "25px"; proObj.style.zIndex = "10001"; //msgObj.style.overflow = "auto"; proObj.style.overflowy = "visible"; var schoolObj = document.createElement("div"); //创建一个div对象(显示院校) schoolObj.setAttribute("id", "schoolDiv"); schoolObj.setAttribute("align", "center"); schoolObj.style.background = "white"; schoolObj.style.border = "1px solid " + bordercolor; schoolObj.style.position = "relative"; schoolObj.style.font = "12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif"; schoolObj.style.marginLeft = "10px"; if (screen.width == 1024) { schoolObj.style.marginTop = 20 + document.documentElement.scrollTop + "px"; } if (screen.width == 1280) { schoolObj.style.marginTop = 20 + document.documentElement.scrollTop + "px"; } schoolObj.style.width = msgw - 30 + "px"; schoolObj.style.height = "270px"; schoolObj.style.textAlign = "left"; schoolObj.style.lineHeight = "25px"; schoolObj.style.zIndex = "10001"; //msgObj.style.overflow = "auto"; schoolObj.style.overflow = "auto"; document.body.appendChild(msgObj); //在body内添加提示框div对象msgObj document.getElementById("msgDiv").appendChild(title); //在提示框div中添加标题栏对象title document.getElementById("msgDiv").appendChild(proObj); //省份框 document.getElementById("msgDiv").appendChild(schoolObj); //院校框 document.getElementById("msgDiv").onload = loadschoolpro(); function removeObj() {//点击标题栏触发的事件 document.getElementById("msgDiv").removeChild(title); //删除提示框的标题栏 document.getElementById("msgDiv").removeChild(proObj); document.getElementById("msgDiv").removeChild(schoolObj); document.body.removeChild(msgObj); //删除提示框层 } } function loadschoolpro() { //加载省份 var proNodes = xmlDocSchool.childNodes[1].childNodes; //alert(proNodes.length); for (var i = 0; i < proNodes.length; i++) { proname = proNodes[i].getAttribute("Name"); var label = document.createElement("label"); label.setAttribute("id", i); label.innerHTML = "&nbsp;" + proname + "&nbsp;&nbsp;&nbsp;&nbsp;"; label.setAttribute("value", proname); if (i != 0 && (i + 1) % 15 == 0) { label.innerHTML = proname + "<br/>"; } document.getElementById("proDiv").appendChild(label); label.style.cursor = "pointer"; label.style.color = "#336699"; label.onmouseover = OverchangeColor; label.onmouseout = OutchangeColor; label.onclick = loadschool; } //加载默认省份的学校 var cityNodes = xmlDocSchool.getElementsByTagName("Province")[0].childNodes; //创建table var tab = document.createElement('table'); tab.setAttribute("id", "tabSchool1"); // tab.setAttribute("className", "TableLine"); //设定样式 tab.setAttribute("width", '98%'); tab.setAttribute("cellpadding", '3'); tab.setAttribute("cellspacing", '0'); var row = tab.insertRow(); // row.style.setAttribute("backgroundColor", "#e0e0e0"); for (var j = 0; j < cityNodes.length; j++) { cityname = cityNodes[j].childNodes[0].nodeValue; cityid = cityNodes[j].getAttribute("ID"); var col = row.insertCell(); col.setAttribute("id", cityid); col.setAttribute("value", cityname); col.setAttribute("className", "border:1px solid #9BC2E0;"); col.setAttribute("align", "left"); col.style.fontSize = "13px"; col.style.color = "#336699"; // col.style.fontWeight = "Bold"; col.style.cursor = "pointer"; col.onmouseover = OverchangeColor; col.onmouseout = OutchangeColor; col.onclick = checkschool; col.innerHTML = "·" + cityname; if (j != 0 && (j + 1) % 3 == 0) { row = tab.insertRow(); // row.style.setAttribute("backgroundColor", "#e0e0e0"); } } document.getElementById("schoolDiv").appendChild(tab); } function loadschool() { var currentcityobj = document.getElementById("schoolDiv"); if (currentcityobj != null) {//加载时先移除前一个 currentcityobj.innerHTML = ""; } var proid; proid = this.id; var cityNodes = xmlDocSchool.getElementsByTagName("Province")[proid].childNodes; //创建table var table = document.createElement('table'); table.setAttribute("id", "tableSchool"); // table.setAttribute("className", "TableLine"); //设定样式 table.setAttribute("width", '98%'); table.setAttribute("cellpadding", '3'); table.setAttribute("cellspacing", '0'); var row = table.insertRow(); // row.style.setAttribute("backgroundColor", "#e0e0e0"); for (var j = 0; j < cityNodes.length; j++) { cityname = cityNodes[j].childNodes[0].nodeValue; cityid = cityNodes[j].getAttribute("ID"); var col = row.insertCell(); col.setAttribute("id", cityid); col.setAttribute("value", cityname); col.setAttribute("className", "border:1px solid #9BC2E0;"); col.setAttribute("align", "left"); col.style.fontSize = "13px"; col.style.color = "#336699"; // col.style.fontWeight = "Bold"; col.style.cursor = "pointer"; col.onmouseover = OverchangeColor; col.onmouseout = OutchangeColor; col.onclick = checkschool; col.innerHTML = "·" + cityname; if (j != 0 && (j + 1) % 3 == 0) { row = table.insertRow(); // row.style.setAttribute("backgroundColor", "#e0e0e0"); } } document.getElementById("schoolDiv").appendChild(table); } function checkschool() {//选中院校 var cityname = this.value; // this.style.color = "red"; var title = document.getElementById("msgTitle"); var proObj = document.getElementById("proDiv"); var schoolObj = document.getElementById("schoolDiv"); var msgObj = document.getElementById("msgDiv"); document.getElementById("msgDiv").removeChild(title); //删除提示框的标题栏 document.getElementById("msgDiv").removeChild(proObj); document.getElementById("msgDiv").removeChild(schoolObj); document.body.removeChild(msgObj); document.getElementById(controlName).value = cityname; } function OverchangeColor() { this.style.color = "#CC6600"; } function OutchangeColor() { this.style.color = "#336699"; }
JavaScript
 //获取省份文档 var xmlPro; try {//IE xmlPro = new ActiveXObject("Microsoft.XMLDOM"); } catch (e) {//Firefox,Mozilla,Opera,etc. try { xmlPro = document.implementation.createDocument("", "", null); } catch (e) { alert(e.message); } } xmlPro.async = false; xmlPro.load("../xml/Regions.xml"); function showArea() { var msgw, msgh, bordercolor; msgw = 500; //提示窗口的宽度 msgh = 246; //提示窗口的高度 titleheight = 25 //提示窗口标题高度 bordercolor = "#336699"; //提示窗口的边框颜色 titlecolor = "#99CCFF"; //提示窗口的标题颜色 var sWidth, sHeight; sWidth = document.body.offsetWidth; //浏览器工作区域内页面宽度 sHeight = screen.height; //屏幕高度(垂直分辨率) //背景层(大小与窗口有效区域相同,即当弹出对话框时,背景显示为放射状透明灰色) var bgObj = document.createElement("div"); //创建一个div对象(背景层) //定义div属性,即相当于 //<div id="bgDiv" style="position:absolute; top:0; background-color:#777; filter:progid:DXImagesTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75); opacity:0.6; left:0; width:918px; height:768px; z-index:10000;"></div> bgObj.setAttribute('id', 'bgDiv'); bgObj.style.position = "absolute"; bgObj.style.top = "0"; bgObj.style.background = "#777"; bgObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75"; bgObj.style.opacity = "0.6"; bgObj.style.left = "0"; bgObj.style.width = sWidth + "px"; bgObj.style.height = sHeight + "px"; bgObj.style.zIndex = "10000"; document.body.appendChild(bgObj); //在body内添加该灰色背景层 var msgObj = document.createElement("div"); //创建一个div对象(提示框层) //定义div属性,即相当于 //<div id="msgDiv" align="center" style="background-color:white; border:1px solid #336699; position:absolute; left:50%; top:50%; font:12px/1.6em Verdana,Geneva,Arial,Helvetica,sans-serif; margin-left:-225px; margin-top:npx; width:400px; height:100px; text-align:center; line-height:25px; z-index:100001;"></div> msgObj.setAttribute("id", "msgDiv"); msgObj.setAttribute("align", "center"); msgObj.style.background = "white"; msgObj.style.border = "1px solid " + bordercolor; msgObj.style.position = "absolute"; msgObj.style.left = "50%"; msgObj.style.top = "50%"; msgObj.style.font = "12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif"; msgObj.style.marginLeft = "-220px"; if (screen.width == 1366) { msgObj.style.marginTop = -65 + document.documentElement.scrollTop + "px"; } if (screen.width == 1280) { msgObj.style.marginTop = -95 + document.documentElement.scrollTop + "px"; } msgObj.style.width = msgw + "px"; msgObj.style.height = msgh + "px"; msgObj.style.textAlign = "left"; msgObj.style.lineHeight = "25px"; msgObj.style.zIndex = "10001"; //msgObj.style.overflow = "auto"; msgObj.style.overflowy = "visible"; //msgObj.setAttribute("onload", "loadpro()"); //加载省份 var title = document.createElement("h4"); //创建一个h4对象(提示框标题栏) //定义h4的属性,即相当于 //<h4 id="msgTitle" align="right" style="margin:0; padding:3px; background-color:#336699; filter:progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100); opacity:0.75; border:1px solid #336699; height:18px; font:12px Verdana,Geneva,Arial,Helvetica,sans-serif; color:white; cursor:pointer;" onclick="">关闭</h4> title.setAttribute("id", "msgTitle"); title.setAttribute("align", "right"); title.style.margin = "0"; title.style.padding = "3px"; title.style.background = bordercolor; title.style.filter = "progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100);"; title.style.opacity = "0.75"; title.style.border = "1px solid " + bordercolor; title.style.height = "18px"; title.style.font = "12px Verdana, Geneva, Arial, Helvetica, sans-serif"; title.style.color = "white"; title.style.cursor = "pointer"; title.innerHTML = " <table style='width:100%;font-size:14px; font-weight:bold'> <tr> <td align='left'> 请选择城市&nbsp;</td> <td align='right'>关闭 &nbsp;</td> </tr> </table>"; title.onclick = removeObj; document.body.appendChild(msgObj); //在body内添加提示框div对象msgObj document.getElementById("msgDiv").appendChild(title); //在提示框div中添加标题栏对象title document.getElementById("msgDiv").onload = loadpro(); function removeObj() {//点击标题栏触发的事件 document.body.removeChild(bgObj); //删除背景层Div document.getElementById("msgDiv").removeChild(title); //删除提示框的标题栏 document.body.removeChild(msgObj); //删除提示框层 } } function loadpro() { var proNodes = null; try { proNodes = xmlPro.childNodes[1].childNodes; } catch (e) { try { proNodes = xmlPro.childNodes[0].childNodes; } catch (e) { alert(e.message); } } //alert(proNodes.length); //创建table var table = document.createElement('table'); table.setAttribute("id", "tableSchool"); // table.setAttribute("className", "TableLine"); //设定样式 table.setAttribute("width", '98%'); table.setAttribute("cellpadding", '3'); table.setAttribute("cellspacing", '0'); var row = table.insertRow(); for (var i = 0; i < proNodes.length; i++) { proname = proNodes[i].getAttribute("Name"); var col = row.insertCell(); col.setAttribute("id", proname); col.setAttribute("value", i); col.setAttribute("className", "border:1px solid #9BC2E0;"); col.setAttribute("align", "left"); col.style.fontSize = "13px"; col.style.color = "#336699"; col.style.cursor = "pointer"; col.onmouseover = OverchangeColor; col.onmouseout = OutchangeColor; col.onclick = loadcity; col.innerHTML = "·" + proname; if (i != 0 && (i + 1) % 5 == 0) { row = table.insertRow(); } } document.getElementById("msgDiv").appendChild(table); } function loadcity() { var currentcityobj = document.getElementById("cityDiv"); if (currentcityobj != null) {//加载时先移除前一个 document.getElementById("msgDiv").removeChild(currentcityobj); } var cityw, cityh, bordercolor; cityw = 500; //提示窗口的宽度 cityh = 150; //提示窗口的高度 bordercolor = "#336699"; //提示窗口的边框颜色 var cityObj = document.createElement("div"); //创建一个div对象(城市层) //定义div属性,即相当于 //<div id="msgDiv" align="center" style="background-color:white; border:1px solid #336699; position:absolute; left:50%; top:50%; font:12px/1.6em Verdana,Geneva,Arial,Helvetica,sans-serif; margin-left:-225px; margin-top:npx; width:400px; height:100px; text-align:center; line-height:25px; z-index:100001;"></div> cityObj.setAttribute("id", "cityDiv"); cityObj.setAttribute("align", "center"); cityObj.style.background = "white"; cityObj.style.border = "1px solid " + bordercolor; cityObj.style.position = "absolute"; if (screen.width == 1366) { cityObj.style.left = event.clientX - 180; cityObj.style.top = event.clientY - 150; } if (screen.width == 1280) { cityObj.style.left = event.clientX; cityObj.style.top = event.clientY; } cityObj.style.font = "12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif"; cityObj.style.marginLeft = "-225px"; //cityObj.style.marginTop = -75 + document.documentElement.scrollTop + "px"; cityObj.style.width = cityw + "px"; cityObj.style.height = "auto"; //cityh + "px"; cityObj.style.textAlign = "left"; cityObj.style.lineHeight = "25px"; cityObj.style.zIndex = "1"; cityObj.style.overflow = "auto"; document.getElementById("msgDiv").appendChild(cityObj); // var proid; proid = this.value; var provicename = this.id; var cityNodes = xmlPro.getElementsByTagName("Province")[proid].childNodes; //创建table var table = document.createElement('table'); table.setAttribute("id", "tableSchool"); table.setAttribute("width", '98%'); table.setAttribute("cellpadding", '3'); table.setAttribute("cellspacing", '0'); var row = table.insertRow(); var col = row.insertCell(); col.setAttribute("id", provicename); col.setAttribute("value", proid); col.setAttribute("className", "border:1px solid #9BC2E0;"); col.setAttribute("colspan", "4"); col.style.fontWeight = "Bold"; col.setAttribute("align", "left"); col.style.fontSize = "13px"; col.style.color = "#336699"; col.innerHTML = "·" + provicename; row = table.insertRow(); for (var j = 0; j < cityNodes.length; j++) { cityname = cityNodes[j].childNodes[0].nodeValue; cityid = cityNodes[j].getAttribute("ID"); col = row.insertCell(); col.setAttribute("id", cityname); col.setAttribute("value", cityid); col.setAttribute("className", "border:1px solid #9BC2E0;"); col.setAttribute("align", "left"); col.style.fontSize = "12px"; col.style.color = "#336699"; col.style.cursor = "pointer"; col.onclick = checkcity; col.onmouseover = OverchangeColor; col.onmouseout = OutchangeColor; col.innerHTML = "·" + cityname; if (j != 0 && (j + 1) % 4 == 0) { row = table.insertRow(); } } document.getElementById("cityDiv").appendChild(table); } function checkpro() {//选中省份 var proname = this.id; var cityObj = document.getElementById("cityDiv"); var msgObj = document.getElementById("msgDiv"); var bgObj = document.getElementById("bgDiv"); if (cityObj != null) { document.getElementById("msgDiv").removeChild(cityObj); } return; document.body.removeChild(bgObj); document.body.removeChild(msgObj); //document.getElementById("area").value = proname; document.getElementById("ctl00_ContentPlaceHolder1_Hidden_Area").value = proname; } function checkcity() {//选中城市 var cityname = this.id; var cityid = this.value; //alert(cityid); var proname = xmlPro.getElementsByTagName("City")[cityid].parentNode.getAttribute("Name"); //根据城市id获取省份名称 //alert(proname); var cityObj = document.getElementById("cityDiv"); var msgObj = document.getElementById("msgDiv"); var bgObj = document.getElementById("bgDiv"); if (cityObj != null) { document.getElementById("msgDiv").removeChild(cityObj); } document.body.removeChild(bgObj); document.body.removeChild(msgObj); //document.getElementById("area").value = proname + "+" + cityname; document.getElementById("ctl00_ContentPlaceHolder1_Hidden_Area").value = proname + "+" + cityname; } function OverchangeColor() { this.style.color = "#CC6600"; } function OutchangeColor() { this.style.color = "#336699"; }
JavaScript
var searchData= [ ['pi',['pi',['../cellmath_8h.html#a1daf785e3f68d293c7caa1c756d5cb74',1,'pi():&#160;cellmath.h'],['../glwidget_8h.html#a1daf785e3f68d293c7caa1c756d5cb74',1,'pi():&#160;glwidget.h']]] ];
JavaScript
var searchData= [ ['lastpos',['lastPos',['../class_g_l_widget.html#a9fb7fece62b92f7a0bb4167ea1e05c28',1,'GLWidget']]], ['lastselectobject',['lastSelectObject',['../class_select_object_command.html#a9541c3a0465cb001255cd0d72e8da708',1,'SelectObjectCommand']]], ['leftpart',['leftPart',['../class_cell_main_window.html#ae6cbeab1770540ff52c627137e4674ae',1,'CellMainWindow']]], ['linebutton',['lineButton',['../class_cell_main_window.html#a1f59a5dbbba2398a1cdf8fe61f3a17ad',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['labelstyle',['LabelStyle',['../stylesheet_8cpp.html#ad4710621d3d2708f8f76eb980078e4b6',1,'LabelStyle():&#160;stylesheet.cpp'],['../stylesheet_8h.html#ad4710621d3d2708f8f76eb980078e4b6',1,'LabelStyle():&#160;stylesheet.cpp']]], ['lastpos',['lastPos',['../class_g_l_widget.html#a9fb7fece62b92f7a0bb4167ea1e05c28',1,'GLWidget']]], ['lastselectobject',['lastSelectObject',['../class_select_object_command.html#a9541c3a0465cb001255cd0d72e8da708',1,'SelectObjectCommand']]], ['leftpart',['leftPart',['../class_cell_main_window.html#ae6cbeab1770540ff52c627137e4674ae',1,'CellMainWindow']]], ['lenght',['Lenght',['../class_vector3.html#af14c1570f3ac79f1ab8f09cc3200b51b',1,'Vector3']]], ['linebutton',['lineButton',['../class_cell_main_window.html#a1f59a5dbbba2398a1cdf8fe61f3a17ad',1,'CellMainWindow']]], ['lineeditstyle',['LineEditStyle',['../stylesheet_8cpp.html#a75a2be1d1c0696663b4f1ffc7815d0d6',1,'LineEditStyle():&#160;stylesheet.cpp'],['../stylesheet_8h.html#a75a2be1d1c0696663b4f1ffc7815d0d6',1,'LineEditStyle():&#160;stylesheet.cpp']]], ['lineintersection',['lineIntersection',['../class_cell_math.html#a2701b1d56419b4119a9b647706891897',1,'CellMath']]], ['lineintersectiontriangle',['lineIntersectionTriangle',['../class_cell_math.html#a230f3ac0ddea2ea8b337f55f0999ed86',1,'CellMath']]] ];
JavaScript
var searchData= [ ['vector3',['Vector3',['../class_vector3.html',1,'']]], ['vertex3',['Vertex3',['../class_vertex3.html',1,'']]] ];
JavaScript
var searchData= [ ['helpmenu',['helpMenu',['../class_cell_main_window.html#a21d71143834026197b511eb200333313',1,'CellMainWindow']]], ['homepage',['Homepage',['../index.html',1,'']]] ];
JavaScript
var searchData= [ ['glwidget_2ecpp',['glwidget.cpp',['../glwidget_8cpp.html',1,'']]], ['glwidget_2eh',['glwidget.h',['../glwidget_8h.html',1,'']]], ['glwidget_5fcsg_2ecpp',['glwidget_csg.cpp',['../glwidget__csg_8cpp.html',1,'']]], ['glwidget_5fdraw_2ecpp',['glwidget_draw.cpp',['../glwidget__draw_8cpp.html',1,'']]], ['glwidget_5fdrawobject_2ecpp',['glwidget_drawobject.cpp',['../glwidget__drawobject_8cpp.html',1,'']]], ['glwidget_5feditmesh_2ecpp',['glwidget_editmesh.cpp',['../glwidget__editmesh_8cpp.html',1,'']]], ['glwidget_5finput_2ecpp',['glwidget_input.cpp',['../glwidget__input_8cpp.html',1,'']]], ['glwidget_5fpick_2ecpp',['glwidget_pick.cpp',['../glwidget__pick_8cpp.html',1,'']]] ];
JavaScript
var searchData= [ ['frompolygons',['fromPolygons',['../class_c_s_g.html#a404d410933b49cbebc05019b495b954b',1,'CSG']]] ];
JavaScript
var searchData= [ ['back',['back',['../class_node.html#ab33aad003480968839f7344f3c31bbc1',1,'Node']]], ['basementmembranewidget',['basementMembraneWidget',['../class_cell_main_window.html#a5cdf7e845f7891c5292dcc7c26975b92',1,'CellMainWindow']]], ['bloodvesselwidget',['bloodVesselWidget',['../class_cell_main_window.html#a692ac72f7d4f0242f5f36bbb180a4eca',1,'CellMainWindow']]], ['booleanmenu',['booleanMenu',['../class_cell_main_window.html#a50e817a7acd8ba5f316e6c362e7de9c7',1,'CellMainWindow']]], ['box',['box',['../class_my_polygon.html#a26030d5e4b329b159a92a908af03364d',1,'MyPolygon::box()'],['../class_node.html#abf02cf739e251d070b594c309e3c3abe',1,'Node::box()']]] ];
JavaScript
var searchData= [ ['bufsize',['BUFSIZE',['../common_8h.html#aeca034f67218340ecb2261a22c2f3dcd',1,'common.h']]] ];
JavaScript
var searchData= [ ['aabb_5fmax',['aabb_max',['../class_a_a_b_b_box.html#a4f4e5369d3d3ab1d0783ecdfddc3dc6c',1,'AABBBox']]], ['aabb_5fmin',['aabb_min',['../class_a_a_b_b_box.html#a9930a034b8f8b00e7976bfd8ad910719',1,'AABBBox']]], ['axisx',['axisX',['../class_cell_object.html#af03833e2a001c1c532eb7dc7d5b9036f',1,'CellObject::axisX()'],['../class_intersection_plane.html#af17766c1ddf0cc4d011407cfabbb25bb',1,'IntersectionPlane::axisX()']]], ['axisy',['axisY',['../class_cell_object.html#a6f3283c3f5eb1646c32d2d8b7a356ea3',1,'CellObject::axisY()'],['../class_intersection_plane.html#aafaf467a11d1e5977c055d7d38430cbb',1,'IntersectionPlane::axisY()']]], ['axisz',['axisZ',['../class_cell_object.html#a199f935c9636276d50cc77ede88055cb',1,'CellObject::axisZ()'],['../class_intersection_plane.html#a38e4c7364f3e54d00bca42a756034d44',1,'IntersectionPlane::axisZ()']]] ];
JavaScript
var searchData= [ ['dtor',['DTOR',['../cellobject_8cpp.html#a06e28c801ea48dde51889eb3c4836c78',1,'cellobject.cpp']]] ];
JavaScript
var searchData= [ ['vector3',['Vector3',['../class_vector3.html#a0f49191f7e001e7f7ae1cb49522118b4',1,'Vector3::Vector3()'],['../class_vector3.html#a61caf3c2269cee584e55c84a6ec0a475',1,'Vector3::Vector3(double a, double b, double c)']]], ['vertex3',['Vertex3',['../class_vertex3.html#a76436502bf82862107c0303b5d7142a6',1,'Vertex3']]], ['viewtoolgroupclicked',['viewToolGroupClicked',['../class_cell_main_window.html#ab1cfac173c12c12be1af639551920000',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['keypressevent',['keyPressEvent',['../class_cell_main_window.html#aa2007d9d894b01594491685203c1308a',1,'CellMainWindow']]], ['keyreleaseevent',['keyReleaseEvent',['../class_cell_main_window.html#a9ceba7c569c30cf6f17fede643a68f13',1,'CellMainWindow']]], ['keyvalue',['keyValue',['../class_g_l_widget.html#a29d90308b20a67e54457c66e22f0014d',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['paintgl',['paintGL',['../class_g_l_widget.html#a640b5570cb2b37724fd5b58a77339c5e',1,'GLWidget']]], ['painttoolgroupclicked',['paintToolGroupClicked',['../class_cell_main_window.html#a8d31f35d9da83a654153c99ccfce1c3f',1,'CellMainWindow']]], ['paste',['paste',['../class_cell_main_window.html#a4f83ec1116cc028d07c6fe13c2e1fec0',1,'CellMainWindow']]], ['pasteobject',['pasteObject',['../class_g_l_widget.html#a7bc8e64fed1473911836820c70bec614',1,'GLWidget']]], ['pick',['pick',['../class_g_l_widget.html#acb1d50634e92282082c9f3a6044d298f',1,'GLWidget']]], ['pickeditface',['pickEditFace',['../class_g_l_widget.html#a6d14bca61d266bbca3078d057f5d1bba',1,'GLWidget']]], ['pickeditmeshtranslateaxis',['pickEditMeshTranslateAxis',['../class_g_l_widget.html#a82290b60810c32555b17b741449fbbb4',1,'GLWidget']]], ['pickeditpoint',['pickEditPoint',['../class_g_l_widget.html#a3284bcb2366d178eeb1bad60550995c4',1,'GLWidget']]], ['pickfacesinarea',['pickFacesInArea',['../class_g_l_widget.html#aa61b5c8170029df829f904aaabba1ad6',1,'GLWidget']]], ['pickinfourview',['pickInFourView',['../class_g_l_widget.html#ac0b1d5f9a7fac1894f21806542b926b9',1,'GLWidget']]], ['pickpointsinarea',['pickPointsInArea',['../class_g_l_widget.html#a77d810f334b97ebbd9d7b9423fce4c57',1,'GLWidget']]], ['pickrotateaxis',['pickRotateAxis',['../class_g_l_widget.html#a350afea0fcb61179e884ad772bb7df69',1,'GLWidget']]], ['pickscaleaxis',['pickScaleAxis',['../class_g_l_widget.html#a544d0e0b1ba6a38b091617beeb53b48c',1,'GLWidget']]], ['picktranslateaxis',['pickTranslateAxis',['../class_g_l_widget.html#a807c64e9b6c79f44f2040e00ccacd31b',1,'GLWidget']]], ['plane',['Plane',['../class_plane.html#a2ac0fd939beb69bf926faae570f4266f',1,'Plane']]], ['processhits',['processHits',['../class_g_l_widget.html#aa2831ece6db8ee743e0eb883aef6eeba',1,'GLWidget']]], ['pushbuttonstyle',['PushButtonStyle',['../stylesheet_8cpp.html#a4439301edf3ab83835cfd1194b5844e2',1,'PushButtonStyle(const QString &amp;img):&#160;stylesheet.cpp'],['../stylesheet_8h.html#a4439301edf3ab83835cfd1194b5844e2',1,'PushButtonStyle(const QString &amp;img):&#160;stylesheet.cpp']]] ];
JavaScript
var searchData= [ ['helpmenu',['helpMenu',['../class_cell_main_window.html#a21d71143834026197b511eb200333313',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['glwidget',['GLWidget',['../class_g_l_widget.html',1,'']]] ];
JavaScript
var searchData= [ ['x',['x',['../class_vector3.html#a60aa84ebc037dec9faba617f8ddb231d',1,'Vector3']]] ];
JavaScript
var searchData= [ ['vertice',['vertice',['../class_cell_object.html#a4b91e554356b29c6fe876b2a2e7dec1a',1,'CellObject']]], ['vertice_5fnum',['vertice_num',['../class_cell_object.html#a0e21c1b3ce66d6ee6ebceffb48a8f9fa',1,'CellObject']]], ['vertices',['vertices',['../class_my_polygon.html#aadfabb5de0ca01b232a6b5faa78ed4f4',1,'MyPolygon']]], ['viewmode',['viewMode',['../class_g_l_widget.html#ac40074e2de80bfae3e2c0434a30b5949',1,'GLWidget']]], ['viewtoolgroup',['viewToolGroup',['../class_cell_main_window.html#a9a51ad1bca96792a706f8655e2210b36',1,'CellMainWindow']]], ['viewtoolwidget',['viewToolWidget',['../class_cell_main_window.html#a873903508a408bb1f12197fb878bb978',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['wheelevent',['wheelEvent',['../class_g_l_widget.html#a5702a23f7cf42d05fe55a417d810a4b6',1,'GLWidget']]], ['widgetstyle',['WidgetStyle',['../stylesheet_8cpp.html#a9fa4b085490b3d073f76665501f65a17',1,'WidgetStyle():&#160;stylesheet.cpp'],['../stylesheet_8h.html#a9fa4b085490b3d073f76665501f65a17',1,'WidgetStyle():&#160;stylesheet.cpp']]] ];
JavaScript
var searchData= [ ['node',['Node',['../class_node.html',1,'']]] ];
JavaScript
var searchData= [ ['qscrollareastyle',['QScrollAreaStyle',['../stylesheet_8cpp.html#aff5a04a7dd345cbd50d2a3b893ea493d',1,'QScrollAreaStyle():&#160;stylesheet.cpp'],['../stylesheet_8h.html#aff5a04a7dd345cbd50d2a3b893ea493d',1,'QScrollAreaStyle():&#160;stylesheet.cpp']]] ];
JavaScript
var searchData= [ ['bpa',['BPA',['../class_b_p_a.html#a835a931279554e707ecaf2a25fef4fb5',1,'BPA']]], ['build',['build',['../class_node.html#a83102db3d3c1ce624bf3d78e145103fc',1,'Node']]], ['buildcone',['buildCone',['../class_cell_object.html#a7ff84b62058366ff9990798797654558',1,'CellObject']]], ['buildcube',['buildCube',['../class_cell_object.html#a44d19baaa2a6b2e155b54f9e0d3fd447',1,'CellObject']]], ['buildcylinder',['buildCylinder',['../class_cell_object.html#a2678fde0d94ce34a17a79dc61a5a528b',1,'CellObject']]], ['buildobject',['buildObject',['../class_cell_object.html#a9f873b83c6351b51678c2e2faa033fea',1,'CellObject']]], ['buildopencylinder',['buildOpenCylinder',['../class_cell_object.html#ac5dbe0ce8d5e74fe36b04facd4b111cc',1,'CellObject']]], ['buildplane',['buildPlane',['../class_cell_object.html#a77d8e2e274b9a04284d22b4137c9e911',1,'CellObject']]], ['buildsphere',['buildSphere',['../class_cell_object.html#a38522df55fd7263d604f9ab0f4847af2',1,'CellObject']]] ];
JavaScript
var searchData= [ ['bpa',['BPA',['../class_b_p_a.html',1,'']]] ];
JavaScript
var searchData= [ ['qscrollareastyle',['QScrollAreaStyle',['../stylesheet_8cpp.html#aff5a04a7dd345cbd50d2a3b893ea493d',1,'QScrollAreaStyle():&#160;stylesheet.cpp'],['../stylesheet_8h.html#aff5a04a7dd345cbd50d2a3b893ea493d',1,'QScrollAreaStyle():&#160;stylesheet.cpp']]] ];
JavaScript
var searchData= [ ['unioncommand',['UnionCommand',['../class_union_command.html',1,'']]] ];
JavaScript
var searchData= [ ['stylesheet_2ecpp',['stylesheet.cpp',['../stylesheet_8cpp.html',1,'']]], ['stylesheet_2eh',['stylesheet.h',['../stylesheet_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['cross',['Cross',['../class_vector3.html#ab271ae54719908906f1acf4d60668547',1,'Vector3']]] ];
JavaScript
var searchData= [ ['deleteface',['deleteFace',['../class_cell_object.html#a03dafda22c9588986336121914c3602a',1,'CellObject']]], ['deletepoint',['deletePoint',['../class_cell_object.html#a13940c0740614f4a7e04d17396ed1b00',1,'CellObject']]], ['dispalymodetoolgroup',['dispalyModeToolGroup',['../class_cell_main_window.html#a1e3e2c98834722739fafda138478dfd7',1,'CellMainWindow']]], ['displaymenu',['displayMenu',['../class_cell_main_window.html#abe9dfeec24becc5a804169d0b5accf88',1,'CellMainWindow']]], ['displaymode',['displayMode',['../class_g_l_widget.html#a354e4fd124a8f522ac52ecbb1f1a6d3c',1,'GLWidget']]], ['displaymodetoolwidget',['displayModeToolWidget',['../class_cell_main_window.html#a0b7f8c87952109d36313861cef663f93',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['operator_2a',['operator*',['../class_vector3.html#a8eb7b80968ff52ad83d1010fc717fd50',1,'Vector3::operator*()'],['../class_vector3.html#ab27ca5627cbe91c355b16a323e6ef1ca',1,'Vector3::operator*()'],['../class_vector3.html#a6d1842ad958eba8bc7ec9de0c46e3d7d',1,'Vector3::operator*()']]], ['operator_2b',['operator+',['../class_vector3.html#ab7e44563aab6a2c1231aee03ca792b9a',1,'Vector3']]], ['operator_2d',['operator-',['../class_vector3.html#af6a71d8f6c8d21c22d4025faa286d396',1,'Vector3']]], ['operator_2f',['operator/',['../class_vector3.html#a47e8c3cc81129fb021e68339f3be06f4',1,'Vector3']]], ['operator_3d_3d',['operator==',['../class_vector3.html#a41f163265cb2926e79b8e26fa8fc06d8',1,'Vector3']]] ];
JavaScript
var searchData= [ ['labelstyle',['LabelStyle',['../stylesheet_8cpp.html#ad4710621d3d2708f8f76eb980078e4b6',1,'LabelStyle():&#160;stylesheet.cpp'],['../stylesheet_8h.html#ad4710621d3d2708f8f76eb980078e4b6',1,'LabelStyle():&#160;stylesheet.cpp']]], ['lenght',['Lenght',['../class_vector3.html#af14c1570f3ac79f1ab8f09cc3200b51b',1,'Vector3']]], ['lineeditstyle',['LineEditStyle',['../stylesheet_8cpp.html#a75a2be1d1c0696663b4f1ffc7815d0d6',1,'LineEditStyle():&#160;stylesheet.cpp'],['../stylesheet_8h.html#a75a2be1d1c0696663b4f1ffc7815d0d6',1,'LineEditStyle():&#160;stylesheet.cpp']]], ['lineintersection',['lineIntersection',['../class_cell_math.html#a2701b1d56419b4119a9b647706891897',1,'CellMath']]], ['lineintersectiontriangle',['lineIntersectionTriangle',['../class_cell_math.html#a230f3ac0ddea2ea8b337f55f0999ed86',1,'CellMath']]] ];
JavaScript
var searchData= [ ['translatecommand',['TranslateCommand',['../class_translate_command.html',1,'']]] ];
JavaScript
var searchData= [ ['keyvalue',['keyValue',['../class_g_l_widget.html#a29d90308b20a67e54457c66e22f0014d',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['cellmainwindow',['CellMainWindow',['../class_cell_main_window.html',1,'']]], ['cellmath',['CellMath',['../class_cell_math.html',1,'']]], ['cellobject',['CellObject',['../class_cell_object.html',1,'']]], ['csg',['CSG',['../class_c_s_g.html',1,'']]], ['cubeinputcommand',['CubeInputCommand',['../class_cube_input_command.html',1,'']]], ['cylinderinputcommand',['CylinderInputCommand',['../class_cylinder_input_command.html',1,'']]] ];
JavaScript
var searchData= [ ['plane',['Plane',['../class_plane.html',1,'']]] ];
JavaScript
var searchData= [ ['back',['back',['../class_node.html#ab33aad003480968839f7344f3c31bbc1',1,'Node']]], ['basementmembranewidget',['basementMembraneWidget',['../class_cell_main_window.html#a5cdf7e845f7891c5292dcc7c26975b92',1,'CellMainWindow']]], ['bloodvesselwidget',['bloodVesselWidget',['../class_cell_main_window.html#a692ac72f7d4f0242f5f36bbb180a4eca',1,'CellMainWindow']]], ['booleanmenu',['booleanMenu',['../class_cell_main_window.html#a50e817a7acd8ba5f316e6c362e7de9c7',1,'CellMainWindow']]], ['box',['box',['../class_my_polygon.html#a26030d5e4b329b159a92a908af03364d',1,'MyPolygon::box()'],['../class_node.html#abf02cf739e251d070b594c309e3c3abe',1,'Node::box()']]], ['bpa',['BPA',['../class_b_p_a.html',1,'BPA'],['../class_b_p_a.html#a835a931279554e707ecaf2a25fef4fb5',1,'BPA::BPA()']]], ['bpa_2ecpp',['bpa.cpp',['../bpa_8cpp.html',1,'']]], ['bpa_2eh',['bpa.h',['../bpa_8h.html',1,'']]], ['bufsize',['BUFSIZE',['../common_8h.html#aeca034f67218340ecb2261a22c2f3dcd',1,'common.h']]], ['build',['build',['../class_node.html#a83102db3d3c1ce624bf3d78e145103fc',1,'Node']]], ['buildcone',['buildCone',['../class_cell_object.html#a7ff84b62058366ff9990798797654558',1,'CellObject']]], ['buildcube',['buildCube',['../class_cell_object.html#a44d19baaa2a6b2e155b54f9e0d3fd447',1,'CellObject']]], ['buildcylinder',['buildCylinder',['../class_cell_object.html#a2678fde0d94ce34a17a79dc61a5a528b',1,'CellObject']]], ['buildobject',['buildObject',['../class_cell_object.html#a9f873b83c6351b51678c2e2faa033fea',1,'CellObject']]], ['buildopencylinder',['buildOpenCylinder',['../class_cell_object.html#ac5dbe0ce8d5e74fe36b04facd4b111cc',1,'CellObject']]], ['buildplane',['buildPlane',['../class_cell_object.html#a77d8e2e274b9a04284d22b4137c9e911',1,'CellObject']]], ['buildsphere',['buildSphere',['../class_cell_object.html#a38522df55fd7263d604f9ab0f4847af2',1,'CellObject']]] ];
JavaScript
var searchData= [ ['w',['w',['../class_my_polygon.html#a385fecc2be056e66ef767cf1c7672faa',1,'MyPolygon::w()'],['../class_plane.html#a2eb55b72cfed8e065ea2bd71a3b01db2',1,'Plane::w()']]], ['windowheight',['windowHeight',['../class_g_l_widget.html#a5836a4a1ab022883c9d0cf63974dd590',1,'GLWidget']]], ['windowwidth',['windowWidth',['../class_g_l_widget.html#a4b215b2bafba14dafe139bc0e342bd9d',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['intersectionplane_2ecpp',['intersectionplane.cpp',['../intersectionplane_8cpp.html',1,'']]], ['intersectionplane_2eh',['intersectionplane.h',['../intersectionplane_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['yrotationchanged',['yRotationChanged',['../class_g_l_widget.html#a0a8a85d18e3fedd7461cca6575095d7f',1,'GLWidget']]], ['yscalationchanged',['yScalationChanged',['../class_g_l_widget.html#a0f02e08fc0e8bc6b69039947949cbefc',1,'GLWidget']]], ['ytanslationchanged',['yTanslationChanged',['../class_g_l_widget.html#af9f20365b6859e5b2becfad6944a52ec',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['cameramovebutton',['cameraMoveButton',['../class_cell_main_window.html#ac1c20972851172ec544e5354afcf0e2c',1,'CellMainWindow']]], ['camerarotatebutton',['cameraRotateButton',['../class_cell_main_window.html#a094da8891d785f3bc081e28751a75432',1,'CellMainWindow']]], ['cameratoolgroup',['cameraToolGroup',['../class_cell_main_window.html#a0c04ee64c6a800d65a8e346571827a98',1,'CellMainWindow']]], ['cameratoolwidget',['cameraToolWidget',['../class_cell_main_window.html#a31d56187b16c6cc51940fb90b4ad312f',1,'CellMainWindow']]], ['camerazoombutton',['cameraZoomButton',['../class_cell_main_window.html#af2ab4abd9d3917da7e36b80557da779b',1,'CellMainWindow']]], ['cellwidget',['cellWidget',['../class_cell_main_window.html#af362c56d9a26df4a0816f65c21fcd581',1,'CellMainWindow']]], ['centerlayout',['centerLayout',['../class_cell_main_window.html#a9327b5fdabca31abba80496e77ba8ae4',1,'CellMainWindow']]], ['centralwidget',['centralWidget',['../class_cell_main_window.html#a4e3f239fde4a3a2201caba16e5b18e03',1,'CellMainWindow']]], ['changedobject',['changedObject',['../class_mesh_changed_command.html#a39462b94da2cf4c05afa016685136e24',1,'MeshChangedCommand']]], ['clustering',['clustering',['../class_b_p_a.html#ae76b712e9c0adddbe20c547467fc2b9a',1,'BPA']]], ['copyaction',['copyAction',['../class_cell_main_window.html#a89e370ca1a5091f21dc3b86befbf2a4f',1,'CellMainWindow']]], ['copyactiontb',['copyActionTB',['../class_cell_main_window.html#ae7b37807a0cf60fec31fe74f3453eaf6',1,'CellMainWindow']]], ['copyobject',['copyObject',['../class_g_l_widget.html#adc5a9364e846d017e8b73b87771af995',1,'GLWidget']]], ['csgobject',['csgObject',['../class_cell_object.html#a4a50cc71aaaf732f50c235686f864209',1,'CellObject']]], ['cubedepth',['cubeDepth',['../class_cell_object.html#ac371e5980701c1c9fe236773f18ac8d1',1,'CellObject']]], ['cubedepthseg',['cubeDepthSeg',['../class_cell_object.html#afd712fc9d9578aca0376fb8170c935e6',1,'CellObject']]], ['cubeheight',['cubeHeight',['../class_cell_object.html#a8ee898efdf140d26bff610f5bd6235f6',1,'CellObject']]], ['cubeheightseg',['cubeHeightSeg',['../class_cell_object.html#a7fd7e9c89ae8bd0944796ee4b187564f',1,'CellObject']]], ['cubeinputwidget',['cubeInputWidget',['../class_cell_main_window.html#add3e94cd88ddb15714cd901bf41df6d7',1,'CellMainWindow']]], ['cubenum',['cubeNum',['../class_g_l_widget.html#a16729acdcb4b0c30cea1f9ab5f6e0786',1,'GLWidget']]], ['cubewidth',['cubeWidth',['../class_cell_object.html#af30828580a04174a25eb071f87021cee',1,'CellObject']]], ['cubewidthseg',['cubeWidthSeg',['../class_cell_object.html#abd24ef948d20c41477ea4b441125c4be',1,'CellObject']]], ['cutaction',['cutAction',['../class_cell_main_window.html#a9d98ff2ca448c2de1a379d5dc79ebd0f',1,'CellMainWindow']]], ['cutactiontb',['cutActionTB',['../class_cell_main_window.html#aa02a409beb9ee5d103871b0406e937ca',1,'CellMainWindow']]], ['cutobject',['cutObject',['../class_g_l_widget.html#a163191dbf7a1949f9485753da2353850',1,'GLWidget']]], ['cylinderaxisseg',['cylinderAxisSeg',['../class_cell_object.html#a3b0c9bd91c5f890d71147357b8d6d25c',1,'CellObject']]], ['cylinderheight',['cylinderHeight',['../class_cell_object.html#a35b37d2543cf18eb009c2f4289ea736f',1,'CellObject']]], ['cylinderheightseg',['cylinderHeightSeg',['../class_cell_object.html#abf2f5f37c4c426ab21849ab493480d14',1,'CellObject']]], ['cylinderinputwidget',['cylinderInputWidget',['../class_cell_main_window.html#a4699e866bc546da5ae71aa20b92a2c8c',1,'CellMainWindow']]], ['cylindernum',['cylinderNum',['../class_g_l_widget.html#a0ce1278ca9b4cbe3d313fcd0330fb39a',1,'GLWidget']]], ['cylinderradius',['cylinderRadius',['../class_cell_object.html#a1ac8f9c6e351053dcf8adf370e0af362',1,'CellObject']]] ];
JavaScript
var searchData= [ ['ecmwidget',['ECMWidget',['../class_cell_main_window.html#ac223b036daf9ed474aa6e37ef7bcf26a',1,'CellMainWindow']]], ['editfeather',['editFeather',['../class_g_l_widget.html#aa7038cf26533086753646f3bd1762ad9',1,'GLWidget']]], ['editmenu',['editMenu',['../class_cell_main_window.html#ac117ac218e3e3e05830b7210763b15e9',1,'CellMainWindow']]], ['editmeshaction',['editMeshAction',['../class_cell_main_window.html#ac47975a57a809c91c360a795e79b80b3',1,'CellMainWindow']]], ['editmeshdockwidget',['editMeshDockWidget',['../class_cell_main_window.html#a1417f8b60ae8a27e134a2339b975be55',1,'CellMainWindow']]], ['editmeshwidget',['editMeshWidget',['../class_cell_main_window.html#a2640959fe15afb60faf35ad65e62e9a1',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['y',['y',['../class_vector3.html#ae4965693beffdb6069e0618222cae459',1,'Vector3']]] ];
JavaScript
var searchData= [ ['unchangedobject',['unchangedObject',['../class_mesh_changed_command.html#afc042cc2effc31571c186f5ffca091bf',1,'MeshChangedCommand']]], ['undoaction',['undoAction',['../class_cell_main_window.html#ab2d8289a94600d80e99a7953c15a680d',1,'CellMainWindow']]], ['undoactiontb',['undoActionTB',['../class_cell_main_window.html#a39376f16cd2610da684d492a316526cf',1,'CellMainWindow']]], ['undostack',['undoStack',['../class_cell_main_window.html#aedeaac3850722bf0624733ac2933d45c',1,'CellMainWindow']]], ['unionaction',['unionAction',['../class_cell_main_window.html#a5ab9cb7a59fc99c964d5dc957ef1c875',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['zrotationchanged',['zRotationChanged',['../class_g_l_widget.html#a06bc36cd7b8c19fec218165037e1c56d',1,'GLWidget']]], ['zscalationchanged',['zScalationChanged',['../class_g_l_widget.html#aefb767552fb4b476e4c8aa720f3eac80',1,'GLWidget']]], ['ztanslationchanged',['zTanslationChanged',['../class_g_l_widget.html#a9616c8f342baa005778d29762239a479',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['dot',['Dot',['../class_vector3.html#a7dbfb016a8ed359b7d287c964b26f274',1,'Vector3']]] ];
JavaScript
var searchData= [ ['homepage',['Homepage',['../index.html',1,'']]] ];
JavaScript
var searchData= [ ['xrotationchanged',['xRotationChanged',['../class_g_l_widget.html#a9d0c92030343892bf152f669815047cb',1,'GLWidget']]], ['xscalationchanged',['xScalationChanged',['../class_g_l_widget.html#a6fa37cb9d39008465caf53312c8a5ae0',1,'GLWidget']]], ['xtanslationchanged',['xTanslationChanged',['../class_g_l_widget.html#aaa8e475f101152a5bc0673faa3eb2fd1',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['m',['m',['../class_b_p_a.html#aa7bc2f2a789d4562a0b76e10adfa8406',1,'BPA']]], ['mesheditmodegroup',['meshEditModeGroup',['../class_cell_main_window.html#a8e86066157b03f76299042b0aad6ab04',1,'CellMainWindow']]], ['meshnum',['meshNum',['../class_g_l_widget.html#a57f6f2c71ab6ccacf664e9ed1dca6cc8',1,'GLWidget']]], ['mode',['mode',['../class_g_l_widget.html#ae6797d28507b8c27bb18b0e02b1a824e',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['getaxisx',['getAxisX',['../class_cell_object.html#a5f1d3f245b7b26b5998361ce4c313539',1,'CellObject']]], ['getaxisy',['getAxisY',['../class_cell_object.html#ae465329518ba914721422f3193578c44',1,'CellObject']]], ['getaxisz',['getAxisZ',['../class_cell_object.html#a9f0cfaea167657b5826832b398e6d186',1,'CellObject']]], ['getcsg',['getCSG',['../class_cell_object.html#adb4695833a5f3a632968ab0a49840e41',1,'CellObject']]], ['getcubedepth',['getCubeDepth',['../class_cell_object.html#a14b5f50e42f8b5b7aac4c1ec9a0e75ed',1,'CellObject']]], ['getcubedepthseg',['getCubeDepthSeg',['../class_cell_object.html#aefb8b0e3ce23dc118d5a0b3f3359f59c',1,'CellObject']]], ['getcubeheight',['getCubeHeight',['../class_cell_object.html#a39b25ba597d18f60c4b298bce756f549',1,'CellObject']]], ['getcubeheightseg',['getCubeHeightSeg',['../class_cell_object.html#a584ed3d5ad1340b3080bcde1a6d4ea8c',1,'CellObject']]], ['getcubenum',['getCubeNum',['../class_g_l_widget.html#ade1a2469fee074fe54954d3d06086bbb',1,'GLWidget']]], ['getcubewidth',['getCubeWidth',['../class_cell_object.html#a0ae2886022b94f59a3d100111fd67ae7',1,'CellObject']]], ['getcubewidthseg',['getCubeWidthSeg',['../class_cell_object.html#a3fe45637d958ade8d214288fc3a22b18',1,'CellObject']]], ['getcylinderaxisseg',['getCylinderAxisSeg',['../class_cell_object.html#a89a06b6ba84b0e2cb4187c0cafeaedb1',1,'CellObject']]], ['getcylinderheight',['getCylinderHeight',['../class_cell_object.html#a444832cd292d311022487c3c71e34309',1,'CellObject']]], ['getcylinderheightseg',['getCylinderHeightSeg',['../class_cell_object.html#ad23b2575c3d30a7b9952dd0f0c58505c',1,'CellObject']]], ['getcylindernum',['getCylinderNum',['../class_g_l_widget.html#a0649a85a7848138556ade3357360f0d8',1,'GLWidget']]], ['getcylinderradius',['getCylinderRadius',['../class_cell_object.html#af293d16236bd942af101cd9a992f4e80',1,'CellObject']]], ['getface',['getFace',['../class_cell_object.html#a96963a11106dbafc35f0c601fd0bd1e0',1,'CellObject']]], ['getfacenum',['getFaceNum',['../class_cell_object.html#a5474ebf6405f663a202f04d5fda9713f',1,'CellObject']]], ['getglandular',['getGlandular',['../class_g_l_widget.html#a69267306e13fa430b2955220dcc7393a',1,'GLWidget']]], ['getindexvertex',['GetIndexVertex',['../class_b_p_a.html#a57ffa971dd81d9f65adadd1685b6993b',1,'BPA']]], ['getmode',['getMode',['../class_g_l_widget.html#ad3b8e9e3b95716cb5a5539a14a6923bd',1,'GLWidget']]], ['getname',['getName',['../class_cell_object.html#a0d2595c4a648a0fb35aa8ef0e4d71b1d',1,'CellObject']]], ['getnormal',['getNormal',['../class_cell_object.html#a092bbee3cfb709abd154861a7bd661e0',1,'CellObject']]], ['getobjects',['getObjects',['../class_g_l_widget.html#a4d2a57f03f73490b81c4d6494f75ac4b',1,'GLWidget']]], ['getplanedepth',['getPlaneDepth',['../class_cell_object.html#a0b6f30829cfcdd5b5aa83289c5db904b',1,'CellObject']]], ['getplanedepthseg',['getPlaneDepthSeg',['../class_cell_object.html#ae46f4608b9a5fa99373081886206e088',1,'CellObject']]], ['getplanewidth',['getPlaneWidth',['../class_cell_object.html#a14d41ab3a33aa0eb8ead9b14d034fc56',1,'CellObject']]], ['getplanewidthseg',['getPlaneWidthSeg',['../class_cell_object.html#a8ab9e79bc43a9eca9f68af45fee888ca',1,'CellObject']]], ['getrotatex',['getRotateX',['../class_cell_object.html#acb7b46484d01f8a6c2a73fb9e21c7a26',1,'CellObject']]], ['getrotatey',['getRotateY',['../class_cell_object.html#a0640c9eae6b7f5a37196cfc1b07ae3d0',1,'CellObject']]], ['getrotatez',['getRotateZ',['../class_cell_object.html#ab666112ab76bb14a5e1a62c12ca1633a',1,'CellObject']]], ['getscalex',['getScaleX',['../class_cell_object.html#a3e177e622d552bb523b240ce01671a85',1,'CellObject']]], ['getscaley',['getScaleY',['../class_cell_object.html#a789a09cfc40efe4195b0f1d6004ab791',1,'CellObject']]], ['getscalez',['getScaleZ',['../class_cell_object.html#a5e391abed7e2b54fb69b1ac4633b1f98',1,'CellObject']]], ['getselectmode',['getSelectMode',['../class_g_l_widget.html#a15aca1701de489f8e9f76abbae8da44e',1,'GLWidget']]], ['getsphereaxisseg',['getSphereAxisSeg',['../class_cell_object.html#ae8262c2f8d33299f9241a31897778b73',1,'CellObject']]], ['getsphereheightseg',['getSphereHeightSeg',['../class_cell_object.html#a5763ea4621372749fabdd37f6cb63675',1,'CellObject']]], ['getspherenum',['getSphereNum',['../class_g_l_widget.html#a6c5ac108e729291abe12bda15d6debe2',1,'GLWidget']]], ['getsphereradius',['getSphereRadius',['../class_cell_object.html#a75b18c98f66bd26542bfda257ac0bfe7',1,'CellObject']]], ['gettranslatex',['getTranslateX',['../class_cell_object.html#aac7f26c2a71de1185ad0db12d16c8450',1,'CellObject']]], ['gettranslatey',['getTranslateY',['../class_cell_object.html#ab7850f79c142539f838719deea08552c',1,'CellObject']]], ['gettranslatez',['getTranslateZ',['../class_cell_object.html#a3ef77e1c665b8c9aef32851aab1133cc',1,'CellObject']]], ['gettype',['getType',['../class_cell_object.html#ac9cd4706f605bc2fa183b5bd3d4e478a',1,'CellObject']]], ['getvertice',['getVertice',['../class_cell_object.html#a4502dd8cf6bae786ae245ea071f23e48',1,'CellObject']]], ['getverticenum',['getVerticeNum',['../class_cell_object.html#ab69ffea795f5ce91e2686970081d5553',1,'CellObject']]], ['glwidget',['GLWidget',['../class_g_l_widget.html#ab79c391c86de1ffb76f6950b49d82c0c',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['vector3',['Vector3',['../class_vector3.html',1,'Vector3'],['../class_vector3.html#a0f49191f7e001e7f7ae1cb49522118b4',1,'Vector3::Vector3()'],['../class_vector3.html#a61caf3c2269cee584e55c84a6ec0a475',1,'Vector3::Vector3(double a, double b, double c)']]], ['vertex3',['Vertex3',['../class_vertex3.html',1,'Vertex3'],['../class_vertex3.html#a76436502bf82862107c0303b5d7142a6',1,'Vertex3::Vertex3()']]], ['vertice',['vertice',['../class_cell_object.html#a4b91e554356b29c6fe876b2a2e7dec1a',1,'CellObject']]], ['vertice_5fnum',['vertice_num',['../class_cell_object.html#a0e21c1b3ce66d6ee6ebceffb48a8f9fa',1,'CellObject']]], ['vertices',['vertices',['../class_my_polygon.html#aadfabb5de0ca01b232a6b5faa78ed4f4',1,'MyPolygon']]], ['viewmode',['viewMode',['../class_g_l_widget.html#ac40074e2de80bfae3e2c0434a30b5949',1,'GLWidget']]], ['viewtoolgroup',['viewToolGroup',['../class_cell_main_window.html#a9a51ad1bca96792a706f8655e2210b36',1,'CellMainWindow']]], ['viewtoolgroupclicked',['viewToolGroupClicked',['../class_cell_main_window.html#ab1cfac173c12c12be1af639551920000',1,'CellMainWindow']]], ['viewtoolwidget',['viewToolWidget',['../class_cell_main_window.html#a873903508a408bb1f12197fb878bb978',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['keypressevent',['keyPressEvent',['../class_cell_main_window.html#aa2007d9d894b01594491685203c1308a',1,'CellMainWindow']]], ['keyreleaseevent',['keyReleaseEvent',['../class_cell_main_window.html#a9ceba7c569c30cf6f17fede643a68f13',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['cell_5falt',['CELL_ALT',['../common_8h.html#a589b955d919c335b879e83031fdd5f7b',1,'common.h']]], ['cell_5fcameramove',['CELL_CAMERAMOVE',['../common_8h.html#a940a8e654763830f630c6b158d1253d2',1,'common.h']]], ['cell_5fcamerarotate',['CELL_CAMERAROTATE',['../common_8h.html#ad127931845b50333cdcaa02d12c4bf59',1,'common.h']]], ['cell_5fcamerazoom',['CELL_CAMERAZOOM',['../common_8h.html#aa13d63218deaf54af6e0b849e8de3261',1,'common.h']]], ['cell_5fcube',['CELL_CUBE',['../common_8h.html#ac67d653a5fc377e59931f04d46f0bb72',1,'common.h']]], ['cell_5fcylinder',['CELL_CYLINDER',['../common_8h.html#a03861be5ac13a4eab691f81205d0a2b1',1,'common.h']]], ['cell_5fdelete',['CELL_DELETE',['../common_8h.html#a152704f78dd4f0155e50388b6ab19808',1,'common.h']]], ['cell_5feditmeshface',['CELL_EDITMESHFACE',['../common_8h.html#a6b817de326b17821c76c401b57236176',1,'common.h']]], ['cell_5feditmeshpoint',['CELL_EDITMESHPOINT',['../common_8h.html#a76b6759a2daf85f9e8bf357d974a2aae',1,'common.h']]], ['cell_5feps',['CELL_EPS',['../common_8h.html#abf7ed52f2b67d87e264c2936ae3a6b62',1,'common.h']]], ['cell_5ffourview',['CELL_FOURVIEW',['../common_8h.html#a4fcced87452d50451bd57a3f7b2d54b0',1,'common.h']]], ['cell_5ffourviewmargin',['CELL_FOURVIEWMARGIN',['../common_8h.html#a5e078f65b26c2668eb3f396f6b5beee8',1,'common.h']]], ['cell_5ffront',['CELL_FRONT',['../common_8h.html#a1f5321598e610b4e5852627f216101b6',1,'common.h']]], ['cell_5fkeyrelease',['CELL_KEYRELEASE',['../common_8h.html#accb3bfe9a092bc6458a159c78d12cb6a',1,'common.h']]], ['cell_5fline',['CELL_LINE',['../common_8h.html#a8b5b2f8163bcf745c85c1a520627e7ce',1,'common.h']]], ['cell_5fliquidfy',['CELL_LIQUIDFY',['../common_8h.html#a9c7ef181a2761bfe33850c7cd305295c',1,'common.h']]], ['cell_5fmax',['CELL_MAX',['../common_8h.html#a52544ecf9eb10c405b059a79813e726b',1,'common.h']]], ['cell_5fmesh',['CELL_MESH',['../common_8h.html#a6037b21d2b8dfd0bd7bdd02e8a9b8484',1,'common.h']]], ['cell_5fnone',['CELL_NONE',['../common_8h.html#a7865d2da3ef8c1e41e0867a894c70242',1,'common.h']]], ['cell_5fnopaint',['CELL_NOPAINT',['../common_8h.html#a283d7c0933da61a6e63a06b5aa3b6c78',1,'common.h']]], ['cell_5fopencylinder',['CELL_OPENCYLINDER',['../common_8h.html#ae805e2699836c2557f28da863e245958',1,'common.h']]], ['cell_5fopengloffsetx',['CELL_OPENGLOFFSETX',['../common_8h.html#a74f7ee886558f57f7c3b4aec7c31af63',1,'common.h']]], ['cell_5fopengloffsety',['CELL_OPENGLOFFSETY',['../common_8h.html#a045face6cf6ac4fbd8cb6c59ab25f0da',1,'common.h']]], ['cell_5fpalnebaced',['CELL_PALNEBACED',['../common_8h.html#a439c54e03609dd66916e831c404a54d7',1,'common.h']]], ['cell_5fperspective',['CELL_PERSPECTIVE',['../common_8h.html#ae85f6d0605420f6c2befe0954cd9272a',1,'common.h']]], ['cell_5fplane',['CELL_PLANE',['../common_8h.html#a4a6820b982c2bad994b872b055d1c057',1,'common.h']]], ['cell_5fpoint',['CELL_POINT',['../common_8h.html#a2901487a310b1c1b494cd6579bcbcec8',1,'common.h']]], ['cell_5fright',['CELL_RIGHT',['../common_8h.html#a7baacc40e7b72e7b96bd1ea9ec6ae7c9',1,'common.h']]], ['cell_5frotate',['CELL_ROTATE',['../common_8h.html#a7ea573f952aea31d842440ea1faa4056',1,'common.h']]], ['cell_5frotateaxisx',['CELL_ROTATEAXISX',['../common_8h.html#af81301904f39c4d02a6f7228f8e21a5e',1,'common.h']]], ['cell_5frotateaxisy',['CELL_ROTATEAXISY',['../common_8h.html#ad9ac87d3c99ed5df7d955468d28759cc',1,'common.h']]], ['cell_5frotateaxisz',['CELL_ROTATEAXISZ',['../common_8h.html#a735ab541583cb0c8407e9bf1b9878ad4',1,'common.h']]], ['cell_5fscale',['CELL_SCALE',['../common_8h.html#af054cff9a3c480c909afaa05eac3ea44',1,'common.h']]], ['cell_5fscaleaxisx',['CELL_SCALEAXISX',['../common_8h.html#a3605965de4b9c7f76da89ac5b8386da5',1,'common.h']]], ['cell_5fscaleaxisxyz',['CELL_SCALEAXISXYZ',['../common_8h.html#ae7976a4f7dd0456bc8dd2c284c747763',1,'common.h']]], ['cell_5fscaleaxisy',['CELL_SCALEAXISY',['../common_8h.html#af9f56e9a31eda940bcf5d250745611b5',1,'common.h']]], ['cell_5fscaleaxisz',['CELL_SCALEAXISZ',['../common_8h.html#a0273b51a3bf011a5773336d4c38f83e1',1,'common.h']]], ['cell_5fselect',['CELL_SELECT',['../common_8h.html#ab4c17b8c329d2b9c598c4791e124c8ac',1,'common.h']]], ['cell_5fshift',['CELL_SHIFT',['../common_8h.html#ab5cf1807981740666ef91eed40dd7318',1,'common.h']]], ['cell_5fsphere',['CELL_SPHERE',['../common_8h.html#a7aa4fe7e067f5ee1ee27f4bae4c40bc6',1,'common.h']]], ['cell_5fstop',['CELL_STOP',['../common_8h.html#a1b29fb8272fdcc44e1f8c917f5913484',1,'common.h']]], ['cell_5ftop',['CELL_TOP',['../common_8h.html#aee7a22bcf61538926f647691b3adb5a2',1,'common.h']]], ['cell_5ftranslate',['CELL_TRANSLATE',['../common_8h.html#a595d122334f6a8f0ae21597bbd6d0df7',1,'common.h']]], ['cell_5ftranslateaxisx',['CELL_TRANSLATEAXISX',['../common_8h.html#a42b8966d00e0fc8e4e39ffb0ac6bf968',1,'common.h']]], ['cell_5ftranslateaxisxy',['CELL_TRANSLATEAXISXY',['../common_8h.html#a7b5d4572a2b165c0b4c7e6729591f966',1,'common.h']]], ['cell_5ftranslateaxisy',['CELL_TRANSLATEAXISY',['../common_8h.html#a7c6c8bbb900fc02b2c9271d0ff0cb519',1,'common.h']]], ['cell_5ftranslateaxisyz',['CELL_TRANSLATEAXISYZ',['../common_8h.html#a1218b3ffa5792fd57eda61bf460f623a',1,'common.h']]], ['cell_5ftranslateaxisz',['CELL_TRANSLATEAXISZ',['../common_8h.html#a4832f0abe6a656bd07283742466a9528',1,'common.h']]], ['cell_5ftranslateaxiszx',['CELL_TRANSLATEAXISZX',['../common_8h.html#a721483dad58c83b9f62af79883497278',1,'common.h']]], ['cell_5ftriangle',['CELL_TRIANGLE',['../common_8h.html#afb07badbfe97f652f81f9b65dbde6cc4',1,'common.h']]] ];
JavaScript
var searchData= [ ['objecttocsg',['ObjectToCSG',['../class_g_l_widget.html#a437d6ed5521291e89d768255159ee26a',1,'GLWidget']]], ['operator_2d',['operator-',['../class_vector3.html#a72a36c71164f1532d24ec49c3d7056fc',1,'Vector3']]] ];
JavaScript
var searchData= [ ['z',['z',['../class_vector3.html#aa5f4108b2839a110eeaec8606780eaff',1,'Vector3']]], ['zrotationchanged',['zRotationChanged',['../class_g_l_widget.html#a06bc36cd7b8c19fec218165037e1c56d',1,'GLWidget']]], ['zscalationchanged',['zScalationChanged',['../class_g_l_widget.html#aefb767552fb4b476e4c8aa720f3eac80',1,'GLWidget']]], ['ztanslationchanged',['zTanslationChanged',['../class_g_l_widget.html#a9616c8f342baa005778d29762239a479',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['bpa_2ecpp',['bpa.cpp',['../bpa_8cpp.html',1,'']]], ['bpa_2eh',['bpa.h',['../bpa_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['meshchangedcommand',['MeshChangedCommand',['../class_mesh_changed_command.html',1,'']]], ['myface',['MyFace',['../class_my_face.html',1,'']]], ['mymesh',['MyMesh',['../class_my_mesh.html',1,'']]], ['mypolygon',['MyPolygon',['../class_my_polygon.html',1,'']]], ['myusedtypes',['MyUsedTypes',['../struct_my_used_types.html',1,'']]], ['myvertex',['MyVertex',['../class_my_vertex.html',1,'']]] ];
JavaScript
var searchData= [ ['w',['w',['../class_my_polygon.html#a385fecc2be056e66ef767cf1c7672faa',1,'MyPolygon::w()'],['../class_plane.html#a2eb55b72cfed8e065ea2bd71a3b01db2',1,'Plane::w()']]], ['wheelevent',['wheelEvent',['../class_g_l_widget.html#a5702a23f7cf42d05fe55a417d810a4b6',1,'GLWidget']]], ['widgetstyle',['WidgetStyle',['../stylesheet_8cpp.html#a9fa4b085490b3d073f76665501f65a17',1,'WidgetStyle():&#160;stylesheet.cpp'],['../stylesheet_8h.html#a9fa4b085490b3d073f76665501f65a17',1,'WidgetStyle():&#160;stylesheet.cpp']]], ['windowheight',['windowHeight',['../class_g_l_widget.html#a5836a4a1ab022883c9d0cf63974dd590',1,'GLWidget']]], ['windowwidth',['windowWidth',['../class_g_l_widget.html#a4b215b2bafba14dafe139bc0e342bd9d',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['scalecommand',['ScaleCommand',['../class_scale_command.html',1,'']]], ['selectobjectcommand',['SelectObjectCommand',['../class_select_object_command.html',1,'']]], ['sphereinputcommand',['SphereInputCommand',['../class_sphere_input_command.html',1,'']]], ['subtractcommand',['SubtractCommand',['../class_subtract_command.html',1,'']]] ];
JavaScript
var searchData= [ ['my_20personal_20index_20page',['My Personal Index Page',['../index.html',1,'']]] ];
JavaScript
var searchData= [ ['y',['y',['../class_vector3.html#ae4965693beffdb6069e0618222cae459',1,'Vector3']]], ['yrotationchanged',['yRotationChanged',['../class_g_l_widget.html#a0a8a85d18e3fedd7461cca6575095d7f',1,'GLWidget']]], ['yscalationchanged',['yScalationChanged',['../class_g_l_widget.html#a0f02e08fc0e8bc6b69039947949cbefc',1,'GLWidget']]], ['ytanslationchanged',['yTanslationChanged',['../class_g_l_widget.html#af9f20365b6859e5b2becfad6944a52ec',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['aabbbox',['AABBBox',['../class_a_a_b_b_box.html',1,'']]], ['addobjectcommand',['AddObjectCommand',['../class_add_object_command.html',1,'']]] ];
JavaScript
var searchData= [ ['newscene',['newScene',['../class_cell_main_window.html#ab310bb8b48305729d7254bb2f85e1fc4',1,'CellMainWindow::newScene()'],['../class_g_l_widget.html#a45abf32fe20ecb5ca5b3a23821799d9e',1,'GLWidget::newScene()']]], ['node',['Node',['../class_node.html#adb27f18bf1b226e608f17880f5a8345d',1,'Node::Node(vector&lt; MyPolygon &gt; polygons)'],['../class_node.html#a49671be091a3b75f20a4cdaf114dcdef',1,'Node::Node(Node *n)'],['../class_node.html#ad7a34779cad45d997bfd6d3d8043c75f',1,'Node::Node()']]], ['normalize',['Normalize',['../class_vector3.html#a9c94cc16049543fc8edaba52c2b266b7',1,'Vector3']]] ];
JavaScript
var searchData= [ ['edgeintersection',['edgeIntersection',['../class_cell_math.html#a26f166868ca69c02a246a4b792256177',1,'CellMath']]], ['editmeshslot',['editMeshSlot',['../class_cell_main_window.html#ab14428f2f8b812feb57008bb971601e0',1,'CellMainWindow']]], ['eventfilter',['eventFilter',['../class_cell_main_window.html#ae1b4bed9e29264f1ab3f206ee60b5135',1,'CellMainWindow']]] ];
JavaScript
var searchData= [ ['m',['m',['../class_b_p_a.html#aa7bc2f2a789d4562a0b76e10adfa8406',1,'BPA']]], ['main',['main',['../main_8cpp.html#a0ddf1224851353fc92bfbff6f499fa97',1,'main.cpp']]], ['main_2ecpp',['main.cpp',['../main_8cpp.html',1,'']]], ['matmutiply',['matMutiply',['../class_cell_math.html#ac14c173eea324853c3159a5366beae0d',1,'CellMath']]], ['matmutiplyvector',['matMutiplyVector',['../class_cell_math.html#a0d25706f57401a07f996e10888e70dbf',1,'CellMath']]], ['meshchangedcommand',['MeshChangedCommand',['../class_mesh_changed_command.html',1,'MeshChangedCommand'],['../class_mesh_changed_command.html#afb395f1456055e6cb7cc901d66cd59df',1,'MeshChangedCommand::MeshChangedCommand()']]], ['mesheditmodegroup',['meshEditModeGroup',['../class_cell_main_window.html#a8e86066157b03f76299042b0aad6ab04',1,'CellMainWindow']]], ['mesheditmodegroupclicked',['meshEditModeGroupClicked',['../class_cell_main_window.html#ab78fd4a878d3d383f052d8db9f92f71b',1,'CellMainWindow']]], ['meshnum',['meshNum',['../class_g_l_widget.html#a57f6f2c71ab6ccacf664e9ed1dca6cc8',1,'GLWidget']]], ['messageboxstyle',['MessageBoxStyle',['../stylesheet_8cpp.html#abf6660fe430e1f604fb029a3fae47ff9',1,'MessageBoxStyle():&#160;stylesheet.cpp'],['../stylesheet_8h.html#abf6660fe430e1f604fb029a3fae47ff9',1,'MessageBoxStyle():&#160;stylesheet.cpp']]], ['mode',['mode',['../class_g_l_widget.html#ae6797d28507b8c27bb18b0e02b1a824e',1,'GLWidget']]], ['mousemoveevent',['mouseMoveEvent',['../class_cell_main_window.html#a1ccd0536320d7e0e01544a32f0571c27',1,'CellMainWindow']]], ['mousepressevent',['mousePressEvent',['../class_cell_main_window.html#adfef47ef29183471e16dff3b17993c3f',1,'CellMainWindow']]], ['mousereleaseevent',['mouseReleaseEvent',['../class_cell_main_window.html#a7750223f484e3b93c3bb0b3caafcbc32',1,'CellMainWindow']]], ['moveselectfaces',['moveSelectFaces',['../class_cell_object.html#a42f297d521081b6b253d1f43b0123a76',1,'CellObject']]], ['moveselectfacesfeather',['moveSelectFacesFeather',['../class_cell_object.html#ab0b2cdffb74ecc3cf5db76bba41f89ce',1,'CellObject']]], ['moveselectpoints',['moveSelectPoints',['../class_cell_object.html#ab5656d252680881d27c4fa987df3a9f9',1,'CellObject']]], ['moveselectpointsfeather',['moveSelectPointsFeather',['../class_cell_object.html#a14a2dd221543424f69cbccd85092353b',1,'CellObject']]], ['myface',['MyFace',['../class_my_face.html',1,'']]], ['mymesh',['MyMesh',['../class_my_mesh.html',1,'']]], ['mymousemoveevent',['myMouseMoveEvent',['../class_g_l_widget.html#a7f8afe20c5fe87891ecb03e855040085',1,'GLWidget']]], ['mymousepressevent',['myMousePressEvent',['../class_g_l_widget.html#a18f210cf6be7b507a62e09fcc2f25529',1,'GLWidget']]], ['mymousereleaseevent',['myMouseReleaseEvent',['../class_g_l_widget.html#a194ff62c3ced89bdf5facd1a19fc134d',1,'GLWidget']]], ['mypolygon',['MyPolygon',['../class_my_polygon.html',1,'MyPolygon'],['../class_my_polygon.html#a2661852a272ea82080d84ab38e2bfca7',1,'MyPolygon::MyPolygon()']]], ['myusedtypes',['MyUsedTypes',['../struct_my_used_types.html',1,'']]], ['myvertex',['MyVertex',['../class_my_vertex.html',1,'']]] ];
JavaScript
var searchData= [ ['x',['x',['../class_vector3.html#a60aa84ebc037dec9faba617f8ddb231d',1,'Vector3']]], ['xrotationchanged',['xRotationChanged',['../class_g_l_widget.html#a9d0c92030343892bf152f669815047cb',1,'GLWidget']]], ['xscalationchanged',['xScalationChanged',['../class_g_l_widget.html#a6fa37cb9d39008465caf53312c8a5ae0',1,'GLWidget']]], ['xtanslationchanged',['xTanslationChanged',['../class_g_l_widget.html#aaa8e475f101152a5bc0673faa3eb2fd1',1,'GLWidget']]] ];
JavaScript
var searchData= [ ['z',['z',['../class_vector3.html#aa5f4108b2839a110eeaec8606780eaff',1,'Vector3']]] ];
JavaScript
var searchData= [ ['cellmainwindow_2ecpp',['cellmainwindow.cpp',['../cellmainwindow_8cpp.html',1,'']]], ['cellmainwindow_2eh',['cellmainwindow.h',['../cellmainwindow_8h.html',1,'']]], ['cellmainwindow_5fslot_2ecpp',['cellmainwindow_slot.cpp',['../cellmainwindow__slot_8cpp.html',1,'']]], ['cellmath_2ecpp',['cellmath.cpp',['../cellmath_8cpp.html',1,'']]], ['cellmath_2eh',['cellmath.h',['../cellmath_8h.html',1,'']]], ['cellobject_2ecpp',['cellobject.cpp',['../cellobject_8cpp.html',1,'']]], ['cellobject_2eh',['cellobject.h',['../cellobject_8h.html',1,'']]], ['commands_2ecpp',['commands.cpp',['../commands_8cpp.html',1,'']]], ['commands_2eh',['commands.h',['../commands_8h.html',1,'']]], ['common_2eh',['common.h',['../common_8h.html',1,'']]], ['csg_2ecpp',['csg.cpp',['../csg_8cpp.html',1,'']]], ['csg_2eh',['csg.h',['../csg_8h.html',1,'']]], ['csg_5ftype_2ecpp',['csg_type.cpp',['../csg__type_8cpp.html',1,'']]], ['csg_5ftype_2eh',['csg_type.h',['../csg__type_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['intersectcommand',['IntersectCommand',['../class_intersect_command.html',1,'']]], ['intersectionplane',['IntersectionPlane',['../class_intersection_plane.html',1,'']]] ];
JavaScript
var searchData= [ ['rotatecommand',['RotateCommand',['../class_rotate_command.html',1,'']]] ];
JavaScript
var searchData= [ ['main_2ecpp',['main.cpp',['../main_8cpp.html',1,'']]] ];
JavaScript