code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
var Class = { create: function() { return function() { //vararg this.initialize.apply(this, arguments); } } }; Color = Class.create(); Color.prototype = { red: 0, green: 0, blue: 0, initialize: function(r,g,b) { this.red = r; this.green = g; this.blue = b; } } function bench(x) { var d = new Date; var colors = new Array(16); for (var i=0;i<1e8;i++) { colors[i&0xf] = (new Color(1,2,3)); } print(new Date - d); return colors; } bench(17); print("Swapping out call"); Function.prototype.call = function() { throw "This should not happen, apply should be called instead"; }; bench(17); print("All done!");
hazzik/nashorn
test/examples/apply_to_call_benchmark.js
JavaScript
gpl-2.0
674
// IT lang variables tinyMCE.addToLang('',{ bold_desc : 'Grassetto (Ctrl+B)', italic_desc : 'Corsivo (Ctrl+I)', underline_desc : 'Sottolineato (Ctrl+U)', striketrough_desc : 'Barrato', justifyleft_desc : 'Allinea a sinistra', justifycenter_desc : 'Allinea al centro', justifyright_desc : 'Allinea a destra', justifyfull_desc : 'Giustifica', bullist_desc : 'Elenco puntato', numlist_desc : 'Elenco numerato', outdent_desc : 'Riduci rientro', indent_desc : 'Aumenta rientro', undo_desc : 'Annulla (Ctrl+Z)', redo_desc : 'Ripeti (Ctrl+Y)', link_desc : 'Inserisci o modifica link', unlink_desc : 'Elimina link', image_desc : 'Inserisci o modifica immagine', cleanup_desc : 'Pulisci il codice HTML', focus_alert : 'Fare clic su un\' istanza dell\'editor prima di eseguire questo comando', edit_confirm : 'Vuoi usare l\'editor visuale in quest\'area di testo?', insert_link_title : 'Inserisci o modifica link', insert : 'Inserisci', update : 'Modifica', cancel : 'Annulla', insert_link_url : 'URL del collegamento', insert_link_target : 'Destinazione', insert_link_target_same : 'Apri il link nella stessa finestra', insert_link_target_blank : 'Apri il link in una nuova finestra', insert_image_title : 'Inserisci o modifica immagine', insert_image_src : 'URL dell\'immagine', insert_image_alt : 'Descrizione', help_desc : 'Aiuto', bold_img : "bold.gif", italic_img : "italic.gif", underline_img : "underline.gif", clipboard_msg : 'Le operazioni di taglia, copia e incolla non sono disponibili in Firefox. Vuoi ricevere ulteriori informazioni al riguardo?', popup_blocked : 'Un blocco popup sta impedendo l\'utilizzo di alcune funzionalit&agrave;. Dovresti disabilitare il blocco per questo sito.', insert_image_delta_width : 50, insert_link_delta_width : 75 });
pzingg/saugus_elgg
_tinymce/jscripts/tiny_mce/langs/it.js
JavaScript
gpl-2.0
1,801
"use strict"; var assert = require("assert"), Promise = require("promise"), _ = require("underscore"), configController = require('../controllers/configController.js'); describe('configController', function() { it('init should load the config file', function(done) { configController.init(function(err) { assert(!err); assert(configController.initialized); assert(configController.config); assert(_.isString(configController.config.host)); assert(_.isNumber(configController.config.port)); assert(_.isNumber(configController.config.internalPort)); assert(_.isNumber(configController.config.redisPort)); assert(_.isArray(configController.config.admins)); assert(_.isString(configController.config.amaraKey)); assert(_.isString(configController.config.emailService)); assert(_.isString(configController.config.smtpUser)); assert(_.isString(configController.config.smtpPass)); assert(_.isString(configController.config.emailFrom)); }); done(); }); });
bbondy/codefirefox
test/test-configController.js
JavaScript
gpl-2.0
1,051
(function ($) { Drupal.viewsSlideshow = Drupal.viewsSlideshow || {}; /** * Views Slideshow Controls */ Drupal.viewsSlideshowControls = Drupal.viewsSlideshowControls || {}; /** * Implement the play hook for controls. */ Drupal.viewsSlideshowControls.play = function (options) { // Route the control call to the correct control type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].play == 'function') { Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].play(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].play == 'function') { Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].play(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Implement the pause hook for controls. */ Drupal.viewsSlideshowControls.pause = function (options) { // Route the control call to the correct control type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].pause == 'function') { Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].pause(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].pause == 'function') { Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].pause(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Views Slideshow Text Controls */ // Add views slieshow api calls for views slideshow text controls. Drupal.behaviors.viewsSlideshowControlsText = { attach: function (context) { // Process previous link $('.views_slideshow_controls_text_previous:not(.views-slideshow-controls-text-previous-processed)', context).addClass('views-slideshow-controls-text-previous-processed').each(function() { var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_previous_', ''); $(this).click(function() { Drupal.viewsSlideshow.action({ "action": 'previousSlide', "slideshowID": uniqueID }); return false; }); }); // Process next link $('.views_slideshow_controls_text_next:not(.views-slideshow-controls-text-next-processed)', context).addClass('views-slideshow-controls-text-next-processed').each(function() { var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_next_', ''); $(this).click(function() { Drupal.viewsSlideshow.action({ "action": 'nextSlide', "slideshowID": uniqueID }); return false; }); }); // Process pause link $('.views_slideshow_controls_text_pause:not(.views-slideshow-controls-text-pause-processed)', context).addClass('views-slideshow-controls-text-pause-processed').each(function() { var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_pause_', ''); $(this).click(function() { if (Drupal.settings.viewsSlideshow[uniqueID].paused) { Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": uniqueID, "force": true }); } else { Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": uniqueID, "force": true }); } return false; }); }); } }; Drupal.viewsSlideshowControlsText = Drupal.viewsSlideshowControlsText || {}; /** * Implement the pause hook for text controls. */ Drupal.viewsSlideshowControlsText.pause = function (options) { var pauseText = Drupal.theme.prototype['viewsSlideshowControlsPause'] ? Drupal.theme('viewsSlideshowControlsPause') : ''; $('#views_slideshow_controls_text_pause_' + options.slideshowID + ' a').text(pauseText); }; /** * Implement the play hook for text controls. */ Drupal.viewsSlideshowControlsText.play = function (options) { var playText = Drupal.theme.prototype['viewsSlideshowControlsPlay'] ? Drupal.theme('viewsSlideshowControlsPlay') : ''; $('#views_slideshow_controls_text_pause_' + options.slideshowID + ' a').text(playText); }; // Theme the resume control. Drupal.theme.prototype.viewsSlideshowControlsPause = function () { return Drupal.t('Resume'); }; // Theme the pause control. Drupal.theme.prototype.viewsSlideshowControlsPlay = function () { return Drupal.t('Pause'); }; /** * Views Slideshow Pager */ Drupal.viewsSlideshowPager = Drupal.viewsSlideshowPager || {}; /** * Implement the transitionBegin hook for pagers. */ Drupal.viewsSlideshowPager.transitionBegin = function (options) { // Route the pager call to the correct pager type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].transitionBegin == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].transitionBegin(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].transitionBegin == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].transitionBegin(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Implement the goToSlide hook for pagers. */ Drupal.viewsSlideshowPager.goToSlide = function (options) { // Route the pager call to the correct pager type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].goToSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].goToSlide(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].goToSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].goToSlide(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Implement the previousSlide hook for pagers. */ Drupal.viewsSlideshowPager.previousSlide = function (options) { // Route the pager call to the correct pager type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].previousSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].previousSlide(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].previousSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].previousSlide(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Implement the nextSlide hook for pagers. */ Drupal.viewsSlideshowPager.nextSlide = function (options) { // Route the pager call to the correct pager type. // Need to use try catch so we don't have to check to make sure every part // of the object is defined. try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].nextSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].nextSlide(options); } } catch(err) { // Don't need to do anything on error. } try { if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].nextSlide == 'function') { Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].nextSlide(options); } } catch(err) { // Don't need to do anything on error. } }; /** * Views Slideshow Pager Fields */ // Add views slieshow api calls for views slideshow pager fields. Drupal.behaviors.viewsSlideshowPagerFields = { attach: function (context) { // Process pause on hover. $('.views_slideshow_pager_field:not(.views-slideshow-pager-field-processed)', context).addClass('views-slideshow-pager-field-processed').each(function() { // Parse out the location and unique id from the full id. var pagerInfo = $(this).attr('id').split('_'); var location = pagerInfo[2]; pagerInfo.splice(0, 3); var uniqueID = pagerInfo.join('_'); // Add the activate and pause on pager hover event to each pager item. if (Drupal.settings.viewsSlideshowPagerFields[uniqueID][location].activatePauseOnHover) { $(this).children().each(function(index, pagerItem) { var mouseIn = function() { Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index }); Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": uniqueID }); } var mouseOut = function() { Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": uniqueID }); } if (jQuery.fn.hoverIntent) { $(pagerItem).hoverIntent(mouseIn, mouseOut); } else { $(pagerItem).hover(mouseIn, mouseOut); } }); } else { $(this).children().each(function(index, pagerItem) { $(pagerItem).click(function() { Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index }); }); }); } }); } }; Drupal.viewsSlideshowPagerFields = Drupal.viewsSlideshowPagerFields || {}; /** * Implement the transitionBegin hook for pager fields pager. */ Drupal.viewsSlideshowPagerFields.transitionBegin = function (options) { for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) { // Remove active class from pagers $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active'); // Add active class to active pager. $('#views_slideshow_pager_field_item_'+ pagerLocation + '_' + options.slideshowID + '_' + options.slideNum).addClass('active'); } }; /** * Implement the goToSlide hook for pager fields pager. */ Drupal.viewsSlideshowPagerFields.goToSlide = function (options) { for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) { // Remove active class from pagers $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active'); // Add active class to active pager. $('#views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_' + options.slideNum).addClass('active'); } }; /** * Implement the previousSlide hook for pager fields pager. */ Drupal.viewsSlideshowPagerFields.previousSlide = function (options) { for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) { // Get the current active pager. var pagerNum = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"].active').attr('id').replace('views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_', ''); // If we are on the first pager then activate the last pager. // Otherwise activate the previous pager. if (pagerNum == 0) { pagerNum = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').length() - 1; } else { pagerNum--; } // Remove active class from pagers $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active'); // Add active class to active pager. $('#views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_' + pagerNum).addClass('active'); } }; /** * Implement the nextSlide hook for pager fields pager. */ Drupal.viewsSlideshowPagerFields.nextSlide = function (options) { for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) { // Get the current active pager. var pagerNum = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"].active').attr('id').replace('views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_', ''); var totalPagers = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').length(); // If we are on the last pager then activate the first pager. // Otherwise activate the next pager. pagerNum++; if (pagerNum == totalPagers) { pagerNum = 0; } // Remove active class from pagers $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active'); // Add active class to active pager. $('#views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_' + slideNum).addClass('active'); } }; /** * Views Slideshow Slide Counter */ Drupal.viewsSlideshowSlideCounter = Drupal.viewsSlideshowSlideCounter || {}; /** * Implement the transitionBegin for the slide counter. */ Drupal.viewsSlideshowSlideCounter.transitionBegin = function (options) { $('#views_slideshow_slide_counter_' + options.slideshowID + ' .num').text(options.slideNum + 1); }; /** * This is used as a router to process actions for the slideshow. */ Drupal.viewsSlideshow.action = function (options) { // Set default values for our return status. var status = { 'value': true, 'text': '' } // If an action isn't specified return false. if (typeof options.action == 'undefined' || options.action == '') { status.value = false; status.text = Drupal.t('There was no action specified.'); return error; } // If we are using pause or play switch paused state accordingly. if (options.action == 'pause') { Drupal.settings.viewsSlideshow[options.slideshowID].paused = 1; // If the calling method is forcing a pause then mark it as such. if (options.force) { Drupal.settings.viewsSlideshow[options.slideshowID].pausedForce = 1; } } else if (options.action == 'play') { // If the slideshow isn't forced pause or we are forcing a play then play // the slideshow. // Otherwise return telling the calling method that it was forced paused. if (!Drupal.settings.viewsSlideshow[options.slideshowID].pausedForce || options.force) { Drupal.settings.viewsSlideshow[options.slideshowID].paused = 0; Drupal.settings.viewsSlideshow[options.slideshowID].pausedForce = 0; } else { status.value = false; status.text += ' ' + Drupal.t('This slideshow is forced paused.'); return status; } } // We use a switch statement here mainly just to limit the type of actions // that are available. switch (options.action) { case "goToSlide": case "transitionBegin": case "transitionEnd": // The three methods above require a slide number. Checking if it is // defined and it is a number that is an integer. if (typeof options.slideNum == 'undefined' || typeof options.slideNum !== 'number' || parseInt(options.slideNum) != (options.slideNum - 0)) { status.value = false; status.text = Drupal.t('An invalid integer was specified for slideNum.'); } case "pause": case "play": case "nextSlide": case "previousSlide": // Grab our list of methods. var methods = Drupal.settings.viewsSlideshow[options.slideshowID]['methods']; // if the calling method specified methods that shouldn't be called then // exclude calling them. var excludeMethodsObj = {}; if (typeof options.excludeMethods !== 'undefined') { // We need to turn the excludeMethods array into an object so we can use the in // function. for (var i=0; i < excludeMethods.length; i++) { excludeMethodsObj[excludeMethods[i]] = ''; } } // Call every registered method and don't call excluded ones. for (i = 0; i < methods[options.action].length; i++) { if (Drupal[methods[options.action][i]] != undefined && typeof Drupal[methods[options.action][i]][options.action] == 'function' && !(methods[options.action][i] in excludeMethodsObj)) { Drupal[methods[options.action][i]][options.action](options); } } break; // If it gets here it's because it's an invalid action. default: status.value = false; status.text = Drupal.t('An invalid action "!action" was specified.', { "!action": options.action }); } return status; }; })(jQuery); ; (function($){ Drupal.behaviors.contextReactionBlock = {attach: function(context) { $('form.context-editor:not(.context-block-processed)') .addClass('context-block-processed') .each(function() { var id = $(this).attr('id'); Drupal.contextBlockEditor = Drupal.contextBlockEditor || {}; $(this).bind('init.pageEditor', function(event) { Drupal.contextBlockEditor[id] = new DrupalContextBlockEditor($(this)); }); $(this).bind('start.pageEditor', function(event, context) { // Fallback to first context if param is empty. if (!context) { context = $(this).data('defaultContext'); } Drupal.contextBlockEditor[id].editStart($(this), context); }); $(this).bind('end.pageEditor', function(event) { Drupal.contextBlockEditor[id].editFinish(); }); }); // // Admin Form ======================================================= // // ContextBlockForm: Init. $('#context-blockform:not(.processed)').each(function() { $(this).addClass('processed'); Drupal.contextBlockForm = new DrupalContextBlockForm($(this)); Drupal.contextBlockForm.setState(); }); // ContextBlockForm: Attach block removal handlers. // Lives in behaviors as it may be required for attachment to new DOM elements. $('#context-blockform a.remove:not(.processed)').each(function() { $(this).addClass('processed'); $(this).click(function() { $(this).parents('tr').eq(0).remove(); Drupal.contextBlockForm.setState(); return false; }); }); }}; /** * Context block form. Default form for editing context block reactions. */ DrupalContextBlockForm = function(blockForm) { this.state = {}; this.setState = function() { $('table.context-blockform-region', blockForm).each(function() { var region = $(this).attr('id').split('context-blockform-region-')[1]; var blocks = []; $('tr', $(this)).each(function() { var bid = $(this).attr('id'); var weight = $(this).find('select').val(); blocks.push({'bid' : bid, 'weight' : weight}); }); Drupal.contextBlockForm.state[region] = blocks; }); // Serialize here and set form element value. $('form input.context-blockform-state').val(JSON.stringify(this.state)); // Hide enabled blocks from selector that are used $('table.context-blockform-region tr').each(function() { var bid = $(this).attr('id'); $('div.context-blockform-selector input[value='+bid+']').parents('div.form-item').eq(0).hide(); }); // Show blocks in selector that are unused $('div.context-blockform-selector input').each(function() { var bid = $(this).val(); if ($('table.context-blockform-region tr#'+bid).size() === 0) { $(this).parents('div.form-item').eq(0).show(); } }); }; // make sure we update the state right before submits, this takes care of an // apparent race condition between saving the state and the weights getting set // by tabledrag $('#ctools-export-ui-edit-item-form').submit(function() { Drupal.contextBlockForm.setState(); }); // Tabledrag // Add additional handlers to update our blocks. $.each(Drupal.settings.tableDrag, function(base) { var table = $('#' + base + ':not(.processed)', blockForm); if (table && table.is('.context-blockform-region')) { table.addClass('processed'); table.bind('mouseup', function(event) { Drupal.contextBlockForm.setState(); return; }); } }); // Add blocks to a region $('td.blocks a', blockForm).each(function() { $(this).click(function() { var region = $(this).attr('href').split('#')[1]; var selected = $("div.context-blockform-selector input:checked"); if (selected.size() > 0) { selected.each(function() { // create new block markup var block = document.createElement('tr'); var text = $(this).parents('div.form-item').eq(0).hide().children('label').text(); var select = '<div class="form-item form-type-select"><select class="tabledrag-hide form-select">'; var i; for (i = -10; i < 10; ++i) { select += '<option>' + i + '</option>'; } select += '</select></div>'; $(block).attr('id', $(this).attr('value')).addClass('draggable'); $(block).html("<td>"+ text + "</td><td>" + select + "</td><td><a href='' class='remove'>X</a></td>"); // add block item to region var base = "context-blockform-region-"+ region; Drupal.tableDrag[base].makeDraggable(block); $('table#'+base).append(block); if ($.cookie('Drupal.tableDrag.showWeight') == 1) { $('table#'+base).find('.tabledrag-hide').css('display', ''); $('table#'+base).find('.tabledrag-handle').css('display', 'none'); } else { $('table#'+base).find('.tabledrag-hide').css('display', 'none'); $('table#'+base).find('.tabledrag-handle').css('display', ''); } Drupal.attachBehaviors($('table#'+base)); Drupal.contextBlockForm.setState(); $(this).removeAttr('checked'); }); } return false; }); }); }; /** * Context block editor. AHAH editor for live block reaction editing. */ DrupalContextBlockEditor = function(editor) { this.editor = editor; this.state = {}; this.blocks = {}; this.regions = {}; // Category selector handler. // Also set to "Choose a category" option as browsers can retain // form values from previous page load. $('select.context-block-browser-categories', editor).change(function() { var category = $(this).val(); var params = { containment: 'document', revert: true, dropOnEmpty: true, placeholder: 'draggable-placeholder', forcePlaceholderSize: true, helper: 'clone', appendTo: 'body', connectWith: ($.ui.version === '1.6') ? ['.ui-sortable'] : '.ui-sortable' }; $('div.category', editor).hide().sortable('destroy'); $('div.category-'+category, editor).show().sortable(params); }); $('select.context-block-browser-categories', editor).val(0).change(); return this; }; DrupalContextBlockEditor.prototype.initBlocks = function(blocks) { var self = this; this.blocks = blocks; blocks.each(function() { if($(this).hasClass('context-block-empty')) { $(this).removeClass('context-block-hidden'); } $(this).addClass('draggable'); $(this).prepend($('<a class="context-block-handle"></a>')); $(this).prepend($('<a class="context-block-remove"></a>').click(function() { $(this).parent ('.block').eq(0).fadeOut('medium', function() { $(this).remove(); self.updateBlocks(); }); return false; })); }); }; DrupalContextBlockEditor.prototype.initRegions = function(regions) { this.regions = regions; }; /** * Update UI to match the current block states. */ DrupalContextBlockEditor.prototype.updateBlocks = function() { var browser = $('div.context-block-browser'); // For all enabled blocks, mark corresponding addables as having been added. $('.block, .admin-block').each(function() { var bid = $(this).attr('id').split('block-')[1]; // Ugh. $('#context-block-addable-'+bid, browser).draggable('disable').addClass('context-block-added').removeClass('context-block-addable'); }); // For all hidden addables with no corresponding blocks, mark as addable. $('.context-block-item', browser).each(function() { var bid = $(this).attr('id').split('context-block-addable-')[1]; if ($('#block-'+bid).size() === 0) { $(this).draggable('enable').removeClass('context-block-added').addClass('context-block-addable'); } }); // Mark empty regions. $(this.regions).each(function() { if ($('.block:has(a.context-block)', this).size() > 0) { $(this).removeClass('context-block-region-empty'); } else { $(this).addClass('context-block-region-empty'); } }); }; /** * Live update a region. */ DrupalContextBlockEditor.prototype.updateRegion = function(event, ui, region, op) { switch (op) { case 'over': $(region).removeClass('context-block-region-empty'); break; case 'out': if ( // jQuery UI 1.8 $('.draggable-placeholder', region).size() === 1 && $('.block:has(a.context-block)', region).size() == 0 // jQuery UI 1.6 // $('div.draggable-placeholder', region).size() === 0 && // $('div.block:has(a.context-block)', region).size() == 1 && // $('div.block:has(a.context-block)', region).attr('id') == ui.item.attr('id') ) { $(region).addClass('context-block-region-empty'); } break; } }; /** * Remove script elements while dragging & dropping. */ DrupalContextBlockEditor.prototype.scriptFix = function(event, ui, editor, context) { if ($('script', ui.item)) { var placeholder = $(Drupal.settings.contextBlockEditor.scriptPlaceholder); var label = $('div.handle label', ui.item).text(); placeholder.children('strong').html(label); $('script', ui.item).parent().empty().append(placeholder); } }; /** * Add a block to a region through an AHAH load of the block contents. */ DrupalContextBlockEditor.prototype.addBlock = function(event, ui, editor, context) { var self = this; if (ui.item.is('.context-block-addable')) { var bid = ui.item.attr('id').split('context-block-addable-')[1]; // Construct query params for our AJAX block request. var params = Drupal.settings.contextBlockEditor.params; params.context_block = bid + ',' + context; // Replace item with loading block. var blockLoading = $('<div class="context-block-item context-block-loading"><span class="icon"></span></div>'); ui.item.addClass('context-block-added'); ui.item.after(blockLoading); ui.sender.append(ui.item); $.getJSON(Drupal.settings.contextBlockEditor.path, params, function(data) { if (data.status) { var newBlock = $(data.block); if ($('script', newBlock)) { $('script', newBlock).remove(); } blockLoading.fadeOut(function() { $(this).replaceWith(newBlock); self.initBlocks(newBlock); self.updateBlocks(); Drupal.attachBehaviors(); }); } else { blockLoading.fadeOut(function() { $(this).remove(); }); } }); } else if (ui.item.is(':has(a.context-block)')) { self.updateBlocks(); } }; /** * Update form hidden field with JSON representation of current block visibility states. */ DrupalContextBlockEditor.prototype.setState = function() { var self = this; $(this.regions).each(function() { var region = $('a.context-block-region', this).attr('id').split('context-block-region-')[1]; var blocks = []; $('a.context-block', $(this)).each(function() { if ($(this).attr('class').indexOf('edit-') != -1) { var bid = $(this).attr('id').split('context-block-')[1]; var context = $(this).attr('class').split('edit-')[1].split(' ')[0]; context = context ? context : 0; var block = {'bid': bid, 'context': context}; blocks.push(block); } }); self.state[region] = blocks; }); // Serialize here and set form element value. $('input.context-block-editor-state', this.editor).val(JSON.stringify(this.state)); }; /** * Disable text selection. */ DrupalContextBlockEditor.prototype.disableTextSelect = function() { if ($.browser.safari) { $('.block:has(a.context-block):not(:has(input,textarea))').css('WebkitUserSelect','none'); } else if ($.browser.mozilla) { $('.block:has(a.context-block):not(:has(input,textarea))').css('MozUserSelect','none'); } else if ($.browser.msie) { $('.block:has(a.context-block):not(:has(input,textarea))').bind('selectstart.contextBlockEditor', function() { return false; }); } else { $(this).bind('mousedown.contextBlockEditor', function() { return false; }); } }; /** * Enable text selection. */ DrupalContextBlockEditor.prototype.enableTextSelect = function() { if ($.browser.safari) { $('*').css('WebkitUserSelect',''); } else if ($.browser.mozilla) { $('*').css('MozUserSelect',''); } else if ($.browser.msie) { $('*').unbind('selectstart.contextBlockEditor'); } else { $(this).unbind('mousedown.contextBlockEditor'); } }; /** * Start editing. Attach handlers, begin draggable/sortables. */ DrupalContextBlockEditor.prototype.editStart = function(editor, context) { var self = this; // This is redundant to the start handler found in context_ui.js. // However it's necessary that we trigger this class addition before // we call .sortable() as the empty regions need to be visible. $(document.body).addClass('context-editing'); this.editor.addClass('context-editing'); this.disableTextSelect(); this.initBlocks($('.block:has(a.context-block.edit-'+context+')')); this.initRegions($('a.context-block-region').parent()); this.updateBlocks(); // First pass, enable sortables on all regions. $(this.regions).each(function() { var region = $(this); var params = { containment: 'document', revert: true, dropOnEmpty: true, placeholder: 'draggable-placeholder', forcePlaceholderSize: true, items: '> .block:has(a.context-block.editable)', handle: 'a.context-block-handle', start: function(event, ui) { self.scriptFix(event, ui, editor, context); }, stop: function(event, ui) { self.addBlock(event, ui, editor, context); }, receive: function(event, ui) { self.addBlock(event, ui, editor, context); }, over: function(event, ui) { self.updateRegion(event, ui, region, 'over'); }, out: function(event, ui) { self.updateRegion(event, ui, region, 'out'); } }; region.sortable(params); }); // Second pass, hook up all regions via connectWith to each other. $(this.regions).each(function() { $(this).sortable('option', 'connectWith', ['.ui-sortable']); }); // Terrible, terrible workaround for parentoffset issue in Safari. // The proper fix for this issue has been committed to jQuery UI, but was // not included in the 1.6 release. Therefore, we do a browser agent hack // to ensure that Safari users are covered by the offset fix found here: // http://dev.jqueryui.com/changeset/2073. if ($.ui.version === '1.6' && $.browser.safari) { $.browser.mozilla = true; } }; /** * Finish editing. Remove handlers. */ DrupalContextBlockEditor.prototype.editFinish = function() { this.editor.removeClass('context-editing'); this.enableTextSelect(); // Remove UI elements. $(this.blocks).each(function() { $('a.context-block-handle, a.context-block-remove', this).remove(); if($(this).hasClass('context-block-empty')) { $(this).addClass('context-block-hidden'); } $(this).removeClass('draggable'); }); this.regions.sortable('destroy'); this.setState(); // Unhack the user agent. if ($.ui.version === '1.6' && $.browser.safari) { $.browser.mozilla = false; } }; })(jQuery); ; (function ($) { Drupal.behaviors.textarea = { attach: function (context, settings) { $('.form-textarea-wrapper.resizable', context).once('textarea', function () { var staticOffset = null; var textarea = $(this).addClass('resizable-textarea').find('textarea'); var grippie = $('<div class="grippie"></div>').mousedown(startDrag); grippie.insertAfter(textarea); function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag); textarea.css('opacity', 1); } }); } }; })(jQuery); ; /** * JavaScript behaviors for the front-end display of webforms. */ (function ($) { Drupal.behaviors.webform = Drupal.behaviors.webform || {}; Drupal.behaviors.webform.attach = function(context) { // Calendar datepicker behavior. Drupal.webform.datepicker(context); }; Drupal.webform = Drupal.webform || {}; Drupal.webform.datepicker = function(context) { $('div.webform-datepicker').each(function() { var $webformDatepicker = $(this); var $calendar = $webformDatepicker.find('input.webform-calendar'); var startDate = $calendar[0].className.replace(/.*webform-calendar-start-(\d{4}-\d{2}-\d{2}).*/, '$1').split('-'); var endDate = $calendar[0].className.replace(/.*webform-calendar-end-(\d{4}-\d{2}-\d{2}).*/, '$1').split('-'); var firstDay = $calendar[0].className.replace(/.*webform-calendar-day-(\d).*/, '$1'); // Convert date strings into actual Date objects. startDate = new Date(startDate[0], startDate[1] - 1, startDate[2]); endDate = new Date(endDate[0], endDate[1] - 1, endDate[2]); // Ensure that start comes before end for datepicker. if (startDate > endDate) { var laterDate = startDate; startDate = endDate; endDate = laterDate; } var startYear = startDate.getFullYear(); var endYear = endDate.getFullYear(); // Set up the jQuery datepicker element. $calendar.datepicker({ dateFormat: 'yy-mm-dd', yearRange: startYear + ':' + endYear, firstDay: parseInt(firstDay), minDate: startDate, maxDate: endDate, onSelect: function(dateText, inst) { var date = dateText.split('-'); $webformDatepicker.find('select.year, input.year').val(+date[0]); $webformDatepicker.find('select.month').val(+date[1]); $webformDatepicker.find('select.day').val(+date[2]); }, beforeShow: function(input, inst) { // Get the select list values. var year = $webformDatepicker.find('select.year, input.year').val(); var month = $webformDatepicker.find('select.month').val(); var day = $webformDatepicker.find('select.day').val(); // If empty, default to the current year/month/day in the popup. var today = new Date(); year = year ? year : today.getFullYear(); month = month ? month : today.getMonth() + 1; day = day ? day : today.getDate(); // Make sure that the default year fits in the available options. year = (year < startYear || year > endYear) ? startYear : year; // jQuery UI Datepicker will read the input field and base its date off // of that, even though in our case the input field is a button. $(input).val(year + '-' + month + '-' + day); } }); // Prevent the calendar button from submitting the form. $calendar.click(function(event) { $(this).focus(); event.preventDefault(); }); }); } })(jQuery); ; (function ($) { /** * Automatically display the guidelines of the selected text format. */ Drupal.behaviors.filterGuidelines = { attach: function (context) { $('.filter-guidelines', context).once('filter-guidelines') .find(':header').hide() .closest('.filter-wrapper').find('select.filter-list') .bind('change', function () { $(this).closest('.filter-wrapper') .find('.filter-guidelines-item').hide() .siblings('.filter-guidelines-' + this.value).show(); }) .change(); } }; })(jQuery); ; (function ($) { /** * Toggle the visibility of a fieldset using smooth animations. */ Drupal.toggleFieldset = function (fieldset) { var $fieldset = $(fieldset); if ($fieldset.is('.collapsed')) { var $content = $('> .fieldset-wrapper', fieldset).hide(); $fieldset .removeClass('collapsed') .trigger({ type: 'collapsed', value: false }) .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide')); $content.slideDown({ duration: 'fast', easing: 'linear', complete: function () { Drupal.collapseScrollIntoView(fieldset); fieldset.animating = false; }, step: function () { // Scroll the fieldset into view. Drupal.collapseScrollIntoView(fieldset); } }); } else { $fieldset.trigger({ type: 'collapsed', value: true }); $('> .fieldset-wrapper', fieldset).slideUp('fast', function () { $fieldset .addClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show')); fieldset.animating = false; }); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = document.documentElement.clientHeight || document.body.clientHeight || 0; var offset = document.documentElement.scrollTop || document.body.scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = { attach: function (context, settings) { $('fieldset.collapsible', context).once('collapse', function () { var $fieldset = $(this); // Expand fieldset if there are errors inside, or if it contains an // element that is targeted by the uri fragment identifier. var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : ''; if ($('.error' + anchor, $fieldset).length) { $fieldset.removeClass('collapsed'); } var summary = $('<span class="summary"></span>'); $fieldset. bind('summaryUpdated', function () { var text = $.trim($fieldset.drupalGetSummary()); summary.html(text ? ' (' + text + ')' : ''); }) .trigger('summaryUpdated'); // Turn the legend into a clickable link, but retain span.fieldset-legend // for CSS positioning. var $legend = $('> legend .fieldset-legend', this); $('<span class="fieldset-legend-prefix element-invisible"></span>') .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide')) .prependTo($legend) .after(' '); // .wrapInner() does not retain bound events. var $link = $('<a class="fieldset-title" href="#"></a>') .prepend($legend.contents()) .appendTo($legend) .click(function () { var fieldset = $fieldset.get(0); // Don't animate multiple times. if (!fieldset.animating) { fieldset.animating = true; Drupal.toggleFieldset(fieldset); } return false; }); $legend.append(summary); }); } }; })(jQuery); ; (function ($) { /** * Attaches sticky table headers. */ Drupal.behaviors.tableHeader = { attach: function (context, settings) { if (!$.support.positionFixed) { return; } $('table.sticky-enabled', context).once('tableheader', function () { $(this).data("drupal-tableheader", new Drupal.tableHeader(this)); }); } }; /** * Constructor for the tableHeader object. Provides sticky table headers. * * @param table * DOM object for the table to add a sticky header to. */ Drupal.tableHeader = function (table) { var self = this; this.originalTable = $(table); this.originalHeader = $(table).children('thead'); this.originalHeaderCells = this.originalHeader.find('> tr > th'); this.displayWeight = null; // React to columns change to avoid making checks in the scroll callback. this.originalTable.bind('columnschange', function (e, display) { // This will force header size to be calculated on scroll. self.widthCalculated = (self.displayWeight !== null && self.displayWeight === display); self.displayWeight = display; }); // Clone the table header so it inherits original jQuery properties. Hide // the table to avoid a flash of the header clone upon page load. this.stickyTable = $('<table class="sticky-header"/>') .insertBefore(this.originalTable) .css({ position: 'fixed', top: '0px' }); this.stickyHeader = this.originalHeader.clone(true) .hide() .appendTo(this.stickyTable); this.stickyHeaderCells = this.stickyHeader.find('> tr > th'); this.originalTable.addClass('sticky-table'); $(window) .bind('scroll.drupal-tableheader', $.proxy(this, 'eventhandlerRecalculateStickyHeader')) .bind('resize.drupal-tableheader', { calculateWidth: true }, $.proxy(this, 'eventhandlerRecalculateStickyHeader')) // Make sure the anchor being scrolled into view is not hidden beneath the // sticky table header. Adjust the scrollTop if it does. .bind('drupalDisplaceAnchor.drupal-tableheader', function () { window.scrollBy(0, -self.stickyTable.outerHeight()); }) // Make sure the element being focused is not hidden beneath the sticky // table header. Adjust the scrollTop if it does. .bind('drupalDisplaceFocus.drupal-tableheader', function (event) { if (self.stickyVisible && event.clientY < (self.stickyOffsetTop + self.stickyTable.outerHeight()) && event.$target.closest('sticky-header').length === 0) { window.scrollBy(0, -self.stickyTable.outerHeight()); } }) .triggerHandler('resize.drupal-tableheader'); // We hid the header to avoid it showing up erroneously on page load; // we need to unhide it now so that it will show up when expected. this.stickyHeader.show(); }; /** * Event handler: recalculates position of the sticky table header. * * @param event * Event being triggered. */ Drupal.tableHeader.prototype.eventhandlerRecalculateStickyHeader = function (event) { var self = this; var calculateWidth = event.data && event.data.calculateWidth; // Reset top position of sticky table headers to the current top offset. this.stickyOffsetTop = Drupal.settings.tableHeaderOffset ? eval(Drupal.settings.tableHeaderOffset + '()') : 0; this.stickyTable.css('top', this.stickyOffsetTop + 'px'); // Save positioning data. var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight; if (calculateWidth || this.viewHeight !== viewHeight) { this.viewHeight = viewHeight; this.vPosition = this.originalTable.offset().top - 4 - this.stickyOffsetTop; this.hPosition = this.originalTable.offset().left; this.vLength = this.originalTable[0].clientHeight - 100; calculateWidth = true; } // Track horizontal positioning relative to the viewport and set visibility. var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft; var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition; this.stickyVisible = vOffset > 0 && vOffset < this.vLength; this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' }); // Only perform expensive calculations if the sticky header is actually // visible or when forced. if (this.stickyVisible && (calculateWidth || !this.widthCalculated)) { this.widthCalculated = true; var $that = null; var $stickyCell = null; var display = null; var cellWidth = null; // Resize header and its cell widths. // Only apply width to visible table cells. This prevents the header from // displaying incorrectly when the sticky header is no longer visible. for (var i = 0, il = this.originalHeaderCells.length; i < il; i += 1) { $that = $(this.originalHeaderCells[i]); $stickyCell = this.stickyHeaderCells.eq($that.index()); display = $that.css('display'); if (display !== 'none') { cellWidth = $that.css('width'); // Exception for IE7. if (cellWidth === 'auto') { cellWidth = $that[0].clientWidth + 'px'; } $stickyCell.css({'width': cellWidth, 'display': display}); } else { $stickyCell.css('display', 'none'); } } this.stickyTable.css('width', this.originalTable.css('width')); } }; })(jQuery); ; (function ($) { Drupal.behaviors.tokenTree = { attach: function (context, settings) { $('table.token-tree', context).once('token-tree', function () { $(this).treeTable(); }); } }; Drupal.behaviors.tokenInsert = { attach: function (context, settings) { // Keep track of which textfield was last selected/focused. $('textarea, input[type="text"]', context).focus(function() { Drupal.settings.tokenFocusedField = this; }); $('.token-click-insert .token-key', context).once('token-click-insert', function() { var newThis = $('<a href="javascript:void(0);" title="' + Drupal.t('Insert this token into your form') + '">' + $(this).html() + '</a>').click(function(){ if (typeof Drupal.settings.tokenFocusedField == 'undefined') { alert(Drupal.t('First click a text field to insert your tokens into.')); } else { var myField = Drupal.settings.tokenFocusedField; var myValue = $(this).text(); //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); } else { myField.value += myValue; } $('html,body').animate({scrollTop: $(myField).offset().top}, 500); } return false; }); $(this).html(newThis); }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.pathFieldsetSummaries = { attach: function (context) { $('fieldset.path-form', context).drupalSetSummary(function (context) { var path = $('.form-item-path-alias input').val(); var automatic = $('.form-item-path-pathauto input').attr('checked'); if (automatic) { return Drupal.t('Automatic alias'); } if (path) { return Drupal.t('Alias: @alias', { '@alias': path }); } else { return Drupal.t('No alias'); } }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.menuFieldsetSummaries = { attach: function (context) { $('fieldset.block-form', context).drupalSetSummary(function (context) { if ($('#edit-media-gallery-expose-block-und', context).attr('checked')) { return Drupal.t('Enabled'); } else { return Drupal.t('Not enabled'); } }); } }; Drupal.behaviors.media_gallery_form = {}; Drupal.behaviors.media_gallery_form.attach = function (context, settings) { // Change the "Presentation settings" image to match the radio buttons / checkbox. var inputs = $('.presentation-settings input', context); if (inputs.length) { inputs.bind('change', Drupal.behaviors.media_gallery_form.format_select); Drupal.behaviors.media_gallery_form.format_select(); } }; Drupal.behaviors.media_gallery_form.format_select = function (event) { var radioValue = $('.presentation-settings input:radio:checked').val(); var icon = $('.presentation-settings .setting-icon'); var checkbox = $('.presentation-settings .field-name-media-gallery-lightbox-extras input'); // Depending on the radio button chosen add a class if (radioValue == 'node') { icon.attr('class', 'setting-icon display-page'); // Disable the checkbox checkbox.attr('disabled', true); } else { icon.attr('class', 'setting-icon display-lightbox'); // Turn on the checkbox checkbox.attr('disabled', false); // Add a class if the checkbox is checked if (checkbox.is(':checked')) { icon.attr('class', 'setting-icon display-extras'); } } }; })(jQuery); ;
mikeusry/HolidayInnAthens
hotel_athens_ga/js/js_i0lWZY61n-2X7sezox7DfNdyQ2tsrQFGHT9wlJhktj8.js
JavaScript
gpl-2.0
51,563
/* * jQuery.liveFilter * * Copyright (c) 2009 Mike Merritt * * Forked by Lim Chee Aun (cheeaun.com) * */ (function($){ $.fn.liveFilter = function(inputEl, filterEl, options){ var defaults = { filterChildSelector: null, filter: function(el, val){ return $(el).text().toUpperCase().indexOf(val.toUpperCase()) >= 0; }, before: function(){}, after: function(){} }; var options = $.extend(defaults, options); var el = $(this).find(filterEl); if (options.filterChildSelector) el = el.find(options.filterChildSelector); var filter = options.filter; $(inputEl).keyup(function(){ var val = $(this).val(); var contains = el.filter(function(){ return filter(this, val); }); var containsNot = el.not(contains); if (options.filterChildSelector){ contains = contains.parents(filterEl); containsNot = containsNot.parents(filterEl).hide(); } options.before.call(this, contains, containsNot); contains.show(); containsNot.hide(); if (val === '') { contains.show(); containsNot.show(); } options.after.call(this, contains, containsNot); }); } })(jQuery);
unicef/uPortal
sites/all/themes/uportal_backend_theme/scripts/plugins/jquery.liveFilter.js
JavaScript
gpl-2.0
1,210
http://jsfiddle.net/fusioncharts/38U6R/ http://jsfiddle.net/gh/get/jquery/1.9.1/sguha-work/fiddletest/tree/master/fiddles/Chart/Data-Labels/Configuring-x-axis-data-labels-display---wrap-mode_466/
sguha-work/fiddletest
fiddles/Chart/Data-Labels/Configuring-x-axis-data-labels-display---wrap-mode_466/url.js
JavaScript
gpl-2.0
195
var path = require('path'); var ndir = require('ndir'); var express = require('express'); var MongoStore = require('connect-mongo')(express); var ejs = require('ejs'); var routes = require('./routes'); var config = require('./config').config; var adminFilter = require('./filter/adminFilter'); var businessFilter = require('./filter/businessFilter'); var home = require('./controllers/open/home'); var maxAge = 3600000 * 24 * 30; var staticDir = path.join(__dirname, 'assets'); // 静态文件存放更目录. config.upload_temp_dir = config.upload_temp_dir || path.join(__dirname, 'assets', 'user_data'); // ensure upload dir exists ndir.mkdir(config.upload_temp_dir, function(err) { // 建立上传文件目录 if (err) { throw err; } }); config.upload_img_dir = config.upload_img_dir || path.join(__dirname, 'assets', 'user_data', 'images'); ndir.mkdir(config.upload_img_dir, function(err) { // 建立上传文件目录 if (err) { throw err; } }); var app = express(); // all environments app.configure(function() { app.set('title', 'Zero App'); app.set('port', 80); app.set('env', 'production'); ejs.open = '{{'; ejs.close = '}}'; app.engine('.html', ejs.__express); app.set('view engine', 'html'); app.set('views', path.join(__dirname, 'views')); // html 文件存放目录 app.use(express.cookieParser()); require('./model'); var mongoose = require('mongoose'); app.use(express.session({ secret: config.session_secret, store: new MongoStore({ mongooseConnection: mongoose.connection }), cookie: { maxAge: 3600000 } })); // --- 设置中间件 --- app.use(express.favicon(path.join(__dirname, 'assets/img/favicon.ico'))); app.use('/assets', express.static(staticDir)); app.use(express.logger('dev')); app.use('/admin', adminFilter.userNeeded); app.use('/business', businessFilter.bserNeeded); app.use('/', home.init); app.use(express.bodyParser({ uploadDir: config.upload_temp_dir })); app.use(express.methodOverride()); // 配置路由 routes(app); }) // development only app.configure('development', function() { app.use(express.errorHandler()); }) // production only app.configure('production', function() { //FIXME: // app.use(function(err, req, res, next) { // console.error(err.stack); // res.redirect('/500'); // }); }); app.listen(app.get('port'), function() { console.log('Express server listening on port ' + app.get('port')); });
victzero/wanzi
wanzi/app.js
JavaScript
gpl-2.0
2,518
var events = {}; function showEvent(e) { eid = e.getAttribute('data-event-id'); fid = e.getAttribute('data-frame-id'); var url = '?view=event&eid='+eid+'&fid='+fid; url += filterQuery; window.location.href = url; //video element is blocking video elements elsewhere in chrome possible interaction with mouseover event? //FIXME unless an exact cause can be determined should store all video controls and do something to the other controls when we want to load a new video seek etc or whatever may block /*var vid= $('preview'); vid.oncanplay=null; // vid.currentTime=vid.currentTime-0.1; vid.pause();*/ } function createEventHtml(zm_event, frame) { var eventHtml = new Element('div'); if ( zm_event.Archived > 0 ) { eventHtml.addClass('archived'); } new Element('p').inject(eventHtml).set('text', monitors[zm_event.MonitorId].Name); new Element('p').inject(eventHtml).set('text', zm_event.Name+(frame?('('+frame.FrameId+')'):'')); new Element('p').inject(eventHtml).set('text', zm_event.StartTime+' - '+zm_event.Length+'s'); new Element('p').inject(eventHtml).set('text', zm_event.Cause); if ( event.Notes ) { new Element('p').inject(eventHtml).set('text', event.Notes); } if ( event.Archived > 0 ) { new Element('p').inject(eventHtml).set( 'text', archivedString); } return eventHtml; } function showEventDetail( eventHtml ) { $('instruction').addClass( 'hidden' ); $('eventData').empty(); $('eventData').adopt( eventHtml ); $('eventData').removeClass( 'hidden' ); } function eventDataResponse( respObj, respText ) { var zm_event = respObj.event; if ( !zm_event ) { console.log('Null event'); return; } events[zm_event.Id] = zm_event; if ( respObj.loopback ) { requestFrameData(zm_event.Id, respObj.loopback); } } function frameDataResponse( respObj, respText ) { var frame = respObj.frameimage; if ( !frame.FrameId ) { console.log('Null frame'); return; } var zm_event = events[frame.EventId]; if ( !zm_event ) { console.error('No event '+frame.eventId+' found'); return; } if ( !zm_event['frames'] ) { console.log("No frames data in event response"); console.log(zm_event); console.log(respObj); zm_event['frames'] = {}; } zm_event['frames'][frame.FrameId] = frame; zm_event['frames'][frame.FrameId]['html'] = createEventHtml( zm_event, frame ); showEventData(frame.EventId, frame.FrameId); } function showEventData(eventId, frameId) { if ( events[eventId] ) { var zm_event = events[eventId]; if ( zm_event['frames'] ) { if ( zm_event['frames'][frameId] ) { showEventDetail( zm_event['frames'][frameId]['html'] ); var imagePath = 'index.php?view=image&eid='+eventId+'&fid='+frameId; var videoName = zm_event.DefaultVideo; loadEventImage( imagePath, eventId, frameId, zm_event.Width, zm_event.Height, zm_event.Frames/zm_event.Length, videoName, zm_event.Length, zm_event.StartTime, monitors[zm_event.MonitorId]); return; } else { console.log('No frames for ' + frameId); } } else { console.log('No frames'); } } else { console.log('No event for ' + eventId); } } var eventQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse }); var frameQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse }); function requestFrameData( eventId, frameId ) { if ( !events[eventId] ) { eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId; eventQuery.send(); } else { frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId; frameQuery.send(); } } function previewEvent(slot) { eventId = slot.getAttribute('data-event-id'); frameId = slot.getAttribute('data-frame-id'); if ( events[eventId] ) { showEventData(eventId, frameId); } else { requestFrameData(eventId, frameId); } } function loadEventImage( imagePath, eid, fid, width, height, fps, videoName, duration, startTime, Monitor ) { var vid = $('preview'); var imageSrc = $('imageSrc'); if ( videoName && vid ) { vid.show(); imageSrc.hide(); var newsource=imagePath.slice(0, imagePath.lastIndexOf('/'))+'/'+videoName; //console.log(newsource); //console.log(sources[0].src.slice(-newsource.length)); if ( newsource != vid.currentSrc.slice(-newsource.length) || vid.readyState == 0 ) { //console.log("loading new"); //it is possible to set a long source list here will that be unworkable? var sources = vid.getElementsByTagName('source'); sources[0].src = newsource; var tracks = vid.getElementsByTagName('track'); if (tracks.length) { tracks[0].parentNode.removeChild(tracks[0]); } vid.load(); addVideoTimingTrack(vid, Monitor.LabelFormat, Monitor.Name, duration, startTime); vid.currentTime = fid/fps; } else { if ( ! vid.seeking ) { vid.currentTime=fid/fps; } } } else { if ( vid ) vid.hide(); imageSrc.show(); imageSrc.setProperty('src', imagePath); imageSrc.setAttribute('data-event-id', eid); imageSrc.setAttribute('data-frame-id', fid); imageSrc.onclick=window['showEvent'].bind(imageSrc, imageSrc); } var eventData = $('eventData'); eventData.removeEvent('click'); eventData.addEvent('click', showEvent.pass()); } function tlZoomBounds( minTime, maxTime ) { location.replace('?view='+currentView+filterQuery+'&minTime='+minTime+'&maxTime='+maxTime); } function tlZoomOut() { location.replace('?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+zoom_range); } function tlPanLeft() { location.replace('?view='+currentView+filterQuery+'&midTime='+minTime+'&range='+range); } function tlPanRight() { location.replace('?view='+currentView+filterQuery+'&midTime='+maxTime+'&range='+range); } window.addEventListener("DOMContentLoaded", function() { document.querySelectorAll("div.event").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); document.querySelectorAll("div.activity").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); });
Simpler1/ZoneMinder
web/skins/classic/views/js/timeline.js
JavaScript
gpl-2.0
6,613
// Catch Flames Custom Scripts jQuery(document).ready(function() { /* Waypoint */ if ( jQuery.isFunction( jQuery.fn.waypoint ) ) { var waypointheader = new Waypoint({ element: document.getElementById('page'), handler: function(direction) { if( direction == 'down' ) { jQuery('#header-top').addClass( 'fixed-header' ); } else { jQuery('#header-top').removeClass( 'fixed-header' ); } }, offset: -50 }) var waypointtoup = new Waypoint({ element: document.getElementById('page'), handler: function(direction) { if( direction == 'up' ) { jQuery('#scrollup').fadeOut(); } else { jQuery('#scrollup').fadeIn(); } }, offset: -500 }) } jQuery('#scrollup').click(function () { jQuery('body,html').animate({ scrollTop: 1 }, 800); return false; }); /* Social */ jQuery( '#header-social-toggle' ).on( 'click.catchflames', function( event ) { var that = jQuery( this ), wrapper = jQuery( '#header-social' ); that.toggleClass( 'displayblock' ); wrapper.toggleClass( 'displaynone' ); }); /* Search */ jQuery( '#header-search-toggle' ).on( 'click.catchflames', function( event ) { var that = jQuery( this ), wrapper = jQuery( '#header-search' ); that.toggleClass( 'displayblock' ); wrapper.toggleClass( 'displaynone' ); }); //sidr if ( jQuery.isFunction( jQuery.fn.sidr ) ) { jQuery('#fixed-header-menu').sidr({ name: 'mobile-top-nav', side: 'left' // By default }); jQuery('#header-left-menu').sidr({ name: 'mobile-header-left-nav', side: 'left' // By default }); } });
ilke-zilci/newcomers-wp
wp-content/themes/catch-flames/js/catchflames-custom.js
JavaScript
gpl-2.0
1,623
// jshint ignore: start /* eslint-disable */ /** * WordPress dependencies */ const { __ } = wp.i18n; const { Component, createRef, useMemo, Fragment } = wp.element; const { ToggleControl, withSpokenMessages, } = wp.components; const { LEFT, RIGHT, UP, DOWN, BACKSPACE, ENTER, ESCAPE } = wp.keycodes; const { getRectangleFromRange } = wp.dom; const { prependHTTP } = wp.url; const { create, insert, isCollapsed, applyFormat, getTextContent, slice, } = wp.richText; const { URLPopover } = wp.blockEditor; /** * Internal dependencies */ import { createLinkFormat, isValidHref } from './utils'; import PositionedAtSelection from './positioned-at-selection'; import LinkEditor from './link-editor'; import LinkViewer from './link-viewer'; const stopKeyPropagation = ( event ) => event.stopPropagation(); function isShowingInput( props, state ) { return props.addingLink || state.editLink; } const URLPopoverAtLink = ( { isActive, addingLink, value, resetOnMount, ...props } ) => { const anchorRect = useMemo( () => { const selection = window.getSelection(); const range = selection.rangeCount > 0 ? selection.getRangeAt( 0 ) : null; if ( ! range ) { return; } if ( addingLink ) { return getRectangleFromRange( range ); } let element = range.startContainer; // If the caret is right before the element, select the next element. element = element.nextElementSibling || element; while ( element.nodeType !== window.Node.ELEMENT_NODE ) { element = element.parentNode; } const closest = element.closest( 'a' ); if ( closest ) { return closest.getBoundingClientRect(); } }, [ isActive, addingLink, value.start, value.end ] ); if ( ! anchorRect ) { return null; } resetOnMount( anchorRect ); return <URLPopover anchorRect={ anchorRect } { ...props } />; }; class InlineLinkUI extends Component { constructor() { super( ...arguments ); this.editLink = this.editLink.bind( this ); this.submitLink = this.submitLink.bind( this ); this.onKeyDown = this.onKeyDown.bind( this ); this.onChangeInputValue = this.onChangeInputValue.bind( this ); this.setLinkTarget = this.setLinkTarget.bind( this ); this.setNoFollow = this.setNoFollow.bind( this ); this.setSponsored = this.setSponsored.bind( this ); this.onFocusOutside = this.onFocusOutside.bind( this ); this.resetState = this.resetState.bind( this ); this.autocompleteRef = createRef(); this.resetOnMount = this.resetOnMount.bind( this ); this.state = { opensInNewWindow: false, noFollow: false, sponsored: false, inputValue: '', anchorRect: false, }; } static getDerivedStateFromProps( props, state ) { const { activeAttributes: { url, target, rel } } = props; const opensInNewWindow = target === '_blank'; if ( ! isShowingInput( props, state ) ) { if ( url !== state.inputValue ) { return { inputValue: url }; } if ( opensInNewWindow !== state.opensInNewWindow ) { return { opensInNewWindow }; } if ( typeof rel === 'string' ) { const noFollow = rel.split( ' ' ).includes( 'nofollow' ); const sponsored = rel.split( ' ' ).includes( 'sponsored' ); if ( noFollow !== state.noFollow ) { return { noFollow }; } if ( sponsored !== state.sponsored ) { return { sponsored }; } } } return null; } onKeyDown( event ) { if ( [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ].indexOf( event.keyCode ) > -1 ) { // Stop the key event from propagating up to ObserveTyping.startTypingInTextField. event.stopPropagation(); } if ( [ ESCAPE ].indexOf( event.keyCode ) > -1 ) { this.resetState(); } } onChangeInputValue( inputValue ) { this.setState( { inputValue } ); } setLinkTarget( opensInNewWindow ) { const { activeAttributes: { url = '' }, value, onChange } = this.props; this.setState( { opensInNewWindow } ); // Apply now if URL is not being edited. if ( ! isShowingInput( this.props, this.state ) ) { const selectedText = getTextContent( slice( value ) ); onChange( applyFormat( value, createLinkFormat( { url, opensInNewWindow, noFollow: this.state.noFollow, sponsored: this.state.sponsored, text: selectedText, } ) ) ); } } setNoFollow( noFollow ) { const { activeAttributes: { url = '' }, value, onChange } = this.props; this.setState( { noFollow } ); // Apply now if URL is not being edited. if ( ! isShowingInput( this.props, this.state ) ) { const selectedText = getTextContent( slice( value ) ); onChange( applyFormat( value, createLinkFormat( { url, opensInNewWindow: this.state.opensInNewWindow, noFollow, sponsored: this.state.sponsored, text: selectedText, } ) ) ); } } setSponsored( sponsored ) { const { activeAttributes: { url = '' }, value, onChange } = this.props; this.setState( { sponsored } ); // Apply now if URL is not being edited. if ( ! isShowingInput( this.props, this.state ) ) { const selectedText = getTextContent( slice( value ) ); onChange( applyFormat( value, createLinkFormat( { url, opensInNewWindow: this.state.opensInNewWindow, noFollow: this.state.noFollow, sponsored, text: selectedText, } ) ) ); } } editLink( event ) { this.setState( { editLink: true } ); event.preventDefault(); } submitLink( event ) { const { isActive, value, onChange, speak } = this.props; const { inputValue, opensInNewWindow, noFollow, sponsored } = this.state; const url = prependHTTP( inputValue ); const selectedText = getTextContent( slice( value ) ); const format = createLinkFormat( { url, opensInNewWindow, noFollow, sponsored, text: selectedText, } ); event.preventDefault(); if ( isCollapsed( value ) && ! isActive ) { const toInsert = applyFormat( create( { text: url } ), format, 0, url.length ); onChange( insert( value, toInsert ) ); } else { onChange( applyFormat( value, format ) ); } this.resetState(); if ( ! isValidHref( url ) ) { speak( __( 'Warning: the link has been inserted but could have errors. Please test it.', 'all-in-one-seo-pack' ), 'assertive' ); } else if ( isActive ) { speak( __( 'Link edited.', 'all-in-one-seo-pack' ), 'assertive' ); } else { speak( __( 'Link inserted.', 'all-in-one-seo-pack' ), 'assertive' ); } } onFocusOutside() { // The autocomplete suggestions list renders in a separate popover (in a portal), // so onClickOutside fails to detect that a click on a suggestion occured in the // LinkContainer. Detect clicks on autocomplete suggestions using a ref here, and // return to avoid the popover being closed. const autocompleteElement = this.autocompleteRef.current; if ( autocompleteElement && autocompleteElement.contains( event.target ) ) { return; } this.resetState(); } resetState() { this.props.stopAddingLink(); this.setState( { editLink: false } ); } resetOnMount( anchorRect ) { if ( this.state.anchorRect !== anchorRect ) { this.setState( { opensInNewWindow: false, noFollow: false, sponsored: false, anchorRect: anchorRect } ); } } render() { const { isActive, activeAttributes: { url, target, rel }, addingLink, value } = this.props; if ( ! isActive && ! addingLink ) { return null; } const { inputValue, opensInNewWindow, noFollow, sponsored } = this.state; const showInput = isShowingInput( this.props, this.state ); if ( ! opensInNewWindow && target === '_blank' ) { this.setState( { opensInNewWindow: true } ); } if ( typeof rel === 'string' ) { const relNoFollow = rel.split( ' ' ).includes( 'nofollow' ); const relSponsored = rel.split( ' ' ).includes( 'sponsored' ); if ( relNoFollow !== noFollow ) { this.setState( { noFollow: relNoFollow } ); } if ( relSponsored !== sponsored ) { this.setState( { sponsored: relSponsored } ); } } return ( <PositionedAtSelection key={ `${ value.start }${ value.end }` /* Used to force rerender on selection change */ } > <URLPopoverAtLink resetOnMount={ this.resetOnMount } value={ value } isActive={ isActive } addingLink={ addingLink } onFocusOutside={ this.onFocusOutside } onClose={ () => { if ( ! inputValue ) { this.resetState(); } } } focusOnMount={ showInput ? 'firstElement' : false } renderSettings={ () => ( <Fragment> <ToggleControl label={ __( 'Open in New Tab', 'all-in-one-seo-pack' ) } checked={ opensInNewWindow } onChange={ this.setLinkTarget } /> <ToggleControl label={ __( 'Add "nofollow" to link', 'all-in-one-seo-pack' ) } checked={ noFollow } onChange={ this.setNoFollow } /> <ToggleControl label={ __( 'Add "sponsored" to link', 'all-in-one-seo-pack' ) } checked={ sponsored } onChange={ this.setSponsored } /> </Fragment> ) } > { showInput ? ( <LinkEditor className="editor-format-toolbar__link-container-content block-editor-format-toolbar__link-container-content" value={ inputValue } onChangeInputValue={ this.onChangeInputValue } onKeyDown={ this.onKeyDown } onKeyPress={ stopKeyPropagation } onSubmit={ this.submitLink } autocompleteRef={ this.autocompleteRef } /> ) : ( <LinkViewer className="editor-format-toolbar__link-container-content block-editor-format-toolbar__link-container-content" onKeyPress={ stopKeyPropagation } url={ url } onEditLinkClick={ this.editLink } linkClassName={ isValidHref( prependHTTP( url ) ) ? undefined : 'has-invalid-link' } /> ) } </URLPopoverAtLink> </PositionedAtSelection> ); } } export default withSpokenMessages( InlineLinkUI );
semperfiwebdesign/all-in-one-seo-pack
src/components/inline.js
JavaScript
gpl-2.0
9,828
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp","tr",{title:"Erişilebilirlik Talimatları",contents:"Yardım içeriği. Bu pencereyi kapatmak için ESC tuşuna basın.",legend:[{name:"Genel",items:[{name:"Düzenleyici Araç Çubuğu",legend:"Araç çubuğunda gezinmek için ${toolbarFocus} basın. TAB ve SHIFT-TAB ile önceki ve sonraki araç çubuğu grubuna taşıyın. SAĞ OK veya SOL OK ile önceki ve sonraki bir araç çubuğu düğmesini hareket ettirin. SPACE tuşuna basın veya araç çubuğu düğmesini etkinleştirmek için ENTER tuşna basın."}, {name:"Diyalog Düzenleyici",legend:"Dialog penceresi içinde, sonraki iletişim alanına gitmek için SEKME tuşuna basın, önceki alana geçmek için SHIFT + TAB tuşuna basın, pencereyi göndermek için ENTER tuşuna basın, dialog penceresini iptal etmek için ESC tuşuna basın. Birden çok sekme sayfaları olan diyalogların, sekme listesine gitmek için ALT + F10 tuşlarına basın. Sonra TAB veya SAĞ OK sonraki sekmeye taşıyın. SHIFT + TAB veya SOL OK ile önceki sekmeye geçin. Sekme sayfayı seçmek için SPACE veya ENTER tuşuna basın."}, {name:"İçerik Menü Editörü",legend:"İçerik menüsünü açmak için ${contextMenu} veya UYGULAMA TUŞU'na basın. Daha sonra SEKME veya AŞAĞI OK ile bir sonraki menü seçeneği taşıyın. SHIFT + TAB veya YUKARI OK ile önceki seçeneğe gider. Menü seçeneğini seçmek için SPACE veya ENTER tuşuna basın. Seçili seçeneğin alt menüsünü SPACE ya da ENTER veya SAĞ OK açın. Üst menü öğesini geçmek için ESC veya SOL OK ile geri dönün. ESC ile bağlam menüsünü kapatın."},{name:"Liste Kutusu Editörü",legend:"Liste kutusu içinde, bir sonraki liste öğesine SEKME VEYA AŞAĞI OK ile taşıyın. SHIFT + TAB veya YUKARI önceki liste öğesi taşıyın. Liste seçeneği seçmek için SPACE veya ENTER tuşuna basın. Liste kutusunu kapatmak için ESC tuşuna basın."}, {name:"Element Yol Çubuğu Editörü",legend:"Elementlerin yol çubuğunda gezinmek için ${ElementsPathFocus} basın. SEKME veya SAĞ OK ile sonraki element düğmesine taşıyın. SHIFT + TAB veya SOL OK önceki düğmeye hareket ettirin. Editör içindeki elementi seçmek için ENTER veya SPACE tuşuna basın."}]},{name:"Komutlar",items:[{name:"Komutu geri al",legend:"$(undo)'ya basın"},{name:"Komutu geri al",legend:"${redo} basın"},{name:" Kalın komut",legend:"${bold} basın"},{name:" İtalik komutu",legend:"${italic} basın"}, {name:" Alttan çizgi komutu",legend:"${underline} basın"},{name:" Bağlantı komutu",legend:"${link} basın"},{name:" Araç çubuğu Toplama komutu",legend:"${toolbarCollapse} basın"},{name:"Önceki komut alanına odaklan",legend:"Düzeltme imleçinden önce, en yakın uzaktaki alana erişmek için ${accessPreviousSpace} basın, örneğin: iki birleşik HR elementleri. Aynı tuş kombinasyonu tekrarıyla diğer alanlarada ulaşın."},{name:"Sonraki komut alanına odaklan",legend:"Düzeltme imleçinden sonra, en yakın uzaktaki alana erişmek için ${accessNextSpace} basın, örneğin: iki birleşik HR elementleri. Aynı tuş kombinasyonu tekrarıyla diğer alanlarada ulaşın."}, {name:"Erişilebilirlik Yardımı",legend:"${a11yHelp}'e basın"}]}],backspace:"Backspace",tab:"Tab",enter:"Enter",shift:"Shift",ctrl:"Ctrl",alt:"Alt",pause:"Pause",capslock:"Caps Lock",escape:"Escape",pageUp:"Sayfa Yukarı",pageDown:"Sayfa Aşağı",end:"End",home:"Home",leftArrow:"Sol ok",upArrow:"Yukarı ok",rightArrow:"Sağ ok",downArrow:"Aşağı ok",insert:"Insert","delete":"Silme",leftWindowKey:"Sol windows tuşu",rightWindowKey:"Sağ windows tuşu",selectKey:"Select key",numpad0:"Numpad 0",numpad1:"Numpad 1", numpad2:"Numpad 2",numpad3:"Numpad 3",numpad4:"Numpad 4",numpad5:"Numpad 5",numpad6:"Numpad 6",numpad7:"Numpad 7",numpad8:"Numpad 8",numpad9:"Numpad 9",multiply:"Çarpma",add:"Toplama",subtract:"Çıkarma",decimalPoint:"Ondalık işareti",divide:"Bölme",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Noktalı virgül",equalSign:"Eşittir",comma:"Virgül",dash:"Eksi",period:"Nokta",forwardSlash:"Forward Slash", graveAccent:"Grave Accent",openBracket:"Parantez aç",backSlash:"Backslash",closeBracket:"Parantez kapa",singleQuote:"Tek tırnak"});
mJehanno/myLittleBlog
Back/ckeditor/plugins/a11yhelp/dialogs/lang/tr.js
JavaScript
gpl-2.0
4,484
/** * Express configuration */ 'use strict'; import express from 'express'; import favicon from 'serve-favicon'; import morgan from 'morgan'; import compression from 'compression'; import bodyParser from 'body-parser'; import methodOverride from 'method-override'; import cookieParser from 'cookie-parser'; import errorHandler from 'errorhandler'; import path from 'path'; import lusca from 'lusca'; import config from './environment'; import passport from 'passport'; import session from 'express-session'; import connectMongo from 'connect-mongo'; import mongoose from 'mongoose'; var MongoStore = connectMongo(session); export default function(app) { var env = app.get('env'); if (env === 'development' || env === 'test') { app.use(express.static(path.join(config.root, '.tmp'))); } if (env === 'production') { app.use(favicon(path.join(config.root, 'client', 'favicon.ico'))); } app.set('appPath', path.join(config.root, 'client')); app.use(express.static(app.get('appPath'))); app.use(morgan('dev')); app.set('views', `${config.root}/server/views`); app.set('view engine', 'jade'); app.use(compression()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(cookieParser()); app.use(passport.initialize()); // Persist sessions with MongoStore / sequelizeStore // We need to enable sessions for passport-twitter because it's an // oauth 1.0 strategy, and Lusca depends on sessions app.use(session({ secret: config.secrets.session, saveUninitialized: true, resave: false, store: new MongoStore({ mongooseConnection: mongoose.connection, db: 'eecr' }) })); /** * Lusca - express server security * https://github.com/krakenjs/lusca */ if (env !== 'test' && !process.env.SAUCE_USERNAME) { app.use(lusca({ csrf: { angular: true }, xframe: 'SAMEORIGIN', hsts: { maxAge: 31536000, //1 year, in seconds includeSubDomains: true, preload: true }, xssProtection: true })); } if ('development' === env) { const webpackDevMiddleware = require('webpack-dev-middleware'); const stripAnsi = require('strip-ansi'); const webpack = require('webpack'); const makeWebpackConfig = require('../../webpack.make'); const webpackConfig = makeWebpackConfig({ DEV: true }); const compiler = webpack(webpackConfig); const browserSync = require('browser-sync').create(); /** * Run Browsersync and use middleware for Hot Module Replacement */ browserSync.init({ open: false, logFileChanges: false, proxy: 'localhost:' + config.port, ws: true, middleware: [ webpackDevMiddleware(compiler, { noInfo: false, stats: { colors: true, timings: true, chunks: false } }) ], port: config.browserSyncPort, plugins: ['bs-fullscreen-message'] }); /** * Reload all devices when bundle is complete * or send a fullscreen error message to the browser instead */ compiler.plugin('done', function(stats) { console.log('webpack done hook'); if (stats.hasErrors() || stats.hasWarnings()) { return browserSync.sockets.emit('fullscreen:message', { title: 'Webpack Error:', body: stripAnsi(stats.toString()), timeout: 100000 }); } browserSync.reload(); }); } if (env === 'development' || env === 'test') { app.use(errorHandler()); // Error handler - has to be last } }
arkdelkaos/EECR
server/config/express.js
JavaScript
gpl-2.0
3,663
module.exports = async ({ client, configJS, Utils: { IsURL }, Constants: { Colors } }, msg, commandData) => { const handleQuit = () => { msg.reply({ embed: { color: Colors.RED, description: `You've exited the profile setup menu!`, }, }); }; if (msg.suffix === "setup") { let m = await msg.reply({ embed: { color: Colors.LIGHT_BLUE, author: { name: `Profile setup for ${msg.author.tag}`, }, title: `Let's setup your GAwesomeBot profile ~~--~~ See it by clicking here`, url: `${configJS.hostingURL}activity/users?q=${encodeURIComponent(`${msg.author.tag}`)}`, thumbnail: { url: msg.author.displayAvatarURL({ size: 64, format: "png" }), }, description: `First of all, do you want to make data such as mutual servers with me and profile fields public?`, footer: { text: msg.author.userDocument.isProfilePublic ? `It's already public now, by answering "yes" you're keeping it that way.` : `It's currently not public, by answering "yes" you're making it public.`, }, }, }); const changes = {}; let message = null; try { message = await client.awaitPMMessage(msg.channel, msg.author); } catch (err) { switch (err.code) { case "AWAIT_QUIT": return handleQuit(); case "AWAIT_EXPIRED": { m = await m.edit({ embed: { color: Colors.LIGHT_ORANGE, description: `You didn't answer in time... We'll keep your profile's publicity the way it currently is.`, footer: { text: `Changed your mind? Type "quit" and restart the process by running "profile setup"`, }, }, }); changes.isProfilePublic = msg.author.userDocument.isProfilePublic; } } } if (message && message.content) changes.isProfilePublic = configJS.yesStrings.includes(message.content.toLowerCase().trim()); m = await msg.reply({ embed: { color: Colors.LIGHT_BLUE, title: `Next, here's your current backround.`, image: { url: IsURL(msg.author.userDocument.profile_background_image) ? msg.author.userDocument.profile_background_image : ``, }, thumbnail: { url: msg.author.displayAvatarURL({ size: 64, format: "png" }), }, author: { name: `Profile setup for ${msg.author.tag}`, }, description: `Your current image URL is: \`\`\`\n${msg.author.userDocument.profile_background_image}\`\`\`\nWould you like a new one? Just paste in a URL.`, footer: { text: `Answer with "." to not change it, or "default" to reset it to the default image. | This message expires in 2 minutes`, }, }, }); try { message = await client.awaitPMMessage(msg.channel, msg.author, 120000); } catch (err) { message = undefined; switch (err.code) { case "AWAIT_QUIT": return handleQuit(); case "AWAIT_EXPIRED": { m = await m.edit({ embed: { color: Colors.LIGHT_ORANGE, description: `You didn't answer in time... We'll keep your current profile backround.`, footer: { text: `Changed your mind? Type "quit" and restart the process by running "profile setup"`, }, }, }); changes.profile_background_image = msg.author.userDocument.profile_background_image; } } } if (message) { if (message.content.toLowerCase().trim() === "default") { changes.profile_background_image = "http://i.imgur.com/8UIlbtg.jpg"; } else if (message.content === ".") { changes.profile_background_image = msg.author.userDocument.profile_background_image; } else if (message.content !== "") { changes.profile_background_image = message.content.trim(); } } m = await msg.reply({ embed: { color: Colors.LIGHT_BLUE, title: `Done! That will be your new picture. 🏖`, description: `Now, can you please tell us a little about yourself...? (max 2000 characters)`, thumbnail: { url: msg.author.displayAvatarURL({ size: 64, format: "png" }), }, author: { name: `Profile setup for ${msg.author.tag}`, }, footer: { text: `Answer with "." to not change your bio, or "none" to reset it | This message expires in 5 minutes`, }, }, }); try { message = await client.awaitPMMessage(msg.channel, msg.author, 300000); } catch (err) { message = undefined; switch (err.code) { case "AWAIT_QUIT": return handleQuit(); case "AWAIT_EXPIRED": { m = await m.edit({ embed: { color: Colors.LIGHT_ORANGE, description: `You didn't answer in time... We'll keep your current bio.`, footer: { text: `Changed your mind? Type "quit" and restart the process by running "profile setup"`, }, }, }); if (msg.author.userDocument.profile_fields && msg.author.userDocument.profile_fields.Bio) changes.Bio = msg.author.userDocument.profile_fields.Bio; } } } if (message && message.content) { if (message.content.trim() === ".") { if (msg.author.userDocument.profile_fields && msg.author.userDocument.profile_fields.Bio) changes.Bio = msg.author.userDocument.profile_fields.Bio; else changes.Bio = null; } else if (message.content.toLowerCase().trim() === "none") { changes.Bio = "delete"; } else { changes.Bio = message.content.trim(); } } const userQueryDocument = msg.author.userDocument.query; userQueryDocument.set("isProfilePublic", changes.isProfilePublic) .set("profile_background_image", changes.profile_background_image); if (!msg.author.userDocument.profile_fields) userQueryDocument.set("profile_fields", {}); if (changes.Bio === "delete") { userQueryDocument.remove("profile_fields.Bio"); } else if (changes.Bio) { userQueryDocument.set("profile_fields.Bio", changes.Bio); } await msg.author.userDocument.save().catch(err => { logger.warn(`Failed to save user data for profile setup.`, { usrid: msg.author.id }, err); }); msg.reply({ embed: { color: Colors.GREEN, title: `You're all set! ~~--~~ Click here to see your profile. 👀`, description: `Thanks for your input.`, url: `${configJS.hostingURL}activity/users?q=${encodeURIComponent(`${msg.author.tag}`)}`, footer: { text: `Changed your mind? Run "profile setup" once again!`, }, }, }); } };
GilbertGobbels/GAwesomeBot
Commands/PM/profile.js
JavaScript
gpl-2.0
6,231
// ============================================================================= // Module to configure an ExpressJS web server // ============================================================================= // Requires // { // "express": "4.13.3", // "cookie-parser": "1.4.0", // "morgan": "1.6.1", // "body-parser" : "1.14.1", // "express-session" : "1.12.1", // "method-override" : "2.3.5" // } var express = require('express'); var cookieParser = require('cookie-parser'); var methodOverride = require('method-override'); var http = require('http'); var bodyParser = require('body-parser'); var morgan = require('morgan'); var app = express(); app.use(morgan('dev')); // log every request to the console app.use(cookieParser()); // read cookies (needed for auth) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); module.exports = { app : app }
apycazo/nodes
modules/express-cfg.js
JavaScript
gpl-2.0
971
(function ($) { /** * Attaches double-click behavior to toggle full path of Krumo elements. */ Drupal.behaviors.devel = { attach: function (context, settings) { // Add hint to footnote $('.krumo-footnote .krumo-call').once().before('<img style="vertical-align: middle;" title="Click to expand. Double-click to show path." src="' + settings.basePath + 'misc/help.png"/>'); var krumo_name = []; var krumo_type = []; function krumo_traverse(el) { krumo_name.push($(el).html()); krumo_type.push($(el).siblings('em').html().match(/\w*/)[0]); if ($(el).closest('.krumo-nest').length > 0) { krumo_traverse($(el).closest('.krumo-nest').prev().find('.krumo-name')); } } $('.krumo-child > div:first-child', context).dblclick( function(e) { if ($(this).find('> .krumo-php-path').length > 0) { // Remove path if shown. $(this).find('> .krumo-php-path').remove(); } else { // Get elements. krumo_traverse($(this).find('> a.krumo-name')); // Create path. var krumo_path_string = ''; for (var i = krumo_name.length - 1; i >= 0; --i) { // Start element. if ((krumo_name.length - 1) == i) krumo_path_string += '$' + krumo_name[i]; if (typeof krumo_name[(i-1)] !== 'undefined') { if (krumo_type[i] == 'Array') { krumo_path_string += "["; if (!/^\d*$/.test(krumo_name[(i-1)])) krumo_path_string += "'"; krumo_path_string += krumo_name[(i-1)]; if (!/^\d*$/.test(krumo_name[(i-1)])) krumo_path_string += "'"; krumo_path_string += "]"; } if (krumo_type[i] == 'Object') krumo_path_string += '->' + krumo_name[(i-1)]; } } $(this).append('<div class="krumo-php-path" style="font-family: Courier, monospace; font-weight: bold;">' + krumo_path_string + '</div>'); // Reset arrays. krumo_name = []; krumo_type = []; } } ); } }; })(jQuery); ; /** * Cookie plugin 1.0 * * Copyright (c) 2006 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 * */ jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("")}else{var d=null;if(document.cookie&&document.cookie!=""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}}; ; (function ($) { Drupal.ModuleFilter = {}; Drupal.ModuleFilter.explode = function(string) { var queryArray = string.match(/([a-zA-Z]+\:(\w+|"[^"]+")*)|\w+|"[^"]+"/g); if (!queryArray) { queryArray = new Array(); } var i = queryArray.length; while (i--) { queryArray[i] = queryArray[i].replace(/"/g, ""); } return queryArray; }; Drupal.ModuleFilter.getState = function(key) { if (!Drupal.ModuleFilter.state) { Drupal.ModuleFilter.state = {}; var cookie = $.cookie('DrupalModuleFilter'); var query = cookie ? cookie.split('&') : []; if (query) { for (var i in query) { // Extra check to avoid js errors in Chrome, IE and Safari when // combined with JS like twitter's widget.js. // See http://drupal.org/node/798764. if (typeof(query[i]) == 'string' && query[i].indexOf('=') != -1) { var values = query[i].split('='); if (values.length === 2) { Drupal.ModuleFilter.state[values[0]] = values[1]; } } } } } return Drupal.ModuleFilter.state[key] ? Drupal.ModuleFilter.state[key] : false; }; Drupal.ModuleFilter.setState = function(key, value) { var existing = Drupal.ModuleFilter.getState(key); if (existing != value) { Drupal.ModuleFilter.state[key] = value; var query = []; for (var i in Drupal.ModuleFilter.state) { query.push(i + '=' + Drupal.ModuleFilter.state[i]); } $.cookie('DrupalModuleFilter', query.join('&'), { expires: 7, path: '/' }); } }; Drupal.ModuleFilter.Filter = function(element, selector, options) { var self = this; this.element = element; this.text = $(this.element).val(); this.settings = Drupal.settings.moduleFilter; this.selector = selector; this.options = $.extend({ delay: 500, striping: false, childSelector: null, empty: Drupal.t('No results'), rules: new Array() }, options); if (this.options.wrapper == undefined) { this.options.wrapper = $(self.selector).parent(); } // Add clear button. this.element.after('<div class="module-filter-clear"><a href="#" class="js-hide">' + Drupal.t('clear') + '</a></div>'); if (this.text) { $('.module-filter-clear a', this.element.parent()).removeClass('js-hide'); } $('.module-filter-clear a', this.element.parent()).click(function() { self.element.val(''); self.text = ''; delete self.queries; self.applyFilter(); self.element.focus(); $(this).addClass('js-hide'); return false; }); this.updateQueries = function() { var queryStrings = Drupal.ModuleFilter.explode(self.text); self.queries = new Array(); for (var i in queryStrings) { var query = { operator: 'text', string: queryStrings[i] }; if (self.operators != undefined) { // Check if an operator is possibly used. if (queryStrings[i].indexOf(':') > 0) { // Determine operator used. var args = queryStrings[i].split(':', 2); var operator = args.shift(); if (self.operators[operator] != undefined) { query.operator = operator; query.string = args.shift(); } } } query.string = query.string.toLowerCase(); self.queries.push(query); } if (self.queries.length <= 0) { // Add a blank string query. self.queries.push({ operator: 'text', string: '' }); } }; this.applyFilter = function() { self.results = new Array(); self.updateQueries(); if (self.index == undefined) { self.buildIndex(); } self.element.trigger('moduleFilter:start'); $.each(self.index, function(key, item) { var $item = item.element; for (var i in self.queries) { var query = self.queries[i]; if (query.operator == 'text') { if (item.text.indexOf(query.string) < 0) { continue; } } else { var func = self.operators[query.operator]; if (!(func(query.string, self, item))) { continue; } } var rulesResult = self.processRules(item); if (rulesResult !== false) { return true; } } $item.addClass('js-hide'); }); self.element.trigger('moduleFilter:finish', { results: self.results }); if (self.options.striping) { self.stripe(); } if (self.results.length > 0) { self.options.wrapper.find('.module-filter-no-results').remove(); } else { if (!self.options.wrapper.find('.module-filter-no-results').length) { self.options.wrapper.append($('<p class="module-filter-no-results"/>').text(self.options.empty)); }; } }; self.element.keyup(function(e) { switch (e.which) { case 13: if (self.timeOut) { clearTimeout(self.timeOut); } self.applyFilter(); break; default: if (self.text != $(this).val()) { if (self.timeOut) { clearTimeout(self.timeOut); } self.text = $(this).val(); if (self.text) { self.element.parent().find('.module-filter-clear a').removeClass('js-hide'); } else { self.element.parent().find('.module-filter-clear a').addClass('js-hide'); } self.element.trigger('moduleFilter:keyup'); self.timeOut = setTimeout(self.applyFilter, self.options.delay); } break; } }); self.element.keypress(function(e) { if (e.which == 13) e.preventDefault(); }); }; Drupal.ModuleFilter.Filter.prototype.buildIndex = function() { var self = this; var index = new Array(); $(this.selector).each(function(i) { var text = (self.options.childSelector) ? $(self.options.childSelector, this).text() : $(this).text(); var item = { key: i, element: $(this), text: text.toLowerCase() }; for (var j in self.options.buildIndex) { var func = self.options.buildIndex[j]; item = $.extend(func(self, item), item); } $(this).data('indexKey', i); index.push(item); delete item; }); this.index = index; }; Drupal.ModuleFilter.Filter.prototype.processRules = function(item) { var self = this; var $item = item.element; var rulesResult = true; if (self.options.rules.length > 0) { for (var i in self.options.rules) { var func = self.options.rules[i]; rulesResult = func(self, item); if (rulesResult === false) { break; } } } if (rulesResult !== false) { $item.removeClass('js-hide'); self.results.push(item); } return rulesResult; }; Drupal.ModuleFilter.Filter.prototype.stripe = function() { var self = this; var flip = { even: 'odd', odd: 'even' }; var stripe = 'odd'; $.each(self.index, function(key, item) { if (!item.element.hasClass('js-hide')) { item.element.removeClass('odd even') .addClass(stripe); stripe = flip[stripe]; } }); }; $.fn.moduleFilter = function(selector, options) { var filterInput = this; filterInput.parents('.module-filter-inputs-wrapper').show(); if (Drupal.settings.moduleFilter.setFocus) { filterInput.focus(); } filterInput.data('moduleFilter', new Drupal.ModuleFilter.Filter(this, selector, options)); }; })(jQuery); ; (function($) { Drupal.behaviors.moduleFilterUpdateStatus = { attach: function(context) { $('#module-filter-update-status-form').once('update-status', function() { var filterInput = $('input[name="module_filter[name]"]', context); filterInput.moduleFilter('table.update > tbody > tr', { wrapper: $('table.update:first').parent(), delay: 300, childSelector: 'div.project a', rules: [ function(moduleFilter, item) { switch (moduleFilter.options.show) { case 'all': return true; case 'updates': if (item.state == 'warning' || item.state == 'error') { return true; } break; case 'security': if (item.state == 'error') { return true; } break; case 'ignore': if (item.state == 'ignored') { return true; } break; case 'unknown': if (item.state == 'unknown') { return true; } break; } return false; } ], buildIndex: [ function(moduleFilter, item) { if ($('.version-status', item.element).text() == Drupal.t('Ignored from settings')) { item.state = 'ignored'; return item; } if (item.element.is('.ok')) { item.state = 'ok'; } else if (item.element.is('.warning')) { item.state = 'warning'; } else if (item.element.is('.error')) { item.state = 'error'; } else if (item.element.is('.unknown')) { item.state = 'unknown'; } return item; } ], show: $('#edit-module-filter-show input[name="module_filter[show]"]', context).val() }); var moduleFilter = filterInput.data('moduleFilter'); if (Drupal.settings.moduleFilter.rememberUpdateState) { var updateShow = Drupal.ModuleFilter.getState('updateShow'); if (updateShow) { moduleFilter.options.show = updateShow; $('#edit-module-filter-show input[name="module_filter[show]"][value="' + updateShow + '"]', context).click(); } } $('#edit-module-filter-show input[name="module_filter[show]"]', context).change(function() { moduleFilter.options.show = $(this).val(); Drupal.ModuleFilter.setState('updateShow', moduleFilter.options.show); moduleFilter.applyFilter(); }); moduleFilter.element.bind('moduleFilter:start', function() { $('table.update').each(function() { $(this).show().prev('h3').show(); }); }); moduleFilter.element.bind('moduleFilter:finish', function(e, data) { $('table.update').each(function() { var $table = $(this); if ($('tbody tr', $(this)).filter(':visible').length == 0) { $table.hide().prev('h3').hide(); } }); }); moduleFilter.element.bind('moduleFilter:keyup', function() { if (moduleFilter.clearOffset == undefined) { moduleFilter.inputWidth = filterInput.width(); moduleFilter.clearOffset = moduleFilter.element.parent().find('.module-filter-clear a').width(); } if (moduleFilter.text) { filterInput.width(moduleFilter.inputWidth - moduleFilter.clearOffset - 5).parent().css('margin-right', moduleFilter.clearOffset + 5); } else { filterInput.width(moduleFilter.inputWidth).parent().css('margin-right', 0); } }); moduleFilter.element.parent().find('.module-filter-clear a').click(function() { filterInput.width(moduleFilter.inputWidth).parent().css('margin-right', 0); }); moduleFilter.applyFilter(); }); } }; })(jQuery); ;
tapclicks/tapanalytics
sites/default/files/js/js_-uAWVNNLs-CDqxUul18yVdZpeIHUZse1JmT6XcSAYNU.js
JavaScript
gpl-2.0
15,031
var gulp = require("gulp"), concat = require("gulp-concat"), karma = require("karma").server, mocha = require("gulp-mocha"), nodemon = require("gulp-nodemon"), notify = require("gulp-notify"), size = require("gulp-filesize"), sourcemaps = require("gulp-sourcemaps"), uglify = require("gulp-uglify"), typescript = require("gulp-tsc"); gulp.task("default", function () { gulp.start("server"); gulp.start("watch"); }); gulp.task("watch", function () { gulp.watch("assets/js/**/*.ts", ["typescript-client"]); gulp.watch("assets/dist/js/*.js", ["test-client", "client"]); }); gulp.task("client", function () { gulp.src([ "bower_components/jquery/dist/jquery.min.js", "bower_components/lodash/lodash.min.js", "bower_components/rxjs/dist/rx.all.min.js", "bower_components/Rx-jQuery/rx.jquery.js", "assets/dist/js/lib.js" ]) .pipe(sourcemaps.init()) .pipe(concat("app.js")) .pipe(sourcemaps.write()) .pipe(gulp.dest("assets/dist/js")) .pipe(notify("app.js successfully compiled")) .pipe(size()); }); gulp.task("server", function () { nodemon({ script: "app/boot.js", ext: "ts html", ignore: ["assets/**/*", "README"], env: {"NODE_ENV": "development"}, tasks: ["typescript", "test"] }).on("restart", function () { //console.log("Server restarted!"); }); }); gulp.task("typescript-client", function () { tsc("assets/js", "assets/dist/js", "client"); tscClientTest("assets/js"); }); gulp.task("typescript", function () { tsc("app", "app", "server"); }); gulp.task("test-client", function (done) { karma.start({ configFile: process.cwd() + "/assets/js/test/karma.conf.js" }, done); }); gulp.task("test", function () { return gulp.src("app/**/*.spec.js", {read: false}) .pipe(mocha({reporter: "list"})); }); function tsc(path, out, type) { var src = gulp.src([ path + "/**/*.ts", // Ignore specs and typings "!" + path + "/**/*.spec.ts", "!" + path + "/typings/**/*" ], {base: path}); var dest; if (type == "client") { dest = src.pipe(typescript({ target: "ES5", sortOutput: true, sourceMap: false, removeComments: true })) .pipe(concat("lib.js")); //.pipe(uglify()); } else { dest = src.pipe(typescript( { target: "ES5", sourcemap: true, declarationFiles: true, removeComments: true } )); } dest .pipe(gulp.dest(out)) .pipe(notify(path + " tsc compiled into JavaScript")) .pipe(size()); } function tscClientTest(path) { var src = gulp.src([ path + "/**/*.spec.ts" ], {base: path}); src.pipe(typescript({ target: "ES5", sortOutput: true, sourceMap: false, removeComments: true })) .pipe(concat("all.js")) .pipe(gulp.dest(path + "/test")) .pipe(notify(path + " tscTest compiled into JavaScript")) .pipe(size()); }
litchi-io/litchi-awesome
gulpfile.js
JavaScript
gpl-2.0
2,767
var events = new Hash(); function showEvent( eid, fid, width, height ) { var url = '?view=event&eid='+eid+'&fid='+fid; url += filterQuery; createPopup( url, 'zmEvent', 'event', width, height ); } function createEventHtml( event, frame ) { var eventHtml = new Element( 'div' ); if ( event.Archived > 0 ) eventHtml.addClass( 'archived' ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', monitorNames[event.MonitorId] ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.Name+(frame?("("+frame.FrameId+")"):"") ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.StartTime+" - "+event.Length+"s" ); new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.Cause ); if ( event.Notes ) new Element( 'p' ).injectInside( eventHtml ).set( 'text', event.Notes ); if ( event.Archived > 0 ) new Element( 'p' ).injectInside( eventHtml ).set( 'text', archivedString ); return( eventHtml ); } function showEventDetail( eventHtml ) { $('instruction').addClass( 'hidden' ); $('eventData').empty(); $('eventData').adopt( eventHtml ); $('eventData').removeClass( 'hidden' ); } function eventDataResponse( respObj, respText ) { var event = respObj.event; if ( !event ) { console.log( "Null event" ); return; } events[event.Id] = event; if ( respObj.loopback ) { requestFrameData( event.Id, respObj.loopback ); } } function frameDataResponse( respObj, respText ) { var frame = respObj.frameimage; if ( !frame.FrameId ) { console.log( "Null frame" ); return; } var event = events[frame.EventId]; if ( !event ) { console.error( "No event "+frame.eventId+" found" ); return; } if ( !event['frames'] ) event['frames'] = new Hash(); event['frames'][frame.FrameId] = frame; event['frames'][frame.FrameId]['html'] = createEventHtml( event, frame ); showEventDetail( event['frames'][frame.FrameId]['html'] ); loadEventImage( frame.Image.imagePath, event.Id, frame.FrameId, event.Width, event.Height ); } var eventQuery = new Request.JSON( { url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse } ); var frameQuery = new Request.JSON( { url: thisUrl, method: 'post', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse } ); function requestFrameData( eventId, frameId ) { if ( !events[eventId] ) { eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId; eventQuery.send(); } else { frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId; frameQuery.send(); } } function previewEvent( eventId, frameId ) { if ( events[eventId] ) { if ( events[eventId]['frames'] ) { if ( events[eventId]['frames'][frameId] ) { showEventDetail( events[eventId]['frames'][frameId]['html'] ); loadEventImage( events[eventId].frames[frameId].Image.imagePath, eventId, frameId, events[eventId].Width, events[eventId].Height ); return; } } } requestFrameData( eventId, frameId ); } function loadEventImage( imagePath, eid, fid, width, height ) { var imageSrc = $('imageSrc'); imageSrc.setProperty( 'src', imagePrefix+imagePath ); imageSrc.removeEvent( 'click' ); imageSrc.addEvent( 'click', showEvent.pass( [ eid, fid, width, height ] ) ); var eventData = $('eventData'); eventData.removeEvent( 'click' ); eventData.addEvent( 'click', showEvent.pass( [ eid, fid, width, height ] ) ); } function tlZoomBounds( minTime, maxTime ) { console.log( "Zooming" ); window.location = '?view='+currentView+filterQuery+'&minTime='+minTime+'&maxTime='+maxTime; } function tlZoomRange( midTime, range ) { window.location = '?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+range; } function tlPan( midTime, range ) { window.location = '?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+range; }
eyezm/ZoneMinder
web/skins/classic/views/js/timeline.js
JavaScript
gpl-2.0
4,238
(function() { /* constructor */ function PhotoFloat() { this.albumCache = []; } /* public member functions */ PhotoFloat.prototype.album = function(subalbum, callback, error) { var cacheKey, ajaxOptions, self; if (typeof subalbum.photos !== "undefined" && subalbum.photos !== null) { callback(subalbum); return; } if (Object.prototype.toString.call(subalbum).slice(8, -1) === "String") cacheKey = subalbum; else cacheKey = PhotoFloat.cachePath(subalbum.parent.path + "/" + subalbum.path); if (this.albumCache.hasOwnProperty(cacheKey)) { callback(this.albumCache[cacheKey]); return; } self = this; ajaxOptions = { type: "GET", dataType: "json", url: "cache/" + cacheKey + ".json", success: function(album) { var i; for (i = 0; i < album.albums.length; ++i) album.albums[i].parent = album; for (i = 0; i < album.photos.length; ++i) album.photos[i].parent = album; self.albumCache[cacheKey] = album; callback(album); } }; if (typeof error !== "undefined" && error !== null) { ajaxOptions.error = function(jqXHR, textStatus, errorThrown) { error(jqXHR.status); }; } $.ajax(ajaxOptions); }; PhotoFloat.prototype.albumPhoto = function(subalbum, callback, error) { var nextAlbum, self; self = this; nextAlbum = function(album) { //var index = Math.floor(Math.random() * (album.photos.length + album.albums.length)); if (1==1 && album.main != null && album.main != "") { var index = 0; for (index = 0; index < album.photos.length; ++index) { if (PhotoFloat.cachePath(album.photos[index].name) === PhotoFloat.cachePath(album.main)) { break; } } callback(album, album.photos[index]); } else{ var index = 0; if (album.photos.length > 0) { index = album.photos.length - 1; } if (index >= album.photos.length) { index -= album.photos.length; self.album(album.albums[index], nextAlbum, error); } else callback(album, album.photos[index]); } }; if (typeof subalbum.photos !== "undefined" && subalbum.photos !== null) nextAlbum(subalbum); else this.album(subalbum, nextAlbum, error); }; PhotoFloat.prototype.parseHash = function(hash, callback, error) { var index, album, photo; hash = PhotoFloat.cleanHash(hash); index = hash.lastIndexOf("/"); if (!hash.length) { album = PhotoFloat.cachePath("root"); photo = null; } else if (index !== -1 && index !== hash.length - 1) { photo = hash.substring(index + 1); album = hash.substring(0, index); } else { album = hash; photo = null; } this.album(album, function(theAlbum) { var i = -1; if (photo !== null) { for (i = 0; i < theAlbum.photos.length; ++i) { if (PhotoFloat.cachePath(theAlbum.photos[i].name) === photo) { photo = theAlbum.photos[i]; break; } } if (i >= theAlbum.photos.length) { photo = null; i = -1; } } callback(theAlbum, photo, i); }, error); }; PhotoFloat.prototype.authenticate = function(password, result) { $.ajax({ type: "GET", dataType: "text", url: "auth?username=photos&password=" + password, success: function() { result(true); }, error: function() { result(false); } }); }; /* static functions */ PhotoFloat.cachePath = function(path) { if (path === "") return "root"; if (path.charAt(0) === "/") path = path.substring(1); path = path .replace(/ /g, "_") .replace(/\//g, "-") .replace(/\(/g, "") .replace(/\)/g, "") .replace(/#/g, "") .replace(/&/g, "") .replace(/,/g, "") .replace(/\[/g, "") .replace(/\]/g, "") .replace(/"/g, "") .replace(/'/g, "") .replace(/_-_/g, "-") .toLowerCase(); while (path.indexOf("--") !== -1) path = path.replace(/--/g, "-"); while (path.indexOf("__") !== -1) path = path.replace(/__/g, "_"); return path; }; PhotoFloat.photoHash = function(album, photo) { return PhotoFloat.albumHash(album) + "/" + PhotoFloat.cachePath(photo.name); }; PhotoFloat.albumHash = function(album) { if (typeof album.photos !== "undefined" && album.photos !== null) return PhotoFloat.cachePath(album.path); return PhotoFloat.cachePath(album.parent.path + "/" + album.path); }; PhotoFloat.photoPath = function(album, photo, size, square) { var suffix; if (square) suffix = size.toString() + "s"; else suffix = size.toString(); return "cache/" + PhotoFloat.cachePath(PhotoFloat.photoHash(album, photo) + "_" + suffix + ".jpg"); }; PhotoFloat.originalPhotoPath = function(album, photo) { return "albums/" + album.path + "/" + photo.name; }; PhotoFloat.trimExtension = function(name) { var index = name.lastIndexOf("."); if (index !== -1) return name.substring(0, index); return name; }; PhotoFloat.cleanHash = function(hash) { while (hash.length) { if (hash.charAt(0) === "#") hash = hash.substring(1); else if (hash.charAt(0) === "!") hash = hash.substring(1); else if (hash.charAt(0) === "/") hash = hash.substring(1); else if (hash.substring(0, 3) === "%21") hash = hash.substring(3); else if (hash.charAt(hash.length - 1) === "/") hash = hash.substring(0, hash.length - 1); else break; } return hash; }; /* make static methods callable as member functions */ PhotoFloat.prototype.cachePath = PhotoFloat.cachePath; PhotoFloat.prototype.photoHash = PhotoFloat.photoHash; PhotoFloat.prototype.albumHash = PhotoFloat.albumHash; PhotoFloat.prototype.photoPath = PhotoFloat.photoPath; PhotoFloat.prototype.originalPhotoPath = PhotoFloat.originalPhotoPath; PhotoFloat.prototype.trimExtension = PhotoFloat.trimExtension; PhotoFloat.prototype.cleanHash = PhotoFloat.cleanHash; /* expose class globally */ window.PhotoFloat = PhotoFloat; }());
mperceau/PhotoFloat
web/js/010-libphotofloat.js
JavaScript
gpl-2.0
5,824
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Geodesy representation conversion functions (c) Chris Veness 2002-2015 */ /* - www.movable-type.co.uk/scripts/latlong.html MIT Licence */ /* */ /* Sample usage: */ /* var lat = Dms.parseDMS('51° 28′ 40.12″ N'); */ /* var lon = Dms.parseDMS('000° 00′ 05.31″ W'); */ /* var p1 = new LatLon(lat, lon); */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* jshint node:true *//* global define */ 'use strict'; /** * Tools for converting between numeric degrees and degrees / minutes / seconds. * * @namespace */ var Dms = {}; // note Unicode Degree = U+00B0. Prime = U+2032, Double prime = U+2033 /** * Parses string representing degrees/minutes/seconds into numeric degrees. * * This is very flexible on formats, allowing signed decimal degrees, or deg-min-sec optionally * suffixed by compass direction (NSEW). A variety of separators are accepted (eg 3° 37′ 09″W). * Seconds and minutes may be omitted. * * @param {string|number} dmsStr - Degrees or deg/min/sec in variety of formats. * @returns {number} Degrees as decimal number. */ Dms.parseDMS = function(dmsStr) { // check for signed decimal degrees without NSEW, if so return it directly if (typeof dmsStr == 'number' && isFinite(dmsStr)) return Number(dmsStr); // strip off any sign or compass dir'n & split out separate d/m/s var dms = String(dmsStr).trim().replace(/^-/,'').replace(/[NSEW]$/i,'').split(/[^0-9.,]+/); if (dms[dms.length-1]=='') dms.splice(dms.length-1); // from trailing symbol if (dms == '') return NaN; // and convert to decimal degrees... var deg; switch (dms.length) { case 3: // interpret 3-part result as d/m/s deg = dms[0]/1 + dms[1]/60 + dms[2]/3600; break; case 2: // interpret 2-part result as d/m deg = dms[0]/1 + dms[1]/60; break; case 1: // just d (possibly decimal) or non-separated dddmmss deg = dms[0]; // check for fixed-width unseparated format eg 0033709W //if (/[NS]/i.test(dmsStr)) deg = '0' + deg; // - normalise N/S to 3-digit degrees //if (/[0-9]{7}/.test(deg)) deg = deg.slice(0,3)/1 + deg.slice(3,5)/60 + deg.slice(5)/3600; break; default: return NaN; } if (/^-|[WS]$/i.test(dmsStr.trim())) deg = -deg; // take '-', west and south as -ve return Number(deg); }; /** * Converts decimal degrees to deg/min/sec format * - degree, prime, double-prime symbols are added, but sign is discarded, though no compass * direction is added. * * @private * @param {number} deg - Degrees to be formatted as specified. * @param {string} [format=dms] - Return value as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec. * @param {number} [dp=0|2|4] - Number of decimal places to use – default 0 for dms, 2 for dm, 4 for d. * @returns {string} Degrees formatted as deg/min/secs according to specified format. */ Dms.toDMS = function(deg, format, dp) { if (isNaN(deg)) return null; // give up here if we can't make a number from deg // default values if (format === undefined) format = 'dms'; if (dp === undefined) { switch (format) { case 'd': case 'deg': dp = 4; break; case 'dm': case 'deg+min': dp = 2; break; case 'dms': case 'deg+min+sec': dp = 0; break; default: format = 'dms'; dp = 0; // be forgiving on invalid format } } deg = Math.abs(deg); // (unsigned result ready for appending compass dir'n) var dms, d, m, s; switch (format) { default: // invalid format spec! case 'd': case 'deg': d = deg.toFixed(dp); // round degrees if (d<100) d = '0' + d; // pad with leading zeros if (d<10) d = '0' + d; dms = d + '°'; break; case 'dm': case 'deg+min': var min = (deg*60).toFixed(dp); // convert degrees to minutes & round d = Math.floor(min / 60); // get component deg/min m = (min % 60).toFixed(dp); // pad with trailing zeros if (d<100) d = '0' + d; // pad with leading zeros if (d<10) d = '0' + d; if (m<10) m = '0' + m; dms = d + '°' + m + '′'; break; case 'dms': case 'deg+min+sec': var sec = (deg*3600).toFixed(dp); // convert degrees to seconds & round d = Math.floor(sec / 3600); // get component deg/min/sec m = Math.floor(sec/60) % 60; s = (sec % 60).toFixed(dp); // pad with trailing zeros if (d<100) d = '0' + d; // pad with leading zeros if (d<10) d = '0' + d; if (m<10) m = '0' + m; if (s<10) s = '0' + s; dms = d + '°' + m + '′' + s + '″'; break; } return dms; }; /** * Converts numeric degrees to deg/min/sec latitude (2-digit degrees, suffixed with N/S). * * @param {number} deg - Degrees to be formatted as specified. * @param {string} [format=dms] - Return value as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec. * @param {number} [dp=0|2|4] - Number of decimal places to use – default 0 for dms, 2 for dm, 4 for d. * @returns {string} Degrees formatted as deg/min/secs according to specified format. */ Dms.toLat = function(deg, format, dp) { var lat = Dms.toDMS(deg, format, dp); return lat===null ? '–' : lat.slice(1) + (deg<0 ? 'S' : 'N'); // knock off initial '0' for lat! }; /** * Convert numeric degrees to deg/min/sec longitude (3-digit degrees, suffixed with E/W) * * @param {number} deg - Degrees to be formatted as specified. * @param {string} [format=dms] - Return value as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec. * @param {number} [dp=0|2|4] - Number of decimal places to use – default 0 for dms, 2 for dm, 4 for d. * @returns {string} Degrees formatted as deg/min/secs according to specified format. */ Dms.toLon = function(deg, format, dp) { var lon = Dms.toDMS(deg, format, dp); return lon===null ? '–' : lon + (deg<0 ? 'W' : 'E'); }; /** * Converts numeric degrees to deg/min/sec as a bearing (0°..360°) * * @param {number} deg - Degrees to be formatted as specified. * @param {string} [format=dms] - Return value as 'd', 'dm', 'dms' for deg, deg+min, deg+min+sec. * @param {number} [dp=0|2|4] - Number of decimal places to use – default 0 for dms, 2 for dm, 4 for d. * @returns {string} Degrees formatted as deg/min/secs according to specified format. */ Dms.toBrng = function(deg, format, dp) { deg = (Number(deg)+360) % 360; // normalise -ve values to 180°..360° var brng = Dms.toDMS(deg, format, dp); return brng===null ? '–' : brng.replace('360', '0'); // just in case rounding took us up to 360°! }; /** * Returns compass point (to given precision) for supplied bearing. * * @param {number} bearing - Bearing in degrees from north. * @param {number} [precision=3] - Precision (cardinal / intercardinal / secondary-intercardinal). * @returns {string} Compass point for supplied bearing. * * @example * var point = Dms.compassPoint(24); // point = 'NNE' * var point = Dms.compassPoint(24, 1); // point = 'N' */ Dms.compassPoint = function(bearing, precision) { if (precision === undefined) precision = 3; // note precision = max length of compass point; it could be extended to 4 for quarter-winds // (eg NEbN), but I think they are little used bearing = ((bearing%360)+360)%360; // normalise to 0..360 var point; switch (precision) { case 1: // 4 compass points switch (Math.round(bearing*4/360)%4) { case 0: point = 'N'; break; case 1: point = 'E'; break; case 2: point = 'S'; break; case 3: point = 'W'; break; } break; case 2: // 8 compass points switch (Math.round(bearing*8/360)%8) { case 0: point = 'N'; break; case 1: point = 'NE'; break; case 2: point = 'E'; break; case 3: point = 'SE'; break; case 4: point = 'S'; break; case 5: point = 'SW'; break; case 6: point = 'W'; break; case 7: point = 'NW'; break; } break; case 3: // 16 compass points switch (Math.round(bearing*16/360)%16) { case 0: point = 'N'; break; case 1: point = 'NNE'; break; case 2: point = 'NE'; break; case 3: point = 'ENE'; break; case 4: point = 'E'; break; case 5: point = 'ESE'; break; case 6: point = 'SE'; break; case 7: point = 'SSE'; break; case 8: point = 'S'; break; case 9: point = 'SSW'; break; case 10: point = 'SW'; break; case 11: point = 'WSW'; break; case 12: point = 'W'; break; case 13: point = 'WNW'; break; case 14: point = 'NW'; break; case 15: point = 'NNW'; break; } break; default: throw new RangeError('Precision must be between 1 and 3'); } return point; }; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** Polyfill String.trim for old browsers * (q.v. blog.stevenlevithan.com/archives/faster-trim-javascript) */ if (String.prototype.trim === undefined) { String.prototype.trim = function() { return String(this).replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ if (typeof module != 'undefined' && module.exports) module.exports = Dms; // CommonJS (Node) if (typeof define == 'function' && define.amd) define([], function() { return Dms; }); // AMD
celber/arrow
dist/vendor/geodesy/dms.js
JavaScript
gpl-2.0
10,670
;(function($){ $(document).ready( function(){ $('.fa_slider_simple').FeaturedArticles({ slide_selector : '.fa_slide', nav_prev : '.go-back', nav_next : '.go-forward', nav_elem : '.main-nav .fa-nav', effect : false, // events load : load, before : before, after : after, resize : resize, stop : stop, start : start }); }); var resizeDuration = 100; var load = function(){ var options = this.settings(), self = this; this.progressBar = $(this).find('.progress-bar'); this.mouseOver; // height resize if( $(this).data('theme_opt_auto_resize') ){ this.sliderHeight = $(this).height(); var h = $( this.slides()[0] ).find(options.content_container).outerHeight() + 100; setHeight = h > this.sliderHeight ? h : this.sliderHeight; slide = this.slides()[0]; $(slide).css({ 'height' : setHeight }); self.center_img( slide ); $(this) .css({ 'max-height':'none', 'height' : this.sliderHeight }) .animate({ 'height' : setHeight },{ queue: false, duration:resizeDuration , complete: function(){ /* $(this).css({ 'max-height':setHeight }); */ } });// end animate }// end height resize } var before = function(d){ var options = this.settings(), self = this; if( typeof this.progressBar !== 'undefined' ){ this.progressBar.stop().css({'width':0}); } // height resize if( $(this).data('theme_opt_auto_resize') ){ var h = $( d.next ).find(options.content_container).outerHeight() + 100, setHeight = h > this.sliderHeight ? h : this.sliderHeight; $(d.next).css({ height : setHeight }); self.center_img( d.next ); $(this) .css({ 'max-height':'none' }) .animate({ 'height' : setHeight },{ queue: false, duration:resizeDuration , complete: function(){ $(this).css({'max-height':setHeight}); } });// end animate } // end height resize } var resize = function(){ var self = this, options = this.settings(); // height resize if( $(this).data('theme_opt_auto_resize') ){ var h = $( this.get_current() ).find(options.content_container).outerHeight() + 100; this.sliderHeight = $(this).height();; var setHeight = h > this.sliderHeight ? h : this.sliderHeight; $( this.get_current() ).css({ height: setHeight }); self.center_img( self.get_current() ); $(this) .css({ 'max-height':'none', 'height':this.sliderHeight }) .animate({ 'height' : setHeight },{ queue: false, duration:resizeDuration , complete: function(){ $(this).css({'max-height':setHeight}); } }); } // end height resize } var after = function(){ var options = this.settings(), self = this, duration = options.slide_duration; //self.center_current_img(); if( this.mouseOver || this.stopped || !options.auto_slide ){ return; } if( typeof this.progressBar !== 'undefined' ){ this.progressBar.css({width:0}).animate( {'width' : '100%'}, {duration: duration, queue:false, complete: function(){ $(this).css({'width':0}); } }); } } var stop = function(){ if( typeof this.progressBar !== 'undefined' ){ this.progressBar.stop().css({'width':0}); } this.mouseOver = true; } var start = function(){ this.mouseOver = false; if( this.animating() ){ return; } var options = this.settings(), duration = options.slide_duration; if( typeof this.progressBar !== 'undefined' ){ this.progressBar.css({width:0}).animate( {'width' : '100%'}, {duration: duration, queue:false, complete: function(){ $(this).css({'width':0}); } }); } } })(jQuery);
vrxm/htdocs
wp-content/plugins/featured-articles-lite/themes/simple/starter.dev.js
JavaScript
gpl-2.0
4,040
var rcp_validating_discount = false; var rcp_validating_gateway = false; var rcp_validating_level = false; var rcp_processing = false; jQuery(document).ready(function($) { // Initial validation of subscription level and gateway options rcp_validate_form( true ); // Trigger gateway change event when gateway option changes $('#rcp_payment_gateways select, #rcp_payment_gateways input').change( function() { $('body').trigger( 'rcp_gateway_change' ); }); // Trigger subscription level change event when level selection changes $('.rcp_level').change(function() { $('body').trigger( 'rcp_level_change' ); }); $('body').on( 'rcp_gateway_change', function() { rcp_validate_form( true ); }).on( 'rcp_level_change', function() { rcp_validate_form( true ); }); // Validate discount code $('#rcp_apply_discount').on( 'click', function(e) { e.preventDefault(); rcp_validate_discount(); }); $(document).on('click', '#rcp_registration_form #rcp_submit', function(e) { var submission_form = document.getElementById('rcp_registration_form'); var form = $('#rcp_registration_form'); if( typeof submission_form.checkValidity === "function" && false === submission_form.checkValidity() ) { return; } e.preventDefault(); var submit_register_text = $(this).val(); form.block({ message: rcp_script_options.pleasewait, css: { border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .5, color: '#fff' } }); $('#rcp_submit', form).val( rcp_script_options.pleasewait ); // Don't allow form to be submitted multiple times simultaneously if( rcp_processing ) { return; } rcp_processing = true; $.post( rcp_script_options.ajaxurl, form.serialize() + '&action=rcp_process_register_form&rcp_ajax=true', function(response) { $('.rcp-submit-ajax', form).remove(); $('.rcp_message.error', form).remove(); if ( response.success ) { $('body').trigger( 'rcp_register_form_submission' ); $(submission_form).submit(); } else { $('#rcp_submit', form).val( submit_register_text ); $('#rcp_submit', form).before( response.data.errors ); $('#rcp_register_nonce', form).val( response.data.nonce ); form.unblock(); rcp_processing = false; } }).done(function( response ) { }).fail(function( response ) { console.log( response ); }).always(function( response ) { }); }); }); function rcp_validate_form( validate_gateways ) { // Validate the subscription level rcp_validate_subscription_level(); if( validate_gateways ) { // Validate the discount selected gateway rcp_validate_gateways(); } rcp_validate_discount(); } function rcp_validate_subscription_level() { if( rcp_validating_level ) { return; } var $ = jQuery; var is_free = false; var options = []; var level = jQuery( '#rcp_subscription_levels input:checked' ); var full = $('.rcp_gateway_fields').hasClass( 'rcp_discounted_100' ); rcp_validating_level = true; if( level.attr('rel') == 0 ) { is_free = true; } if( is_free ) { $('.rcp_gateway_fields,#rcp_auto_renew_wrap,#rcp_discount_code_wrap').hide(); $('.rcp_gateway_fields').removeClass( 'rcp_discounted_100' ); $('#rcp_discount_code_wrap input').val(''); $('.rcp_discount_amount,#rcp_gateway_extra_fields').remove(); $('.rcp_discount_valid, .rcp_discount_invalid').hide(); $('#rcp_auto_renew_wrap input').attr('checked', false); } else { if( full ) { $('#rcp_gateway_extra_fields').remove(); } else { $('.rcp_gateway_fields,#rcp_auto_renew_wrap').show(); } $('#rcp_discount_code_wrap').show(); } rcp_validating_level = false; } function rcp_validate_gateways() { if( rcp_validating_gateway ) { return; } var $ = jQuery; var form = $('#rcp_registration_form'); var is_free = false; var options = []; var level = jQuery( '#rcp_subscription_levels input:checked' ); var full = $('.rcp_gateway_fields').hasClass( 'rcp_discounted_100' ); var gateway; rcp_validating_gateway = true; if( level.attr('rel') == 0 ) { is_free = true; } $('.rcp_message.error', form).remove(); if( $('#rcp_payment_gateways').length > 0 ) { gateway = $( '#rcp_payment_gateways select option:selected' ); if( gateway.length < 1 ) { // Support radio input fields gateway = $( 'input[name="rcp_gateway"]:checked' ); } } else { gateway = $( 'input[name="rcp_gateway"]' ); } if( is_free ) { $('.rcp_gateway_fields').hide(); $('#rcp_auto_renew_wrap').hide(); $('#rcp_auto_renew_wrap input').attr('checked', false); $('#rcp_gateway_extra_fields').remove(); } else { if( full ) { $('#rcp_gateway_extra_fields').remove(); } else { form.block({ message: rcp_script_options.pleasewait, css: { border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .5, color: '#fff' } }); $('.rcp_gateway_fields').show(); var data = { action: 'rcp_load_gateway_fields', rcp_gateway: gateway.val() }; $.post( rcp_script_options.ajaxurl, data, function(response) { $('#rcp_gateway_extra_fields').remove(); if( response.success && response.data.fields ) { if( $('.rcp_gateway_fields' ).length ) { $( '<div class="rcp_gateway_' + gateway.val() + '_fields" id="rcp_gateway_extra_fields">' + response.data.fields + '</div>' ).insertAfter('.rcp_gateway_fields'); } else { // Pre 2.1 template files $( '<div class="rcp_gateway_' + gateway.val() + '_fields" id="rcp_gateway_extra_fields">' + response.data.fields + '</div>' ).insertAfter('.rcp_gateways_fieldset'); } } form.unblock(); }); } if( 'yes' == gateway.data( 'supports-recurring' ) && ! full ) { $('#rcp_auto_renew_wrap').show(); } else { $('#rcp_auto_renew_wrap').hide(); $('#rcp_auto_renew_wrap input').attr('checked', false); } $('#rcp_discount_code_wrap').show(); } rcp_validating_gateway = false; } function rcp_validate_discount() { if( rcp_validating_discount ) { return; } var $ = jQuery; var gateway_fields = $('.rcp_gateway_fields'); var discount = $('#rcp_discount_code').val(); if( $('#rcp_subscription_levels input:checked').length ) { var subscription = $('#rcp_subscription_levels input:checked').val(); } else { var subscription = $('input[name="rcp_level"]').val(); } if( ! discount ) { return; } var data = { action: 'validate_discount', code: discount, subscription_id: subscription }; rcp_validating_discount = true; $.post(rcp_script_options.ajaxurl, data, function(response) { $('.rcp_discount_amount').remove(); $('.rcp_discount_valid, .rcp_discount_invalid').hide(); if( ! response.valid ) { // code is invalid $('.rcp_discount_invalid').show(); gateway_fields.removeClass('rcp_discounted_100'); $('.rcp_gateway_fields,#rcp_auto_renew_wrap').show(); } else if( response.valid ) { // code is valid $('.rcp_discount_valid').show(); $('#rcp_discount_code_wrap label').append( '<span class="rcp_discount_amount"> - ' + response.amount + '</span>' ); if( response.full ) { $('#rcp_auto_renew_wrap').hide(); gateway_fields.hide().addClass('rcp_discounted_100'); $('#rcp_gateway_extra_fields').remove(); } else { $('#rcp_auto_renew_wrap').show(); gateway_fields.show().removeClass('rcp_discounted_100'); } } rcp_validating_discount = false; $('body').trigger('rcp_discount_applied', [ response ] ); }); }
CGCookie/Restrict-Content-Pro
includes/js/register.js
JavaScript
gpl-2.0
7,721
/* The main program of test panel */ requirejs.config({ paths : { "dualless" : ".." }, baseUrl : ".." }); require(["debug/view/component", "debug/view/information", "dualless/directives/winbutton" ], function app(component, information, winbutton){ var module = angular.module('main', []); module.config(['$routeProvider', function configRouteProvider($routeProvider) { $routeProvider.when('/info', information); //$routeProvider.when('/component', component); $routeProvider.when('/preparetest', {templateUrl: "view/preparetest.html"}); $routeProvider.otherwise({redirectTo : "/info" }) }]); module.directive('winbutton',winbutton); $(document).ready(function() { angular.bootstrap(document,["main"]); }); });
benlau/dualless
src/chrome/debug/app.js
JavaScript
gpl-2.0
824
(function($) { Drupal.wysiwyg.editor.init.ckeditor = function(settings) { window.CKEDITOR_BASEPATH = settings.global.editorBasePath + '/'; CKEDITOR.basePath = window.CKEDITOR_BASEPATH; // Drupal.wysiwyg.editor['initialized']['ckeditor'] = true; // Plugins must only be loaded once. Only the settings from the first format // will be used but they're identical anyway. var registeredPlugins = {}; for (var format in settings) { if (Drupal.settings.wysiwyg.plugins[format]) { // Register native external plugins. // Array syntax required; 'native' is a predefined token in JavaScript. for (var pluginName in Drupal.settings.wysiwyg.plugins[format]['native']) { if (!registeredPlugins[pluginName]) { var plugin = Drupal.settings.wysiwyg.plugins[format]['native'][pluginName]; CKEDITOR.plugins.addExternal(pluginName, plugin.path, plugin.fileName); registeredPlugins[pluginName] = true; } } // Register Drupal plugins. for (var pluginName in Drupal.settings.wysiwyg.plugins[format].drupal) { if (!registeredPlugins[pluginName]) { Drupal.wysiwyg.editor.instance.ckeditor.addPlugin(pluginName, Drupal.settings.wysiwyg.plugins[format].drupal[pluginName], Drupal.settings.wysiwyg.plugins.drupal[pluginName]); registeredPlugins[pluginName] = true; } } } } }; /** * Attach this editor to a target element. */ Drupal.wysiwyg.editor.attach.ckeditor = function(context, params, settings) { // Apply editor instance settings. CKEDITOR.config.customConfig = ''; settings.on = { instanceReady: function(ev) { var editor = ev.editor; // Get a list of block, list and table tags from CKEditor's XHTML DTD. // @see http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Output_Formatting. var dtd = CKEDITOR.dtd; var tags = CKEDITOR.tools.extend({}, dtd.$block, dtd.$listItem, dtd.$tableContent); // Set source formatting rules for each listed tag except <pre>. // Linebreaks can be inserted before or after opening and closing tags. if (settings.apply_source_formatting) { // Mimic FCKeditor output, by breaking lines between tags. for (var tag in tags) { if (tag == 'pre') { continue; } this.dataProcessor.writer.setRules(tag, { indent: true, breakBeforeOpen: true, breakAfterOpen: false, breakBeforeClose: false, breakAfterClose: true }); } } else { // CKEditor adds default formatting to <br>, so we want to remove that // here too. tags.br = 1; // No indents or linebreaks; for (var tag in tags) { if (tag == 'pre') { continue; } this.dataProcessor.writer.setRules(tag, { indent: false, breakBeforeOpen: false, breakAfterOpen: false, breakBeforeClose: false, breakAfterClose: false }); } } }, pluginsLoaded: function(ev) { // Override the conversion methods to let Drupal plugins modify the data. var editor = ev.editor; if (editor.dataProcessor && Drupal.settings.wysiwyg.plugins[params.format]) { editor.dataProcessor.toHtml = CKEDITOR.tools.override(editor.dataProcessor.toHtml, function(originalToHtml) { // Convert raw data for display in WYSIWYG mode. return function(data, fixForBody) { for (var plugin in Drupal.settings.wysiwyg.plugins[params.format].drupal) { if (typeof Drupal.wysiwyg.plugins[plugin].attach == 'function') { data = Drupal.wysiwyg.plugins[plugin].attach(data, Drupal.settings.wysiwyg.plugins.drupal[plugin], editor.name); data = Drupal.wysiwyg.instances[params.field].prepareContent(data); } } return originalToHtml.call(this, data, fixForBody); }; }); editor.dataProcessor.toDataFormat = CKEDITOR.tools.override(editor.dataProcessor.toDataFormat, function(originalToDataFormat) { // Convert WYSIWYG mode content to raw data. return function(data, fixForBody) { data = originalToDataFormat.call(this, data, fixForBody); for (var plugin in Drupal.settings.wysiwyg.plugins[params.format].drupal) { if (typeof Drupal.wysiwyg.plugins[plugin].detach == 'function') { data = Drupal.wysiwyg.plugins[plugin].detach(data, Drupal.settings.wysiwyg.plugins.drupal[plugin], editor.name); } } return data; }; }); } }, selectionChange: function (event) { var pluginSettings = Drupal.settings.wysiwyg.plugins[params.format]; if (pluginSettings && pluginSettings.drupal) { $.each(pluginSettings.drupal, function (name) { var plugin = Drupal.wysiwyg.plugins[name]; if ($.isFunction(plugin.isNode)) { var node = event.data.selection.getSelectedElement(); var state = plugin.isNode(node ? node.$ : null) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF; event.editor.getCommand(name).setState(state); } }); } }, focus: function(ev) { Drupal.wysiwyg.activeId = ev.editor.name; } }; // Attach editor. CKEDITOR.replace(params.field, settings); }; /** * Detach a single or all editors. * * @todo 3.x: editor.prototype.getInstances() should always return an array * containing all instances or the passed in params.field instance, but * always return an array to simplify all detach functions. */ Drupal.wysiwyg.editor.detach.ckeditor = function(context, params) { if (typeof params != 'undefined') { var instance = CKEDITOR.instances[params.field]; if (instance) { instance.destroy(); } } else { for (var instanceName in CKEDITOR.instances) { CKEDITOR.instances[instanceName].destroy(); } } }; Drupal.wysiwyg.editor.instance.ckeditor = { addPlugin: function(pluginName, settings, pluginSettings) { CKEDITOR.plugins.add(pluginName, { // Wrap Drupal plugin in a proxy pluygin. init: function(editor) { if (settings.css) { editor.on('mode', function(ev) { if (ev.editor.mode == 'wysiwyg') { // Inject CSS files directly into the editing area head tag. $('head', $('#cke_contents_' + ev.editor.name + ' iframe').eq(0).contents()).append('<link rel="stylesheet" href="' + settings.css + '" type="text/css" >'); } }); } if (typeof Drupal.wysiwyg.plugins[pluginName].invoke == 'function') { var pluginCommand = { exec: function (editor) { var data = { format: 'html', node: null, content: '' }; var selection = editor.getSelection(); if (selection) { data.node = selection.getSelectedElement(); if (data.node) { data.node = data.node.$; } if (selection.getType() == CKEDITOR.SELECTION_TEXT) { if (CKEDITOR.env.ie) { data.content = selection.getNative().createRange().text; } else { data.content = selection.getNative().toString(); } } else if (data.node) { // content is supposed to contain the "outerHTML". data.content = data.node.parentNode.innerHTML; } } Drupal.wysiwyg.plugins[pluginName].invoke(data, pluginSettings, editor.name); } }; editor.addCommand(pluginName, pluginCommand); } editor.ui.addButton(pluginName, { label: settings.iconTitle, command: pluginName, icon: settings.icon }); // @todo Add button state handling. } }); }, prepareContent: function(content) { // @todo Don't know if we need this yet. return content; }, insert: function(content) { content = this.prepareContent(content); CKEDITOR.instances[this.field].insertHtml(content); } }; })(jQuery); ; (function($) { /** * Attach this editor to a target element. * * @param context * A DOM element, supplied by Drupal.attachBehaviors(). * @param params * An object containing input format parameters. Default parameters are: * - editor: The internal editor name. * - theme: The name/key of the editor theme/profile to use. * - field: The CSS id of the target element. * @param settings * An object containing editor settings for all enabled editor themes. */ Drupal.wysiwyg.editor.attach.none = function(context, params, settings) { if (params.resizable) { var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first'); $wrapper.addClass('resizable'); if (Drupal.behaviors.textarea.attach) { Drupal.behaviors.textarea.attach(); } } }; /** * Detach a single or all editors. * * @param context * A DOM element, supplied by Drupal.attachBehaviors(). * @param params * (optional) An object containing input format parameters. If defined, * only the editor instance in params.field should be detached. Otherwise, * all editors should be detached and saved, so they can be submitted in * AJAX/AHAH applications. */ Drupal.wysiwyg.editor.detach.none = function(context, params) { if (typeof params != 'undefined') { var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first'); $wrapper.removeOnce('textarea').removeClass('.resizable-textarea') .find('.grippie').remove(); } }; /** * Instance methods for plain text areas. */ Drupal.wysiwyg.editor.instance.none = { insert: function(content) { var editor = document.getElementById(this.field); // IE support. if (document.selection) { editor.focus(); var sel = document.selection.createRange(); sel.text = content; } // Mozilla/Firefox/Netscape 7+ support. else if (editor.selectionStart || editor.selectionStart == '0') { var startPos = editor.selectionStart; var endPos = editor.selectionEnd; editor.value = editor.value.substring(0, startPos) + content + editor.value.substring(endPos, editor.value.length); } // Fallback, just add to the end of the content. else { editor.value += content; } } }; })(jQuery); ; (function($) { //Global container. window.imce = {tree: {}, findex: [], fids: {}, selected: {}, selcount: 0, ops: {}, cache: {}, urlId: {}, vars: {previewImages: 1, cache: 1}, hooks: {load: [], list: [], navigate: [], cache: []}, //initiate imce. initiate: function() { imce.conf = Drupal.settings.imce || {}; if (imce.conf.error != false) return; imce.FLW = imce.el('file-list-wrapper'), imce.SBW = imce.el('sub-browse-wrapper'); imce.NW = imce.el('navigation-wrapper'), imce.BW = imce.el('browse-wrapper'); imce.PW = imce.el('preview-wrapper'), imce.FW = imce.el('forms-wrapper'); imce.updateUI(); imce.prepareMsgs();//process initial status messages imce.initiateTree();//build directory tree imce.hooks.list.unshift(imce.processRow);//set the default list-hook. imce.initiateList();//process file list imce.initiateOps();//prepare operation tabs imce.refreshOps(); imce.invoke('load', window);//run functions set by external applications. }, //process navigation tree initiateTree: function() { $('#navigation-tree li').each(function(i) { var a = this.firstChild, txt = a.firstChild; txt && (txt.data = imce.decode(txt.data)); var branch = imce.tree[a.title] = {'a': a, li: this, ul: this.lastChild.tagName == 'UL' ? this.lastChild : null}; if (a.href) imce.dirClickable(branch); imce.dirCollapsible(branch); }); }, //Add a dir to the tree under parent dirAdd: function(dir, parent, clickable) { if (imce.tree[dir]) return clickable ? imce.dirClickable(imce.tree[dir]) : imce.tree[dir]; var parent = parent || imce.tree['.']; parent.ul = parent.ul ? parent.ul : parent.li.appendChild(imce.newEl('ul')); var branch = imce.dirCreate(dir, imce.decode(dir.substr(dir.lastIndexOf('/')+1)), clickable); parent.ul.appendChild(branch.li); return branch; }, //create list item for navigation tree dirCreate: function(dir, text, clickable) { if (imce.tree[dir]) return imce.tree[dir]; var branch = imce.tree[dir] = {li: imce.newEl('li'), a: imce.newEl('a')}; $(branch.a).addClass('folder').text(text).attr('title', dir).appendTo(branch.li); imce.dirCollapsible(branch); return clickable ? imce.dirClickable(branch) : branch; }, //change currently active directory dirActivate: function(dir) { if (dir != imce.conf.dir) { if (imce.tree[imce.conf.dir]){ $(imce.tree[imce.conf.dir].a).removeClass('active'); } $(imce.tree[dir].a).addClass('active'); imce.conf.dir = dir; } return imce.tree[imce.conf.dir]; }, //make a dir accessible dirClickable: function(branch) { if (branch.clkbl) return branch; $(branch.a).attr('href', '#').removeClass('disabled').click(function() {imce.navigate(this.title); return false;}); branch.clkbl = true; return branch; }, //sub-directories expand-collapse ability dirCollapsible: function (branch) { if (branch.clpsbl) return branch; $(imce.newEl('span')).addClass('expander').html('&nbsp;').click(function() { if (branch.ul) { $(branch.ul).toggle(); $(branch.li).toggleClass('expanded'); $.browser.msie && $('#navigation-header').css('top', imce.NW.scrollTop); } else if (branch.clkbl){ $(branch.a).click(); } }).prependTo(branch.li); branch.clpsbl = true; return branch; }, //update navigation tree after getting subdirectories. dirSubdirs: function(dir, subdirs) { var branch = imce.tree[dir]; if (subdirs && subdirs.length) { var prefix = dir == '.' ? '' : dir +'/'; for (var i in subdirs) {//add subdirectories imce.dirAdd(prefix + subdirs[i], branch, true); } $(branch.li).removeClass('leaf').addClass('expanded'); $(branch.ul).show(); } else if (!branch.ul){//no subdirs->leaf $(branch.li).removeClass('expanded').addClass('leaf'); } }, //process file list initiateList: function(cached) { var L = imce.hooks.list, dir = imce.conf.dir, token = {'%dir': dir == '.' ? $(imce.tree['.'].a).text() : imce.decode(dir)} imce.findex = [], imce.fids = {}, imce.selected = {}, imce.selcount = 0, imce.vars.lastfid = null; imce.tbody = imce.el('file-list').tBodies[0]; if (imce.tbody.rows.length) { for (var row, i = 0; row = imce.tbody.rows[i]; i++) { var fid = row.id; imce.findex[i] = imce.fids[fid] = row; if (cached) { if (imce.hasC(row, 'selected')) { imce.selected[imce.vars.lastfid = fid] = row; imce.selcount++; } } else { for (var func, j = 0; func = L[j]; j++) func(row);//invoke list-hook } } } if (!imce.conf.perm.browse) { imce.setMessage(Drupal.t('File browsing is disabled in directory %dir.', token), 'error'); } }, //add a file to the list. (having properties name,size,formatted size,width,height,date,formatted date) fileAdd: function(file) { var row, fid = file.name, i = imce.findex.length, attr = ['name', 'size', 'width', 'height', 'date']; if (!(row = imce.fids[fid])) { row = imce.findex[i] = imce.fids[fid] = imce.tbody.insertRow(i); for (var i in attr) row.insertCell(i).className = attr[i]; } row.cells[0].innerHTML = row.id = fid; row.cells[1].innerHTML = file.fsize; row.cells[1].id = file.size; row.cells[2].innerHTML = file.width; row.cells[3].innerHTML = file.height; row.cells[4].innerHTML = file.fdate; row.cells[4].id = file.date; imce.invoke('list', row); if (imce.vars.prvfid == fid) imce.setPreview(fid); if (file.id) imce.urlId[imce.getURL(fid)] = file.id; }, //remove a file from the list fileRemove: function(fid) { if (!(row = imce.fids[fid])) return; imce.fileDeSelect(fid); imce.findex.splice(row.rowIndex, 1); $(row).remove(); delete imce.fids[fid]; if (imce.vars.prvfid == fid) imce.setPreview(); }, //return a file object containing all properties. fileGet: function (fid) { var row = imce.fids[fid]; var url = imce.getURL(fid); return row ? { name: imce.decode(fid), url: url, size: row.cells[1].innerHTML, bytes: row.cells[1].id * 1, width: row.cells[2].innerHTML * 1, height: row.cells[3].innerHTML * 1, date: row.cells[4].innerHTML, time: row.cells[4].id * 1, id: imce.urlId[url] || 0, //file id for newly uploaded files relpath: (imce.conf.dir == '.' ? '' : imce.conf.dir +'/') + fid //rawurlencoded path relative to file directory path. } : null; }, //simulate row click. selection-highlighting fileClick: function(row, ctrl, shft) { if (!row) return; var fid = typeof(row) == 'string' ? row : row.id; if (ctrl || fid == imce.vars.prvfid) { imce.fileToggleSelect(fid); } else if (shft) { var last = imce.lastFid(); var start = last ? imce.fids[last].rowIndex : -1; var end = imce.fids[fid].rowIndex; var step = start > end ? -1 : 1; while (start != end) { start += step; imce.fileSelect(imce.findex[start].id); } } else { for (var fname in imce.selected) { imce.fileDeSelect(fname); } imce.fileSelect(fid); } //set preview imce.setPreview(imce.selcount == 1 ? imce.lastFid() : null); }, //file select/deselect functions fileSelect: function (fid) { if (imce.selected[fid] || !imce.fids[fid]) return; imce.selected[fid] = imce.fids[imce.vars.lastfid=fid]; $(imce.selected[fid]).addClass('selected'); imce.selcount++; }, fileDeSelect: function (fid) { if (!imce.selected[fid] || !imce.fids[fid]) return; if (imce.vars.lastfid == fid) imce.vars.lastfid = null; $(imce.selected[fid]).removeClass('selected'); delete imce.selected[fid]; imce.selcount--; }, fileToggleSelect: function (fid) { imce['file'+ (imce.selected[fid] ? 'De' : '') +'Select'](fid); }, //process file operation form and create operation tabs. initiateOps: function() { imce.setHtmlOps(); imce.setUploadOp();//upload imce.setFileOps();//thumb, delete, resize }, //process existing html ops. setHtmlOps: function () { $(imce.el('ops-list')).children('li').each(function() { if (!this.firstChild) return $(this).remove(); var name = this.id.substr(8); var Op = imce.ops[name] = {div: imce.el('op-content-'+ name), li: imce.el('op-item-'+ name)}; Op.a = Op.li.firstChild; Op.title = Op.a.innerHTML; $(Op.a).click(function() {imce.opClick(name); return false;}); }); }, //convert upload form to an op. setUploadOp: function () { var form = imce.el('imce-upload-form'); if (!form) return; $(form).ajaxForm(imce.uploadSettings()).find('fieldset').each(function() {//clean up fieldsets this.removeChild(this.firstChild); $(this).after(this.childNodes); }).remove(); imce.opAdd({name: 'upload', title: Drupal.t('Upload'), content: form});//add op }, //convert fileop form submit buttons to ops. setFileOps: function () { var form = imce.el('imce-fileop-form'); if (!form) return; $(form.elements.filenames).parent().remove(); $(form).find('fieldset').each(function() {//remove fieldsets var $sbmt = $('input:submit', this); if (!$sbmt.size()) return; var Op = {name: $sbmt.attr('id').substr(5)}; var func = function() {imce.fopSubmit(Op.name); return false;}; $sbmt.click(func); Op.title = $(this).children('legend').remove().text() || $sbmt.val(); Op.name == 'delete' ? (Op.func = func) : (Op.content = this.childNodes); imce.opAdd(Op); }).remove(); imce.vars.opform = $(form).serialize();//serialize remaining parts. }, //refresh ops states. enable/disable refreshOps: function() { for (var p in imce.conf.perm) { if (imce.conf.perm[p]) imce.opEnable(p); else imce.opDisable(p); } }, //add a new file operation opAdd: function (op) { var oplist = imce.el('ops-list'), opcons = imce.el('op-contents'); var name = op.name || ('op-'+ $(oplist).children('li').size()); var title = op.title || 'Untitled'; var Op = imce.ops[name] = {title: title}; if (op.content) { Op.div = imce.newEl('div'); $(Op.div).attr({id: 'op-content-'+ name, 'class': 'op-content'}).appendTo(opcons).append(op.content); } Op.a = imce.newEl('a'); Op.li = imce.newEl('li'); $(Op.a).attr({href: '#', name: name, title: title}).html('<span>' + title +'</span>').click(imce.opClickEvent); $(Op.li).attr('id', 'op-item-'+ name).append(Op.a).appendTo(oplist); Op.func = op.func || imce.opVoid; return Op; }, //click event for file operations opClickEvent: function(e) { imce.opClick(this.name); return false; }, //void operation function opVoid: function() {}, //perform op click opClick: function(name) { var Op = imce.ops[name], oldop = imce.vars.op; if (!Op || Op.disabled) { return imce.setMessage(Drupal.t('You can not perform this operation.'), 'error'); } if (Op.div) { if (oldop) { var toggle = oldop == name; imce.opShrink(oldop, toggle ? 'fadeOut' : 'hide'); if (toggle) return false; } var left = Op.li.offsetLeft; var $opcon = $('#op-contents').css({left: 0}); $(Op.div).fadeIn('normal', function() { setTimeout(function() { if (imce.vars.op) { var $inputs = $('input', imce.ops[imce.vars.op].div); $inputs.eq(0).focus(); //form inputs become invisible in IE. Solution is as stupid as the behavior. $('html').is('.ie') && $inputs.addClass('dummyie').removeClass('dummyie'); } }); }); var diff = left + $opcon.width() - $('#imce-content').width(); $opcon.css({left: diff > 0 ? left - diff - 1 : left}); $(Op.li).addClass('active'); $(imce.opCloseLink).fadeIn(300); imce.vars.op = name; } Op.func(true); return true; }, //enable a file operation opEnable: function(name) { var Op = imce.ops[name]; if (Op && Op.disabled) { Op.disabled = false; $(Op.li).show(); } }, //disable a file operation opDisable: function(name) { var Op = imce.ops[name]; if (Op && !Op.disabled) { Op.div && imce.opShrink(name); $(Op.li).hide(); Op.disabled = true; } }, //hide contents of a file operation opShrink: function(name, effect) { if (imce.vars.op != name) return; var Op = imce.ops[name]; $(Op.div).stop(true, true)[effect || 'hide'](); $(Op.li).removeClass('active'); $(imce.opCloseLink).hide(); Op.func(false); imce.vars.op = null; }, //navigate to dir navigate: function(dir) { if (imce.vars.navbusy || (dir == imce.conf.dir && !confirm(Drupal.t('Do you want to refresh the current directory?')))) return; var cache = imce.vars.cache && dir != imce.conf.dir; var set = imce.navSet(dir, cache); if (cache && imce.cache[dir]) {//load from the cache set.success({data: imce.cache[dir]}); set.complete(); } else $.ajax(set);//live load }, //ajax navigation settings navSet: function (dir, cache) { $(imce.tree[dir].li).addClass('loading'); imce.vars.navbusy = dir; return {url: imce.ajaxURL('navigate', dir), type: 'GET', dataType: 'json', success: function(response) { if (response.data && !response.data.error) { if (cache) imce.navCache(imce.conf.dir, dir);//cache the current dir imce.navUpdate(response.data, dir); } imce.processResponse(response); }, complete: function () { $(imce.tree[dir].li).removeClass('loading'); imce.vars.navbusy = null; } }; }, //update directory using the given data navUpdate: function(data, dir) { var cached = data == imce.cache[dir], olddir = imce.conf.dir; if (cached) data.files.id = 'file-list'; $(imce.FLW).html(data.files); imce.dirActivate(dir); imce.dirSubdirs(dir, data.subdirectories); $.extend(imce.conf.perm, data.perm); imce.refreshOps(); imce.initiateList(cached); imce.setPreview(imce.selcount == 1 ? imce.lastFid() : null); imce.SBW.scrollTop = 0; imce.invoke('navigate', data, olddir, cached); }, //set cache navCache: function (dir, newdir) { var C = imce.cache[dir] = {'dir': dir, files: imce.el('file-list'), dirsize: imce.el('dir-size').innerHTML, perm: $.extend({}, imce.conf.perm)}; C.files.id = 'cached-list-'+ dir; imce.FW.appendChild(C.files); imce.invoke('cache', C, newdir); }, //validate upload form uploadValidate: function (data, form, options) { var path = data[0].value; if (!path) return false; if (imce.conf.extensions != '*') { var ext = path.substr(path.lastIndexOf('.') + 1); if ((' '+ imce.conf.extensions +' ').indexOf(' '+ ext.toLowerCase() +' ') == -1) { return imce.setMessage(Drupal.t('Only files with the following extensions are allowed: %files-allowed.', {'%files-allowed': imce.conf.extensions}), 'error'); } } var sep = path.indexOf('/') == -1 ? '\\' : '/'; options.url = imce.ajaxURL('upload');//make url contain current dir. imce.fopLoading('upload', true); return true; }, //settings for upload uploadSettings: function () { return {beforeSubmit: imce.uploadValidate, success: function (response) {imce.processResponse($.parseJSON(response));}, complete: function () {imce.fopLoading('upload', false);}, resetForm: true}; }, //validate default ops(delete, thumb, resize) fopValidate: function(fop) { if (!imce.validateSelCount(1, imce.conf.filenum)) return false; switch (fop) { case 'delete': return confirm(Drupal.t('Delete selected files?')); case 'thumb': if (!$('input:checked', imce.ops['thumb'].div).size()) { return imce.setMessage(Drupal.t('Please select a thumbnail.'), 'error'); } return imce.validateImage(); case 'resize': var w = imce.el('edit-width').value, h = imce.el('edit-height').value; var maxDim = imce.conf.dimensions.split('x'); var maxW = maxDim[0]*1, maxH = maxW ? maxDim[1]*1 : 0; if (!(/^[1-9][0-9]*$/).test(w) || !(/^[1-9][0-9]*$/).test(h) || (maxW && (maxW < w*1 || maxH < h*1))) { return imce.setMessage(Drupal.t('Please specify dimensions within the allowed range that is from 1x1 to @dimensions.', {'@dimensions': maxW ? imce.conf.dimensions : Drupal.t('unlimited')}), 'error'); } return imce.validateImage(); } var func = fop +'OpValidate'; if (imce[func]) return imce[func](fop); return true; }, //submit wrapper for default ops fopSubmit: function(fop) { switch (fop) { case 'thumb': case 'delete': case 'resize': return imce.commonSubmit(fop); } var func = fop +'OpSubmit'; if (imce[func]) return imce[func](fop); }, //common submit function shared by default ops commonSubmit: function(fop) { if (!imce.fopValidate(fop)) return false; imce.fopLoading(fop, true); $.ajax(imce.fopSettings(fop)); }, //settings for default file operations fopSettings: function (fop) { return {url: imce.ajaxURL(fop), type: 'POST', dataType: 'json', success: imce.processResponse, complete: function (response) {imce.fopLoading(fop, false);}, data: imce.vars.opform +'&filenames='+ imce.serialNames() +'&jsop='+ fop + (imce.ops[fop].div ? '&'+ $('input, select, textarea', imce.ops[fop].div).serialize() : '')}; }, //toggle loading state fopLoading: function(fop, state) { var el = imce.el('edit-'+ fop), func = state ? 'addClass' : 'removeClass' if (el) { $(el)[func]('loading').attr('disabled', state); } else { $(imce.ops[fop].li)[func]('loading'); imce.ops[fop].disabled = state; } }, //preview a file. setPreview: function (fid) { var row, html = ''; imce.vars.prvfid = fid; if (fid && (row = imce.fids[fid])) { var width = row.cells[2].innerHTML * 1; html = imce.vars.previewImages && width ? imce.imgHtml(fid, width, row.cells[3].innerHTML) : imce.decodePlain(fid); html = '<a href="#" onclick="imce.send(\''+ fid +'\'); return false;" title="'+ (imce.vars.prvtitle||'') +'">'+ html +'</a>'; } imce.el('file-preview').innerHTML = html; }, //default file send function. sends the file to the new window. send: function (fid) { fid && window.open(imce.getURL(fid)); }, //add an operation for an external application to which the files are send. setSendTo: function (title, func) { imce.send = function (fid) { fid && func(imce.fileGet(fid), window);}; var opFunc = function () { if (imce.selcount != 1) return imce.setMessage(Drupal.t('Please select a file.'), 'error'); imce.send(imce.vars.prvfid); }; imce.vars.prvtitle = title; return imce.opAdd({name: 'sendto', title: title, func: opFunc}); }, //move initial page messages into log prepareMsgs: function () { var msgs; if (msgs = imce.el('imce-messages')) { $('>div', msgs).each(function (){ var type = this.className.split(' ')[1]; var li = $('>ul li', this); if (li.size()) li.each(function () {imce.setMessage(this.innerHTML, type);}); else imce.setMessage(this.innerHTML, type); }); $(msgs).remove(); } }, //insert log message setMessage: function (msg, type) { var $box = $(imce.msgBox); var logs = imce.el('log-messages') || $(imce.newEl('div')).appendTo('#help-box-content').before('<h4>'+ Drupal.t('Log messages') +':</h4>').attr('id', 'log-messages')[0]; var msg = '<div class="message '+ (type || 'status') +'">'+ msg +'</div>'; $box.queue(function() { $box.css({opacity: 0, display: 'block'}).html(msg); $box.dequeue(); }); var q = $box.queue().length, t = imce.vars.msgT || 1000; q = q < 2 ? 1 : q < 3 ? 0.8 : q < 4 ? 0.7 : 0.4;//adjust speed with respect to queue length $box.fadeTo(600 * q, 1).fadeTo(t * q, 1).fadeOut(400 * q); $(logs).append(msg); return false; }, //invoke hooks invoke: function (hook) { var i, args, func, funcs; if ((funcs = imce.hooks[hook]) && funcs.length) { (args = $.makeArray(arguments)).shift(); for (i = 0; func = funcs[i]; i++) func.apply(this, args); } }, //process response processResponse: function (response) { if (response.data) imce.resData(response.data); if (response.messages) imce.resMsgs(response.messages); }, //process response data resData: function (data) { var i, added, removed; if (added = data.added) { var cnt = imce.findex.length; for (i in added) {//add new files or update existing imce.fileAdd(added[i]); } if (added.length == 1) {//if it is a single file operation imce.highlight(added[0].name);//highlight } if (imce.findex.length != cnt) {//if new files added, scroll to bottom. $(imce.SBW).animate({scrollTop: imce.SBW.scrollHeight}).focus(); } } if (removed = data.removed) for (i in removed) { imce.fileRemove(removed[i]); } imce.conf.dirsize = data.dirsize; imce.updateStat(); }, //set response messages resMsgs: function (msgs) { for (var type in msgs) for (var i in msgs[type]) { imce.setMessage(msgs[type][i], type); } }, //return img markup imgHtml: function (fid, width, height) { return '<img src="'+ imce.getURL(fid) +'" width="'+ width +'" height="'+ height +'" alt="'+ imce.decodePlain(fid) +'">'; }, //check if the file is an image isImage: function (fid) { return imce.fids[fid].cells[2].innerHTML * 1; }, //find the first non-image in the selection getNonImage: function (selected) { for (var fid in selected) { if (!imce.isImage(fid)) return fid; } return false; }, //validate current selection for images validateImage: function () { var nonImg = imce.getNonImage(imce.selected); return nonImg ? imce.setMessage(Drupal.t('%filename is not an image.', {'%filename': imce.decode(nonImg)}), 'error') : true; }, //validate number of selected files validateSelCount: function (Min, Max) { if (Min && imce.selcount < Min) { return imce.setMessage(Min == 1 ? Drupal.t('Please select a file.') : Drupal.t('You must select at least %num files.', {'%num': Min}), 'error'); } if (Max && Max < imce.selcount) { return imce.setMessage(Drupal.t('You are not allowed to operate on more than %num files.', {'%num': Max}), 'error'); } return true; }, //update file count and dir size updateStat: function () { imce.el('file-count').innerHTML = imce.findex.length; imce.el('dir-size').innerHTML = imce.conf.dirsize; }, //serialize selected files. return fids with a colon between them serialNames: function () { var str = ''; for (var fid in imce.selected) { str += ':'+ fid; } return str.substr(1); }, //get file url. re-encode & and # for mod rewrite getURL: function (fid) { var path = (imce.conf.dir == '.' ? '' : imce.conf.dir +'/') + fid; return imce.conf.furl + (imce.conf.modfix ? path.replace(/%(23|26)/g, '%25$1') : path); }, //el. by id el: function (id) { return document.getElementById(id); }, //find the latest selected fid lastFid: function () { if (imce.vars.lastfid) return imce.vars.lastfid; for (var fid in imce.selected); return fid; }, //create ajax url ajaxURL: function (op, dir) { return imce.conf.url + (imce.conf.clean ? '?' :'&') +'jsop='+ op +'&dir='+ (dir||imce.conf.dir); }, //fast class check hasC: function (el, name) { return el.className && (' '+ el.className +' ').indexOf(' '+ name +' ') != -1; }, //highlight a single file highlight: function (fid) { if (imce.vars.prvfid) imce.fileClick(imce.vars.prvfid); imce.fileClick(fid); }, //process a row processRow: function (row) { row.cells[0].innerHTML = '<span>' + imce.decodePlain(row.id) + '</span>'; row.onmousedown = function(e) { var e = e||window.event; imce.fileClick(this, e.ctrlKey, e.shiftKey); return !(e.ctrlKey || e.shiftKey); }; row.ondblclick = function(e) { imce.send(this.id); return false; }; }, //decode urls. uses unescape. can be overridden to use decodeURIComponent decode: function (str) { return unescape(str); }, //decode and convert to plain text decodePlain: function (str) { return Drupal.checkPlain(imce.decode(str)); }, //global ajax error function ajaxError: function (e, response, settings, thrown) { imce.setMessage(Drupal.ajaxError(response, settings.url).replace(/\n/g, '<br />'), 'error'); }, //convert button elements to standard input buttons convertButtons: function(form) { $('button:submit', form).each(function(){ $(this).replaceWith('<input type="submit" value="'+ $(this).text() +'" name="'+ this.name +'" class="form-submit" id="'+ this.id +'" />'); }); }, //create element newEl: function(name) { return document.createElement(name); }, //scroll syncronization for section headers syncScroll: function(scrlEl, fixEl, bottom) { var $fixEl = $(fixEl); var prop = bottom ? 'bottom' : 'top'; var factor = bottom ? -1 : 1; var syncScrl = function(el) { $fixEl.css(prop, factor * el.scrollTop); } $(scrlEl).scroll(function() { var el = this; syncScrl(el); setTimeout(function() { syncScrl(el); }); }); }, //get UI ready. provide backward compatibility. updateUI: function() { //file urls. var furl = imce.conf.furl, isabs = furl.indexOf('://') > -1; var absurls = imce.conf.absurls = imce.vars.absurls || imce.conf.absurls; var host = location.host; var baseurl = location.protocol + '//' + host; if (furl.charAt(furl.length - 1) != '/') { furl = imce.conf.furl = furl + '/'; } imce.conf.modfix = imce.conf.clean && furl.indexOf(host + '/system/') > -1; if (absurls && !isabs) { imce.conf.furl = baseurl + furl; } else if (!absurls && isabs && furl.indexOf(baseurl) == 0) { imce.conf.furl = furl.substr(baseurl.length); } //convert button elements to input elements. imce.convertButtons(imce.FW); //ops-list $('#ops-list').removeClass('tabs secondary').addClass('clear-block clearfix'); imce.opCloseLink = $(imce.newEl('a')).attr({id: 'op-close-link', href: '#', title: Drupal.t('Close')}).click(function() { imce.vars.op && imce.opClick(imce.vars.op); return false; }).appendTo('#op-contents')[0]; //navigation-header if (!$('#navigation-header').size()) { $(imce.NW).children('.navigation-text').attr('id', 'navigation-header').wrapInner('<span></span>'); } //log $('#log-prv-wrapper').before($('#log-prv-wrapper > #preview-wrapper')).remove(); $('#log-clearer').remove(); //content resizer $('#content-resizer').remove(); //message-box imce.msgBox = imce.el('message-box') || $(imce.newEl('div')).attr('id', 'message-box').prependTo('#imce-content')[0]; //create help tab var $hbox = $('#help-box'); $hbox.is('a') && $hbox.replaceWith($(imce.newEl('div')).attr('id', 'help-box').append($hbox.children())); imce.hooks.load.push(function() { imce.opAdd({name: 'help', title: $('#help-box-title').remove().text(), content: $('#help-box').show()}); }); //add ie classes $.browser.msie && $('html').addClass('ie') && parseFloat($.browser.version) < 8 && $('html').addClass('ie-7'); // enable box view for file list imce.vars.boxW && imce.boxView(); //scrolling file list imce.syncScroll(imce.SBW, '#file-header-wrapper'); imce.syncScroll(imce.SBW, '#dir-stat', true); //scrolling directory tree imce.syncScroll(imce.NW, '#navigation-header'); } }; //initiate $(document).ready(imce.initiate).ajaxError(imce.ajaxError); })(jQuery);; /* * IMCE Integration by URL * Ex-1: http://example.com/imce?app=XEditor|url@urlFieldId|width@widthFieldId|height@heightFieldId * Creates "Insert file" operation tab, which fills the specified fields with url, width, height properties * of the selected file in the parent window * Ex-2: http://example.com/imce?app=XEditor|sendto@functionName * "Insert file" operation calls parent window's functionName(file, imceWindow) * Ex-3: http://example.com/imce?app=XEditor|imceload@functionName * Parent window's functionName(imceWindow) is called as soon as IMCE UI is ready. Send to operation * needs to be set manually. See imce.setSendTo() method in imce.js */ (function($) { var appFields = {}, appWindow = (top.appiFrm||window).opener || parent; // Execute when imce loads. imce.hooks.load.push(function(win) { var index = location.href.lastIndexOf('app='); if (index == -1) return; var data = decodeURIComponent(location.href.substr(index + 4)).split('|'); var arr, prop, str, func, appName = data.shift(); // Extract fields for (var i = 0, len = data.length; i < len; i++) { str = data[i]; if (!str.length) continue; if (str.indexOf('&') != -1) str = str.split('&')[0]; arr = str.split('@'); if (arr.length > 1) { prop = arr.shift(); appFields[prop] = arr.join('@'); } } // Run custom onload function if available if (appFields.imceload && (func = isFunc(appFields.imceload))) { func(win); delete appFields.imceload; } // Set custom sendto function. appFinish is the default. var sendtoFunc = appFields.url ? appFinish : false; //check sendto@funcName syntax in URL if (appFields.sendto && (func = isFunc(appFields.sendto))) { sendtoFunc = func; delete appFields.sendto; } // Check old method windowname+ImceFinish. else if (win.name && (func = isFunc(win.name +'ImceFinish'))) { sendtoFunc = func; } // Highlight file if (appFields.url) { // Support multiple url fields url@field1,field2.. if (appFields.url.indexOf(',') > -1) { var arr = appFields.url.split(','); for (var i in arr) { if ($('#'+ arr[i], appWindow.document).size()) { appFields.url = arr[i]; break; } } } var filename = $('#'+ appFields.url, appWindow.document).val() || ''; imce.highlight(filename.substr(filename.lastIndexOf('/')+1)); } // Set send to sendtoFunc && imce.setSendTo(Drupal.t('Insert file'), sendtoFunc); }); // Default sendTo function var appFinish = function(file, win) { var $doc = $(appWindow.document); for (var i in appFields) { $doc.find('#'+ appFields[i]).val(file[i]); } if (appFields.url) { try{ $doc.find('#'+ appFields.url).blur().change().focus(); }catch(e){ try{ $doc.find('#'+ appFields.url).trigger('onblur').trigger('onchange').trigger('onfocus');//inline events for IE }catch(e){} } } appWindow.focus(); win.close(); }; // Checks if a string is a function name in the given scope. // Returns function reference. Supports x.y.z notation. var isFunc = function(str, scope) { var obj = scope || appWindow; var parts = str.split('.'), len = parts.length; for (var i = 0; i < len && (obj = obj[parts[i]]); i++); return obj && i == len && (typeof obj == 'function' || typeof obj != 'string' && !obj.nodeName && obj.constructor != Array && /^[\s[]?function/.test(obj.toString())) ? obj : false; } })(jQuery);; /** * Wysiwyg API integration helper function. */ function imceImageBrowser(field_name, url, type, win) { // TinyMCE. if (win !== 'undefined') { win.open(Drupal.settings.imce.url + encodeURIComponent(field_name), '', 'width=760,height=560,resizable=1'); } } /** * CKeditor integration. */ var imceCkeditSendTo = function (file, win) { var parts = /\?(?:.*&)?CKEditorFuncNum=(\d+)(?:&|$)/.exec(win.location.href); if (parts && parts.length > 1) { CKEDITOR.tools.callFunction(parts[1], file.url); win.close(); } else { throw 'CKEditorFuncNum parameter not found or invalid: ' + win.location.href; } }; ; /** * @file: Popup dialog interfaces for the media project. * * Drupal.media.popups.mediaBrowser * Launches the media browser which allows users to pick a piece of media. * * Drupal.media.popups.mediaStyleSelector * Launches the style selection form where the user can choose * what format / style they want their media in. * */ (function ($) { namespace('Drupal.media.popups'); /** * Media browser popup. Creates a media browser dialog. * * @param {function} * onSelect Callback for when dialog is closed, received (Array * media, Object extra); * @param {Object} * globalOptions Global options that will get passed upon initialization of the browser. * @see Drupal.media.popups.mediaBrowser.getDefaults(); * * @param {Object} * pluginOptions Options for specific plugins. These are passed * to the plugin upon initialization. If a function is passed here as * a callback, it is obviously not passed, but is accessible to the plugin * in Drupal.settings.variables. * * Example * pluginOptions = {library: {url_include_patterns:'/foo/bar'}}; * * @param {Object} * widgetOptions Options controlling the appearance and behavior of the * modal dialog. * @see Drupal.media.popups.mediaBrowser.getDefaults(); */ Drupal.media.popups.mediaBrowser = function (onSelect, globalOptions, pluginOptions, widgetOptions) { var options = Drupal.media.popups.mediaBrowser.getDefaults(); options.global = $.extend({}, options.global, globalOptions); options.plugins = pluginOptions; options.widget = $.extend({}, options.widget, widgetOptions); // Create it as a modal window. var browserSrc = options.widget.src; if ($.isArray(browserSrc) && browserSrc.length) { browserSrc = browserSrc[browserSrc.length - 1]; } // Params to send along to the iframe. WIP. var params = {}; $.extend(params, options.global); params.plugins = options.plugins; browserSrc += '&' + $.param(params); var mediaIframe = Drupal.media.popups.getPopupIframe(browserSrc, 'mediaBrowser'); // Attach the onLoad event mediaIframe.bind('load', options, options.widget.onLoad); /** * Setting up the modal dialog */ var ok = 'OK'; var cancel = 'Cancel'; var notSelected = 'You have not selected anything!'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); cancel = Drupal.t(cancel); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = options.dialog; dialogOptions.buttons[ok] = function () { var selected = this.contentWindow.Drupal.media.browser.selectedMedia; if (selected.length < 1) { alert(notSelected); return; } onSelect(selected); $(this).dialog("destroy"); $(this).remove(); }; dialogOptions.buttons[cancel] = function () { $(this).dialog("destroy"); $(this).remove(); }; Drupal.media.popups.setDialogPadding(mediaIframe.dialog(dialogOptions)); // Remove the title bar. mediaIframe.parents(".ui-dialog").find(".ui-dialog-titlebar").remove(); Drupal.media.popups.overlayDisplace(mediaIframe.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad = function (e) { var options = e.data; if (this.contentWindow.Drupal.media.browser.selectedMedia.length > 0) { var ok = $(this).dialog('option', 'buttons')['OK']; ok.call(this); return; } }; Drupal.media.popups.mediaBrowser.getDefaults = function () { return { global: { types: [], // Types to allow, defaults to all. activePlugins: [] // If provided, a list of plugins which should be enabled. }, widget: { // Settings for the actual iFrame which is launched. src: Drupal.settings.media.browserUrl, // Src of the media browser (if you want to totally override it) onLoad: Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad // Onload function when iFrame loads. }, dialog: Drupal.media.popups.getDialogOptions() }; }; Drupal.media.popups.mediaBrowser.finalizeSelection = function () { var selected = this.contentWindow.Drupal.media.browser.selectedMedia; if (selected.length < 1) { alert(notSelected); return; } onSelect(selected); $(this).dialog("destroy"); $(this).remove(); } /** * Style chooser Popup. Creates a dialog for a user to choose a media style. * * @param mediaFile * The mediaFile you are requesting this formatting form for. * @todo: should this be fid? That's actually all we need now. * * @param Function * onSubmit Function to be called when the user chooses a media * style. Takes one parameter (Object formattedMedia). * * @param Object * options Options for the mediaStyleChooser dialog. */ Drupal.media.popups.mediaStyleSelector = function (mediaFile, onSelect, options) { var defaults = Drupal.media.popups.mediaStyleSelector.getDefaults(); // @todo: remove this awful hack :( defaults.src = defaults.src.replace('-media_id-', mediaFile.fid); options = $.extend({}, defaults, options); // Create it as a modal window. var mediaIframe = Drupal.media.popups.getPopupIframe(options.src, 'mediaStyleSelector'); // Attach the onLoad event mediaIframe.bind('load', options, options.onLoad); /** * Set up the button text */ var ok = 'OK'; var cancel = 'Cancel'; var notSelected = 'Very sorry, there was an unknown error embedding media.'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); cancel = Drupal.t(cancel); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = Drupal.media.popups.getDialogOptions(); dialogOptions.buttons[ok] = function () { var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia(); if (!formattedMedia) { alert(notSelected); return; } onSelect(formattedMedia); $(this).dialog("destroy"); $(this).remove(); }; dialogOptions.buttons[cancel] = function () { $(this).dialog("destroy"); $(this).remove(); }; Drupal.media.popups.setDialogPadding(mediaIframe.dialog(dialogOptions)); // Remove the title bar. mediaIframe.parents(".ui-dialog").find(".ui-dialog-titlebar").remove(); Drupal.media.popups.overlayDisplace(mediaIframe.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaStyleSelector.mediaBrowserOnLoad = function (e) { }; Drupal.media.popups.mediaStyleSelector.getDefaults = function () { return { src: Drupal.settings.media.styleSelectorUrl, onLoad: Drupal.media.popups.mediaStyleSelector.mediaBrowserOnLoad }; }; /** * Style chooser Popup. Creates a dialog for a user to choose a media style. * * @param mediaFile * The mediaFile you are requesting this formatting form for. * @todo: should this be fid? That's actually all we need now. * * @param Function * onSubmit Function to be called when the user chooses a media * style. Takes one parameter (Object formattedMedia). * * @param Object * options Options for the mediaStyleChooser dialog. */ Drupal.media.popups.mediaFieldEditor = function (fid, onSelect, options) { var defaults = Drupal.media.popups.mediaFieldEditor.getDefaults(); // @todo: remove this awful hack :( defaults.src = defaults.src.replace('-media_id-', fid); options = $.extend({}, defaults, options); // Create it as a modal window. var mediaIframe = Drupal.media.popups.getPopupIframe(options.src, 'mediaFieldEditor'); // Attach the onLoad event // @TODO - This event is firing too early in IE on Windows 7, // - so the height being calculated is too short for the content. mediaIframe.bind('load', options, options.onLoad); /** * Set up the button text */ var ok = 'OK'; var cancel = 'Cancel'; var notSelected = 'Very sorry, there was an unknown error embedding media.'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); cancel = Drupal.t(cancel); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = Drupal.media.popups.getDialogOptions(); dialogOptions.buttons[ok] = function () { alert('hell yeah'); return "poo"; var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia(); if (!formattedMedia) { alert(notSelected); return; } onSelect(formattedMedia); $(this).dialog("destroy"); $(this).remove(); }; dialogOptions.buttons[cancel] = function () { $(this).dialog("destroy"); $(this).remove(); }; Drupal.media.popups.setDialogPadding(mediaIframe.dialog(dialogOptions)); // Remove the title bar. mediaIframe.parents(".ui-dialog").find(".ui-dialog-titlebar").remove(); Drupal.media.popups.overlayDisplace(mediaIframe.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaFieldEditor.mediaBrowserOnLoad = function (e) { }; Drupal.media.popups.mediaFieldEditor.getDefaults = function () { return { // @todo: do this for real src: '/media/-media_id-/edit?render=media-popup', onLoad: Drupal.media.popups.mediaFieldEditor.mediaBrowserOnLoad }; }; /** * Generic functions to both the media-browser and style selector */ /** * Returns the commonly used options for the dialog. */ Drupal.media.popups.getDialogOptions = function () { return { buttons: {}, dialogClass: 'media-wrapper', modal: true, draggable: false, resizable: false, minWidth: 600, width: 800, height: 550, position: 'center', overlay: { backgroundColor: '#000000', opacity: 0.4 } }; }; /** * Created padding on a dialog * * @param jQuery dialogElement * The element which has .dialog() attached to it. */ Drupal.media.popups.setDialogPadding = function (dialogElement) { // @TODO: Perhaps remove this hardcoded reference to height. // - It's included to make IE on Windows 7 display the dialog without // collapsing. 550 is the height that displays all of the tab panes // within the Add Media overlay. This is either a bug in the jQuery // UI library, a bug in IE on Windows 7 or a bug in the way the // dialog is instantiated. Or a combo of the three. // All browsers except IE on Win7 ignore these defaults and adjust // the height of the iframe correctly to match the content in the panes dialogElement.height(dialogElement.dialog('option', 'height')); dialogElement.width(dialogElement.dialog('option', 'width')); }; /** * Get an iframe to serve as the dialog's contents. Common to both plugins. */ Drupal.media.popups.getPopupIframe = function (src, id, options) { var defaults = {width: '800px', scrolling: 'no'}; var options = $.extend({}, defaults, options); return $('<iframe class="media-modal-frame"/>') .attr('src', src) .attr('width', options.width) .attr('id', id) .attr('scrolling', options.scrolling); }; Drupal.media.popups.overlayDisplace = function (dialog) { if (parent.window.Drupal.overlay) { var overlayDisplace = parent.window.Drupal.overlay.getDisplacement('top'); if (dialog.offset().top < overlayDisplace) { dialog.css('top', overlayDisplace); } } } })(jQuery); ; /** * @file * Attach Media WYSIWYG behaviors. */ (function ($) { Drupal.media = Drupal.media || {}; // Define the behavior. Drupal.wysiwyg.plugins.media = { /** * Initializes the tag map. */ initializeTagMap: function () { if (typeof Drupal.settings.tagmap == 'undefined') { Drupal.settings.tagmap = { }; } }, /** * Execute the button. * @TODO: Debug calls from this are never called. What's its function? */ invoke: function (data, settings, instanceId) { if (data.format == 'html') { Drupal.media.popups.mediaBrowser(function (mediaFiles) { Drupal.wysiwyg.plugins.media.mediaBrowserOnSelect(mediaFiles, instanceId); }, settings['global']); } }, /** * Respond to the mediaBrowser's onSelect event. * @TODO: Debug calls from this are never called. What's its function? */ mediaBrowserOnSelect: function (mediaFiles, instanceId) { var mediaFile = mediaFiles[0]; var options = {}; Drupal.media.popups.mediaStyleSelector(mediaFile, function (formattedMedia) { Drupal.wysiwyg.plugins.media.insertMediaFile(mediaFile, formattedMedia.type, formattedMedia.html, formattedMedia.options, Drupal.wysiwyg.instances[instanceId]); }, options); return; }, insertMediaFile: function (mediaFile, viewMode, formattedMedia, options, wysiwygInstance) { this.initializeTagMap(); // @TODO: the folks @ ckeditor have told us that there is no way // to reliably add wrapper divs via normal HTML. // There is some method of adding a "fake element" // But until then, we're just going to embed to img. // This is pretty hacked for now. // var imgElement = $(this.stripDivs(formattedMedia)); this.addImageAttributes(imgElement, mediaFile.fid, viewMode, options); var toInsert = this.outerHTML(imgElement); // Create an inline tag var inlineTag = Drupal.wysiwyg.plugins.media.createTag(imgElement); // Add it to the tag map in case the user switches input formats Drupal.settings.tagmap[inlineTag] = toInsert; wysiwygInstance.insert(toInsert); }, /** * Gets the HTML content of an element * * @param jQuery element */ outerHTML: function (element) { return $('<div>').append( element.eq(0).clone() ).html(); }, addImageAttributes: function (imgElement, fid, view_mode, additional) { // imgElement.attr('fid', fid); // imgElement.attr('view_mode', view_mode); // Class so we can find this image later. imgElement.addClass('media-image'); this.forceAttributesIntoClass(imgElement, fid, view_mode, additional); if (additional) { for (k in additional) { if (additional.hasOwnProperty(k)) { if (k === 'attr') { imgElement.attr(k, additional[k]); } } } } }, /** * Due to problems handling wrapping divs in ckeditor, this is needed. * * Going forward, if we don't care about supporting other editors * we can use the fakeobjects plugin to ckeditor to provide cleaner * transparency between what Drupal will output <div class="field..."><img></div> * instead of just <img>, for now though, we're going to remove all the stuff surrounding the images. * * @param String formattedMedia * Element containing the image * * @return HTML of <img> tag inside formattedMedia */ stripDivs: function (formattedMedia) { // Check to see if the image tag has divs to strip var stripped = null; if ($(formattedMedia).is('img')) { stripped = this.outerHTML($(formattedMedia)); } else { stripped = this.outerHTML($('img', $(formattedMedia))); } // This will fail if we pass the img tag without anything wrapping it, like we do when re-enabling WYSIWYG return stripped; }, /** * Attach function, called when a rich text editor loads. * This finds all [[tags]] and replaces them with the html * that needs to show in the editor. * */ attach: function (content, settings, instanceId) { var matches = content.match(/\[\[.*?\]\]/g); this.initializeTagMap(); var tagmap = Drupal.settings.tagmap; if (matches) { var inlineTag = ""; for (i = 0; i < matches.length; i++) { inlineTag = matches[i]; if (tagmap[inlineTag]) { // This probably needs some work... // We need to somehow get the fid propogated here. // We really want to var tagContent = tagmap[inlineTag]; var mediaMarkup = this.stripDivs(tagContent); // THis is <div>..<img> var _tag = inlineTag; _tag = _tag.replace('[[',''); _tag = _tag.replace(']]',''); try { mediaObj = JSON.parse(_tag); } catch(err) { mediaObj = null; } if(mediaObj) { var imgElement = $(mediaMarkup); this.addImageAttributes(imgElement, mediaObj.fid, mediaObj.view_mode); var toInsert = this.outerHTML(imgElement); content = content.replace(inlineTag, toInsert); } } else { debug.debug("Could not find content for " + inlineTag); } } } return content; }, /** * Detach function, called when a rich text editor detaches */ detach: function (content, settings, instanceId) { // Replace all Media placeholder images with the appropriate inline json // string. Using a regular expression instead of jQuery manipulation to // prevent <script> tags from being displaced. // @see http://drupal.org/node/1280758. if (matches = content.match(/<img[^>]+class=([\'"])media-image[^>]*>/gi)) { for (var i = 0; i < matches.length; i++) { var imageTag = matches[i]; var inlineTag = Drupal.wysiwyg.plugins.media.createTag($(imageTag)); Drupal.settings.tagmap[inlineTag] = imageTag; content = content.replace(imageTag, inlineTag); } } return content; }, /** * @param jQuery imgNode * Image node to create tag from */ createTag: function (imgNode) { // Currently this is the <img> itself // Collect all attribs to be stashed into tagContent var mediaAttributes = {}; var imgElement = imgNode[0]; var sorter = []; // @todo: this does not work in IE, width and height are always 0. for (i=0; i< imgElement.attributes.length; i++) { var attr = imgElement.attributes[i]; if (attr.specified == true) { if (attr.name !== 'class') { sorter.push(attr); } else { // Exctract expando properties from the class field. var attributes = this.getAttributesFromClass(attr.value); for (var name in attributes) { if (attributes.hasOwnProperty(name)) { var value = attributes[name]; if (value.type && value.type === 'attr') { sorter.push(value); } } } } } } sorter.sort(this.sortAttributes); for (var prop in sorter) { mediaAttributes[sorter[prop].name] = sorter[prop].value; } // The following 5 ifs are dedicated to IE7 // If the style is null, it is because IE7 can't read values from itself if (jQuery.browser.msie && jQuery.browser.version == '7.0') { if (mediaAttributes.style === "null") { var imgHeight = imgNode.css('height'); var imgWidth = imgNode.css('width'); mediaAttributes.style = { height: imgHeight, width: imgWidth } if (!mediaAttributes['width']) { mediaAttributes['width'] = imgWidth; } if (!mediaAttributes['height']) { mediaAttributes['height'] = imgHeight; } } // If the attribute width is zero, get the CSS width if (Number(mediaAttributes['width']) === 0) { mediaAttributes['width'] = imgNode.css('width'); } // IE7 does support 'auto' as a value of the width attribute. It will not // display the image if this value is allowed to pass through if (mediaAttributes['width'] === 'auto') { delete mediaAttributes['width']; } // If the attribute height is zero, get the CSS height if (Number(mediaAttributes['height']) === 0) { mediaAttributes['height'] = imgNode.css('height'); } // IE7 does support 'auto' as a value of the height attribute. It will not // display the image if this value is allowed to pass through if (mediaAttributes['height'] === 'auto') { delete mediaAttributes['height']; } } // Remove elements from attribs using the blacklist for (var blackList in Drupal.settings.media.blacklist) { delete mediaAttributes[Drupal.settings.media.blacklist[blackList]]; } tagContent = { "type": 'media', // @todo: This will be selected from the format form "view_mode": attributes['view_mode'].value, "fid" : attributes['fid'].value, "attributes": mediaAttributes }; return '[[' + JSON.stringify(tagContent) + ']]'; }, /** * Forces custom attributes into the class field of the specified image. * * Due to a bug in some versions of Firefox * (http://forums.mozillazine.org/viewtopic.php?f=9&t=1991855), the * custom attributes used to share information about the image are * being stripped as the image markup is set into the rich text * editor. Here we encode these attributes into the class field so * the data survives. * * @param imgElement * The image * @fid * The file id. * @param view_mode * The view mode. * @param additional * Additional attributes to add to the image. */ forceAttributesIntoClass: function (imgElement, fid, view_mode, additional) { var wysiwyg = imgElement.attr('wysiwyg'); if (wysiwyg) { imgElement.addClass('attr__wysiwyg__' + wysiwyg); } var format = imgElement.attr('format'); if (format) { imgElement.addClass('attr__format__' + format); } var typeOf = imgElement.attr('typeof'); if (typeOf) { imgElement.addClass('attr__typeof__' + typeOf); } if (fid) { imgElement.addClass('img__fid__' + fid); } if (view_mode) { imgElement.addClass('img__view_mode__' + view_mode); } if (additional) { for (var name in additional) { if (additional.hasOwnProperty(name)) { if (name !== 'alt') { imgElement.addClass('attr__' + name + '__' + additional[name]); } } } } }, /** * Retrieves encoded attributes from the specified class string. * * @param classString * A string containing the value of the class attribute. * @return * An array containing the attribute names as keys, and an object * with the name, value, and attribute type (either 'attr' or * 'img', depending on whether it is an image attribute or should * be it the attributes section) */ getAttributesFromClass: function (classString) { var actualClasses = []; var otherAttributes = []; var classes = classString.split(' '); var regexp = new RegExp('^(attr|img)__([^\S]*)__([^\S]*)$'); for (var index = 0; index < classes.length; index++) { var matches = classes[index].match(regexp); if (matches && matches.length === 4) { otherAttributes[matches[2]] = {name: matches[2], value: matches[3], type: matches[1]}; } else { actualClasses.push(classes[index]); } } if (actualClasses.length > 0) { otherAttributes['class'] = {name: 'class', value: actualClasses.join(' '), type: 'attr'}; } return otherAttributes; }, /* * */ sortAttributes: function (a, b) { var nameA = a.name.toLowerCase(); var nameB = b.name.toLowerCase(); if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } return 0; } }; })(jQuery); ; (function ($) { // @todo Array syntax required; 'break' is a predefined token in JavaScript. Drupal.wysiwyg.plugins['break'] = { /** * Return whether the passed node belongs to this plugin. */ isNode: function(node) { return ($(node).is('img.wysiwyg-break')); }, /** * Execute the button. */ invoke: function(data, settings, instanceId) { if (data.format == 'html') { // Prevent duplicating a teaser break. if ($(data.node).is('img.wysiwyg-break')) { return; } var content = this._getPlaceholder(settings); } else { // Prevent duplicating a teaser break. // @todo data.content is the selection only; needs access to complete content. if (data.content.match(/<!--break-->/)) { return; } var content = '<!--break-->'; } if (typeof content != 'undefined') { Drupal.wysiwyg.instances[instanceId].insert(content); } }, /** * Replace all <!--break--> tags with images. */ attach: function(content, settings, instanceId) { content = content.replace(/<!--break-->/g, this._getPlaceholder(settings)); return content; }, /** * Replace images with <!--break--> tags in content upon detaching editor. */ detach: function(content, settings, instanceId) { var $content = $('<div>' + content + '</div>'); // No .outerHTML() in jQuery :( // #404532: document.createComment() required or IE will strip the comment. // #474908: IE 8 breaks when using jQuery methods to replace the elements. // @todo Add a generic implementation for all Drupal plugins for this. $.each($('img.wysiwyg-break', $content), function (i, elem) { elem.parentNode.insertBefore(document.createComment('break'), elem); elem.parentNode.removeChild(elem); }); return $content.html(); }, /** * Helper function to return a HTML placeholder. */ _getPlaceholder: function (settings) { return '<img src="' + settings.path + '/images/spacer.gif" alt="&lt;--break-&gt;" title="&lt;--break--&gt;" class="wysiwyg-break drupal-content" />'; } }; })(jQuery); ; (function ($) { /** * Auto-hide summary textarea if empty and show hide and unhide links. */ Drupal.behaviors.textSummary = { attach: function (context, settings) { $('.text-summary', context).once('text-summary', function () { var $widget = $(this).closest('div.field-type-text-with-summary'); var $summaries = $widget.find('div.text-summary-wrapper'); $summaries.once('text-summary-wrapper').each(function(index) { var $summary = $(this); var $summaryLabel = $summary.find('label'); var $full = $widget.find('.text-full').eq(index).closest('.form-item'); var $fullLabel = $full.find('label'); // Create a placeholder label when the field cardinality is // unlimited or greater than 1. if ($fullLabel.length == 0) { $fullLabel = $('<label></label>').prependTo($full); } // Setup the edit/hide summary link. var $link = $('<span class="field-edit-link">(<a class="link-edit-summary" href="#">' + Drupal.t('Hide summary') + '</a>)</span>').toggle( function () { $summary.hide(); $(this).find('a').html(Drupal.t('Edit summary')).end().appendTo($fullLabel); return false; }, function () { $summary.show(); $(this).find('a').html(Drupal.t('Hide summary')).end().appendTo($summaryLabel); return false; } ).appendTo($summaryLabel); // If no summary is set, hide the summary field. if ($(this).find('.text-summary').val() == '') { $link.click(); } return; }); }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.textarea = { attach: function (context, settings) { $('.form-textarea-wrapper.resizable', context).once('textarea', function () { var staticOffset = null; var textarea = $(this).addClass('resizable-textarea').find('textarea'); var grippie = $('<div class="grippie"></div>').mousedown(startDrag); grippie.insertAfter(textarea); function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag); textarea.css('opacity', 1); } }); } }; })(jQuery); ; (function ($) { /** * Automatically display the guidelines of the selected text format. */ Drupal.behaviors.filterGuidelines = { attach: function (context) { $('.filter-guidelines', context).once('filter-guidelines') .find(':header').hide() .parents('.filter-wrapper').find('select.filter-list') .bind('change', function () { $(this).parents('.filter-wrapper') .find('.filter-guidelines-item').hide() .siblings('.filter-guidelines-' + this.value).show(); }) .change(); } }; })(jQuery); ; (function ($) { /** * Toggle the visibility of a fieldset using smooth animations. */ Drupal.toggleFieldset = function (fieldset) { var $fieldset = $(fieldset); if ($fieldset.is('.collapsed')) { var $content = $('> .fieldset-wrapper', fieldset).hide(); $fieldset .removeClass('collapsed') .trigger({ type: 'collapsed', value: false }) .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide')); $content.slideDown({ duration: 'fast', easing: 'linear', complete: function () { Drupal.collapseScrollIntoView(fieldset); fieldset.animating = false; }, step: function () { // Scroll the fieldset into view. Drupal.collapseScrollIntoView(fieldset); } }); } else { $fieldset.trigger({ type: 'collapsed', value: true }); $('> .fieldset-wrapper', fieldset).slideUp('fast', function () { $fieldset .addClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show')); fieldset.animating = false; }); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = document.documentElement.clientHeight || document.body.clientHeight || 0; var offset = document.documentElement.scrollTop || document.body.scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = { attach: function (context, settings) { $('fieldset.collapsible', context).once('collapse', function () { var $fieldset = $(this); // Expand fieldset if there are errors inside, or if it contains an // element that is targeted by the uri fragment identifier. var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : ''; if ($('.error' + anchor, $fieldset).length) { $fieldset.removeClass('collapsed'); } var summary = $('<span class="summary"></span>'); $fieldset. bind('summaryUpdated', function () { var text = $.trim($fieldset.drupalGetSummary()); summary.html(text ? ' (' + text + ')' : ''); }) .trigger('summaryUpdated'); // Turn the legend into a clickable link, but retain span.fieldset-legend // for CSS positioning. var $legend = $('> legend .fieldset-legend', this); $('<span class="fieldset-legend-prefix element-invisible"></span>') .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide')) .prependTo($legend) .after(' '); // .wrapInner() does not retain bound events. var $link = $('<a class="fieldset-title" href="#"></a>') .prepend($legend.contents()) .appendTo($legend) .click(function () { var fieldset = $fieldset.get(0); // Don't animate multiple times. if (!fieldset.animating) { fieldset.animating = true; Drupal.toggleFieldset(fieldset); } return false; }); $legend.append(summary); }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.menuFieldsetSummaries = { attach: function (context) { $('fieldset.menu-link-form', context).drupalSetSummary(function (context) { if ($('.form-item-menu-enabled input', context).is(':checked')) { return Drupal.checkPlain($('.form-item-menu-link-title input', context).val()); } else { return Drupal.t('Not in menu'); } }); } }; /** * Automatically fill in a menu link title, if possible. */ Drupal.behaviors.menuLinkAutomaticTitle = { attach: function (context) { $('fieldset.menu-link-form', context).each(function () { // Try to find menu settings widget elements as well as a 'title' field in // the form, but play nicely with user permissions and form alterations. var $checkbox = $('.form-item-menu-enabled input', this); var $link_title = $('.form-item-menu-link-title input', context); var $title = $(this).closest('form').find('.form-item-title input'); // Bail out if we do not have all required fields. if (!($checkbox.length && $link_title.length && $title.length)) { return; } // If there is a link title already, mark it as overridden. The user expects // that toggling the checkbox twice will take over the node's title. if ($checkbox.is(':checked') && $link_title.val().length) { $link_title.data('menuLinkAutomaticTitleOveridden', true); } // Whenever the value is changed manually, disable this behavior. $link_title.keyup(function () { $link_title.data('menuLinkAutomaticTitleOveridden', true); }); // Global trigger on checkbox (do not fill-in a value when disabled). $checkbox.change(function () { if ($checkbox.is(':checked')) { if (!$link_title.data('menuLinkAutomaticTitleOveridden')) { $link_title.val($title.val()); } } else { $link_title.val(''); $link_title.removeData('menuLinkAutomaticTitleOveridden'); } $checkbox.closest('fieldset.vertical-tabs-pane').trigger('summaryUpdated'); $checkbox.trigger('formUpdated'); }); // Take over any title change. $title.keyup(function () { if (!$link_title.data('menuLinkAutomaticTitleOveridden') && $checkbox.is(':checked')) { $link_title.val($title.val()); $link_title.val($title.val()).trigger('formUpdated'); } }); }); } }; })(jQuery); ; (function ($) { /** * Attaches sticky table headers. */ Drupal.behaviors.tableHeader = { attach: function (context, settings) { if (!$.support.positionFixed) { return; } $('table.sticky-enabled', context).once('tableheader', function () { $(this).data("drupal-tableheader", new Drupal.tableHeader(this)); }); } }; /** * Constructor for the tableHeader object. Provides sticky table headers. * * @param table * DOM object for the table to add a sticky header to. */ Drupal.tableHeader = function (table) { var self = this; this.originalTable = $(table); this.originalHeader = $(table).children('thead'); this.originalHeaderCells = this.originalHeader.find('> tr > th'); // Clone the table header so it inherits original jQuery properties. Hide // the table to avoid a flash of the header clone upon page load. this.stickyTable = $('<table class="sticky-header"/>') .insertBefore(this.originalTable) .css({ position: 'fixed', top: '0px' }); this.stickyHeader = this.originalHeader.clone(true) .hide() .appendTo(this.stickyTable); this.stickyHeaderCells = this.stickyHeader.find('> tr > th'); this.originalTable.addClass('sticky-table'); $(window) .bind('scroll.drupal-tableheader', $.proxy(this, 'eventhandlerRecalculateStickyHeader')) .bind('resize.drupal-tableheader', { calculateWidth: true }, $.proxy(this, 'eventhandlerRecalculateStickyHeader')) // Make sure the anchor being scrolled into view is not hidden beneath the // sticky table header. Adjust the scrollTop if it does. .bind('drupalDisplaceAnchor.drupal-tableheader', function () { window.scrollBy(0, -self.stickyTable.outerHeight()); }) // Make sure the element being focused is not hidden beneath the sticky // table header. Adjust the scrollTop if it does. .bind('drupalDisplaceFocus.drupal-tableheader', function (event) { if (self.stickyVisible && event.clientY < (self.stickyOffsetTop + self.stickyTable.outerHeight()) && event.$target.closest('sticky-header').length === 0) { window.scrollBy(0, -self.stickyTable.outerHeight()); } }) .triggerHandler('resize.drupal-tableheader'); // We hid the header to avoid it showing up erroneously on page load; // we need to unhide it now so that it will show up when expected. this.stickyHeader.show(); }; /** * Event handler: recalculates position of the sticky table header. * * @param event * Event being triggered. */ Drupal.tableHeader.prototype.eventhandlerRecalculateStickyHeader = function (event) { var self = this; var calculateWidth = event.data && event.data.calculateWidth; // Reset top position of sticky table headers to the current top offset. this.stickyOffsetTop = Drupal.settings.tableHeaderOffset ? eval(Drupal.settings.tableHeaderOffset + '()') : 0; this.stickyTable.css('top', this.stickyOffsetTop + 'px'); // Save positioning data. var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight; if (calculateWidth || this.viewHeight !== viewHeight) { this.viewHeight = viewHeight; this.vPosition = this.originalTable.offset().top - 4 - this.stickyOffsetTop; this.hPosition = this.originalTable.offset().left; this.vLength = this.originalTable[0].clientHeight - 100; calculateWidth = true; } // Track horizontal positioning relative to the viewport and set visibility. var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft; var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition; this.stickyVisible = vOffset > 0 && vOffset < this.vLength; this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' }); // Only perform expensive calculations if the sticky header is actually // visible or when forced. if (this.stickyVisible && (calculateWidth || !this.widthCalculated)) { this.widthCalculated = true; // Resize header and its cell widths. this.stickyHeaderCells.each(function (index) { var cellWidth = self.originalHeaderCells.eq(index).css('width'); // Exception for IE7. if (cellWidth == 'auto') { cellWidth = self.originalHeaderCells.get(index).clientWidth + 'px'; } $(this).css('width', cellWidth); }); this.stickyTable.css('width', this.originalTable.css('width')); } }; })(jQuery); ; (function ($) { Drupal.behaviors.tokenTree = { attach: function (context, settings) { $('table.token-tree', context).once('token-tree', function () { $(this).treeTable(); }); } }; Drupal.behaviors.tokenInsert = { attach: function (context, settings) { // Keep track of which textfield was last selected/focused. $('textarea, input[type="text"]', context).focus(function() { Drupal.settings.tokenFocusedField = this; }); $('.token-click-insert .token-key', context).once('token-click-insert', function() { var newThis = $('<a href="javascript:void(0);" title="' + Drupal.t('Insert this token into your form') + '">' + $(this).html() + '</a>').click(function(){ if (typeof Drupal.settings.tokenFocusedField == 'undefined') { alert(Drupal.t('First click a text field to insert your tokens into.')); } else { var myField = Drupal.settings.tokenFocusedField; var myValue = $(this).text(); //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); } else { myField.value += myValue; } $('html,body').animate({scrollTop: $(myField).offset().top}, 500); } return false; }); $(this).html(newThis); }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.metatagFieldsetSummaries = { attach: function (context) { $('fieldset.metatags-form', context).drupalSetSummary(function (context) { var vals = []; $("input[type='text'], select, textarea", context).each(function() { var default_name = $(this).attr('name').replace(/\[value\]/, '[default]'); var default_value = $("input[type='hidden'][name='" + default_name + "']", context); if (default_value.length && default_value.val() == $(this).val()) { // Meta tag has a default value and form value matches default value. return true; } else if (!default_value.length && !$(this).val().length) { // Meta tag has no default value and form value is empty. return true; } var label = $("label[for='" + $(this).attr('id') + "']").text(); vals.push(Drupal.t('@label: @value', { '@label': label.trim(), '@value': Drupal.truncate($(this).val(), 25) || Drupal.t('None') })); }); if (vals.length === 0) { return Drupal.t('Using defaults'); } else { return vals.join('<br />'); } }); } }; /** * Encode special characters in a plain-text string for display as HTML. */ Drupal.truncate = function (str, limit) { if (str.length > limit) { return str.substr(0, limit) + '...'; } else { return str; } }; })(jQuery); ; (function ($) { Drupal.behaviors.pathFieldsetSummaries = { attach: function (context) { $('fieldset.path-form', context).drupalSetSummary(function (context) { var path = $('.form-item-path-alias input').val(); var automatic = $('.form-item-path-pathauto input').attr('checked'); if (automatic) { return Drupal.t('Automatic alias'); } if (path) { return Drupal.t('Alias: @alias', { '@alias': path }); } else { return Drupal.t('No alias'); } }); } }; })(jQuery); ; (function ($) { Drupal.behaviors.commentFieldsetSummaries = { attach: function (context) { $('fieldset.comment-node-settings-form', context).drupalSetSummary(function (context) { return Drupal.checkPlain($('.form-item-comment input:checked', context).next('label').text()); }); // Provide the summary for the node type form. $('fieldset.comment-node-type-settings-form', context).drupalSetSummary(function(context) { var vals = []; // Default comment setting. vals.push($(".form-item-comment select option:selected", context).text()); // Threading. var threading = $(".form-item-comment-default-mode input:checked", context).next('label').text(); if (threading) { vals.push(threading); } // Comments per page. var number = $(".form-item-comment-default-per-page select option:selected", context).val(); vals.push(Drupal.t('@number comments per page', {'@number': number})); return Drupal.checkPlain(vals.join(', ')); }); } }; })(jQuery); ; (function ($) { /** * Attaches the autocomplete behavior to all required fields. */ Drupal.behaviors.autocomplete = { attach: function (context, settings) { var acdb = []; $('input.autocomplete', context).once('autocomplete', function () { var uri = this.value; if (!acdb[uri]) { acdb[uri] = new Drupal.ACDB(uri); } var $input = $('#' + this.id.substr(0, this.id.length - 13)) .attr('autocomplete', 'OFF') .attr('aria-autocomplete', 'list'); $($input[0].form).submit(Drupal.autocompleteSubmit); $input.parent() .attr('role', 'application') .append($('<span class="element-invisible" aria-live="assertive"></span>') .attr('id', $input.attr('id') + '-autocomplete-aria-live') ); new Drupal.jsAC($input, acdb[uri]); }); } }; /** * Prevents the form from submitting if the suggestions popup is open * and closes the suggestions popup when doing so. */ Drupal.autocompleteSubmit = function () { return $('#autocomplete').each(function () { this.owner.hidePopup(); }).size() == 0; }; /** * An AutoComplete object. */ Drupal.jsAC = function ($input, db) { var ac = this; this.input = $input[0]; this.ariaLive = $('#' + this.input.id + '-autocomplete-aria-live'); this.db = db; $input .keydown(function (event) { return ac.onkeydown(this, event); }) .keyup(function (event) { ac.onkeyup(this, event); }) .blur(function () { ac.hidePopup(); ac.db.cancel(); }); }; /** * Handler for the "keydown" event. */ Drupal.jsAC.prototype.onkeydown = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 40: // down arrow. this.selectDown(); return false; case 38: // up arrow. this.selectUp(); return false; default: // All other keys. return true; } }; /** * Handler for the "keyup" event. */ Drupal.jsAC.prototype.onkeyup = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 16: // Shift. case 17: // Ctrl. case 18: // Alt. case 20: // Caps lock. case 33: // Page up. case 34: // Page down. case 35: // End. case 36: // Home. case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return true; case 9: // Tab. case 13: // Enter. case 27: // Esc. this.hidePopup(e.keyCode); return true; default: // All other keys. if (input.value.length > 0) this.populatePopup(); else this.hidePopup(e.keyCode); return true; } }; /** * Puts the currently highlighted suggestion into the autocomplete field. */ Drupal.jsAC.prototype.select = function (node) { this.input.value = $(node).data('autocompleteValue'); }; /** * Highlights the next suggestion. */ Drupal.jsAC.prototype.selectDown = function () { if (this.selected && this.selected.nextSibling) { this.highlight(this.selected.nextSibling); } else if (this.popup) { var lis = $('li', this.popup); if (lis.size() > 0) { this.highlight(lis.get(0)); } } }; /** * Highlights the previous suggestion. */ Drupal.jsAC.prototype.selectUp = function () { if (this.selected && this.selected.previousSibling) { this.highlight(this.selected.previousSibling); } }; /** * Highlights a suggestion. */ Drupal.jsAC.prototype.highlight = function (node) { if (this.selected) { $(this.selected).removeClass('selected'); } $(node).addClass('selected'); this.selected = node; $(this.ariaLive).html($(this.selected).html()); }; /** * Unhighlights a suggestion. */ Drupal.jsAC.prototype.unhighlight = function (node) { $(node).removeClass('selected'); this.selected = false; $(this.ariaLive).empty(); }; /** * Hides the autocomplete suggestions. */ Drupal.jsAC.prototype.hidePopup = function (keycode) { // Select item if the right key or mousebutton was pressed. if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) { this.input.value = $(this.selected).data('autocompleteValue'); } // Hide popup. var popup = this.popup; if (popup) { this.popup = null; $(popup).fadeOut('fast', function () { $(popup).remove(); }); } this.selected = false; $(this.ariaLive).empty(); }; /** * Positions the suggestions popup and starts a search. */ Drupal.jsAC.prototype.populatePopup = function () { var $input = $(this.input); var position = $input.position(); // Show popup. if (this.popup) { $(this.popup).remove(); } this.selected = false; this.popup = $('<div id="autocomplete"></div>')[0]; this.popup.owner = this; $(this.popup).css({ top: parseInt(position.top + this.input.offsetHeight, 10) + 'px', left: parseInt(position.left, 10) + 'px', width: $input.innerWidth() + 'px', display: 'none' }); $input.before(this.popup); // Do search. this.db.owner = this; this.db.search(this.input.value); }; /** * Fills the suggestion popup with any matches received. */ Drupal.jsAC.prototype.found = function (matches) { // If no value in the textfield, do not show the popup. if (!this.input.value.length) { return false; } // Prepare matches. var ul = $('<ul></ul>'); var ac = this; for (key in matches) { $('<li></li>') .html($('<div></div>').html(matches[key])) .mousedown(function () { ac.select(this); }) .mouseover(function () { ac.highlight(this); }) .mouseout(function () { ac.unhighlight(this); }) .data('autocompleteValue', key) .appendTo(ul); } // Show popup with matches, if any. if (this.popup) { if (ul.children().size()) { $(this.popup).empty().append(ul).show(); $(this.ariaLive).html(Drupal.t('Autocomplete popup')); } else { $(this.popup).css({ visibility: 'hidden' }); this.hidePopup(); } } }; Drupal.jsAC.prototype.setStatus = function (status) { switch (status) { case 'begin': $(this.input).addClass('throbbing'); $(this.ariaLive).html(Drupal.t('Searching for matches...')); break; case 'cancel': case 'error': case 'found': $(this.input).removeClass('throbbing'); break; } }; /** * An AutoComplete DataBase object. */ Drupal.ACDB = function (uri) { this.uri = uri; this.delay = 300; this.cache = {}; }; /** * Performs a cached and delayed search. */ Drupal.ACDB.prototype.search = function (searchString) { var db = this; this.searchString = searchString; // See if this string needs to be searched for anyway. searchString = searchString.replace(/^\s+|\s+$/, ''); if (searchString.length <= 0 || searchString.charAt(searchString.length - 1) == ',') { return; } // See if this key has been searched for before. if (this.cache[searchString]) { return this.owner.found(this.cache[searchString]); } // Initiate delayed search. if (this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(function () { db.owner.setStatus('begin'); // Ajax GET request for autocompletion. $.ajax({ type: 'GET', url: db.uri + '/' + encodeURIComponent(searchString), dataType: 'json', success: function (matches) { if (typeof matches.status == 'undefined' || matches.status != 0) { db.cache[searchString] = matches; // Verify if these are still the matches the user wants to see. if (db.searchString == searchString) { db.owner.found(matches); } db.owner.setStatus('found'); } }, error: function (xmlhttp) { alert(Drupal.ajaxError(xmlhttp, db.uri)); } }); }, this.delay); }; /** * Cancels the current autocomplete request. */ Drupal.ACDB.prototype.cancel = function () { if (this.owner) this.owner.setStatus('cancel'); if (this.timer) clearTimeout(this.timer); this.searchString = ''; }; })(jQuery); ; (function ($) { Drupal.behaviors.nodeFieldsetSummaries = { attach: function (context) { $('fieldset.node-form-revision-information', context).drupalSetSummary(function (context) { var revisionCheckbox = $('.form-item-revision input', context); // Return 'New revision' if the 'Create new revision' checkbox is checked, // or if the checkbox doesn't exist, but the revision log does. For users // without the "Administer content" permission the checkbox won't appear, // but the revision log will if the content type is set to auto-revision. if (revisionCheckbox.is(':checked') || (!revisionCheckbox.length && $('.form-item-log textarea', context).length)) { return Drupal.t('New revision'); } return Drupal.t('No revision'); }); $('fieldset.node-form-author', context).drupalSetSummary(function (context) { var name = $('.form-item-name input', context).val() || Drupal.settings.anonymous, date = $('.form-item-date input', context).val(); return date ? Drupal.t('By @name on @date', { '@name': name, '@date': date }) : Drupal.t('By @name', { '@name': name }); }); $('fieldset.node-form-options', context).drupalSetSummary(function (context) { var vals = []; $('input:checked', context).parent().each(function () { vals.push(Drupal.checkPlain($.trim($(this).text()))); }); if (!$('.form-item-status input', context).is(':checked')) { vals.unshift(Drupal.t('Not published')); } return vals.join(', '); }); } }; })(jQuery); ;
ghigata/prowood
sites/default/files/js/js_kJRR2EPkdTyr2CIdeTvE1Z1h-ltSkNI_HTuwHAsTNDE.js
JavaScript
gpl-2.0
95,145
/* * Copyright (C) eZ Systems AS. All rights reserved. * For full copyright and license information view LICENSE file distributed with this source code. */ YUI.add('ez-dashboardview', function (Y) { "use strict"; /** * Provides the Dashboard View class * * @module ez-dashboardview */ Y.namespace('eZ'); /** * The dashboard view * * @namespace eZ * @class DashboardView * @constructor * @extends eZ.TemplateBasedView */ Y.eZ.DashboardView = Y.Base.create('dashboardView', Y.eZ.TemplateBasedView, [Y.eZ.HeightFit], { initializer: function () { this.after('activeChange', this._setIFrameSource); }, /** * Renders the dashboard view * * @method render * @return {eZ.DashboardView} the view itself */ render: function () { this.get('container').setHTML(this.template()); this._attachedViewEvents.push(Y.on("windowresize", Y.bind(this._uiSetHeight, this, 0))); return this; }, /** * Sets the source of the iframe to the value of the iframeSource attribute. * * @method _setIFrameSource * @private */ _setIFrameSource: function () { this.get('container').one('.ez-dashboard-content').set('src', this.get('iframeSource')); } }, { ATTRS: { /** * Stores the iframe Source * * @attribute iframeSource * @type String * @default 'http://ez.no/in-product/eZ-Platform' * @readOnly */ iframeSource: { value: '//ez.no/in-product/eZ-Platform', readOnly: true, }, }, }); });
StephaneDiot/PlatformUIBundle-1
Resources/public/js/views/ez-dashboardview.js
JavaScript
gpl-2.0
1,838
window.addEvent("domready", function() { var carousel = new iCarousel("carousel_content", { idPrevious: "carousel_prev", idNext: "carousel_next", idToggle: "undefined", item: { klass: "carouselitem_right", size: 265 }, animation: { type: "scroll", duration: 700, amount: 1 } }); $$('.carousel_header a').each(function (el,index){ el.addEvent("click", function(event){ new Event(event).stop(); carousel.goTo(index); $$('.carousel_header a').removeClass('active'); $('carousel_link'+index).addClass('active'); }); }); });
thtinh/hb
templates/vxg_hb/js/carousel_impl.js
JavaScript
gpl-2.0
715
// closure to avoid namespace collision (function(){ //------- var html_form = '<div id="text_box-form">\ <p class="popup_submit_wrap"><span class="wpp_helper_box"><a onclick="open_win(\'http://www.youtube.com/watch?v=Y_7snOfYato&list=PLI8Gq0WzVWvJ60avoe8rMyfoV5qZr3Atm&index=10\')">Видео урок</a></span><input type="button" id="text_box_submit" class="button-primary" value="Вставить" name="submit" /></p>\ <div class="ps_text_box_form coach_box">\ <div>\ <label class="ps_text_box wppage_checkbox ps_text_box_1"><input type="radio" name="text_box_style" value="1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_1_1"><input type="radio" name="text_box_style" value="1_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_2"><input type="radio" name="text_box_style" value="2" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_2_1"><input type="radio" name="text_box_style" value="2_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_3"><input type="radio" name="text_box_style" value="3" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_3_1"><input type="radio" name="text_box_style" value="3_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_4"><input type="radio" name="text_box_style" value="4" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_4_1"><input type="radio" name="text_box_style" value="4_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_5"><input type="radio" name="text_box_style" value="5" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_5_1"><input type="radio" name="text_box_style" value="5_1" /></label>\ <label class="ps_text_box wppage_checkbox ps_text_box_6"><input type="radio" name="text_box_style" value="6" /></label>\ </div>\ </div></div>'; //------- // creates the plugin tinymce.create('tinymce.plugins.textbox', { // creates control instances based on the control's id. // our button's id is "smartresponder_button" createControl : function(id, controlManager) { if (id == 'text_box_button') { // creates the button var button = controlManager.createButton('text_box_button', { title : 'Боксы', // title of the button image : plugin_url+'/wppage/i/box.png', // path to the button's image onclick : function() { // triggers the thickbox tb_show( 'Боксы', '#TB_inline?inlineId=text_box-form' ); jQuery('#TB_ajaxContent').css({'width': '640', 'height': (jQuery('#TB_window').height()-50)+'px'}); jQuery(window).resize(function(){ jQuery('#TB_ajaxContent').css({'width': '640', 'height': (jQuery('#TB_window').height()-50)+'px'}); }); } }); return button; } return null; } }); // registers the plugin. DON'T MISS THIS STEP!!! tinymce.PluginManager.add('textbox', tinymce.plugins.textbox); // executes this when the DOM is ready jQuery(function(){ // creates a form to be displayed everytime the button is clicked // you should achieve this using AJAX instead of direct html code like this var form = jQuery(html_form); form.appendTo('body').hide(); // handles the click event of the submit button form.find('#text_box_submit').click(function(){ // defines the options and their default values // again, this is not the most elegant way to do this // but well, this gets the job done nonetheless var options = { 'id' : '' }; var text_box_style = jQuery('input[name=text_box_style]:checked').val(); var shortcode = '<p class="aligncenter"><div class="ps_text_box ps_text_box_'+text_box_style+'"><p class="ps_text_box_text">Текст</p></div></p><p>&nbsp;</p>'; // inserts the shortcode into the active editor tinyMCE.activeEditor.execCommand('mceInsertContent', 0, shortcode); // closes Thickbox tb_remove(); }); }); })()
SergL/aboutttango
wp-content/plugins/wppage/js/box.js
JavaScript
gpl-2.0
4,002
/** * Lists the number of different characters */ /* global document: true, Node: true, window: true */ exports.version = '1.0'; exports.module = function(phantomas) { 'use strict'; //phantomas.setMetric('differentCharacters'); // @desc the number of different characters in the body @offenders phantomas.on('report', function() { phantomas.log("charactersCount: starting to analyze characters on page..."); phantomas.evaluate(function() { (function(phantomas) { phantomas.spyEnabled(false, 'analyzing characters on page'); function getLetterCount(arr){ return arr.reduce(function(prev, next){ prev[next] = 1; return prev; }, {}); } if (document.body && document.body.textContent) { var allText = ''; // Traverse all DOM Tree to read text var runner = new phantomas.nodeRunner(); runner.walk(document.body, function(node, depth) { switch (node.nodeType) { // Grabing text nodes case Node.TEXT_NODE: if (node.parentNode.tagName !== 'SCRIPT' && node.parentNode.tagName !== 'STYLE') { allText += node.nodeValue; } break; // Grabing CSS content properties case Node.ELEMENT_NODE: if (node.tagName !== 'SCRIPT' && node.tagName !== 'STYLE') { allText += window.getComputedStyle(node).getPropertyValue('content'); allText += window.getComputedStyle(node, ':before').getPropertyValue('content'); allText += window.getComputedStyle(node, ':after').getPropertyValue('content'); } break; } }); // Reduce all text found in page into a string of unique chars var charactersList = getLetterCount(allText.split('')); var charsetString = Object.keys(charactersList).sort().join(''); // Remove blank characters charsetString = charsetString.replace(/\s/g, ''); phantomas.setMetric('differentCharacters', charsetString.length); phantomas.addOffender('differentCharacters', charsetString); } phantomas.spyEnabled(true); }(window.__phantomas)); }); phantomas.log("charactersCount: analyzing characters done."); }); };
gmetais/YellowLabTools
lib/tools/phantomas/custom_modules/modules/charactersCount/charactersCount.js
JavaScript
gpl-2.0
2,928
/* ************************************************************** #Inicia as funções e plugins * ***************************************************************/ (function() { // Ativa o menu mobile app.menu(); // Ativa o slideshow, se presente na página. var slideshow = document.getElementById("slider"); if(slideshow) { window.mySwipe = new Swipe(slideshow, { speed: 400, auto: 4000, continuous: false, callback: function(){ // Ativa os bullets de navegação do slideshow var i = mySwipe.getPos(), el = document.querySelectorAll("#slider > ul > li"); // Remove a classe ".is-active" de todos os bullets for(var x = 0; x < el.length; x++) { if(el[x].classList.contains("is-active")) { el[x].classList.remove("is-active"); } }; // Ativa a bullet correta el[i].classList.add("is-active"); } }); }; })();
nelclassico/hapvidaplanos
wp-content/themes/hapvida/src/js/init.js
JavaScript
gpl-2.0
969
'use strict'; function solve(args) { var $number = +args[0]; var $significantBit = $number => (($number >> 3) & 1); console.log($significantBit($number)); } solve(['15']); solve(['1024']);
iDonev/JavaScript-Fundamentals
Lecture 5. Operators and Expressions/ThirdBit.js
JavaScript
gpl-2.0
199
http://jsfiddle.net/fusioncharts/EZbvy/ http://jsfiddle.net/gh/get/jquery/1.9.1/sguha-work/fiddletest/tree/master/fiddles/Gauge/Tick-Values/Customizing-tick-marks-value-visibility-and-position-in-bullet-chart_323/
sguha-work/fiddletest
fiddles/Gauge/Tick-Values/Customizing-tick-marks-value-visibility-and-position-in-bullet-chart_323/url.js
JavaScript
gpl-2.0
213
/*! * smooth-scroll v16.1.0 * Animate scrolling to anchor links * (c) 2019 Chris Ferdinandi * MIT License * http://github.com/cferdinandi/smooth-scroll */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], (function () { return factory(root); })); } else if (typeof exports === 'object') { module.exports = factory(root); } else { root.SmoothScroll = factory(root); } })(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) { 'use strict'; // // Default settings // var defaults = { // Selectors ignore: '[data-scroll-ignore]', header: null, topOnEmptyHash: true, // Speed & Duration speed: 500, speedAsDuration: false, durationMax: null, durationMin: null, clip: true, offset: 0, // Easing easing: 'easeInOutCubic', customEasing: null, // History updateURL: true, popstate: true, // Custom Events emitEvents: true }; // // Utility Methods // /** * Check if browser supports required methods * @return {Boolean} Returns true if all required methods are supported */ var supports = function () { return ( 'querySelector' in document && 'addEventListener' in window && 'requestAnimationFrame' in window && 'closest' in window.Element.prototype ); }; /** * Merge two or more objects together. * @param {Object} objects The objects to merge together * @returns {Object} Merged values of defaults and options */ var extend = function () { var merged = {}; Array.prototype.forEach.call(arguments, (function (obj) { for (var key in obj) { if (!obj.hasOwnProperty(key)) return; merged[key] = obj[key]; } })); return merged; }; /** * Check to see if user prefers reduced motion * @param {Object} settings Script settings */ var reduceMotion = function () { if ('matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches) { return true; } return false; }; /** * Get the height of an element. * @param {Node} elem The element to get the height of * @return {Number} The element's height in pixels */ var getHeight = function (elem) { return parseInt(window.getComputedStyle(elem).height, 10); }; /** * Escape special characters for use with querySelector * @author Mathias Bynens * @link https://github.com/mathiasbynens/CSS.escape * @param {String} id The anchor ID to escape */ var escapeCharacters = function (id) { // Remove leading hash if (id.charAt(0) === '#') { id = id.substr(1); } var string = String(id); var length = string.length; var index = -1; var codeUnit; var result = ''; var firstCodeUnit = string.charCodeAt(0); while (++index < length) { codeUnit = string.charCodeAt(index); // Note: there’s no need to special-case astral symbols, surrogate // pairs, or lone surrogates. // If the character is NULL (U+0000), then throw an // `InvalidCharacterError` exception and terminate these steps. if (codeUnit === 0x0000) { throw new InvalidCharacterError( 'Invalid character: the input contains U+0000.' ); } if ( // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is // U+007F, […] (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || // If the character is the first character and is in the range [0-9] // (U+0030 to U+0039), […] (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || // If the character is the second character and is in the range [0-9] // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] ( index === 1 && codeUnit >= 0x0030 && codeUnit <= 0x0039 && firstCodeUnit === 0x002D ) ) { // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point result += '\\' + codeUnit.toString(16) + ' '; continue; } // If the character is not handled by one of the above rules and is // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to // U+005A), or [a-z] (U+0061 to U+007A), […] if ( codeUnit >= 0x0080 || codeUnit === 0x002D || codeUnit === 0x005F || codeUnit >= 0x0030 && codeUnit <= 0x0039 || codeUnit >= 0x0041 && codeUnit <= 0x005A || codeUnit >= 0x0061 && codeUnit <= 0x007A ) { // the character itself result += string.charAt(index); continue; } // Otherwise, the escaped character. // http://dev.w3.org/csswg/cssom/#escape-a-character result += '\\' + string.charAt(index); } // Return sanitized hash return '#' + result; }; /** * Calculate the easing pattern * @link https://gist.github.com/gre/1650294 * @param {String} type Easing pattern * @param {Number} time Time animation should take to complete * @returns {Number} */ var easingPattern = function (settings, time) { var pattern; // Default Easing Patterns if (settings.easing === 'easeInQuad') pattern = time * time; // accelerating from zero velocity if (settings.easing === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity if (settings.easing === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration if (settings.easing === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity if (settings.easing === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity if (settings.easing === 'easeInOutCubic') pattern = time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration if (settings.easing === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity if (settings.easing === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity if (settings.easing === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration if (settings.easing === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity if (settings.easing === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity if (settings.easing === 'easeInOutQuint') pattern = time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration // Custom Easing Patterns if (!!settings.customEasing) pattern = settings.customEasing(time); return pattern || time; // no easing, no acceleration }; /** * Determine the document's height * @returns {Number} */ var getDocumentHeight = function () { return Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight ); }; /** * Calculate how far to scroll * Clip support added by robjtede - https://github.com/cferdinandi/smooth-scroll/issues/405 * @param {Element} anchor The anchor element to scroll to * @param {Number} headerHeight Height of a fixed header, if any * @param {Number} offset Number of pixels by which to offset scroll * @param {Boolean} clip If true, adjust scroll distance to prevent abrupt stops near the bottom of the page * @returns {Number} */ var getEndLocation = function (anchor, headerHeight, offset, clip) { var location = 0; if (anchor.offsetParent) { do { location += anchor.offsetTop; anchor = anchor.offsetParent; } while (anchor); } location = Math.max(location - headerHeight - offset, 0); if (clip) { location = Math.min(location, getDocumentHeight() - window.innerHeight); } return location; }; /** * Get the height of the fixed header * @param {Node} header The header * @return {Number} The height of the header */ var getHeaderHeight = function (header) { return !header ? 0 : (getHeight(header) + header.offsetTop); }; /** * Calculate the speed to use for the animation * @param {Number} distance The distance to travel * @param {Object} settings The plugin settings * @return {Number} How fast to animate */ var getSpeed = function (distance, settings) { var speed = settings.speedAsDuration ? settings.speed : Math.abs(distance / 1000 * settings.speed); if (settings.durationMax && speed > settings.durationMax) return settings.durationMax; if (settings.durationMin && speed < settings.durationMin) return settings.durationMin; return parseInt(speed, 10); }; var setHistory = function (options) { // Make sure this should run if (!history.replaceState || !options.updateURL || history.state) return; // Get the hash to use var hash = window.location.hash; hash = hash ? hash : ''; // Set a default history history.replaceState( { smoothScroll: JSON.stringify(options), anchor: hash ? hash : window.pageYOffset }, document.title, hash ? hash : window.location.href ); }; /** * Update the URL * @param {Node} anchor The anchor that was scrolled to * @param {Boolean} isNum If true, anchor is a number * @param {Object} options Settings for Smooth Scroll */ var updateURL = function (anchor, isNum, options) { // Bail if the anchor is a number if (isNum) return; // Verify that pushState is supported and the updateURL option is enabled if (!history.pushState || !options.updateURL) return; // Update URL history.pushState( { smoothScroll: JSON.stringify(options), anchor: anchor.id }, document.title, anchor === document.documentElement ? '#top' : '#' + anchor.id ); }; /** * Bring the anchored element into focus * @param {Node} anchor The anchor element * @param {Number} endLocation The end location to scroll to * @param {Boolean} isNum If true, scroll is to a position rather than an element */ var adjustFocus = function (anchor, endLocation, isNum) { // Is scrolling to top of page, blur if (anchor === 0) { document.body.focus(); } // Don't run if scrolling to a number on the page if (isNum) return; // Otherwise, bring anchor element into focus anchor.focus(); if (document.activeElement !== anchor) { anchor.setAttribute('tabindex', '-1'); anchor.focus(); anchor.style.outline = 'none'; } window.scrollTo(0 , endLocation); }; /** * Emit a custom event * @param {String} type The event type * @param {Object} options The settings object * @param {Node} anchor The anchor element * @param {Node} toggle The toggle element */ var emitEvent = function (type, options, anchor, toggle) { if (!options.emitEvents || typeof window.CustomEvent !== 'function') return; var event = new CustomEvent(type, { bubbles: true, detail: { anchor: anchor, toggle: toggle } }); document.dispatchEvent(event); }; // // SmoothScroll Constructor // var SmoothScroll = function (selector, options) { // // Variables // var smoothScroll = {}; // Object for public APIs var settings, anchor, toggle, fixedHeader, eventTimeout, animationInterval; // // Methods // /** * Cancel a scroll-in-progress */ smoothScroll.cancelScroll = function (noEvent) { cancelAnimationFrame(animationInterval); animationInterval = null; if (noEvent) return; emitEvent('scrollCancel', settings); }; /** * Start/stop the scrolling animation * @param {Node|Number} anchor The element or position to scroll to * @param {Element} toggle The element that toggled the scroll event * @param {Object} options */ smoothScroll.animateScroll = function (anchor, toggle, options) { // Cancel any in progress scrolls smoothScroll.cancelScroll(); // Local settings var _settings = extend(settings || defaults, options || {}); // Merge user options with defaults // Selectors and variables var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; var anchorElem = isNum || !anchor.tagName ? null : anchor; if (!isNum && !anchorElem) return; var startLocation = window.pageYOffset; // Current location on the page if (_settings.header && !fixedHeader) { // Get the fixed header if not already set fixedHeader = document.querySelector(_settings.header); } var headerHeight = getHeaderHeight(fixedHeader); var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof _settings.offset === 'function' ? _settings.offset(anchor, toggle) : _settings.offset), 10), _settings.clip); // Location to scroll to var distance = endLocation - startLocation; // distance to travel var documentHeight = getDocumentHeight(); var timeLapsed = 0; var speed = getSpeed(distance, _settings); var start, percentage, position; /** * Stop the scroll animation when it reaches its target (or the bottom/top of page) * @param {Number} position Current position on the page * @param {Number} endLocation Scroll to location * @param {Number} animationInterval How much to scroll on this loop */ var stopAnimateScroll = function (position, endLocation) { // Get the current location var currentLocation = window.pageYOffset; // Check if the end location has been reached yet (or we've hit the end of the document) if (position == endLocation || currentLocation == endLocation || ((startLocation < endLocation && window.innerHeight + currentLocation) >= documentHeight)) { // Clear the animation timer smoothScroll.cancelScroll(true); // Bring the anchored element into focus adjustFocus(anchor, endLocation, isNum); // Emit a custom event emitEvent('scrollStop', _settings, anchor, toggle); // Reset start start = null; animationInterval = null; return true; } }; /** * Loop scrolling animation */ var loopAnimateScroll = function (timestamp) { if (!start) { start = timestamp; } timeLapsed += timestamp - start; percentage = speed === 0 ? 0 : (timeLapsed / speed); percentage = (percentage > 1) ? 1 : percentage; position = startLocation + (distance * easingPattern(_settings, percentage)); window.scrollTo(0, Math.floor(position)); if (!stopAnimateScroll(position, endLocation)) { animationInterval = window.requestAnimationFrame(loopAnimateScroll); start = timestamp; } }; /** * Reset position to fix weird iOS bug * @link https://github.com/cferdinandi/smooth-scroll/issues/45 */ if (window.pageYOffset === 0) { window.scrollTo(0, 0); } // Update the URL updateURL(anchor, isNum, _settings); // If the user prefers reduced motion, jump to location if (reduceMotion()) { window.scrollTo(0, Math.floor(endLocation)); return; } // Emit a custom event emitEvent('scrollStart', _settings, anchor, toggle); // Start scrolling animation smoothScroll.cancelScroll(true); window.requestAnimationFrame(loopAnimateScroll); }; /** * If smooth scroll element clicked, animate scroll */ var clickHandler = function (event) { // Don't run if event was canceled but still bubbled up // By @mgreter - https://github.com/cferdinandi/smooth-scroll/pull/462/ if (event.defaultPrevented) return; // Don't run if right-click or command/control + click or shift + click if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey) return; // Check if event.target has closest() method // By @totegi - https://github.com/cferdinandi/smooth-scroll/pull/401/ if (!('closest' in event.target)) return; // Check if a smooth scroll link was clicked toggle = event.target.closest(selector); if (!toggle || toggle.tagName.toLowerCase() !== 'a' || event.target.closest(settings.ignore)) return; // Only run if link is an anchor and points to the current page if (toggle.hostname !== window.location.hostname || toggle.pathname !== window.location.pathname || !/#/.test(toggle.href)) return; // Get an escaped version of the hash var hash = escapeCharacters(toggle.hash); // Get the anchored element var anchor; if (hash === '#') { if (!settings.topOnEmptyHash) return; anchor = document.documentElement; } else { anchor = document.querySelector(hash); } anchor = !anchor && hash === '#top' ? document.documentElement : anchor; // If anchored element exists, scroll to it if (!anchor) return; event.preventDefault(); setHistory(settings); smoothScroll.animateScroll(anchor, toggle); }; /** * Animate scroll on popstate events */ var popstateHandler = function (event) { // Stop if history.state doesn't exist (ex. if clicking on a broken anchor link). // fixes `Cannot read property 'smoothScroll' of null` error getting thrown. if (history.state === null) return; // Only run if state is a popstate record for this instantiation if (!history.state.smoothScroll || history.state.smoothScroll !== JSON.stringify(settings)) return; // Only run if state includes an anchor // if (!history.state.anchor && history.state.anchor !== 0) return; // Get the anchor var anchor = history.state.anchor; if (typeof anchor === 'string' && anchor) { anchor = document.querySelector(escapeCharacters(history.state.anchor)); if (!anchor) return; } // Animate scroll to anchor link smoothScroll.animateScroll(anchor, null, {updateURL: false}); }; /** * Destroy the current initialization. */ smoothScroll.destroy = function () { // If plugin isn't already initialized, stop if (!settings) return; // Remove event listeners document.removeEventListener('click', clickHandler, false); window.removeEventListener('popstate', popstateHandler, false); // Cancel any scrolls-in-progress smoothScroll.cancelScroll(); // Reset variables settings = null; anchor = null; toggle = null; fixedHeader = null; eventTimeout = null; animationInterval = null; }; /** * Initialize Smooth Scroll * @param {Object} options User settings */ var init = function () { // feature test if (!supports()) throw 'Smooth Scroll: This browser does not support the required JavaScript methods and browser APIs.'; // Destroy any existing initializations smoothScroll.destroy(); // Selectors and variables settings = extend(defaults, options || {}); // Merge user options with defaults fixedHeader = settings.header ? document.querySelector(settings.header) : null; // Get the fixed header // When a toggle is clicked, run the click handler document.addEventListener('click', clickHandler, false); // If updateURL and popState are enabled, listen for pop events if (settings.updateURL && settings.popstate) { window.addEventListener('popstate', popstateHandler, false); } }; // // Initialize plugin // init(); // // Public APIs // return smoothScroll; }; return SmoothScroll; }));
MattTavares/MattTavares.github.io
assets/js/plugins/SmoothScroll/SmoothScroll.js
JavaScript
gpl-2.0
23,210
{ "CMSMAIN.WARNINGSAVEPAGESBEFOREADDING" : "You have to save a page before adding children underneath it", "CMSMAIN.CANTADDCHILDREN" : "You can't add children to the selected node", "CMSMAIN.ERRORADDINGPAGE" : "Error adding page", "CMSMAIN.FILTEREDTREE" : "Filtered tree to only show changed pages", "CMSMAIN.ERRORFILTERPAGES" : "Could not filter tree to only show changed pages<br />%s", "CMSMAIN.ERRORUNFILTER" : "Unfiltered tree", "CMSMAIN.PUBLISHINGPAGES" : "Publishing pages...", "CMSMAIN.SELECTONEPAGE" : "Please select at least 1 page.", "CMSMAIN.ERRORPUBLISHING" : "Error publishing pages", "CMSMAIN.REALLYDELETEPAGES" : "Do you really want to delete the %s marked pages?", "CMSMAIN.DELETINGPAGES" : "Deleting pages...", "CMSMAIN.ERRORDELETINGPAGES": "Error deleting pages", "CMSMAIN.PUBLISHING" : "Publishing...", "CMSMAIN.RESTORING": "Restoring...", "CMSMAIN.ERRORREVERTING": "Error reverting to live content", "CMSMAIN.SAVING" : "saving...", "CMSMAIN.SELECTMOREPAGES" : "You have %s pages selected.\n\nDo you really want to perform this action?", "CMSMAIN.ALERTCLASSNAME": "The page type will be updated after the page is saved", "CMSMAIN.URLSEGMENTVALIDATION": "URLs can only be made up of letters, digits and hyphens.", "AssetAdmin.BATCHACTIONSDELETECONFIRM": "Do you really want to delete %s folders?", "AssetTableField.REALLYDELETE": "Do you really want to delete the marked files?", "AssetTableField.MOVING": "Moving %s file(s)", "CMSMAIN.AddSearchCriteria": "Add Criteria", "WidgetAreaEditor.TOOMANY": "Sorry, you have reached the maximum number of widgets in this area", "AssetAdmin.ConfirmDelete": "Do you really want to delete this folder and all contained files?", "Folder.Name": "Folder name", "Tree.AddSubPage": "Add new page here", "Tree.Duplicate": "Duplicate", "Tree.EditPage": "Edit", "Tree.ThisPageOnly": "This page only", "Tree.ThisPageAndSubpages": "This page and subpages", "Tree.ShowAsList": "Show children as list", "CMSMain.ConfirmRestoreFromLive": "Do you really want to copy the published content to the draft site?", "CMSMain.RollbackToVersion": "Do you really want to roll back to version #%s of this page?", "URLSEGMENT.Edit": "Edit", "URLSEGMENT.OK": "OK", "URLSEGMENT.Cancel": "Cancel", "URLSEGMENT.UpdateURL": "Update URL" }
maent45/PersianFeast
cms/javascript/lang/src/en.js
JavaScript
gpl-2.0
2,305
var State = Backbone.State = function(options) { options || (options = {}); }; _.extend(State.prototype, Backbone.Events, { classes: [], before: null, on: null, after: null, events: {}, triggers: [], multistate: [], _isStateDescribedInSet: function( set, state ) { var isDescribed = false; _.each( set, function( entry ) { if( state.match( entry ) ) { isDescribed = true; } }); return isDescribed; }, isStateDescribedInAllowed: function( state ) { return _isStateDescribedInSet( this.multistate.allow, state ); }, isStateDescribedInDisallowed: function( state ) { return _isStateDescribedInSet( this.multistate.disallow, state ); }, isStatePermitted: function( state ) { var allowed = false; if (this.multistate == "any" || this.multistate == "all") { return true; } if(this.isStateDescribedInAllowed( state )) return true; if(this.isStateDescribedInDisallowed( state )) return false; }, }); // Generic State Machine var StateMachine = Backbone.StateMachine = function(options) { options || (options = {}); if( options.el ) { this.setElement( options.el ); } } _.extend(StateMachine.prototype, Backbone.Events, { states: {}, state: null, el: null, $el: null, setElement: function( el ) { this.el = el; this.$el = this.el ? $(this.el) : null; }, get classes( ) { if(this.$el) { return _.toArray( this.$el.attr('class').split(/\s+/) ); } else { return null; } }, set classes( newClasses ) { if( !$this.el) if( typeof newClasses === 'string' ) { this.$el.attr('class', newClasses); } else { this.$el.attr('class', newClasses.join(' ')); } }, createState: function( name, state ) { state = (typeof state === State) ? state : new State( state ); this.states[name] = state; return this; }, // Private method for applying a state _applyState: function( state ) { this.events = _.union( this.events, state.events); this.classes = _.union( this.classes, state.classes); this.state = state; }, // Private method for cleaning up the previous state _removeState: function( state ) { this.events = _.difference( this.events, state.events ); this.classes = _.difference( this.classes, state.classes ); this.state = null; }, //Public method for changing the state pushState: function( name ) { var oldState = this.state, newState = this.states[name]; // Old State if(oldState) { this._removeState( state ); if(oldState.after) oldState.after( name ); } // New State if(newState && newState.before) { newState.before(); } this._applyState( newState ); if(this.state && this.state.on) { this.state.on(); } this.trigger("stateChanged", { oldState: oldState, newState: newState }); } });
jonathanrevell/tokamak
backbone.states.js
JavaScript
gpl-2.0
2,952
'use strict'; module.exports = require('./EuCookies');
Dununan/reactjs-eu-cookies
build/index.js
JavaScript
gpl-2.0
55
/* Syntax highlighting with language autodetection. http://softwaremaniacs.org/soft/highlight/ */ var DEFAULT_LANGUAGES = ['python', 'ruby', 'perl', 'php', 'css', 'xml', 'html', 'django', 'javascript', 'java', 'cpp', 'sql', 'smalltalk']; var ALL_LANGUAGES = (DEFAULT_LANGUAGES.join(',') + ',' + ['1c', 'ada', 'elisp', 'axapta', 'delphi', 'rib', 'rsl', 'vbscript'].join(',')).split(','); var LANGUAGE_GROUPS = { 'xml': 'www', 'html': 'www', 'css': 'www', 'django': 'www', 'python': 'dynamic', 'perl': 'dynamic', 'php': 'dynamic', 'ruby': 'dynamic', 'cpp': 'static', 'java': 'static', 'delphi': 'static' } var IDENT_RE = '[a-zA-Z][a-zA-Z0-9_]*'; var UNDERSCORE_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_]*'; var NUMBER_RE = '\\b\\d+(\\.\\d+)?'; var C_NUMBER_RE = '\\b(0x[A-Za-z0-9]+|\\d+(\\.\\d+)?)'; // Common modes var APOS_STRING_MODE = { className: 'string', begin: '\'', end: '\'', illegal: '\\n', contains: ['escape'], relevance: 0 } var QUOTE_STRING_MODE = { className: 'string', begin: '"', end: '"', illegal: '\\n', contains: ['escape'], relevance: 0 } var BACKSLASH_ESCAPE = { className: 'escape', begin: '\\\\.', end: '^', relevance: 0 } var C_LINE_COMMENT_MODE = { className: 'comment', begin: '//', end: '$', relevance: 0 } var C_BLOCK_COMMENT_MODE = { className: 'comment', begin: '/\\*', end: '\\*/' } var HASH_COMMENT_MODE = { className: 'comment', begin: '#', end: '$' } var C_NUMBER_MODE = { className: 'number', begin: C_NUMBER_RE, end: '^', relevance: 0 } var LANGUAGES = {} var selected_languages = {}; function Highlighter(language_name, value) { function subMode(lexem) { if (!modes[modes.length - 1].contains) return null; for (var i in modes[modes.length - 1].contains) { var className = modes[modes.length - 1].contains[i]; for (var key in language.modes) if (language.modes[key].className == className && language.modes[key].beginRe.test(lexem)) return language.modes[key]; }//for return null; }//subMode function endOfMode(mode_index, lexem) { if (modes[mode_index].end && modes[mode_index].endRe.test(lexem)) return 1; if (modes[mode_index].endsWithParent) { var level = endOfMode(mode_index - 1, lexem); return level ? level + 1 : 0; }//if return 0; }//endOfMode function isIllegal(lexem) { if (!modes[modes.length - 1].illegalRe) return false; return modes[modes.length - 1].illegalRe.test(lexem); }//isIllegal function eatModeChunk(value, index) { if (!modes[modes.length - 1].terminators) { var terminators = []; if (modes[modes.length - 1].contains) for (var key in language.modes) { if (contains(modes[modes.length - 1].contains, language.modes[key].className) && !contains(terminators, language.modes[key].begin)) terminators[terminators.length] = language.modes[key].begin; }//for var mode_index = modes.length - 1; do { if (modes[mode_index].end && !contains(terminators, modes[mode_index].end)) terminators[terminators.length] = modes[mode_index].end; mode_index--; } while (modes[mode_index + 1].endsWithParent); if (modes[modes.length - 1].illegal) if (!contains(terminators, modes[modes.length - 1].illegal)) terminators[terminators.length] = modes[modes.length - 1].illegal; var terminator_re = '(' + terminators[0]; for (var i = 0; i < terminators.length; i++) terminator_re += '|' + terminators[i]; terminator_re += ')'; modes[modes.length - 1].terminators = langRe(language, terminator_re); }//if value = value.substr(index); var match = modes[modes.length - 1].terminators.exec(value); if (!match) return [value, '', true]; if (match.index == 0) return ['', match[0], false]; else return [value.substr(0, match.index), match[0], false]; }//eatModeChunk function escape(value) { return value.replace(/&/gm, '&amp;').replace(/</gm, '&lt;').replace(/>/gm, '&gt;'); }//escape function keywordMatch(mode, match) { var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0] for (var className in mode.keywordGroups) { var value = mode.keywordGroups[className].hasOwnProperty(match_str); if (value) return [className, value]; }//for return false; }//keywordMatch function processKeywords(buffer) { var mode = modes[modes.length - 1]; if (!mode.keywords || !mode.lexems) return escape(buffer); if (!mode.lexemsRe) { var lexems = []; for (var key in mode.lexems) if (!contains(lexems, mode.lexems[key])) lexems[lexems.length] = mode.lexems[key]; var lexems_re = '(' + lexems[0]; for (var i = 1; i < lexems.length; i++) lexems_re += '|' + lexems[i]; lexems_re += ')'; mode.lexemsRe = langRe(language, lexems_re, true); }//if var result = ''; var last_index = 0; mode.lexemsRe.lastIndex = 0; var match = mode.lexemsRe.exec(buffer); while (match) { result += escape(buffer.substr(last_index, match.index - last_index)); keyword_match = keywordMatch(mode, match); if (keyword_match) { keyword_count += keyword_match[1]; result += '<span class="'+ keyword_match[0] +'">' + escape(match[0]) + '</span>'; } else { result += escape(match[0]); }//if last_index = mode.lexemsRe.lastIndex; match = mode.lexemsRe.exec(buffer); }//while result += escape(buffer.substr(last_index, buffer.length - last_index)); return result; }//processKeywords function processModeInfo(buffer, lexem, end) { if (end) { result += processKeywords(modes[modes.length - 1].buffer + buffer); return; }//if if (isIllegal(lexem)) throw 'Illegal'; var new_mode = subMode(lexem); if (new_mode) { modes[modes.length - 1].buffer += buffer; result += processKeywords(modes[modes.length - 1].buffer); if (new_mode.excludeBegin) { result += lexem + '<span class="' + new_mode.className + '">'; new_mode.buffer = ''; } else { result += '<span class="' + new_mode.className + '">'; new_mode.buffer = lexem; }//if modes[modes.length] = new_mode; relevance += modes[modes.length - 1].relevance != undefined ? modes[modes.length - 1].relevance : 1; return; }//if var end_level = endOfMode(modes.length - 1, lexem); if (end_level) { modes[modes.length - 1].buffer += buffer; if (modes[modes.length - 1].excludeEnd) { result += processKeywords(modes[modes.length - 1].buffer) + '</span>' + lexem; } else { result += processKeywords(modes[modes.length - 1].buffer + lexem) + '</span>'; } while (end_level > 1) { result += '</span>'; end_level--; modes.length--; }//while modes.length--; modes[modes.length - 1].buffer = ''; return; }//if }//processModeInfo function highlight(value) { var index = 0; language.defaultMode.buffer = ''; do { var mode_info = eatModeChunk(value, index); processModeInfo(mode_info[0], mode_info[1], mode_info[2]); index += mode_info[0].length + mode_info[1].length; } while (!mode_info[2]); if(modes.length > 1) throw 'Illegal'; }//highlight this.language_name = language_name; var language = LANGUAGES[language_name]; var modes = [language.defaultMode]; var relevance = 0; var keyword_count = 0; var result = ''; try { highlight(value); this.relevance = relevance; this.keyword_count = keyword_count; this.result = result; } catch (e) { if (e == 'Illegal') { this.relevance = 0; this.keyword_count = 0; this.result = escape(value); } else { throw e; }//if }//try }//Highlighter function contains(array, item) { if (!array) return false; for (var key in array) if (array[key] == item) return true; return false; }//contains function blockText(block) { var result = ''; for (var i = 0; i < block.childNodes.length; i++) if (block.childNodes[i].nodeType == 3) result += block.childNodes[i].nodeValue; else if (block.childNodes[i].nodeName == 'BR') result += '\n'; else throw 'Complex markup'; return result; }//blockText function initHighlight(block) { if (block.className.search(/\bno\-highlight\b/) != -1) return; try { blockText(block); } catch (e) { if (e == 'Complex markup') return; }//try var classes = block.className.split(/\s+/); for (var i = 0; i < classes.length; i++) { if (LANGUAGES[classes[i]]) { highlightLanguage(block, classes[i]); return; }//if }//for highlightAuto(block); }//initHighlight function highlightLanguage(block, language) { var highlight = new Highlighter(language, blockText(block)); // See these 4 lines? This is IE's notion of "block.innerHTML = result". Love this browser :-/ var container = document.createElement('div'); container.innerHTML = '<pre><code class="' + block.className + '">' + highlight.result + '</code></pre>'; var environment = block.parentNode.parentNode; environment.replaceChild(container.firstChild, block.parentNode); }//highlightLanguage function highlightAuto(block) { var result = null; var language = ''; var max_relevance = 2; var relevance = 0; var block_text = blockText(block); for (var key in selected_languages) { var highlight = new Highlighter(key, block_text); relevance = highlight.keyword_count + highlight.relevance; if (relevance > max_relevance) { max_relevance = relevance; result = highlight; }//if }//for if(result) { // See these 4 lines? This is IE's notion of "block.innerHTML = result". Love this browser :-/ var container = document.createElement('div'); container.innerHTML = '<pre><code class="' + result.language_name + '">' + result.result + '</code></pre>'; var environment = block.parentNode.parentNode; environment.replaceChild(container.firstChild, block.parentNode); }//if }//highlightAuto function langRe(language, value, global) { var mode = 'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : ''); return new RegExp(value, mode); }//re function compileRes() { for (var i in LANGUAGES) { var language = LANGUAGES[i]; for (var key in language.modes) { if (language.modes[key].begin) language.modes[key].beginRe = langRe(language, '^' + language.modes[key].begin); if (language.modes[key].end) language.modes[key].endRe = langRe(language, '^' + language.modes[key].end); if (language.modes[key].illegal) language.modes[key].illegalRe = langRe(language, '^(?:' + language.modes[key].illegal + ')'); language.defaultMode.illegalRe = langRe(language, '^(?:' + language.defaultMode.illegal + ')'); }//for }//for }//compileRes function compileKeywords() { function compileModeKeywords(mode) { if (!mode.keywordGroups) { for (var key in mode.keywords) { if (mode.keywords[key] instanceof Object) mode.keywordGroups = mode.keywords; else mode.keywordGroups = {'keyword': mode.keywords}; break; }//for }//if }//compileModeKeywords for (var i in LANGUAGES) { var language = LANGUAGES[i]; compileModeKeywords(language.defaultMode); for (var key in language.modes) { compileModeKeywords(language.modes[key]); }//for }//for }//compileKeywords function initHighlighting() { if (initHighlighting.called) return; initHighlighting.called = true; compileRes(); compileKeywords(); if (arguments.length) { for (var i = 0; i < arguments.length; i++) { if (LANGUAGES[arguments[i]]) { selected_languages[arguments[i]] = LANGUAGES[arguments[i]]; }//if }//for } else selected_languages = LANGUAGES; var pres = document.getElementsByTagName('pre'); for (var i = 0; i < pres.length; i++) { if (pres[i].firstChild && pres[i].firstChild.nodeName == 'CODE') initHighlight(pres[i].firstChild); }//for }//initHighlighting function injectScripts(languages) { var scripts = document.getElementsByTagName('SCRIPT'); for (var i=0; i < scripts.length; i++) { if (scripts[i].src.match(/highlight\.js(\?.+)?$/)) { var path = scripts[i].src.replace(/highlight\.js(\?.+)?$/, ''); break; }//if }//for if (languages.length == 0) { languages = DEFAULT_LANGUAGES; }//if var injected = {} for (var i=0; i < languages.length; i++) { var filename = LANGUAGE_GROUPS[languages[i]] ? LANGUAGE_GROUPS[languages[i]] : languages[i]; if (!injected[filename]) { document.write('<script type="text/javascript" src="' + path + 'languages/' + filename + '.js"></script>'); injected[filename] = true; }//if }//for }//injectScripts function initHighlightingOnLoad() { var original_arguments = arguments; injectScripts(arguments); var handler = function(){initHighlighting.apply(null, original_arguments)}; if (window.addEventListener) { window.addEventListener('DOMContentLoaded', handler, false); window.addEventListener('load', handler, false); } else if (window.attachEvent) window.attachEvent('onload', handler); else window.onload = handler; }//initHighlightingOnLoad
enzbang/diouzhtu
external_libraries/highlight/highlight.js
JavaScript
gpl-2.0
13,554
/** * FitVids 1.1 * * Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ * Released under the WTFPL license - http://sam.zoy.org/wtfpl/ */ !function(t){"use strict" t.fn.fitVids=function(e){var i={customSelector:null,ignore:null} if(!document.getElementById("fit-vids-style")){var r=document.head||document.getElementsByTagName("head")[0],a=".fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}",d=document.createElement("div") d.innerHTML='<p>x</p><style id="fit-vids-style">'+a+"</style>",r.appendChild(d.childNodes[1])}return e&&t.extend(i,e),this.each(function(){var e=['iframe[src*="player.vimeo.com"]','iframe[src*="youtube.com"]','iframe[src*="youtube-nocookie.com"]','iframe[src*="kickstarter.com"][src*="video.html"]',"object","embed"] i.customSelector&&e.push(i.customSelector) var r=".fitvidsignore" i.ignore&&(r=r+", "+i.ignore) var a=t(this).find(e.join(",")) a=a.not("object object"),a=a.not(r),a.each(function(){var e=t(this) if(!(e.parents(r).length>0||"embed"===this.tagName.toLowerCase()&&e.parent("object").length||e.parent(".fluid-width-video-wrapper").length)){e.css("height")||e.css("width")||!isNaN(e.attr("height"))&&!isNaN(e.attr("width"))||(e.attr("height",9),e.attr("width",16)) var i="object"===this.tagName.toLowerCase()||e.attr("height")&&!isNaN(parseInt(e.attr("height"),10))?parseInt(e.attr("height"),10):e.height(),a=isNaN(parseInt(e.attr("width"),10))?e.width():parseInt(e.attr("width"),10),d=i/a if(!e.attr("id")){var o="fitvid"+Math.floor(999999*Math.random()) e.attr("id",o)}e.wrap('<div class="fluid-width-video-wrapper"></div>').parent(".fluid-width-video-wrapper").css("padding-top",100*d+"%"),e.removeAttr("height").removeAttr("width")}})})}}(window.jQuery||window.Zepto)
sdsweb/note
assets/js/fitvids.js
JavaScript
gpl-2.0
2,034
import getNotes from './get-notes'; export const noteHasFilteredRead = ( noteState, noteId ) => noteState.filteredNoteReads.includes( noteId ); export default ( state, noteId ) => noteHasFilteredRead( getNotes( state ), noteId );
Automattic/wp-calypso
apps/notifications/src/panel/state/selectors/note-has-filtered-read.js
JavaScript
gpl-2.0
233
"use strict" var merge = require('merge'); var HttpError = require('http-errors'); var Path = require('path'); module.exports = BaseController.extend({ view: { file: '', partials: {}, params: {} }, before: function(next) { this.view.file = this.req.route; next(); }, after: function(next) { if(this.res.headersSent) { return true; } var params = this.view.params; params.partials = {}; // Parse route for partials set not by config for(var i in this.view.partials) { params.partials[i] = Path.join(this.req.route, this.view.partials[i]); } // Merge partials with configuration partials params.partials = merge(true, { _content: this.view.file }, this.config.partials, params.partials); // Test if the partials do exist to prevent hard-to-solve issues for(var i in params.partials) { try { require.resolve(Path.join(app.basedir, app.config.path.view, params.partials[i] + '.hjs')); } catch(e) { throw new HttpError(404, 'Partial ' + partials[i] + ' Not Found'); } } // Do the actial rendering this.res.render(this.config.layout, params); next(); }, init: function(req, res) { // Load specific settings for the WebController this.view = merge(true, this.view, {}); this.config = merge(true, this.config, app.config.web); this.parent(req, res); } });
ehmPlankje/express-mvc-boilerplate
controller/_abstract/WebController.js
JavaScript
gpl-2.0
1,593
/* * This program is copyright © 2008-2012 Eric Bishop and is distributed under the terms of the GNU GPL * version 2.0 with a special clarification/exception that permits adapting the program to * configure proprietary "back end" software provided that all modifications to the web interface * itself remain covered by the GPL. * See http://gargoyle-router.com/faq.html#qfoss for more information */ /* * mountPoint refers to the blkid mount point * mountPath may refer to either blkid mount point * or symlink to dev_[devid], wherever share is * actually mounted */ var driveToMountPoints = []; var mountPointToDrive = []; var mountPointToFs = []; var mountPointToDriveSize = []; /* * These global data structure are special -- they contain * the data that will be saved once the user hits the save changes button * * In other sections we load/save to uci variable, but we have 3 packages (samba, nfsd and vsftpd) to worry * about for shares, and the conversion to uci isn't particularly straightforward. So, we save in a global * variable in a simpler format, and then update uci when we do the final save */ var userNames = []; var nameToSharePath = []; var sharePathList = []; var sharePathToShareData = []; var badUserNames = [ "ftp", "anonymous", "root", "daemon", "network", "nobody" ]; var ftpFirewallRule = "wan_ftp_server_command"; var pasvFirewallRule = "wan_ftp_server_pasv"; function saveChanges() { //proofread var errors = []; var sambaGroup = document.getElementById("cifs_workgroup").value var ftpWanAccess = document.getElementById("ftp_wan_access").checked var ftpWanPasv = document.getElementById("ftp_wan_pasv").checked var pasvMin = document.getElementById("pasv_min_port").value var pasvMax = document.getElementById("pasv_max_port").value if( document.getElementById("shared_disks").style.display != "none") { if(sambaGroup == "") { errors.push("Invalid CIFS Workgroup"); } if(ftpWanAccess && uciOriginal.get("firewall", ftpFirewallRule, "local_port") != "21") { var conflict = checkForPortConflict("21", "tcp"); if(conflict != "") { errors.push("Cannot enable WAN FTP access because port conflicts with " + conflict); } } if(ftpWanAccess && ftpWanPasv) { var intPasvMin = parseInt(pasvMin) var intPasvMax = parseInt(pasvMax) var pasvValid = false if( (!isNaN(intPasvMin)) && (!isNaN(intPasvMax)) ) { if(intPasvMin < intPasvMax) { pasvValid = true } } if(!pasvValid) { errors.push("Invalid FTP passive port range") } else { var oldPasvMin = uciOriginal.get("firewall", pasvFirewallRule, "start_port"); var oldPasvMax = uciOriginal.get("firewall", pasvFirewallRule, "end_port"); var ignorePorts = []; if(oldPasvMin != "" && oldPasvMax != "") { ignorePorts["tcp"] = []; ignorePorts["tcp"][oldPasvMin + "-" + oldPasvMax] = 1 } var conflict = checkForPortConflict( "" + intPasvMin + "-" + intPasvMax, "tcp", ignorePorts ) if(conflict != "") { errors.push("Pasive FTP port range conflicts with " + conflict); } } } } if(errors.length > 0) { alert( errors.join("\n") + "\n\nCould not save settings" ); return; } //prepare to save setControlsEnabled(false, true); var uci = uciOriginal.clone(); //update share_users uci.removeAllSectionsOfType("share_users", "user"); var userTable = document.getElementById("share_user_table"); if(userTable != null) { var userTableData = getTableDataArray(userTable); while(userTableData.length >0) { var nextUserData = userTableData.shift(); var user = nextUserData[0] var pass = (nextUserData[1]).value if( pass != null && pass != "") { uci.set("share_users", user, "", "user") uci.set("share_users", user, "password", pass) } else { var salt = uciOriginal.get("share_users", user, "password_salt") var sha1 = uciOriginal.get("share_users", user, "password_sha1") if(salt != "" && sha1 != "") { uci.set("share_users", user, "", "user") uci.set("share_users", user, "password_salt", salt) uci.set("share_users", user, "password_sha1", sha1) } } } } //update firewall if(ftpWanAccess) { uci.set("firewall", ftpFirewallRule, "", "remote_accept") uci.set("firewall", ftpFirewallRule, "proto", "tcp") uci.set("firewall", ftpFirewallRule, "zone", "wan") uci.set("firewall", ftpFirewallRule, "local_port", "21") uci.set("firewall", ftpFirewallRule, "remote_port", "21") if(ftpWanPasv) { uci.set("firewall", pasvFirewallRule, "", "remote_accept") uci.set("firewall", pasvFirewallRule, "proto", "tcp") uci.set("firewall", pasvFirewallRule, "zone", "wan") uci.set("firewall", pasvFirewallRule, "start_port", pasvMin) uci.set("firewall", pasvFirewallRule, "end_port", pasvMax) } else { uci.removeSection("firewall", pasvFirewallRule); } } else { uci.removeSection("firewall", ftpFirewallRule); uci.removeSection("firewall", pasvFirewallRule); } //update shares uci.removeAllSectionsOfType("samba", "samba") uci.removeAllSectionsOfType("samba", "sambashare") uci.removeAllSectionsOfType("vsftpd", "vsftpd") uci.removeAllSectionsOfType("vsftpd", "share") uci.removeAllSectionsOfType("nfsd", "nfsshare") uci.set("samba", "global", "", "samba") uci.set("samba", "global", "workgroup", sambaGroup); var haveAnonymousFtp = false; var makeDirCmds = []; for( fullMountPath in sharePathToShareData ) { //[shareName, shareDrive, shareDiskMount, shareSubdir, fullSharePath, isCifs, isFtp, isNfs, anonymousAccess, rwUsers, roUsers, nfsAccess, nfsAccessIps] var shareData = sharePathToShareData[fullMountPath] if( shareData[3] != "" ) { makeDirCmds.push("mkdir -p \"" + fullMountPath + "\"" ) } var shareName = shareData[0] var shareId = shareName.replace(/[^0-9A-Za-z]+/, "_").toLowerCase() var isCifs = shareData[5]; var isFtp = shareData[6]; var isNfs = shareData[7]; var anonymousAccess = shareData[8] var rwUsers = shareData[9] var roUsers = shareData[10] var nfsAccess = shareData[11]; var nfsAccessIps = shareData[12] if(isCifs) { var pkg = "samba" uci.set(pkg, shareId, "", "sambashare") uci.set(pkg, shareId, "name", shareName); uci.set(pkg, shareId, "path", fullMountPath); uci.set(pkg, shareId, "create_mask", "0777"); uci.set(pkg, shareId, "dir_mask", "0777"); uci.set(pkg, shareId, "browseable", "yes"); uci.set(pkg, shareId, "read_only", (anonymousAccess == "ro" ? "yes" : "no")); uci.set(pkg, shareId, "guest_ok", (anonymousAccess == "none" ? "no" : "yes")); if(rwUsers.length > 0) { uci.set(pkg, shareId, "users_rw", rwUsers, false) } if(roUsers.length > 0) { uci.set(pkg, shareId, "users_ro", roUsers, false) } } if(isFtp) { var pkg = "vsftpd" uci.set(pkg, shareId, "", "share") uci.set(pkg, shareId, "name", shareName); uci.set(pkg, shareId, "share_dir", fullMountPath); if(rwUsers.length > 0) { uci.set(pkg, shareId, "users_rw", rwUsers, false) } if(roUsers.length > 0) { uci.set(pkg, shareId, "users_ro", roUsers, false) } if(anonymousAccess != "none") { haveAnonymousFtp = true; uci.set(pkg, shareId, "users_" + anonymousAccess, [ "anonymous" ], true); } } if(isNfs) { var pkg = "nfsd" uci.set(pkg, shareId, "", "nfsshare") uci.set(pkg, shareId, "name", shareName); uci.set(pkg, shareId, "path", fullMountPath); uci.set(pkg, shareId, "sync", "1"); uci.set(pkg, shareId, "insecure", "1"); uci.set(pkg, shareId, "subtree_check", "0"); uci.set(pkg, shareId, "read_only", (nfsAccess == "ro" ? "1" : "0")); if(nfsAccessIps instanceof Array) { uci.set(pkg, shareId, "allowed_hosts", nfsAccessIps, false) } else { uci.set(pkg, shareId, "allowed_hosts", [ "*" ], false) } } } uci.set("vsftpd", "global", "", "vsftpd") uci.set("vsftpd", "global", "anonymous", (haveAnonymousFtp ? "yes" : "no")) uci.set("vsftpd", "global", "anonymous_write", (haveAnonymousFtp ? "yes" : "no")) //write possible but write on individual share dirs set individually elsewhere if(ftpWanPasv) { uci.set("vsftpd", "global", "pasv_min_port", pasvMin) uci.set("vsftpd", "global", "pasv_max_port", pasvMax) } var postCommands = []; if( uciOriginal.get("firewall", ftpFirewallRule, "local_port") != uci.get("firewall", ftpFirewallRule, "local_port") || uciOriginal.get("firewall", pasvFirewallRule, "start_port") != uci.get("firewall", pasvFirewallRule, "start_port") || uciOriginal.get("firewall", pasvFirewallRule, "end_port") != uci.get("firewall", pasvFirewallRule, "end_port") ) { postCommands.push("/etc/init.d/firewall restart"); } postCommands.push("/etc/init.d/share_users restart"); postCommands.push("/etc/init.d/samba restart"); postCommands.push("/etc/init.d/vsftpd restart"); postCommands.push("/etc/init.d/nfsd restart"); var commands = uci.getScriptCommands(uciOriginal) + "\n" + makeDirCmds.join("\n") + "\n" + postCommands.join("\n") + "\n"; var param = getParameterDefinition("commands", commands) + "&" + getParameterDefinition("hash", document.cookie.replace(/^.*hash=/,"").replace(/[\t ;]+.*$/, "")); var stateChangeFunction = function(req) { if(req.readyState == 4) { uciOriginal = uci.clone(); setControlsEnabled(true); } } runAjax("POST", "utility/run_commands.sh", param, stateChangeFunction); } function addUser() { var user = document.getElementById("new_user").value var pass1 = document.getElementById("user_pass").value var pass2 = document.getElementById("user_pass_confirm").value //validate var errors = []; var testUser = user.replace(/[0-9a-zA-Z]+/g, ""); if(user == "") { errors.push("Username cannot be empty") } if(testUser != "") { errors.push("Username can contain only letters and numbers") } if(pass1 == "" && pass2 == "") { errors.push("Password cannot be empty") } if(pass1 != pass2) { errors.push("Passwords don't match") } if(errors.length == 0) { //check to make sure user isn't a dupe var userTable = document.getElementById("share_user_table"); if(userTable != null) { var found = 0; var userData = getTableDataArray(userTable, true, false); var userIndex; for(userIndex=0; userIndex < userData.length && found == 0; userIndex++) { found = userData[userIndex][0] == user ? 1 : found; } if(found) { errors.push("Duplicate Username") } } var badUserIndex; for(badUserIndex=0;badUserIndex < badUserNames.length && errors.length == 0; badUserIndex++) { if(user.toLowerCase() == (badUserNames[badUserIndex]).toLowerCase() ) { errors.push("Username '" + user + "' is reserved and not permitted"); } } } if(errors.length > 0) { alert( errors.join("\n") + "\n\nCould not add user" ); } else { var userTable = document.getElementById("share_user_table"); if(userTable == null) { var tableContainer = document.getElementById("user_table_container"); userTable = createTable(["", ""], [], "share_user_table", true, false, removeUserCallback); setSingleChild(tableContainer, userTable); } var userPass = createInput("hidden") userPass.value = pass1 var editButton = createEditButton(editUser); addTableRow(userTable, [ user, userPass, editButton], true, false, removeUserCallback) addOptionToSelectElement("user_access", user, user); userNames.push(user) document.getElementById("new_user").value = "" document.getElementById("user_pass").value = "" document.getElementById("user_pass_confirm").value = "" } } function removeUserCallback(table, row) { var removeUser=row.childNodes[0].firstChild.data; //remove from userNames var newUserNames = removeStringFromArray(userNames, removeUser) userNames = newUserNames; //if no users left, set a message indicating this instead of an empty table if(userNames.length == 0) { var container = document.getElementById("user_table_container"); var tableObject = document.createElement("div"); tableObject.innerHTML = "<span style=\"text-align:center\"><em>No Share Users Defined</em></span>"; setSingleChild(container, tableObject); } //remove in all shares for (sharePath in sharePathToShareData) { var shareData = sharePathToShareData[sharePath] var rwUsers = shareData[9] var roUsers = shareData[10] shareData[9] = removeStringFromArray(rwUsers, removeUser) shareData[10] = removeStringFromArray(roUsers, removeUser) sharePathToShareData[sharePath] = shareData; } //remove from controls of share currently being configured removeOptionFromSelectElement("user_access", removeUser); var accessTable = document.getElementById("user_access_table") if(accessTable != null) { var accessTableData = getTableDataArray(accessTable, true, false); var newTableData = []; while(accessTableData.length >0) { var next = accessTableData.shift(); if(next[0] != removeUser) { newTableData.push(next) } } var newAccessTable = createTable(["", ""], newTableData, "user_access_table", true, false, removeUserAccessCallback); setSingleChild(document.getElementById("user_access_table_container"), newAccessTable); } } function editUser() { if( typeof(editUserWindow) != "undefined" ) { //opera keeps object around after //window is closed, so we need to deal //with error condition try { editUserWindow.close(); } catch(e){} } try { xCoor = window.screenX + 225; yCoor = window.screenY+ 225; } catch(e) { xCoor = window.left + 225; yCoor = window.top + 225; } editUserWindow = window.open("share_user_edit.sh", "edit", "width=560,height=300,left=" + xCoor + ",top=" + yCoor ); var okButton = createInput("button", editUserWindow.document); var cancelButton = createInput("button", editUserWindow.document); okButton.value = "Change Password"; okButton.className = "default_button"; cancelButton.value = "Cancel"; cancelButton.className = "default_button"; editShareUserRow=this.parentNode.parentNode; editShareUser=editShareUserRow.childNodes[0].firstChild.data; runOnEditorLoaded = function () { updateDone=false; if(editUserWindow.document != null) { if(editUserWindow.document.getElementById("bottom_button_container") != null) { editUserWindow.document.getElementById("share_user_text").appendChild( document.createTextNode(editShareUser) ) editUserWindow.document.getElementById("bottom_button_container").appendChild(okButton); editUserWindow.document.getElementById("bottom_button_container").appendChild(cancelButton); cancelButton.onclick = function() { editUserWindow.close(); } okButton.onclick = function() { var pass1 = editUserWindow.document.getElementById("new_password").value; var pass2 = editUserWindow.document.getElementById("new_password_confirm").value; var errors = [] if(pass1 == "" && pass2 == "") { errors.push("Password cannot be empty") } if(pass1 != pass2) { errors.push("Passwords don't match") } if(errors.length > 0) { alert(errors.join("\n") + "\nPassword unchanged."); } else { editShareUserRow.childNodes[1].firstChild.value = pass1 editUserWindow.close(); } } editUserWindow.moveTo(xCoor,yCoor); editUserWindow.focus(); updateDone = true; } } if(!updateDone) { setTimeout( "runOnEditorLoaded()", 250); } } runOnEditorLoaded(); } function updateWanFtpVisibility() { document.getElementById("ftp_pasv_container").style.display = document.getElementById("ftp_wan_access").checked ? "block" : "none" var pasvCheck = document.getElementById("ftp_wan_pasv") enableAssociatedField(pasvCheck, "pasv_min_port", 50990) enableAssociatedField(pasvCheck, "pasv_max_port", 50999) } function resetData() { document.getElementById("no_disks").style.display = storageDrives.length == 0 ? "block" : "none"; document.getElementById("shared_disks").style.display = storageDrives.length > 0 ? "block" : "none"; document.getElementById("disk_unmount").style.display = storageDrives.length > 0 ? "block" : "none"; document.getElementById("disk_format").style.display = storageDrives.length > 0 || drivesWithNoMounts.length > 0 ? "block" : "none" if(storageDrives.length > 0) { //workgroup var s = uciOriginal.getAllSectionsOfType("samba", "samba"); document.getElementById("cifs_workgroup").value = s.length > 0 ? uciOriginal.get("samba", s.shift(), "workgroup") : "Workgroup"; // wan access to FTP var wanFtp = uciOriginal.get("firewall", ftpFirewallRule, "local_port") == "21" document.getElementById("ftp_wan_access").checked = wanFtp; var pminText = document.getElementById("pasv_min_port"); var pmaxText = document.getElementById("pasv_max_port"); var pmin = uciOriginal.get("firewall", pasvFirewallRule, "start_port") var pmax = uciOriginal.get("firewall", pasvFirewallRule, "end_port") pminText.value = pmin == "" || pmax == "" ? 50990 : pmin; pmaxText.value = pmin == "" || pmax == "" ? 50999 : pmax; document.getElementById("ftp_wan_pasv").checked = (wanFtp && pmin != "" && pmax != "") || (!wanFtp); //enable pasv by default when WAN FTP access is selected updateWanFtpVisibility() //share users userNames = uciOriginal.getAllSectionsOfType("share_users", "user"); //global var tableObject; if(userNames.length > 0) { var userTableData = [] var userIndex for(userIndex=0; userIndex < userNames.length; userIndex++) { userEditButton = createEditButton( editUser ) userPass = createInput("hidden") userPass.value = "" userTableData.push( [ userNames[userIndex], userPass, userEditButton ] ) } var tableObject = createTable(["", "", ""], userTableData, "share_user_table", true, false, removeUserCallback); } else { tableObject = document.createElement("div"); tableObject.innerHTML = "<span style=\"text-align:center\"><em>No Share Users Defined</em></span>"; } var tableContainer = document.getElementById("user_table_container"); while(tableContainer.firstChild != null) { tableContainer.removeChild( tableContainer.firstChild); } tableContainer.appendChild(tableObject); setAllowableSelections("user_access", userNames, userNames); //globals driveToMountPoints = []; mountPointToDrive = []; mountPointToFs = []; mountPointToDriveSize = []; mountPointList = [] var driveIndex = 0; for(driveIndex=0; driveIndex < storageDrives.length; driveIndex++) { var mountPoints = [ storageDrives[driveIndex][1], storageDrives[driveIndex][2] ]; driveToMountPoints[ storageDrives[driveIndex][0] ] = mountPoints; var mpIndex; for(mpIndex=0;mpIndex < 2; mpIndex++) { var mp = mountPoints[mpIndex]; mountPointToDrive[ mp ] = storageDrives[driveIndex][0]; mountPointToFs[ mp ] = storageDrives[driveIndex][3]; mountPointToDriveSize[ mp ] = parseBytes( storageDrives[driveIndex][4] ).replace(/ytes/, ""); mountPointList.push(mp); } } sharePathList = []; //global sharePathToShareData = []; //global nameToSharePath = []; //global var mountedDrives = []; var sambaShares = uciOriginal.getAllSectionsOfType("samba", "sambashare"); var nfsShares = uciOriginal.getAllSectionsOfType("nfsd", "nfsshare"); var ftpShares = uciOriginal.getAllSectionsOfType("vsftpd", "share"); var getMounted = function(shareList, config) { var shareIndex; for(shareIndex=0; shareIndex < shareList.length; shareIndex++) { var shareId = shareList[shareIndex] var fullSharePath = uciOriginal.get(config, shareId, (config == "vsftpd" ? "share_dir" : "path") ); var shareMountPoint = null; var shareDirectory = null; var shareDrive = null; var mpIndex; for(mpIndex=0;mpIndex<mountPointList.length && shareMountPoint==null && fullSharePath !=null; mpIndex++) { var mp = mountPointList[mpIndex] if( fullSharePath.indexOf(mp) == 0 ) { shareMountPoint = mp shareDirectory = fullSharePath.substr( mp.length); shareDirectory = shareDirectory.replace(/^\//, "").replace(/\/$/, "") shareDrive = mountPointToDrive[shareMountPoint]; } } if( shareDrive != null ) { mountedDrives[ shareDrive ] = 1; //shareMountPoint->[shareName, shareDrive, shareDiskMount, shareSubdir, fullSharePath, isCifs, isFtp, isNfs, anonymousAccess, rwUsers, roUsers, nfsAccess, nfsAccessIps] var shareData = sharePathToShareData[fullSharePath] == null ? ["", "", "", "", "", false, false, false, "none", [], [], "ro", "*" ] : sharePathToShareData[fullSharePath] ; //name if( shareData[0] == "" || config == "samba") { shareData[0] = uciOriginal.get(config, shareId, "name"); shareData[0] == "" ? shareId : shareData[0]; } shareData[1] = shareDrive //drive shareData[2] = shareMountPoint //share drive mount shareData[3] = shareDirectory //directory shareData[4] = fullSharePath //full path shareData[5] = config == "samba" ? true : shareData[5] //isCIFS shareData[6] = config == "vsftpd" ? true : shareData[6] //isFTP shareData[7] = config == "nfsd" ? true : shareData[7] //isNFS //both samba and vsftpd have ro_users and rw_users list options //however, they handle anonymous access a bit differently //samba has guest_ok option, while vsftpd includes "anonymous" (or "ftp") user in lists if(config == "vsftpd" || config == "samba") { var readTypes = ["rw", "ro"] var readTypeShareDataIndices = [9,10] var rtIndex; for(rtIndex=0; rtIndex < 2; rtIndex++) { var shareDataUserList = []; var readType = readTypes[rtIndex] var userVar = "users_" + readType var userList = uciOriginal.get(config, shareId, userVar); if(userList instanceof Array) { var uIndex; for(uIndex=0; uIndex < userList.length; uIndex++) { var user = userList[uIndex]; if(user == "anonymous" || user == "ftp") { //handle anonymous for vsftpd shareData[ 8 ] = readType } else { shareDataUserList.push(user); } } } shareData[ readTypeShareDataIndices[rtIndex] ] = shareDataUserList; } if(config == "samba") { //handle anonymous for samba if( uciOriginal.get(config, shareId, "guest_ok").toLowerCase() == "yes" || uciOriginal.get(config, shareId, "public").toLowerCase() == "yes" ) { shareData[ 8 ] = uciOriginal.get(config, shareId, "read_only").toLowerCase() == "yes" ? "ro" : "rw" } } } if(config == "nfsd") { shareData[ 11 ] = uciOriginal.get(config, shareList[shareIndex], "read_only") == "1" ? "ro" : "rw"; var allowedHostsStr = uciOriginal.get(config, shareList[shareIndex], "allowed_hosts"); if(allowedHostsStr instanceof Array) { allowedHostsStr = allowedHostsStr.join(","); } if(allowedHosts != "" && allowedHosts != "*") { var allowedHosts = allowedHostsStr.split(/[\t ]*,[\t ]*/); var allowedIps = []; var foundStar = false; while(allowedHosts.length > 0) { var h = allowedHosts.shift(); foundStar = h == "*" ? true : foundStar if(validateIpRange(h) == 0) { allowedIps.push(h); } } shareData[ 12 ] = foundStar ? "*" : allowedIps; } } sharePathToShareData[ fullSharePath ] = shareData if(nameToSharePath [ shareData[0] ] != fullSharePath) { nameToSharePath[ shareData[0] ] = fullSharePath sharePathList.push(fullSharePath) } } } } getMounted(sambaShares, "samba"); getMounted(ftpShares, "vsftpd"); getMounted(nfsShares, "nfsd"); if(setDriveList(document)) { document.getElementById("sharing_add_heading_container").style.display = "block"; document.getElementById("sharing_add_controls_container").style.display = "block"; shareSettingsToDefault(); } else { document.getElementById("sharing_add_heading_container").style.display = "none"; document.getElementById("sharing_add_controls_container").style.display = "none"; } //create current share table //name, disk, subdirectory, type, [edit], [remove] var shareTableData = []; var shareIndex; for(shareIndex=0; shareIndex < sharePathList.length; shareIndex++) { var shareData = sharePathToShareData[ sharePathList[shareIndex] ] var vis = [] vis["cifs"] = shareData[5] vis["ftp"] = shareData[6] vis["nfs"] = shareData[7] shareTableData.push( [ shareData[0], shareData[1], "/" + shareData[3], getVisStr(vis), createEditButton(editShare) ] ) } var shareTable = createTable(["Name", "Disk", "Subdirectory", "Share Type", ""], shareTableData, "share_table", true, false, removeShareCallback); var tableContainer = document.getElementById('sharing_mount_table_container'); setSingleChild(tableContainer, shareTable); } // format setttings // // note that 'drivesWithNoMounts', refers to drives not mounted on the OS, // not lack of network shared/mounts which is what the other variables // refer to. This can be confusing, so I'm putting this comment here if(drivesWithNoMounts.length > 0) { var dindex; var driveIds = []; var driveText = []; for(dindex=0; dindex< drivesWithNoMounts.length ; dindex++) { driveIds.push( "" + dindex); driveText.push( drivesWithNoMounts[dindex][0] + " (" + parseBytes(parseInt(drivesWithNoMounts[dindex][1])) + ")") } setAllowableSelections("format_disk_select", driveIds, driveText); } document.getElementById("swap_percent").value = "25"; document.getElementById("storage_percent").value = "75"; var vis = (drivesWithNoMounts.length > 0); setVisibility( ["no_unmounted_drives", "format_warning", "format_disk_select_container", "swap_percent_container", "storage_percent_container", "usb_format_button_container"], [ (!vis), vis, vis, vis, vis, vis ] ) updateFormatPercentages() } //returns (boolean) whether drive list is empty function setDriveList(controlDocument) { var driveList = []; var driveDisplayList = []; for(driveIndex=0; driveIndex < storageDrives.length; driveIndex++) { var driveName = storageDrives[driveIndex][0] var driveFs = storageDrives[driveIndex][3]; var driveSize = parseBytes( storageDrives[driveIndex][4] ).replace(/ytes/, ""); driveList.push( driveName ) driveDisplayList.push( driveName + " (" + driveFs + ", " + driveSize + ")" ) } setAllowableSelections("share_disk", driveList, driveDisplayList, controlDocument); return (driveList.length > 0) } function shareSettingsToDefault(controlDocument) { controlDocument = controlDocument == null ? document : controlDocument var currentDrive = getSelectedValue("share_disk", controlDocument); var defaultData = [ "share_" + (sharePathList.length + 1), currentDrive, driveToMountPoints[currentDrive][0], "", driveToMountPoints[currentDrive][0], true, true, true, "none", [], [], "ro", "*" ] ; setDocumentFromShareData(controlDocument, defaultData) } function createUserAccessTable(clear, controlDocument) { controlDocument = controlDocument == null ? document : controlDocument var userAccessTable = controlDocument.getElementById("user_access_table"); if(clear || userAccessTable == null) { var container = controlDocument.getElementById("user_access_table_container"); userAccessTable = createTable(["", ""], [], "user_access_table", true, false, removeUserAccessCallback, null, controlDocument); setSingleChild(container, userAccessTable); } } function addUserAccess(controlDocument) { controlDocument = controlDocument == null ? document : controlDocument var addUser = getSelectedValue("user_access", controlDocument) if(addUser == null || addUser == "") { alert("No User To Add -- You must configure a new share user above.") } else { var access = getSelectedValue("user_access_type", controlDocument) removeOptionFromSelectElement("user_access", addUser, controlDocument); createUserAccessTable(false) var userAccessTable = controlDocument.getElementById("user_access_table"); addTableRow(userAccessTable, [ addUser, access ], true, false, removeUserAccessCallback, null, controlDocument) } } function removeUserAccessCallback(table, row) { var removeUser=row.childNodes[0].firstChild.data; addOptionToSelectElement("user_access", removeUser, removeUser, null, table.ownerDocument); } function updateFormatPercentages(ctrlId) { var valid = false; if(ctrlId == null) { ctrlId="swap_percent"; } var otherCtrlId = ctrlId == "swap_percent" ? "storage_percent" : "swap_percent" var sizeId = ctrlId == "swap_percent" ? "swap_size" : "storage_size" var otherSizeId = ctrlId == "swap_percent" ? "storage_size" : "swap_size" var driveId = getSelectedValue("format_disk_select") if(driveId != null) { try { var percent1 = parseFloat(document.getElementById(ctrlId).value) if( percent1 != "NaN" && percent1 <= 100 && percent1 >= 0) { document.getElementById(ctrlId).style.color = "black" var percent2 = 100 - percent1; var size = parseInt(drivesWithNoMounts[parseInt(driveId)][1]); var size1 = (percent1 * size)/100; var size2 = size - size1; document.getElementById(otherCtrlId).value = "" + percent2 setChildText(sizeId, "(" + parseBytes(size1) + ")"); setChildText(otherSizeId, "(" + parseBytes(size2) + ")"); valid=true } else { document.getElementById(ctrlId).style.color = "red" } } catch(e) { document.getElementById(ctrlId).style.color = "red" } } return valid } function getVis(controlDocument) { controlDocument = controlDocument == null ? document : controlDocument var vis = [] var visTypes = ["ftp", "cifs", "nfs"] var vIndex; for(vIndex=0; vIndex < visTypes.length; vIndex++) { vis[ visTypes[vIndex] ] = controlDocument.getElementById( "share_type_" + visTypes[vIndex] ).checked } return vis; } function getVisStr(vis) { var shareTypeStr = function(type){ return vis[type] ? type.toUpperCase() : ""; } var visStr = shareTypeStr("cifs") + "+" + shareTypeStr("ftp") + "+" + shareTypeStr("nfs"); return visStr.replace(/\+\+/g, "+").replace(/^\+/, "").replace(/\+$/, ""); } function getShareDataFromDocument(controlDocument, originalName) { controlDocument = controlDocument == null ? document : controlDocument var shareDrive = getSelectedValue("share_disk", controlDocument); var shareSubdir = controlDocument.getElementById("share_dir").value shareSubdir = shareSubdir.replace(/^\//, "").replace(/\/$/, "") var shareSpecificity = getSelectedValue("share_specificity", controlDocument); var shareName = controlDocument.getElementById("share_name").value; var shareDiskMount = driveToMountPoints[shareDrive][ ( shareSpecificity == "blkid" ? 0 : 1 ) ]; var altDiskMount = driveToMountPoints[shareDrive][ ( shareSpecificity == "blkid" ? 1 : 0 ) ]; var fullSharePath = (shareDiskMount + "/" + shareSubdir).replace(/\/\//g, "/").replace(/\/$/, ""); var altSharePath = (altDiskMount + "/" + shareSubdir).replace(/\/\//g, "/").replace(/\/$/, ""); var enabledTypes = getVis(controlDocument); var anonymousAccess = getSelectedValue("anonymous_access", controlDocument) var roUsers = []; var rwUsers = []; var userAccessTable = controlDocument.getElementById("user_access_table") if(userAccessTable != null) { var userAccessTableData = getTableDataArray(userAccessTable, true, false); var uatIndex; for(uatIndex=0; uatIndex < userAccessTableData.length; uatIndex++) { var rowData = userAccessTableData[uatIndex]; if(rowData[1] == "R/O") { roUsers.push(rowData[0]); } if(rowData[1] == "R/W") { rwUsers.push(rowData[0]); } } } var nfsAccess = getSelectedValue("nfs_access", controlDocument) var nfsAccessIps = getSelectedValue("nfs_policy", controlDocument) == "share" ? "*" : []; if( typeof(nfsAccessIps) != "string") { var nfsIpTable = controlDocument.getElementById("nfs_ip_table"); if(nfsIpTable != null) { var nfsIpData = getTableDataArray(nfsIpTable); var nipIndex; for(nipIndex=0; nipIndex < nfsIpData.length; nipIndex++) { nfsAccessIps.push( nfsIpData[nipIndex][0] ); } } } // error checking var errors = []; if( !(enabledTypes["ftp"] || enabledTypes["cifs"] || enabledTypes["nfs"]) ) { errors.push("You must select at least one share type (FTP, CIFS, NFS)") } if( enabledTypes["ftp"] || enabledTypes["cifs"]) { if( roUsers.length == 0 && rwUsers.length == 0 && anonymousAccess == "none" ) { errors.push("FTP and/or CIFS share type selected, but neither anonymous access or users are configured"); } } if( sharePathToShareData[ fullSharePath ] != null || sharePathToShareData[ altSharePath ] != null ) { var existing = sharePathToShareData[ fullSharePath ]; existing = existing == null ? sharePathToShareData[ altSharePath ] : existing if(originalName == null || existing[0] != originalName ) { errors.push("Specified Shared Directory Is Already Configured: " + existing[0]) } } if( nameToSharePath[ shareName ] != null && (originalName == null || originalName != shareName)) { errors.push( "Share name is a duplicate" ) } var result = []; result["errors"] = errors; if(errors.length == 0) { result["share"] = [shareName, shareDrive, shareDiskMount, shareSubdir, fullSharePath, enabledTypes["cifs"], enabledTypes["ftp"], enabledTypes["nfs"], anonymousAccess, rwUsers, roUsers, nfsAccess, nfsAccessIps] } return result; } function setDocumentFromShareData(controlDocument, shareData) { controlDocument = controlDocument == null ? document : controlDocument var shareDrive = shareData[1] setDriveList(controlDocument); setSelectedValue("share_disk", shareDrive, controlDocument) controlDocument.getElementById("share_dir").value = "/" + shareData[3] controlDocument.getElementById("share_name").value = shareData[0] var shareSpecificity = (shareData[2] == driveToMountPoints[shareDrive][0]) ? "blkid" : "dev"; setSelectedValue("share_specificity", shareSpecificity, controlDocument) controlDocument.getElementById("share_type_cifs").checked = shareData[5] controlDocument.getElementById("share_type_ftp").checked = shareData[6] controlDocument.getElementById("share_type_nfs").checked = shareData[7] setSelectedValue("anonymous_access", shareData[8], controlDocument) createUserAccessTable(true,controlDocument) var userAccessTable = controlDocument.getElementById("user_access_table") var userIndices = []; userIndices[9] = "rw" userIndices[10] = "ro" var userTypeIndex var usersWithEntries = []; for( userTypeIndex in userIndices) { var userType = userIndices[userTypeIndex] var userList = shareData[ userTypeIndex ]; var ulIndex; for(ulIndex=0;ulIndex < userList.length; ulIndex++) { addTableRow(userAccessTable, [ userList[ulIndex], userType == "rw" ? "R/W" : "R/O" ], true, false, removeUserAccessCallback, null, controlDocument) usersWithEntries[ userList[ulIndex] ] = 1 } } setSelectedValue("nfs_access", shareData[11], controlDocument); var nfsAccessIps = shareData[12]; setSelectedValue("nfs_policy", typeof(nfsAccessIps) == "string" ? "share" : "ip", controlDocument); if(nfsAccessIps instanceof Array) { addAddressStringToTable(controlDocument,nfsAccessIps.join(","),"nfs_ip_table_container","nfs_ip_table",false, 2, true, 250) } //update user select element var usersWithoutEntries = []; var uIndex; for(uIndex = 0; uIndex < userNames.length; uIndex++) { var u = userNames[uIndex]; if(usersWithEntries[ u ] != 1) { usersWithoutEntries.push(u); } } setAllowableSelections("user_access", usersWithoutEntries, usersWithoutEntries, controlDocument); setShareTypeVisibility(controlDocument) setSharePaths(controlDocument); } function addNewShare() { var rawShareData = getShareDataFromDocument(document, null) var errors = rawShareData["errors"] if(errors.length > 0) { var errStr = errors.join("\n") + "\n\nCould Not Add Share" alert(errStr) } else { var shareData = rawShareData["share"] var shareName = shareData[0] var fullSharePath = shareData[4]; var shareType = getVisStr( getVis() ); sharePathToShareData[ fullSharePath ] = shareData sharePathList.push(fullSharePath) nameToSharePath [ shareName ] = fullSharePath var shareTable = document.getElementById("share_table") addTableRow(shareTable, [shareName, shareData[1], "/" + shareData[3], shareType, createEditButton(editShare) ], true, false, removeShareCallback) shareSettingsToDefault(); } } function setShareTypeVisibility(controlDocument) { controlDocument = controlDocument == null ? document : controlDocument var vis = getVis(controlDocument); vis["ftp_or_cifs"] = vis["ftp"] || vis["cifs"] var getTypeDisplay = function(type) { return vis[type] ? type.toUpperCase() : "" } var userLabel = (getTypeDisplay("cifs") + "/" + getTypeDisplay("ftp")).replace(/^\//, "").replace(/\/$/, ""); setChildText("anonymous_access_label", userLabel + " Anonymous Access:", null, null, null, controlDocument) setChildText("user_access_label", userLabel + " Users With Access:", null, null, null, controlDocument) var visIds = []; visIds[ "ftp_or_cifs" ] = [ "anonymous_access_container", "user_access_container" ]; visIds["nfs"] = [ "nfs_access_container", "nfs_policy_container", "nfs_ip_container", "nfs_spacer", "nfs_path_container" ]; visIds["ftp"] = [ "ftp_path_container" ] for(idType in visIds) { var ids = visIds[idType] var idIndex; for(idIndex=0; idIndex<ids.length;idIndex++) { controlDocument.getElementById( ids[idIndex] ).style.display = vis[ idType ] ? "block" : "none" } } if(vis["nfs"]) { setInvisibleIfIdMatches("nfs_policy", ["share"], "nfs_ip_container", "block", controlDocument); } } function setSharePaths(controlDocument) { controlDocument = controlDocument == null ? document : controlDocument; var escapedName=escape(controlDocument.getElementById("share_name").value); var ip = uciOriginal.get("network", "lan", "ipaddr"); if(controlDocument.getElementById("share_type_nfs").checked) { controlDocument.getElementById("nfs_path_container").style.display = "block"; setChildText("nfs_path", ip + ":/nfs/" + escapedName, null, null, null, controlDocument); } else { controlDocument.getElementById("nfs_path_container").style.display = "none"; } if(controlDocument.getElementById("share_type_ftp").checked) { controlDocument.getElementById("ftp_path_container").style.display = "block"; setChildText("ftp_path", "ftp://" + ip + "/" + escapedName, null, null, null, controlDocument); } else { controlDocument.getElementById("ftp_path_container").style.display = "none"; } } function createEditButton( editFunction ) { editButton = createInput("button"); editButton.value = "Edit"; editButton.className="default_button"; editButton.onclick = editFunction; editButton.className = "default_button" ; editButton.disabled = false ; return editButton; } function removeShareCallback(table, row) { var removeName=row.childNodes[0].firstChild.data; var removePath = nameToSharePath[removeName] delete nameToSharePath[removeName] delete sharePathToShareData[removePath] var newSharePathList = [] while(sharePathList.length > 0) { var next = sharePathList.shift() if(next != removePath){ newSharePathList.push(next) } } sharePathList = newSharePathList; setSharePaths(); } function editShare() { if( typeof(editShareWindow) != "undefined" ) { //opera keeps object around after //window is closed, so we need to deal //with error condition try { editShareWindow.close(); } catch(e){} } try { xCoor = window.screenX + 225; yCoor = window.screenY+ 225; } catch(e) { xCoor = window.left + 225; yCoor = window.top + 225; } editShareWindow = window.open("usb_storage_edit.sh", "edit", "width=560,height=600,left=" + xCoor + ",top=" + yCoor ); var saveButton = createInput("button", editShareWindow.document); var closeButton = createInput("button", editShareWindow.document); saveButton.value = "Close and Apply Changes"; saveButton.className = "default_button"; closeButton.value = "Close and Discard Changes"; closeButton.className = "default_button"; editRow=this.parentNode.parentNode; editName=editRow.childNodes[0].firstChild.data; editPath=nameToSharePath[editName]; editShareData=sharePathToShareData[ editPath ]; var runOnEditorLoaded = function () { var updateDone=false; if(editShareWindow.document != null) { if(editShareWindow.document.getElementById("bottom_button_container") != null) { updateDone = true; editShareWindow.document.getElementById("bottom_button_container").appendChild(saveButton); editShareWindow.document.getElementById("bottom_button_container").appendChild(closeButton); setDocumentFromShareData(editShareWindow.document, editShareData) closeButton.onclick = function() { editShareWindow.close(); } saveButton.onclick = function() { var rawShareData = getShareDataFromDocument(editShareWindow.document, editName) var errors = rawShareData["errors"]; if(errors.length > 0) { alert(errors.join("\n") + "\nCould not update share."); } else { var shareData = rawShareData["share"] var shareName = shareData[0] var fullSharePath = shareData[4]; var shareType = getVisStr( getVis(editShareWindow.document) ); if(editName != shareName) { delete nameToSharePath[ editName ] } if(editPath != fullSharePath) { var newSharePathList = [] while(sharePathList.length > 0) { var next = sharePathList.shift(); if(next != editPath) { newSharePathList.push(next) } } newSharePathList.push(fullSharePath) sharePathList = newSharePathList delete sharePathToShareData[ editPath ] } sharePathToShareData[ fullSharePath ] = shareData nameToSharePath [ shareName ] = fullSharePath editRow.childNodes[0].firstChild.data = shareName editRow.childNodes[1].firstChild.data = shareData[1] editRow.childNodes[2].firstChild.data = "/" + shareData[3] editRow.childNodes[3].firstChild.data = shareType editShareWindow.close(); } } editShareWindow.moveTo(xCoor,yCoor); editShareWindow.focus(); } } if(!updateDone) { setTimeout(runOnEditorLoaded, 250); } } runOnEditorLoaded(); } function unmountAllUsb() { setControlsEnabled(false, true, "Unmounting Disks"); var commands = "/etc/init.d/samba stop ; /etc/init.d/vsftpd stop ; /etc/init.d/nfsd stop ; /etc/init.d/usb_storage stop ; " var param = getParameterDefinition("commands", commands) + "&" + getParameterDefinition("hash", document.cookie.replace(/^.*hash=/,"").replace(/[\t ;]+.*$/, "")); var stateChangeFunction = function(req) { if(req.readyState == 4) { //reload page window.location=window.location setControlsEnabled(true); } } runAjax("POST", "utility/run_commands.sh", param, stateChangeFunction); } function formatDiskRequested() { if( !updateFormatPercentages("swap_percent") ) { alert("ERROR: Invalid Allocation Percentages Specified"); return; } var validFunc = doDiskFormat; var invalidFunc = function(){ alert("ERROR: Invalid Password"); setControlsEnabled(true); } var driveId = drivesWithNoMounts[ parseInt(getSelectedValue("format_disk_select")) ][0] confirmPassword("Are you sure you want to format drive " + driveId + "?\n\n" + "All data on this drive will be lost.\n\nTo proceed, enter your router login password:", validFunc, invalidFunc); } function doDiskFormat() { var driveId = drivesWithNoMounts[ parseInt(getSelectedValue("format_disk_select")) ][0] var swapPercent = parseFloat(document.getElementById("swap_percent").value) //format shell script requires percent as an integer, round as necessary if(swapPercent >0 && swapPercent <1) { swapPercent = 1 } if(swapPercent >99 && swapPercent < 100) { swapPerent = 99 } swapPercent=Math.round(swapPercent) if(confirm("Password Accepted.\n\nThis is your LAST CHANCE to cancel. Press 'OK' only if you are SURE you want to format " + driveId)) { setControlsEnabled(false, true, "Formatting,\nPlease Be Patient..."); var commands = "/usr/sbin/gargoyle_format_usb \"" + driveId + "\" \"" + swapPercent + "\" \"4\" ; sleep 1 ; /etc/init.d/usb_storage restart ; sleep 1 " var param = getParameterDefinition("commands", commands) + "&" + getParameterDefinition("hash", document.cookie.replace(/^.*hash=/,"").replace(/[\t ;]+.*$/, "")); var stateChangeFunction = function(req) { if(req.readyState == 4) { alert("Formatting Complete."); window.location=window.location setControlsEnabled(true) } } runAjax("POST", "utility/run_commands.sh", param, stateChangeFunction); } else { setControlsEnabled(true) } }
ivyswen/m4530r
package/plugin-gargoyle-usb-storage/files/www/js/usb_storage.js
JavaScript
gpl-2.0
45,629
(function( $ ) { 'use strict'; /** * All of the code for your admin-facing JavaScript source * should reside in this file. * * This enables you to define handlers, for when the DOM is ready: * * $(function() { * * }); * * When the window is loaded: * * $( window ).load(function() { * * }); */ $(function() { console.log("Hallo Welt"); }); })( jQuery );
BenRichter/wp-offline-saver
admin/js/offline-saver-admin.js
JavaScript
gpl-2.0
395
/* * Swiper 2.2 - Mobile Touch Slider * http://www.idangero.us/sliders/swiper/ * * Copyright 2012-2013, Vladimir Kharlampidi * The iDangero.us * http://www.idangero.us/ * * Licensed under GPL & MIT * * Updated on: September 15, 2013 */ var Swiper = function (selector, params) { /*========================= A little bit dirty but required part for IE8 and old FF support ===========================*/ if (document.body.__defineGetter__) { if (HTMLElement) { var element = HTMLElement.prototype; if (element.__defineGetter__) { element.__defineGetter__("outerHTML", function () { return new XMLSerializer().serializeToString(this); } ); } } } if (!window.getComputedStyle) { window.getComputedStyle = function (el, pseudo) { this.el = el; this.getPropertyValue = function (prop) { var re = /(\-([a-z]){1})/g; if (prop === 'float') prop = 'styleFloat'; if (re.test(prop)) { prop = prop.replace(re, function () { return arguments[2].toUpperCase(); }); } return el.currentStyle[prop] ? el.currentStyle[prop] : null; } return this; } } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(obj, start) { for (var i = (start || 0), j = this.length; i < j; i++) { if (this[i] === obj) { return i; } } return -1; } } if (!document.querySelectorAll) { if (!window.jQuery) return; } function $$(selector, context) { if (document.querySelectorAll) return (context || document).querySelectorAll(selector); else return jQuery(selector, context); } /*========================= Check for correct selector ===========================*/ if(typeof selector === 'undefined') return; if(!(selector.nodeType)){ if ($$(selector).length === 0) return; } /*========================= _this ===========================*/ var _this = this; /*========================= Default Flags and vars ===========================*/ _this.touches = { start:0, startX:0, startY:0, current:0, currentX:0, currentY:0, diff:0, abs:0 }; _this.positions = { start:0, abs:0, diff:0, current:0 }; _this.times = { start:0, end:0 }; _this.id = (new Date()).getTime(); _this.container = (selector.nodeType) ? selector : $$(selector)[0]; _this.isTouched = false; _this.isMoved = false; _this.activeIndex = 0; _this.activeLoaderIndex = 0; _this.activeLoopIndex = 0; _this.previousIndex = null; _this.velocity = 0; _this.snapGrid = []; _this.slidesGrid = []; _this.imagesToLoad = []; _this.imagesLoaded = 0; _this.wrapperLeft=0; _this.wrapperRight=0; _this.wrapperTop=0; _this.wrapperBottom=0; var wrapper, slideSize, wrapperSize, direction, isScrolling, containerSize; /*========================= Default Parameters ===========================*/ var defaults = { mode : 'horizontal', // or 'vertical' touchRatio : 1, speed : 300, freeMode : false, freeModeFluid : false, momentumRatio: 1, momentumBounce: true, momentumBounceRatio: 1, slidesPerView : 1, slidesPerGroup : 1, simulateTouch : true, followFinger : true, shortSwipes : true, moveStartThreshold:false, autoplay: false, onlyExternal : false, createPagination : true, pagination : false, paginationElement: 'span', paginationClickable: false, paginationAsRange: true, resistance : true, // or false or 100% scrollContainer : false, preventLinks : true, noSwiping : false, // or class noSwipingClass : 'swiper-no-swiping', //:) initialSlide: 0, keyboardControl: false, mousewheelControl : false, mousewheelDebounce: 600, useCSS3Transforms : true, //Loop mode loop:false, loopAdditionalSlides:0, //Auto Height calculateHeight: false, //Images Preloader updateOnImagesReady : true, //Form elements releaseFormElements : true, //Watch for active slide, useful when use effects on different slide states watchActiveIndex: false, //Slides Visibility Fit visibilityFullFit : false, //Slides Offset offsetPxBefore : 0, offsetPxAfter : 0, offsetSlidesBefore : 0, offsetSlidesAfter : 0, centeredSlides: false, //Queue callbacks queueStartCallbacks : false, queueEndCallbacks : false, //Auto Resize autoResize : true, resizeReInit : false, //DOMAnimation DOMAnimation : true, //Slides Loader loader: { slides:[], //array with slides slidesHTMLType:'inner', // or 'outer' surroundGroups: 1, //keep preloaded slides groups around view logic: 'reload', //or 'change' loadAllSlides: false }, //Namespace slideElement : 'div', slideClass : 'swiper-slide', slideActiveClass : 'swiper-slide-active', slideVisibleClass : 'swiper-slide-visible', wrapperClass : 'swiper-wrapper', paginationElementClass: 'swiper-pagination-switch', paginationActiveClass : 'swiper-active-switch', paginationVisibleClass : 'swiper-visible-switch' } params = params || {}; for (var prop in defaults) { if (prop in params && typeof params[prop]==='object') { for (var subProp in defaults[prop]) { if (! (subProp in params[prop])) { params[prop][subProp] = defaults[prop][subProp]; } } } else if (! (prop in params)) { params[prop] = defaults[prop] } } _this.params = params; if (params.scrollContainer) { params.freeMode = true; params.freeModeFluid = true; } if (params.loop) { params.resistance = '100%'; } var isH = params.mode==='horizontal'; /*========================= Define Touch Events ===========================*/ _this.touchEvents = { touchStart : _this.support.touch || !params.simulateTouch ? 'touchstart' : (_this.browser.ie10 ? 'MSPointerDown' : 'mousedown'), touchMove : _this.support.touch || !params.simulateTouch ? 'touchmove' : (_this.browser.ie10 ? 'MSPointerMove' : 'mousemove'), touchEnd : _this.support.touch || !params.simulateTouch ? 'touchend' : (_this.browser.ie10 ? 'MSPointerUp' : 'mouseup') }; /*========================= Wrapper ===========================*/ for (var i = _this.container.childNodes.length - 1; i >= 0; i--) { if (_this.container.childNodes[i].className) { var _wrapperClasses = _this.container.childNodes[i].className.split(' ') for (var j = 0; j < _wrapperClasses.length; j++) { if (_wrapperClasses[j]===params.wrapperClass) { wrapper = _this.container.childNodes[i]; } }; } }; _this.wrapper = wrapper; /*========================= Slide API ===========================*/ _this._extendSwiperSlide = function (el) { el.append = function () { if (params.loop) { el.insertAfter(_this.slides.length-_this.loopedSlides); _this.removeLoopedSlides(); _this.calcSlides(); _this.createLoop(); } else { _this.wrapper.appendChild(el); } _this.reInit(); return el; } el.prepend = function () { if (params.loop) { _this.wrapper.insertBefore(el, _this.slides[_this.loopedSlides]); _this.removeLoopedSlides(); _this.calcSlides(); _this.createLoop(); } else { _this.wrapper.insertBefore(el, _this.wrapper.firstChild); } _this.reInit(); return el; } el.insertAfter = function (index) { if(typeof index === 'undefined') return false; var beforeSlide; if (params.loop) { beforeSlide = _this.slides[index + 1 + _this.loopedSlides]; _this.wrapper.insertBefore(el, beforeSlide); _this.removeLoopedSlides(); _this.calcSlides(); _this.createLoop(); } else { beforeSlide = _this.slides[index + 1]; _this.wrapper.insertBefore(el, beforeSlide) } _this.reInit(); return el; } el.clone = function () { return _this._extendSwiperSlide(el.cloneNode(true)) } el.remove = function () { _this.wrapper.removeChild(el); _this.reInit(); } el.html = function (html) { if (typeof html === 'undefined') { return el.innerHTML; } else { el.innerHTML = html; return el; } } el.index = function () { var index; for (var i = _this.slides.length - 1; i >= 0; i--) { if(el === _this.slides[i]) index = i; } return index; } el.isActive = function () { if (el.index() === _this.activeIndex) return true; else return false; } if (!el.swiperSlideDataStorage) el.swiperSlideDataStorage={}; el.getData = function (name) { return el.swiperSlideDataStorage[name]; } el.setData = function (name, value) { el.swiperSlideDataStorage[name] = value; return el; } el.data = function (name, value) { if (!value) { return el.getAttribute('data-'+name); } else { el.setAttribute('data-'+name,value); return el; } } el.getWidth = function (outer) { return _this.h.getWidth(el, outer); } el.getHeight = function (outer) { return _this.h.getHeight(el, outer); } el.getOffset = function() { return _this.h.getOffset(el); } return el; } //Calculate information about number of slides _this.calcSlides = function (forceCalcSlides) { var oldNumber = _this.slides ? _this.slides.length : false; _this.slides = []; _this.displaySlides = []; for (var i = 0; i < _this.wrapper.childNodes.length; i++) { if (_this.wrapper.childNodes[i].className) { var _className = _this.wrapper.childNodes[i].className; var _slideClasses = _className.split(' '); for (var j = 0; j < _slideClasses.length; j++) { if(_slideClasses[j]===params.slideClass) { _this.slides.push(_this.wrapper.childNodes[i]); } } } } for (i = _this.slides.length - 1; i >= 0; i--) { _this._extendSwiperSlide(_this.slides[i]); } if (!oldNumber) return; if(oldNumber!==_this.slides.length || forceCalcSlides) { // Number of slides has been changed removeSlideEvents(); addSlideEvents(); _this.updateActiveSlide(); if (params.createPagination && _this.params.pagination) _this.createPagination(); _this.callPlugins('numberOfSlidesChanged'); } } //Create Slide _this.createSlide = function (html, slideClassList, el) { var slideClassList = slideClassList || _this.params.slideClass; var el = el||params.slideElement; var newSlide = document.createElement(el); newSlide.innerHTML = html||''; newSlide.className = slideClassList; return _this._extendSwiperSlide(newSlide); } //Append Slide _this.appendSlide = function (html, slideClassList, el) { if (!html) return; if (html.nodeType) { return _this._extendSwiperSlide(html).append() } else { return _this.createSlide(html, slideClassList, el).append() } } _this.prependSlide = function (html, slideClassList, el) { if (!html) return; if (html.nodeType) { return _this._extendSwiperSlide(html).prepend() } else { return _this.createSlide(html, slideClassList, el).prepend() } } _this.insertSlideAfter = function (index, html, slideClassList, el) { if (typeof index === 'undefined') return false; if (html.nodeType) { return _this._extendSwiperSlide(html).insertAfter(index); } else { return _this.createSlide(html, slideClassList, el).insertAfter(index); } } _this.removeSlide = function (index) { if (_this.slides[index]) { if (params.loop) { if (!_this.slides[index+_this.loopedSlides]) return false; _this.slides[index+_this.loopedSlides].remove(); _this.removeLoopedSlides(); _this.calcSlides(); _this.createLoop(); } else _this.slides[index].remove(); return true; } else return false; } _this.removeLastSlide = function () { if (_this.slides.length>0) { if (params.loop) { _this.slides[_this.slides.length - 1 - _this.loopedSlides].remove(); _this.removeLoopedSlides(); _this.calcSlides(); _this.createLoop(); } else _this.slides[ (_this.slides.length-1) ].remove(); return true; } else { return false; } } _this.removeAllSlides = function () { for (var i = _this.slides.length - 1; i >= 0; i--) { _this.slides[i].remove() } } _this.getSlide = function (index) { return _this.slides[index] } _this.getLastSlide = function () { return _this.slides[ _this.slides.length-1 ] } _this.getFirstSlide = function () { return _this.slides[0] } //Currently Active Slide _this.activeSlide = function () { return _this.slides[_this.activeIndex] } /*========================= Plugins API ===========================*/ var _plugins = []; for (var plugin in _this.plugins) { if (params[plugin]) { var p = _this.plugins[plugin](_this, params[plugin]); if (p) _plugins.push( p ); } } _this.callPlugins = function(method, args) { if (!args) args = {} for (var i=0; i<_plugins.length; i++) { if (method in _plugins[i]) { _plugins[i][method](args); } } } /*========================= WP8 Fix ===========================*/ if (_this.browser.ie10 && !params.onlyExternal) { _this.wrapper.classList.add('swiper-wp8-' + (isH ? 'horizontal' : 'vertical')); } /*========================= Free Mode Class ===========================*/ if (params.freeMode) { _this.container.className+=' swiper-free-mode'; } /*================================================== Init/Re-init/Resize Fix ====================================================*/ _this.initialized = false; _this.init = function(force, forceCalcSlides) { var _width = _this.h.getWidth(_this.container); var _height = _this.h.getHeight(_this.container); if (_width===_this.width && _height===_this.height && !force) return; _this.width = _width; _this.height = _height; containerSize = isH ? _width : _height; var wrapper = _this.wrapper; if (force) { _this.calcSlides(forceCalcSlides); } if (params.slidesPerView==='auto') { //Auto mode var slidesWidth = 0; var slidesHeight = 0; //Unset Styles if (params.slidesOffset>0) { wrapper.style.paddingLeft = ''; wrapper.style.paddingRight = ''; wrapper.style.paddingTop = ''; wrapper.style.paddingBottom = ''; } wrapper.style.width = ''; wrapper.style.height = ''; if (params.offsetPxBefore>0) { if (isH) _this.wrapperLeft = params.offsetPxBefore; else _this.wrapperTop = params.offsetPxBefore; } if (params.offsetPxAfter>0) { if (isH) _this.wrapperRight = params.offsetPxAfter; else _this.wrapperBottom = params.offsetPxAfter; } if (params.centeredSlides) { if (isH) { _this.wrapperLeft = (containerSize - this.slides[0].getWidth(true) )/2; _this.wrapperRight = (containerSize - _this.slides[ _this.slides.length-1 ].getWidth(true))/2; } else { _this.wrapperTop = (containerSize - _this.slides[0].getHeight(true))/2; _this.wrapperBottom = (containerSize - _this.slides[ _this.slides.length-1 ].getHeight(true))/2; } } if (isH) { if (_this.wrapperLeft>=0) wrapper.style.paddingLeft = _this.wrapperLeft+'px'; if (_this.wrapperRight>=0) wrapper.style.paddingRight = _this.wrapperRight+'px'; } else { if (_this.wrapperTop>=0) wrapper.style.paddingTop = _this.wrapperTop+'px'; if (_this.wrapperBottom>=0) wrapper.style.paddingBottom = _this.wrapperBottom+'px'; } var slideLeft = 0; var centeredSlideLeft=0; _this.snapGrid = []; _this.slidesGrid = []; var slideMaxHeight = 0; for(var i = 0; i<_this.slides.length; i++) { var slideWidth = _this.slides[i].getWidth(true); var slideHeight = _this.slides[i].getHeight(true); if (params.calculateHeight) { slideMaxHeight = Math.max(slideMaxHeight, slideHeight) } var _slideSize = isH ? slideWidth : slideHeight; if (params.centeredSlides) { var nextSlideWidth = i === _this.slides.length-1 ? 0 : _this.slides[i+1].getWidth(true); var nextSlideHeight = i === _this.slides.length-1 ? 0 : _this.slides[i+1].getHeight(true); var nextSlideSize = isH ? nextSlideWidth : nextSlideHeight; if (_slideSize>containerSize) { for (var j=0; j<=Math.floor(_slideSize/(containerSize+_this.wrapperLeft)); j++) { if (j === 0) _this.snapGrid.push(slideLeft+_this.wrapperLeft); else _this.snapGrid.push(slideLeft+_this.wrapperLeft+containerSize*j); } _this.slidesGrid.push(slideLeft+_this.wrapperLeft); } else { _this.snapGrid.push(centeredSlideLeft); _this.slidesGrid.push(centeredSlideLeft); } centeredSlideLeft += _slideSize/2 + nextSlideSize/2; } else { if (_slideSize>containerSize) { for (var j=0; j<=Math.floor(_slideSize/containerSize); j++) { _this.snapGrid.push(slideLeft+containerSize*j); } } else { _this.snapGrid.push(slideLeft); } _this.slidesGrid.push(slideLeft); } slideLeft += _slideSize; slidesWidth += slideWidth; slidesHeight += slideHeight; } if (params.calculateHeight) _this.height = slideMaxHeight; if(isH) { wrapperSize = slidesWidth + _this.wrapperRight + _this.wrapperLeft; wrapper.style.width = (slidesWidth)+'px'; wrapper.style.height = (_this.height)+'px'; } else { wrapperSize = slidesHeight + _this.wrapperTop + _this.wrapperBottom; wrapper.style.width = (_this.width)+'px'; wrapper.style.height = (slidesHeight)+'px'; } } else if (params.scrollContainer) { //Scroll Container wrapper.style.width = ''; wrapper.style.height = ''; var wrapperWidth = _this.slides[0].getWidth(true); var wrapperHeight = _this.slides[0].getHeight(true); wrapperSize = isH ? wrapperWidth : wrapperHeight; wrapper.style.width = wrapperWidth+'px'; wrapper.style.height = wrapperHeight+'px'; slideSize = isH ? wrapperWidth : wrapperHeight; } else { //For usual slides if (params.calculateHeight) { var slideMaxHeight = 0; var wrapperHeight = 0; //ResetWrapperSize if (!isH) _this.container.style.height= ''; wrapper.style.height=''; for (var i=0; i<_this.slides.length; i++) { //ResetSlideSize _this.slides[i].style.height=''; slideMaxHeight = Math.max( _this.slides[i].getHeight(true), slideMaxHeight ); if (!isH) wrapperHeight+=_this.slides[i].getHeight(true); } var slideHeight = slideMaxHeight; _this.height = slideHeight; if (isH) wrapperHeight = slideHeight; else containerSize = slideHeight, _this.container.style.height= containerSize+'px'; } else { var slideHeight = isH ? _this.height : _this.height/params.slidesPerView; var wrapperHeight = isH ? _this.height : _this.slides.length*slideHeight; } var slideWidth = isH ? _this.width/params.slidesPerView : _this.width; var wrapperWidth = isH ? _this.slides.length*slideWidth : _this.width; slideSize = isH ? slideWidth : slideHeight; if (params.offsetSlidesBefore>0) { if (isH) _this.wrapperLeft = slideSize*params.offsetSlidesBefore; else _this.wrapperTop = slideSize*params.offsetSlidesBefore; } if (params.offsetSlidesAfter>0) { if (isH) _this.wrapperRight = slideSize*params.offsetSlidesAfter; else _this.wrapperBottom = slideSize*params.offsetSlidesAfter; } if (params.offsetPxBefore>0) { if (isH) _this.wrapperLeft = params.offsetPxBefore; else _this.wrapperTop = params.offsetPxBefore; } if (params.offsetPxAfter>0) { if (isH) _this.wrapperRight = params.offsetPxAfter; else _this.wrapperBottom = params.offsetPxAfter; } if (params.centeredSlides) { if (isH) { _this.wrapperLeft = (containerSize - slideSize)/2; _this.wrapperRight = (containerSize - slideSize)/2; } else { _this.wrapperTop = (containerSize - slideSize)/2; _this.wrapperBottom = (containerSize - slideSize)/2; } } if (isH) { if (_this.wrapperLeft>0) wrapper.style.paddingLeft = _this.wrapperLeft+'px'; if (_this.wrapperRight>0) wrapper.style.paddingRight = _this.wrapperRight+'px'; } else { if (_this.wrapperTop>0) wrapper.style.paddingTop = _this.wrapperTop+'px'; if (_this.wrapperBottom>0) wrapper.style.paddingBottom = _this.wrapperBottom+'px'; } wrapperSize = isH ? wrapperWidth + _this.wrapperRight + _this.wrapperLeft : wrapperHeight + _this.wrapperTop + _this.wrapperBottom; wrapper.style.width = wrapperWidth+'px'; wrapper.style.height = wrapperHeight+'px'; var slideLeft = 0; _this.snapGrid = []; _this.slidesGrid = []; for (var i=0; i<_this.slides.length; i++) { _this.snapGrid.push(slideLeft); _this.slidesGrid.push(slideLeft); slideLeft+=slideSize; _this.slides[i].style.width = slideWidth+'px'; _this.slides[i].style.height = slideHeight+'px'; } } if (!_this.initialized) { _this.callPlugins('onFirstInit'); if (params.onFirstInit) params.onFirstInit(_this); } else { _this.callPlugins('onInit'); if (params.onInit) params.onInit(_this); } _this.initialized = true; } _this.reInit = function (forceCalcSlides) { _this.init(true, forceCalcSlides); } _this.resizeFix = function (reInit) { _this.callPlugins('beforeResizeFix'); _this.init(params.resizeReInit || reInit); // swipe to active slide in fixed mode if (!params.freeMode) { _this.swipeTo((params.loop ? _this.activeLoopIndex : _this.activeIndex), 0, false); } // move wrapper to the beginning in free mode else if (_this.getWrapperTranslate() < -maxWrapperPosition()) { _this.setWrapperTransition(0); _this.setWrapperTranslate(-maxWrapperPosition()); } _this.callPlugins('afterResizeFix'); } /*========================================== Max and Min Positions ============================================*/ function maxWrapperPosition() { var a = (wrapperSize - containerSize); if (params.freeMode) { a = wrapperSize - containerSize; } // if (params.loop) a -= containerSize; if (params.slidesPerView > _this.slides.length) a = 0; if (a<0) a = 0; return a; } function minWrapperPosition() { var a = 0; // if (params.loop) a = containerSize; return a; } /*========================================== Event Listeners ============================================*/ function initEvents() { var bind = _this.h.addEventListener; //Touch Events if (!_this.browser.ie10) { if (_this.support.touch) { bind(_this.wrapper, 'touchstart', onTouchStart); bind(_this.wrapper, 'touchmove', onTouchMove); bind(_this.wrapper, 'touchend', onTouchEnd); } if (params.simulateTouch) { bind(_this.wrapper, 'mousedown', onTouchStart); bind(document, 'mousemove', onTouchMove); bind(document, 'mouseup', onTouchEnd); } } else { bind(_this.wrapper, _this.touchEvents.touchStart, onTouchStart); bind(document, _this.touchEvents.touchMove, onTouchMove); bind(document, _this.touchEvents.touchEnd, onTouchEnd); } //Resize Event if (params.autoResize) { bind(window, 'resize', _this.resizeFix); } //Slide Events addSlideEvents(); //Mousewheel _this._wheelEvent = false; if (params.mousewheelControl) { if ( document.onmousewheel !== undefined ) { _this._wheelEvent = "mousewheel"; } try { WheelEvent("wheel"); _this._wheelEvent = "wheel"; } catch (e) {} if ( !_this._wheelEvent ) { _this._wheelEvent = "DOMMouseScroll"; } if (_this._wheelEvent) { bind(_this.container, _this._wheelEvent, handleMousewheel); } } //Keyboard if (params.keyboardControl) { bind(document, 'keydown', handleKeyboardKeys); } if (params.updateOnImagesReady) { _this.imagesToLoad = $$('img', _this.container); for (var i=0; i<_this.imagesToLoad.length; i++) { _loadImage(_this.imagesToLoad[i].getAttribute('src')) } } function _loadImage(src) { var image = new Image(); image.onload = function(){ _this.imagesLoaded++; if (_this.imagesLoaded==_this.imagesToLoad.length) { _this.reInit(); if (params.onImagesReady) params.onImagesReady(_this); } } image.src = src; } } //Remove Event Listeners _this.destroy = function(removeResizeFix){ var unbind = _this.h.removeEventListener; //Touch Events if (!_this.browser.ie10) { if (_this.support.touch) { unbind(_this.wrapper, 'touchstart', onTouchStart); unbind(_this.wrapper, 'touchmove', onTouchMove); unbind(_this.wrapper, 'touchend', onTouchEnd); } if (params.simulateTouch) { unbind(_this.wrapper, 'mousedown', onTouchStart); unbind(document, 'mousemove', onTouchMove); unbind(document, 'mouseup', onTouchEnd); } } else { unbind(_this.wrapper, _this.touchEvents.touchStart, onTouchStart); unbind(document, _this.touchEvents.touchMove, onTouchMove); unbind(document, _this.touchEvents.touchEnd, onTouchEnd); } //Resize Event if (params.autoResize) { unbind(window, 'resize', _this.resizeFix); } //Init Slide Events removeSlideEvents(); //Pagination if (params.paginationClickable) { removePaginationEvents(); } //Mousewheel if (params.mousewheelControl && _this._wheelEvent) { unbind(_this.container, _this._wheelEvent, handleMousewheel); } //Keyboard if (params.keyboardControl) { unbind(document, 'keydown', handleKeyboardKeys); } //Stop autoplay if (params.autoplay) { _this.stopAutoplay(); } _this.callPlugins('onDestroy'); //Destroy variable _this = null; } function addSlideEvents() { var bind = _this.h.addEventListener, i; //Prevent Links Events if (params.preventLinks) { var links = $$('a', _this.container); for (i=0; i<links.length; i++) { bind(links[i], 'click', preventClick); } } //Release Form Elements if (params.releaseFormElements) { var formElements = $$('input, textarea, select', _this.container); for (i=0; i<formElements.length; i++) { bind(formElements[i], _this.touchEvents.touchStart, releaseForms, true); } } //Slide Clicks & Touches if (params.onSlideClick) { for (i=0; i<_this.slides.length; i++) { bind(_this.slides[i], 'click', slideClick); } } if (params.onSlideTouch) { for (i=0; i<_this.slides.length; i++) { bind(_this.slides[i], _this.touchEvents.touchStart, slideTouch); } } } function removeSlideEvents() { var unbind = _this.h.removeEventListener, i; //Slide Clicks & Touches if (params.onSlideClick) { for (i=0; i<_this.slides.length; i++) { unbind(_this.slides[i], 'click', slideClick); } } if (params.onSlideTouch) { for (i=0; i<_this.slides.length; i++) { unbind(_this.slides[i], _this.touchEvents.touchStart, slideTouch); } } //Release Form Elements if (params.releaseFormElements) { var formElements = $$('input, textarea, select', _this.container); for (i=0; i<formElements.length; i++) { unbind(formElements[i], _this.touchEvents.touchStart, releaseForms, true); } } //Prevent Links Events if (params.preventLinks) { var links = $$('a', _this.container); for (i=0; i<links.length; i++) { unbind(links[i], 'click', preventClick); } } } /*========================================== Keyboard Control ============================================*/ function handleKeyboardKeys (e) { var kc = e.keyCode || e.charCode; if (kc==37 || kc==39 || kc==38 || kc==40) { var inView = false; //Check that swiper should be inside of visible area of window var swiperOffset = _this.h.getOffset( _this.container ); var scrollLeft = _this.h.windowScroll().left; var scrollTop = _this.h.windowScroll().top; var windowWidth = _this.h.windowWidth(); var windowHeight = _this.h.windowHeight(); var swiperCoord = [ [swiperOffset.left, swiperOffset.top], [swiperOffset.left + _this.width, swiperOffset.top], [swiperOffset.left, swiperOffset.top + _this.height], [swiperOffset.left + _this.width, swiperOffset.top + _this.height] ] for (var i=0; i<swiperCoord.length; i++) { var point = swiperCoord[i]; if ( point[0]>=scrollLeft && point[0]<=scrollLeft+windowWidth && point[1]>=scrollTop && point[1]<=scrollTop+windowHeight ) { inView = true; } } if (!inView) return; } if (isH) { if (kc==37 || kc==39) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } if (kc == 39) _this.swipeNext(); if (kc == 37) _this.swipePrev(); } else { if (kc==38 || kc==40) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } if (kc == 40) _this.swipeNext(); if (kc == 38) _this.swipePrev(); } } /*========================================== Mousewheel Control ============================================*/ var allowScrollChange = true; function handleMousewheel (e) { var we = _this._wheelEvent; var delta; //Opera & IE if (e.detail) delta = -e.detail; //WebKits else if (we == 'mousewheel') delta = e.wheelDelta; //Old FireFox else if (we == 'DOMMouseScroll') delta = -e.detail; //New FireFox else if (we == 'wheel') { delta = Math.abs(e.deltaX)>Math.abs(e.deltaY) ? - e.deltaX : - e.deltaY; } if (!params.freeMode) { if(delta<0) _this.swipeNext(); else _this.swipePrev(); } else { //Freemode or scrollContainer: var position = _this.getWrapperTranslate() + delta; if (position > 0) position = 0; if (position < -maxWrapperPosition()) position = -maxWrapperPosition(); _this.setWrapperTransition(0); _this.setWrapperTranslate(position); _this.updateActiveSlide(position); } if (params.autoplay) _this.stopAutoplay(); if(e.preventDefault) e.preventDefault(); else e.returnValue = false; return false; } /*========================= Grab Cursor ===========================*/ if (params.grabCursor) { var containerStyle = _this.container.style; containerStyle.cursor = 'move'; containerStyle.cursor = 'grab'; containerStyle.cursor = '-moz-grab'; containerStyle.cursor = '-webkit-grab'; } /*========================= Slides Events Handlers ===========================*/ _this.allowSlideClick = true; function slideClick(event) { if (_this.allowSlideClick) { setClickedSlide(event); params.onSlideClick(_this); } } function slideTouch(event) { setClickedSlide(event); params.onSlideTouch(_this); } function setClickedSlide(event) { // IE 6-8 support if (!event.currentTarget) { var element = event.srcElement; do { if (element.className.indexOf(params.slideClass) > -1) { break; } } while (element = element.parentNode); _this.clickedSlide = element; } else { _this.clickedSlide = event.currentTarget; } _this.clickedSlideIndex = _this.slides.indexOf(_this.clickedSlide); _this.clickedSlideLoopIndex = _this.clickedSlideIndex - (_this.loopedSlides || 0); } _this.allowLinks = true; function preventClick(e) { if (!_this.allowLinks) { if(e.preventDefault) e.preventDefault(); else e.returnValue = false; return false; } } function releaseForms(e) { if (e.stopPropagation) e.stopPropagation(); else e.returnValue = false; return false; } /*================================================== Event Handlers ====================================================*/ var isTouchEvent = false; var allowThresholdMove; var allowMomentumBounce = true; function onTouchStart(event) { //vc gallery when using lightbox fix if(jQuery(event.target).parents('.swiper-container').attr('data-desktop-swipe') == 'false' && !Modernizr.touch) return false; //deactivate touch if only one slide if(jQuery(event.target).parents('.swiper-container').find('.swiper-slide').length == 1) return false; //deactivate touch for duplicate transitions if(jQuery(event.target).parents('.swiper-container').find('.swiper-slide.duplicate-transition').length > 0) return false; if (params.preventLinks) _this.allowLinks = true; //Exit if slider is already was touched if (_this.isTouched || params.onlyExternal) { return false; } if (params.noSwiping && (event.target || event.srcElement) && noSwipingSlide(event.target || event.srcElement)) return false; allowMomentumBounce = false; //Check For Nested Swipers _this.isTouched = true; isTouchEvent = event.type=='touchstart'; if (!isTouchEvent || event.targetTouches.length == 1 ) { _this.callPlugins('onTouchStartBegin'); if(!isTouchEvent) { if(event.preventDefault) event.preventDefault(); else event.returnValue = false; } var pageX = isTouchEvent ? event.targetTouches[0].pageX : (event.pageX || event.clientX); var pageY = isTouchEvent ? event.targetTouches[0].pageY : (event.pageY || event.clientY); //Start Touches to check the scrolling _this.touches.startX = _this.touches.currentX = pageX; _this.touches.startY = _this.touches.currentY = pageY; _this.touches.start = _this.touches.current = isH ? pageX : pageY; //Set Transition Time to 0 _this.setWrapperTransition(0); //Get Start Translate Position _this.positions.start = _this.positions.current = _this.getWrapperTranslate(); //Set Transform _this.setWrapperTranslate(_this.positions.start); //TouchStartTime _this.times.start = (new Date()).getTime(); //Unset Scrolling isScrolling = undefined; //Set Treshold if (params.moveStartThreshold>0) allowThresholdMove = false; //CallBack if (params.onTouchStart) params.onTouchStart(_this); _this.callPlugins('onTouchStartEnd'); } } var velocityPrevPosition, velocityPrevTime; function onTouchMove(event) { // If slider is not touched - exit if (!_this.isTouched || params.onlyExternal) return; if (isTouchEvent && event.type=='mousemove') return; var pageX = isTouchEvent ? event.targetTouches[0].pageX : (event.pageX || event.clientX); var pageY = isTouchEvent ? event.targetTouches[0].pageY : (event.pageY || event.clientY); //check for scrolling if ( typeof isScrolling === 'undefined' && isH) { isScrolling = !!( isScrolling || Math.abs(pageY - _this.touches.startY) > Math.abs( pageX - _this.touches.startX ) ); } if ( typeof isScrolling === 'undefined' && !isH) { isScrolling = !!( isScrolling || Math.abs(pageY - _this.touches.startY) < Math.abs( pageX - _this.touches.startX ) ); } if (isScrolling ) { _this.isTouched = false; return; } //Check For Nested Swipers if (event.assignedToSwiper) { _this.isTouched = false; return; } event.assignedToSwiper = true; //Block inner links if (params.preventLinks) { _this.allowLinks = false; } if (params.onSlideClick) { _this.allowSlideClick = false; } //Stop AutoPlay if exist if (params.autoplay) { _this.stopAutoplay(); } if (!isTouchEvent || event.touches.length == 1) { //Moved Flag if (!_this.isMoved) { _this.callPlugins('onTouchMoveStart'); if (params.loop) { _this.fixLoop(); _this.positions.start = _this.getWrapperTranslate(); } if (params.onTouchMoveStart) params.onTouchMoveStart(_this); } _this.isMoved = true; // cancel event if(event.preventDefault) event.preventDefault(); else event.returnValue = false; _this.touches.current = isH ? pageX : pageY ; _this.positions.current = (_this.touches.current - _this.touches.start) * params.touchRatio + _this.positions.start; //Resistance Callbacks if(_this.positions.current > 0 && params.onResistanceBefore) { params.onResistanceBefore(_this, _this.positions.current); } if(_this.positions.current < -maxWrapperPosition() && params.onResistanceAfter) { params.onResistanceAfter(_this, Math.abs(_this.positions.current + maxWrapperPosition())); } //Resistance if (params.resistance && params.resistance!='100%') { //Resistance for Negative-Back sliding if(_this.positions.current > 0) { var resistance = 1 - _this.positions.current/containerSize/2; if (resistance < 0.5) _this.positions.current = (containerSize/2); else _this.positions.current = _this.positions.current * resistance; } //Resistance for After-End Sliding if ( _this.positions.current < -maxWrapperPosition() ) { var diff = (_this.touches.current - _this.touches.start)*params.touchRatio + (maxWrapperPosition()+_this.positions.start); var resistance = (containerSize+diff)/(containerSize); var newPos = _this.positions.current-diff*(1-resistance)/2; var stopPos = -maxWrapperPosition() - containerSize/2; if (newPos < stopPos || resistance<=0) _this.positions.current = stopPos; else _this.positions.current = newPos; } } if (params.resistance && params.resistance=='100%') { //Resistance for Negative-Back sliding if(_this.positions.current > 0 && !(params.freeMode&&!params.freeModeFluid)) { _this.positions.current = 0; } //Resistance for After-End Sliding if ( (_this.positions.current) < -maxWrapperPosition() && !(params.freeMode&&!params.freeModeFluid)) { _this.positions.current = -maxWrapperPosition(); } } //Move Slides if (!params.followFinger) return; if (!params.moveStartThreshold) { _this.setWrapperTranslate(_this.positions.current); } else { if ( Math.abs(_this.touches.current - _this.touches.start)>params.moveStartThreshold || allowThresholdMove) { allowThresholdMove = true; _this.setWrapperTranslate(_this.positions.current); } else { _this.positions.current = _this.positions.start; } } if (params.freeMode || params.watchActiveIndex) { _this.updateActiveSlide(_this.positions.current); } //Grab Cursor //Grab Cursor if (params.grabCursor) { _this.container.style.cursor = 'move'; _this.container.style.cursor = 'grabbing'; _this.container.style.cursor = '-moz-grabbing'; _this.container.style.cursor = '-webkit-grabbing'; } //Velocity if (!velocityPrevPosition) velocityPrevPosition = _this.touches.current; if (!velocityPrevTime) velocityPrevTime = (new Date).getTime(); _this.velocity = (_this.touches.current - velocityPrevPosition)/((new Date).getTime() - velocityPrevTime)/2; if (Math.abs(_this.touches.current - velocityPrevPosition)<2) _this.velocity=0; velocityPrevPosition = _this.touches.current; velocityPrevTime = (new Date).getTime(); //Callbacks _this.callPlugins('onTouchMoveEnd'); if (params.onTouchMove) params.onTouchMove(_this); return false; } } function onTouchEnd(event) { //Check For scrolling if (isScrolling) { _this.swipeReset(); } // If slider is not touched exit if ( params.onlyExternal || !_this.isTouched ) return; _this.isTouched = false //Return Grab Cursor if (params.grabCursor) { _this.container.style.cursor = 'move'; _this.container.style.cursor = 'grab'; _this.container.style.cursor = '-moz-grab'; _this.container.style.cursor = '-webkit-grab'; } //Check for Current Position if (!_this.positions.current && _this.positions.current!==0) { _this.positions.current = _this.positions.start } //For case if slider touched but not moved if (params.followFinger) { _this.setWrapperTranslate(_this.positions.current); } // TouchEndTime _this.times.end = (new Date()).getTime(); //Difference _this.touches.diff = _this.touches.current - _this.touches.start _this.touches.abs = Math.abs(_this.touches.diff) _this.positions.diff = _this.positions.current - _this.positions.start _this.positions.abs = Math.abs(_this.positions.diff) var diff = _this.positions.diff ; var diffAbs =_this.positions.abs ; var timeDiff = _this.times.end - _this.times.start if(diffAbs < 5 && (timeDiff) < 300 && _this.allowLinks == false) { if (!params.freeMode && diffAbs!=0) _this.swipeReset() //Release inner links if (params.preventLinks) { _this.allowLinks = true; } if (params.onSlideClick) { _this.allowSlideClick = true; } } setTimeout(function () { //Release inner links if (params.preventLinks) { _this.allowLinks = true; } if (params.onSlideClick) { _this.allowSlideClick = true; } }, 100); var maxPosition = maxWrapperPosition(); //Not moved or Prevent Negative Back Sliding/After-End Sliding if (!_this.isMoved && params.freeMode) { _this.isMoved = false; if (params.onTouchEnd) params.onTouchEnd(_this); _this.callPlugins('onTouchEnd'); return; } if (!_this.isMoved || _this.positions.current > 0 || _this.positions.current < -maxPosition) { _this.swipeReset(); if (params.onTouchEnd) params.onTouchEnd(_this); _this.callPlugins('onTouchEnd'); return; } _this.isMoved = false; //Free Mode if (params.freeMode) { if ( params.freeModeFluid ) { var momentumDuration = 1000*params.momentumRatio; var momentumDistance = _this.velocity*momentumDuration; var newPosition = _this.positions.current + momentumDistance var doBounce = false; var afterBouncePosition; var bounceAmount = Math.abs( _this.velocity )*20*params.momentumBounceRatio; if (newPosition < -maxPosition) { if (params.momentumBounce && _this.support.transitions) { if (newPosition + maxPosition < -bounceAmount) newPosition = -maxPosition-bounceAmount; afterBouncePosition = -maxPosition; doBounce=true; allowMomentumBounce = true; } else newPosition = -maxPosition; } if (newPosition > 0) { if (params.momentumBounce && _this.support.transitions) { if (newPosition>bounceAmount) newPosition = bounceAmount; afterBouncePosition = 0 doBounce = true; allowMomentumBounce = true; } else newPosition = 0; } //Fix duration if (_this.velocity!=0) momentumDuration = Math.abs((newPosition - _this.positions.current)/_this.velocity) _this.setWrapperTranslate(newPosition); _this.setWrapperTransition( momentumDuration ); if (params.momentumBounce && doBounce) { _this.wrapperTransitionEnd(function () { if (!allowMomentumBounce) return; if (params.onMomentumBounce) params.onMomentumBounce(_this); _this.setWrapperTranslate(afterBouncePosition); _this.setWrapperTransition(300); }) } _this.updateActiveSlide(newPosition) } if (!params.freeModeFluid || timeDiff >= 300) _this.updateActiveSlide(_this.positions.current) if (params.onTouchEnd) params.onTouchEnd(_this) _this.callPlugins('onTouchEnd'); return; } //Direction direction = diff < 0 ? "toNext" : "toPrev" //Short Touches if (direction=="toNext" && ( timeDiff <= 300 ) ) { if (diffAbs < 30 || !params.shortSwipes) _this.swipeReset() else _this.swipeNext(true); } if (direction=="toPrev" && ( timeDiff <= 300 ) ) { if (diffAbs < 30 || !params.shortSwipes) _this.swipeReset() else _this.swipePrev(true); } //Long Touches var targetSlideSize = 0; if(params.slidesPerView == 'auto') { //Define current slide's width var currentPosition = Math.abs(_this.getWrapperTranslate()); var slidesOffset = 0; var _slideSize; for (var i=0; i<_this.slides.length; i++) { _slideSize = isH ? _this.slides[i].getWidth(true) : _this.slides[i].getHeight(true); slidesOffset+= _slideSize; if (slidesOffset>currentPosition) { targetSlideSize = _slideSize; break; } } if (targetSlideSize>containerSize) targetSlideSize = containerSize; } else { targetSlideSize = slideSize * params.slidesPerView; } if (direction=="toNext" && ( timeDiff > 300 ) ) { if (diffAbs >= targetSlideSize*0.5) { _this.swipeNext(true) } else { _this.swipeReset() } } if (direction=="toPrev" && ( timeDiff > 300 ) ) { if (diffAbs >= targetSlideSize*0.5) { _this.swipePrev(true); } else { _this.swipeReset() } } if (params.onTouchEnd) params.onTouchEnd(_this) _this.callPlugins('onTouchEnd'); } /*================================================== noSwiping Bubble Check by Isaac Strack ====================================================*/ function noSwipingSlide(el){ /*This function is specifically designed to check the parent elements for the noSwiping class, up to the wrapper. We need to check parents because while onTouchStart bubbles, _this.isTouched is checked in onTouchStart, which stops the bubbling. So, if a text box, for example, is the initial target, and the parent slide container has the noSwiping class, the _this.isTouched check will never find it, and what was supposed to be noSwiping is able to be swiped. This function will iterate up and check for the noSwiping class in parents, up through the wrapperClass.*/ // First we create a truthy variable, which is that swiping is allowd (noSwiping = false) var noSwiping = false; // Now we iterate up (parentElements) until we reach the node with the wrapperClass. do{ // Each time, we check to see if there's a 'swiper-no-swiping' class (noSwipingClass). if (el.className.indexOf(params.noSwipingClass)>-1) { noSwiping = true; // If there is, we set noSwiping = true; } el = el.parentElement; // now we iterate up (parent node) } while(!noSwiping && el.parentElement && el.className.indexOf(params.wrapperClass)==-1); // also include el.parentElement truthy, just in case. // because we didn't check the wrapper itself, we do so now, if noSwiping is false: if (!noSwiping && el.className.indexOf(params.wrapperClass)>-1 && el.className.indexOf(params.noSwipingClass)>-1) noSwiping = true; // if the wrapper has the noSwipingClass, we set noSwiping = true; return noSwiping; } /*================================================== Swipe Functions ====================================================*/ _this.swipeNext = function(internal){ if (!internal && params.loop) _this.fixLoop(); _this.callPlugins('onSwipeNext'); var currentPosition = _this.getWrapperTranslate(); var newPosition = currentPosition; if (params.slidesPerView=='auto') { for (var i=0; i<_this.snapGrid.length; i++) { if (-currentPosition >= _this.snapGrid[i] && -currentPosition<_this.snapGrid[i+1]) { newPosition = -_this.snapGrid[i+1] break; } } } else { var groupSize = slideSize * params.slidesPerGroup; newPosition = -(Math.floor(Math.abs(currentPosition)/Math.floor(groupSize))*groupSize + groupSize); } if (newPosition < - maxWrapperPosition()) { newPosition = - maxWrapperPosition() }; if (newPosition == currentPosition) return false; swipeToPosition(newPosition, 'next'); return true } _this.swipePrev = function(internal){ if (!internal && params.loop) _this.fixLoop(); if (!internal && params.autoplay) _this.stopAutoplay(); _this.callPlugins('onSwipePrev'); var currentPosition = Math.ceil(_this.getWrapperTranslate()); var newPosition; if (params.slidesPerView=='auto') { newPosition = 0; for (var i=1; i<_this.snapGrid.length; i++) { if (-currentPosition == _this.snapGrid[i]) { newPosition = -_this.snapGrid[i-1] break; } if (-currentPosition > _this.snapGrid[i] && -currentPosition<_this.snapGrid[i+1]) { newPosition = -_this.snapGrid[i] break; } } } else { var groupSize = slideSize * params.slidesPerGroup; newPosition = -(Math.ceil(-currentPosition/groupSize)-1)*groupSize; } if (newPosition > 0) newPosition = 0; if (newPosition == currentPosition) return false; swipeToPosition(newPosition, 'prev'); return true; } _this.swipeReset = function(){ _this.callPlugins('onSwipeReset'); var currentPosition = _this.getWrapperTranslate(); var groupSize = slideSize * params.slidesPerGroup; var newPosition; var maxPosition = -maxWrapperPosition(); if (params.slidesPerView=='auto') { newPosition = 0; for (var i=0; i<_this.snapGrid.length; i++) { if (-currentPosition===_this.snapGrid[i]) return; if (-currentPosition >= _this.snapGrid[i] && -currentPosition<_this.snapGrid[i+1]) { if(_this.positions.diff>0) newPosition = -_this.snapGrid[i+1] else newPosition = -_this.snapGrid[i] break; } } if (-currentPosition >= _this.snapGrid[_this.snapGrid.length-1]) newPosition = -_this.snapGrid[_this.snapGrid.length-1]; if (currentPosition <= -maxWrapperPosition()) newPosition = -maxWrapperPosition() } else { newPosition = currentPosition<0 ? Math.round(currentPosition/groupSize)*groupSize : 0 } if (params.scrollContainer) { newPosition = currentPosition<0 ? currentPosition : 0; } if (newPosition < -maxWrapperPosition()) { newPosition = -maxWrapperPosition() } if (params.scrollContainer && (containerSize>slideSize)) { newPosition = 0; } if (newPosition == currentPosition) return false; swipeToPosition(newPosition, 'reset'); return true; } _this.swipeTo = function(index, speed, runCallbacks) { index = parseInt(index, 10); _this.callPlugins('onSwipeTo', {index:index, speed:speed}); if (params.loop) index = index + _this.loopedSlides; var currentPosition = _this.getWrapperTranslate(); if (index > (_this.slides.length-1) || index < 0) return; var newPosition if (params.slidesPerView=='auto') { newPosition = -_this.slidesGrid[ index ]; } else { newPosition = -index*slideSize; } if (newPosition < - maxWrapperPosition()) { newPosition = - maxWrapperPosition(); }; if (newPosition == currentPosition) return false; runCallbacks = runCallbacks===false ? false : true; swipeToPosition(newPosition, 'to', {index:index, speed:speed, runCallbacks:runCallbacks}); return true; } function swipeToPosition(newPosition, action, toOptions) { var speed = (action=='to' && toOptions.speed >= 0) ? toOptions.speed : params.speed; if (_this.support.transitions || !params.DOMAnimation) { _this.setWrapperTranslate(newPosition); _this.setWrapperTransition(speed); } else { //Try the DOM animation var currentPosition = _this.getWrapperTranslate(); var animationStep = Math.ceil( (newPosition - currentPosition)/speed*(1000/60) ); var direction = currentPosition > newPosition ? 'toNext' : 'toPrev'; var condition = direction=='toNext' ? currentPosition > newPosition : currentPosition < newPosition; if (_this._DOMAnimating) return; anim(); } function anim(){ currentPosition += animationStep; condition = direction=='toNext' ? currentPosition > newPosition : currentPosition < newPosition; if (condition) { _this.setWrapperTranslate(Math.round(currentPosition)); _this._DOMAnimating = true window.setTimeout(function(){ anim() }, 1000 / 60) } else { if (params.onSlideChangeEnd) params.onSlideChangeEnd(_this); _this.setWrapperTranslate(newPosition); _this._DOMAnimating = false; } } //Update Active Slide Index _this.updateActiveSlide(newPosition); //Callbacks if (params.onSlideNext && action=='next') { params.onSlideNext(_this, newPosition); } if (params.onSlidePrev && action=='prev') { params.onSlidePrev(_this, newPosition); } //"Reset" Callback if (params.onSlideReset && action=='reset') { params.onSlideReset(_this, newPosition); } //"Next", "Prev" and "To" Callbacks if (action=='next' || action=='prev' || (action=='to' && toOptions.runCallbacks==true)) slideChangeCallbacks(); } /*================================================== Transition Callbacks ====================================================*/ //Prevent Multiple Callbacks _this._queueStartCallbacks = false; _this._queueEndCallbacks = false; function slideChangeCallbacks() { //Transition Start Callback _this.callPlugins('onSlideChangeStart'); if (params.onSlideChangeStart) { if (params.queueStartCallbacks && _this.support.transitions) { if (_this._queueStartCallbacks) return; _this._queueStartCallbacks = true; params.onSlideChangeStart(_this) _this.wrapperTransitionEnd(function(){ _this._queueStartCallbacks = false; }) } else params.onSlideChangeStart(_this) } //Transition End Callback if (params.onSlideChangeEnd) { if (_this.support.transitions) { if (params.queueEndCallbacks) { if (_this._queueEndCallbacks) return; _this._queueEndCallbacks = true; _this.wrapperTransitionEnd(params.onSlideChangeEnd) } else { _this.wrapperTransitionEnd(function(){ _this.fixLoop(); params.onSlideChangeEnd(_this); }); } } else { if (!params.DOMAnimation) { setTimeout(function(){ params.onSlideChangeEnd(_this) },10) } } } } /*================================================== Update Active Slide Index ====================================================*/ _this.updateActiveSlide = function(position) { if (!_this.initialized) return; if (_this.slides.length==0) return; _this.previousIndex = _this.activeIndex; if (typeof position=='undefined') position = _this.getWrapperTranslate(); if (position>0) position=0; if (params.slidesPerView == 'auto') { var slidesOffset = 0; _this.activeIndex = _this.slidesGrid.indexOf(-position); if (_this.activeIndex<0) { for (var i=0; i<_this.slidesGrid.length-1; i++) { if (-position>_this.slidesGrid[i] && -position<_this.slidesGrid[i+1]) { break; } } var leftDistance = Math.abs( _this.slidesGrid[i] + position ) var rightDistance = Math.abs( _this.slidesGrid[i+1] + position ) if (leftDistance<=rightDistance) _this.activeIndex = i; else _this.activeIndex = i+1; } } else { _this.activeIndex = Math[params.visibilityFullFit ? 'ceil' : 'round']( -position/slideSize ); } if (_this.activeIndex == _this.slides.length ) _this.activeIndex = _this.slides.length - 1; if (_this.activeIndex < 0) _this.activeIndex = 0; // Check for slide if (!_this.slides[_this.activeIndex]) return; // Calc Visible slides _this.calcVisibleSlides(position); // Mark visible and active slides with additonal classes var activeClassRegexp = new RegExp( "\\s*" + params.slideActiveClass ); var inViewClassRegexp = new RegExp( "\\s*" + params.slideVisibleClass ); for (var i = 0; i < _this.slides.length; i++) { _this.slides[ i ].className = _this.slides[ i ].className.replace( activeClassRegexp, '' ).replace( inViewClassRegexp, '' ); if ( _this.visibleSlides.indexOf( _this.slides[ i ] )>=0 ) { _this.slides[ i ].className += ' ' + params.slideVisibleClass; } } _this.slides[ _this.activeIndex ].className += ' ' + params.slideActiveClass; //Update loop index if (params.loop) { var ls = _this.loopedSlides; _this.activeLoopIndex = _this.activeIndex - ls; if (_this.activeLoopIndex >= _this.slides.length - ls*2 ) { _this.activeLoopIndex = _this.slides.length - ls*2 - _this.activeLoopIndex; } if (_this.activeLoopIndex<0) { _this.activeLoopIndex = _this.slides.length - ls*2 + _this.activeLoopIndex; } } else { _this.activeLoopIndex = _this.activeIndex; } //Update Pagination if (params.pagination) { _this.updatePagination(position); } } /*================================================== Pagination ====================================================*/ _this.createPagination = function (firstInit) { if (params.paginationClickable && _this.paginationButtons) { removePaginationEvents(); } var paginationHTML = ""; var numOfSlides = _this.slides.length; var numOfButtons = numOfSlides; if (params.loop) numOfButtons -= _this.loopedSlides*2 for (var i = 0; i < numOfButtons; i++) { paginationHTML += '<'+params.paginationElement+' class="'+params.paginationElementClass+'"></'+params.paginationElement+'>' } _this.paginationContainer = params.pagination.nodeType ? params.pagination : $$(params.pagination)[0]; _this.paginationContainer.innerHTML = paginationHTML; _this.paginationButtons = $$('.'+params.paginationElementClass, _this.paginationContainer); if (!firstInit) _this.updatePagination() _this.callPlugins('onCreatePagination'); if (params.paginationClickable) { addPaginationEvents(); } } function removePaginationEvents() { var pagers = _this.paginationButtons; for (var i=0; i<pagers.length; i++) { _this.h.removeEventListener(pagers[i], 'click', paginationClick); } } function addPaginationEvents() { var pagers = _this.paginationButtons; for (var i=0; i<pagers.length; i++) { _this.h.addEventListener(pagers[i], 'click', paginationClick); } } function paginationClick(e){ var index; var target = e.target || e.srcElement; var pagers = _this.paginationButtons; for (var i=0; i<pagers.length; i++) { if (target===pagers[i]) index = i; } _this.swipeTo(index) } _this.updatePagination = function(position) { if (!params.pagination) return; if (_this.slides.length<1) return; var activePagers = $$('.'+params.paginationActiveClass, _this.paginationContainer); if(!activePagers) return; //Reset all Buttons' class to not active var pagers = _this.paginationButtons; if (pagers.length==0) return; for (var i=0; i < pagers.length; i++) { pagers[i].className = params.paginationElementClass } var indexOffset = params.loop ? _this.loopedSlides : 0; if (params.paginationAsRange) { if (!_this.visibleSlides) _this.calcVisibleSlides(position) //Get Visible Indexes var visibleIndexes = []; for (var i = 0; i < _this.visibleSlides.length; i++) { var visIndex = _this.slides.indexOf( _this.visibleSlides[i] ) - indexOffset if (params.loop && visIndex<0) { visIndex = _this.slides.length - _this.loopedSlides*2 + visIndex; } if (params.loop && visIndex>=_this.slides.length-_this.loopedSlides*2) { visIndex = _this.slides.length - _this.loopedSlides*2 - visIndex; visIndex = Math.abs(visIndex) } visibleIndexes.push( visIndex ) } for (i=0; i<visibleIndexes.length; i++) { if (pagers[ visibleIndexes[i] ]) pagers[ visibleIndexes[i] ].className += ' ' + params.paginationVisibleClass; } if (params.loop) { pagers[ _this.activeLoopIndex ].className += ' ' + params.paginationActiveClass; } else { pagers[ _this.activeIndex ].className += ' ' + params.paginationActiveClass; } } else { if (params.loop) { pagers[ _this.activeLoopIndex ].className+=' '+params.paginationActiveClass+' '+params.paginationVisibleClass; } else { pagers[ _this.activeIndex ].className+=' '+params.paginationActiveClass+' '+params.paginationVisibleClass; } } } _this.calcVisibleSlides = function(position){ var visibleSlides = []; var _slideLeft = 0, _slideSize = 0, _slideRight = 0; if (isH && _this.wrapperLeft>0) position = position+_this.wrapperLeft; if (!isH && _this.wrapperTop>0) position = position+_this.wrapperTop; for (var i=0; i<_this.slides.length; i++) { _slideLeft += _slideSize; if (params.slidesPerView == 'auto') _slideSize = isH ? _this.h.getWidth(_this.slides[i],true) : _this.h.getHeight(_this.slides[i],true); else _slideSize = slideSize; _slideRight = _slideLeft + _slideSize; var isVisibile = false; if (params.visibilityFullFit) { if (_slideLeft >= -position && _slideRight <= -position+containerSize) isVisibile = true; if (_slideLeft <= -position && _slideRight >= -position+containerSize) isVisibile = true; } else { if (_slideRight > -position && _slideRight <= ((-position+containerSize))) isVisibile = true; if (_slideLeft >= -position && _slideLeft < ((-position+containerSize))) isVisibile = true; if (_slideLeft < -position && _slideRight > ((-position+containerSize))) isVisibile = true; } if (isVisibile) visibleSlides.push(_this.slides[i]) } if (visibleSlides.length==0) visibleSlides = [ _this.slides[ _this.activeIndex ] ] _this.visibleSlides = visibleSlides; } /*========================================== Autoplay ============================================*/ _this.autoPlayIntervalId = undefined; _this.startAutoplay = function () { if (typeof _this.autoPlayIntervalId !== 'undefined') return false; if (params.autoplay && !params.loop) { _this.autoPlayIntervalId = setInterval(function(){ if (!_this.swipeNext(true)) _this.swipeTo(0); }, params.autoplay) } if (params.autoplay && params.loop) { _this.autoPlayIntervalId = setInterval(function(){ _this.swipeNext(); }, params.autoplay) } _this.callPlugins('onAutoplayStart'); } _this.stopAutoplay = function () { if (_this.autoPlayIntervalId) clearInterval(_this.autoPlayIntervalId); _this.autoPlayIntervalId = undefined; _this.callPlugins('onAutoplayStop'); } /*================================================== Loop ====================================================*/ _this.loopCreated = false; _this.removeLoopedSlides = function(){ if (_this.loopCreated) { for (var i=0; i<_this.slides.length; i++) { if (_this.slides[i].getData('looped')===true) _this.wrapper.removeChild(_this.slides[i]); } } } _this.createLoop = function() { if (_this.slides.length==0) return; _this.loopedSlides = params.slidesPerView + params.loopAdditionalSlides; if (_this.loopedSlides > _this.slides.length) { _this.loopedSlides = _this.slides.length; } var slideFirstHTML = '', slideLastHTML = '', i; //Grab First Slides for (i=0; i<_this.loopedSlides; i++) { slideFirstHTML += _this.slides[i].outerHTML; } //Grab Last Slides for (i=_this.slides.length-_this.loopedSlides; i<_this.slides.length; i++) { slideLastHTML += _this.slides[i].outerHTML; } wrapper.innerHTML = slideLastHTML + wrapper.innerHTML + slideFirstHTML; _this.loopCreated = true; _this.calcSlides(); //Update Looped Slides with special class for (i=0; i<_this.slides.length; i++) { if (i<_this.loopedSlides || i>=_this.slides.length-_this.loopedSlides) _this.slides[i].setData('looped', true); } _this.callPlugins('onCreateLoop'); } _this.fixLoop = function() { if(_this.params.loop == true) { var newIndex; //Fix For Negative Oversliding if (_this.activeIndex < _this.loopedSlides) { newIndex = _this.slides.length - _this.loopedSlides*3 + _this.activeIndex; _this.swipeTo(newIndex, 0, false); } //Fix For Positive Oversliding else if (_this.activeIndex > _this.slides.length - params.slidesPerView*2) { newIndex = -_this.slides.length + _this.activeIndex + _this.loopedSlides _this.swipeTo(newIndex, 0, false); } } } /*================================================== Slides Loader ====================================================*/ _this.loadSlides = function(){ var slidesHTML = ''; _this.activeLoaderIndex = 0; var slides = params.loader.slides; var slidesToLoad = params.loader.loadAllSlides ? slides.length : params.slidesPerView*(1+params.loader.surroundGroups); for (var i=0; i< slidesToLoad; i++) { if (params.loader.slidesHTMLType=='outer') slidesHTML+=slides[i]; else { slidesHTML+='<'+params.slideElement+' class="'+params.slideClass+'" data-swiperindex="'+i+'">'+slides[i]+'</'+params.slideElement+'>'; } } _this.wrapper.innerHTML = slidesHTML; _this.calcSlides(true); //Add permanent transitionEnd callback if (!params.loader.loadAllSlides) { _this.wrapperTransitionEnd(_this.reloadSlides, true); } } _this.reloadSlides = function(){ var slides = params.loader.slides; var newActiveIndex = parseInt(_this.activeSlide().data('swiperindex'),10) if (newActiveIndex<0 || newActiveIndex>slides.length-1) return //<-- Exit _this.activeLoaderIndex = newActiveIndex; var firstIndex = Math.max(0, newActiveIndex - params.slidesPerView*params.loader.surroundGroups) var lastIndex = Math.min(newActiveIndex+params.slidesPerView*(1+params.loader.surroundGroups)-1, slides.length-1) //Update Transforms if (newActiveIndex>0) { var newTransform = -slideSize*(newActiveIndex-firstIndex) _this.setWrapperTranslate(newTransform); _this.setWrapperTransition(0); } //New Slides if (params.loader.logic==='reload') { _this.wrapper.innerHTML = ''; var slidesHTML = ''; for (var i = firstIndex; i<=lastIndex; i++) { slidesHTML += params.loader.slidesHTMLType == 'outer' ? slides[i] : '<'+params.slideElement+' class="'+params.slideClass+'" data-swiperindex="'+i+'">'+slides[i]+'</'+params.slideElement+'>'; } _this.wrapper.innerHTML = slidesHTML; } else { var minExistIndex=1000; var maxExistIndex=0; for (var i=0; i<_this.slides.length; i++) { var index = _this.slides[i].data('swiperindex'); if (index<firstIndex || index>lastIndex) { _this.wrapper.removeChild(_this.slides[i]); } else { minExistIndex = Math.min(index, minExistIndex) maxExistIndex = Math.max(index, maxExistIndex) } } for (var i=firstIndex; i<=lastIndex; i++) { if (i<minExistIndex) { var newSlide = document.createElement(params.slideElement); newSlide.className = params.slideClass; newSlide.setAttribute('data-swiperindex',i); newSlide.innerHTML = slides[i]; _this.wrapper.insertBefore(newSlide, _this.wrapper.firstChild); } if (i>maxExistIndex) { var newSlide = document.createElement(params.slideElement); newSlide.className = params.slideClass; newSlide.setAttribute('data-swiperindex',i); newSlide.innerHTML = slides[i]; _this.wrapper.appendChild(newSlide); } } } //reInit _this.reInit(true); } /*================================================== Make Swiper ====================================================*/ function makeSwiper(){ _this.calcSlides(); if (params.loader.slides.length>0 && _this.slides.length==0) { _this.loadSlides(); } if (params.loop) { _this.createLoop(); } _this.init(); initEvents(); if (params.pagination && params.createPagination) { _this.createPagination(true); } if (params.loop || params.initialSlide>0) { _this.swipeTo( params.initialSlide, 0, false ); } else { _this.updateActiveSlide(0); } if (params.autoplay) { _this.startAutoplay(); } } makeSwiper(); } Swiper.prototype = { plugins : {}, /*================================================== Wrapper Operations ====================================================*/ wrapperTransitionEnd : function(callback, permanent) { var a = this, el = a.wrapper, events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'], i; function fireCallBack() { callback(a); if (a.params.queueEndCallbacks) a._queueEndCallbacks = false; if (!permanent) { for (i=0; i<events.length; i++) { a.h.removeEventListener(el, events[i], fireCallBack); } } } if (callback) { for (i=0; i<events.length; i++) { a.h.addEventListener(el, events[i], fireCallBack); } } }, getWrapperTranslate : function (axis) { var el = this.wrapper, matrix, curTransform, curStyle, transformMatrix; // automatic axis detection if (typeof axis == 'undefined') { axis = this.params.mode == 'horizontal' ? 'x' : 'y'; } curStyle = window.getComputedStyle(el, null); if (window.WebKitCSSMatrix) { transformMatrix = new WebKitCSSMatrix(curStyle.webkitTransform); } else { transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue("transform").replace("translate(", "matrix(1, 0, 0, 1,"); matrix = transformMatrix.toString().split(','); } if (this.support.transforms && this.params.useCSS3Transforms) { if (axis=='x') { //Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m41; //Crazy IE10 Matrix else if (matrix.length==16) curTransform = parseFloat( matrix[12] ); //Normal Browsers else curTransform = parseFloat( matrix[4] ); } if (axis=='y') { //Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m42; //Crazy IE10 Matrix else if (matrix.length==16) curTransform = parseFloat( matrix[13] ); //Normal Browsers else curTransform = parseFloat( matrix[5] ); } } else { if (axis=='x') curTransform = parseFloat(el.style.left,10) || 0; if (axis=='y') curTransform = parseFloat(el.style.top,10) || 0; } return curTransform || 0; }, setWrapperTranslate : function (x, y, z) { var es = this.wrapper.style, coords = {x: 0, y: 0, z: 0}, translate; // passed all coordinates if (arguments.length == 3) { coords.x = x; coords.y = y; coords.z = z; } // passed one coordinate and optional axis else { if (typeof y == 'undefined') { y = this.params.mode == 'horizontal' ? 'x' : 'y'; } coords[y] = x; } if (this.support.transforms && this.params.useCSS3Transforms) { translate = this.support.transforms3d ? 'translate3d(' + coords.x + 'px, ' + coords.y + 'px, ' + coords.z + 'px)' : 'translate(' + coords.x + 'px, ' + coords.y + 'px)'; es.webkitTransform = es.MsTransform = es.msTransform = es.MozTransform = es.OTransform = es.transform = translate; } else { es.left = coords.x + 'px'; es.top = coords.y + 'px'; } this.callPlugins('onSetWrapperTransform', coords); }, setWrapperTransition : function (duration) { var es = this.wrapper.style; es.webkitTransitionDuration = es.MsTransitionDuration = es.msTransitionDuration = es.MozTransitionDuration = es.OTransitionDuration = es.transitionDuration = (duration / 1000) + 's'; this.callPlugins('onSetWrapperTransition', {duration: duration}); }, /*================================================== Helpers ====================================================*/ h : { getWidth: function (el, outer) { var width = window.getComputedStyle(el, null).getPropertyValue('width') var returnWidth = parseFloat(width); //IE Fixes if(isNaN(returnWidth) || width.indexOf('%')>0) { returnWidth = el.offsetWidth - parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-left')) - parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-right')); } if (outer) returnWidth += parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-left')) + parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-right')) return returnWidth; }, getHeight: function(el, outer) { if (outer) return el.offsetHeight; var height = window.getComputedStyle(el, null).getPropertyValue('height') var returnHeight = parseFloat(height); //IE Fixes if(isNaN(returnHeight) || height.indexOf('%')>0) { returnHeight = el.offsetHeight - parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-top')) - parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-bottom')); } if (outer) returnHeight += parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-top')) + parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-bottom')) return returnHeight; }, getOffset: function(el) { var box = el.getBoundingClientRect(); var body = document.body; var clientTop = el.clientTop || body.clientTop || 0; var clientLeft = el.clientLeft || body.clientLeft || 0; var scrollTop = window.pageYOffset || el.scrollTop; var scrollLeft = window.pageXOffset || el.scrollLeft; if (document.documentElement && !window.pageYOffset) { //IE7-8 scrollTop = document.documentElement.scrollTop; scrollLeft = document.documentElement.scrollLeft; } return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }, windowWidth : function() { if (window.innerWidth) return window.innerWidth else if (document.documentElement && document.documentElement.clientWidth) return document.documentElement.clientWidth; }, windowHeight : function() { if (window.innerHeight) return window.innerHeight else if (document.documentElement && document.documentElement.clientHeight) return document.documentElement.clientHeight; }, windowScroll : function() { var left=0, top=0; if (typeof pageYOffset != 'undefined') { return { left: window.pageXOffset, top: window.pageYOffset } } else if (document.documentElement) { return { left: document.documentElement.scrollLeft, top: document.documentElement.scrollTop } } }, addEventListener : function (el, event, listener, useCapture) { if (typeof useCapture == 'undefined') { useCapture = false; } if (el.addEventListener) { el.addEventListener(event, listener, useCapture); } else if (el.attachEvent) { el.attachEvent('on' + event, listener); } }, removeEventListener : function (el, event, listener, useCapture) { if (typeof useCapture == 'undefined') { useCapture = false; } if (el.removeEventListener) { el.removeEventListener(event, listener, useCapture); } else if (el.detachEvent) { el.detachEvent('on' + event, listener); } } }, setTransform : function (el, transform) { var es = el.style es.webkitTransform = es.MsTransform = es.msTransform = es.MozTransform = es.OTransform = es.transform = transform }, setTranslate : function (el, translate) { var es = el.style var pos = { x : translate.x || 0, y : translate.y || 0, z : translate.z || 0 }; var transformString = this.support.transforms3d ? 'translate3d('+(pos.x)+'px,'+(pos.y)+'px,'+(pos.z)+'px)' : 'translate('+(pos.x)+'px,'+(pos.y)+'px)'; es.webkitTransform = es.MsTransform = es.msTransform = es.MozTransform = es.OTransform = es.transform = transformString; if (!this.support.transforms) { es.left = pos.x+'px' es.top = pos.y+'px' } }, setTransition : function (el, duration) { var es = el.style es.webkitTransitionDuration = es.MsTransitionDuration = es.msTransitionDuration = es.MozTransitionDuration = es.OTransitionDuration = es.transitionDuration = duration+'ms'; }, /*================================================== Feature Detection ====================================================*/ support: { touch : (window.Modernizr && Modernizr.touch===true) || (function() { return !!(("ontouchstart" in window) || window.DocumentTouch && document instanceof DocumentTouch); })(), transforms3d : (window.Modernizr && Modernizr.csstransforms3d===true) || (function() { var div = document.createElement('div').style; return ("webkitPerspective" in div || "MozPerspective" in div || "OPerspective" in div || "MsPerspective" in div || "perspective" in div); })(), transforms : (window.Modernizr && Modernizr.csstransforms===true) || (function(){ var div = document.createElement('div').style; return ('transform' in div || 'WebkitTransform' in div || 'MozTransform' in div || 'msTransform' in div || 'MsTransform' in div || 'OTransform' in div); })(), transitions : (window.Modernizr && Modernizr.csstransitions===true) || (function(){ var div = document.createElement('div').style; return ('transition' in div || 'WebkitTransition' in div || 'MozTransition' in div || 'msTransition' in div || 'MsTransition' in div || 'OTransition' in div); })() }, browser : { ie8 : (function(){ var rv = -1; // Return value assumes failure. if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat(RegExp.$1); } return rv != -1 && rv < 9; })(), ie10 : window.navigator.msPointerEnabled } } /*========================= jQuery & Zepto Plugins ===========================*/ if (window.jQuery||window.Zepto) { (function($){ $.fn.swiper = function(params) { var s = new Swiper($(this)[0], params) $(this).data('swiper',s); return s; } })(window.jQuery||window.Zepto) } // component if ( typeof( module ) !== 'undefined' ) { module.exports = Swiper; } Array.prototype.getKeyByValue = function( value ) { for( var prop in this ) { if( this.hasOwnProperty( prop ) ) { if( this[ prop ] === value ) return prop; } } } jQuery(document).ready(function($){ var doneVideoInit = false; var $captionTrans = 0; //move parallax sliders to correct dom location var parallaxSlider = $('.parallax_slider_outer.first-section'); function parallaxSliderPos(){ if(parallaxSlider.parent().attr('class') == 'wpb_wrapper') { parallaxSlider.parents('.wpb_row').remove(); } parallaxSlider.insertBefore('.container-wrap'); } parallaxSliderPos(); var $smoothSrollWidth = ($('body').attr('data-smooth-scrolling') == '1') ? 0 : 0; //will come back to this if($('body > #boxed').length == 0 && $('.nectar-slider-wrap[data-full-width="true"]').parent().attr('id') != 'portfolio-extra' && $('.nectar-slider-wrap[data-full-width="true"]').parents('#post-area:not(".span_12")').length == 0){ $('.nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .nectar-slider-wrap').css('left', -(($(window).width()-$smoothSrollWidth)/2 - $('.main-content').width()/2))+'px'; $('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$(window).width()); } else if( $('.nectar-slider-wrap[data-full-width="true"]').parent().attr('id') == 'portfolio-extra' && $('#full_width_portfolio').length != 0){ $('.nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .nectar-slider-wrap').css('left', -(($(window).width()-$smoothSrollWidth)/2 - $('.main-content').width()/2))+'px'; $('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$(window).width()); } else { var $container = ($('body > #boxed').length == 0) ? '#post-area' : '.container-wrap'; //backup incase only slider is used with nothing else in boxed mode if($($container).width() == '0' && $('body > #boxed').length > 0) $container = '#boxed'; $('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$($container).width()); } //show slider once full width calcs have taken place $('.nectar-slider-wrap').show(); //set bg colors / textures after js has made the slider fullwidth $('.swiper-container, .swiper-slide').css('background-color','#000'); $('.video-texture').css('opacity','1'); //nectar sliders var $nectarSliders = []; $('.nectar-slider-wrap').each(function(i){ var $arrows = $(this).find('.swiper-container').attr('data-arrows'); var $bullets = $(this).find('.swiper-container').attr('data-bullets'); var $swipe = $(this).find('.swiper-container').attr('data-desktop-swipe'); var $loop = $(this).find('.swiper-container').attr('data-loop'); //swipe if($swipe == 'true' && $('#'+$(this).attr('id') +' .swiper-wrapper > div').length > 1 ){ var $grab = 1; var $desktopSwipe = 1; } else { var $grab = 0; var $desktopSwipe = 0; } //bullets if($bullets == 'true' && $(this).find('.swiper-wrapper > div').length > 1){ $bullets = '#'+$(this).attr('id')+' .slider-pagination'; } else { $bullets = null; } //loop $useLoop = ($loop == 'true' && $(this).find('.swiper-wrapper > div').length > 1 && !$('html').hasClass('no-video')) ? true : false; if($useLoop == false) $(this).find('.swiper-container').attr('data-loop','false'); $nectarSliders[i] = new Swiper('#'+$(this).attr('id')+' .swiper-container', { loop: $useLoop, grabCursor: $grab, touchRatio: 0.6, speed: 525, useCSS3Transforms: false, pagination : $bullets, simulateTouch: $desktopSwipe, onSlideChangeEnd: captionTransition, onSlideChangeStart: sliderArrowCount, onTouchMove: clearAutoplay, onFirstInit: nectarInit }); $nectarSliders[i].swipeReset(); //webkit looped slider first video fix if(navigator.userAgent.indexOf('Chrome') > 0) { if( jQuery(this).find('.swiper-slide:nth-child(2) video').length > 0 && jQuery(this).find('.swiper-container').attr('data-loop') == 'true') { var webmSource = jQuery(this).find('.swiper-slide:nth-child(2) video source[type="video/webm"]').attr('src') + "?"+Math.ceil(Math.random()*1000); var firstVideo = jQuery(this).find('.swiper-slide:nth-child(2) video').get(0); firstVideo.src = webmSource; firstVideo.load(); } } function nectarInit(){ if(doneVideoInit == true) return; //videos $('.swiper-slide .slider-video').mediaelementplayer({ enableKeyboard: false, iPadUseNativeControls: false, pauseOtherPlayers: false, // force iPhone's native controls iPhoneUseNativeControls: false, // force Android's native controls AndroidUseNativeControls: false }); //if using pp - init it after slide loads if($().prettyPhoto) prettyPhotoInit(); doneVideoInit = true; } //Navigation arrows if($arrows == 'true' && $('#'+$(this).attr('id') +' .swiper-wrapper > div').length > 1 ){ $('.slide-count i').transition({ scale: 0.5, opacity: 0 }); //hover event $('.swiper-container .slider-prev, .swiper-container .slider-next').hover(function(){ $(this).find('.slide-count i').clearQueue().stop(true,true).delay(100).transition({ scale: 1, opacity: 1 },200); $(this).stop(true,true).animate({ 'width' : '120px' },300,'easeOutCubic'); $(this).find('.slide-count span').clearQueue().stop().delay(100).animate({ 'opacity' : '1' },225,'easeOutCubic'); },function(){ $('.slide-count i').stop(true,true).transition({ scale: 0, opacity: 0 },200); $(this).stop().delay(150).animate({ 'width' : '64px' },300,'easeOutCubic'); $(this).find('.slide-count span').stop(true,true).animate({ 'opacity' : '0' },200,'easeOutCubic'); }); //add slide counts var $slideCount = ($(this).find('.swiper-container').attr('data-loop') != 'true' ) ? $('#'+$(this).attr('id') + ' .swiper-wrapper > div').length : $('#'+$(this).attr('id') + ' .swiper-wrapper > div').length - 2; //ie8 if($('html').hasClass('no-video')) $slideCount = $('#'+$(this).attr('id') + ' .swiper-wrapper > div').length; $('#'+$(this).attr('id')+' .slider-prev .slide-count .slide-total').html( $slideCount ); $('#'+$(this).attr('id')+' .slider-next .slide-count .slide-total').html( $slideCount ); //prev $('#'+$(this).attr('id')+' .slider-prev').click(function(e) { if($(this).hasClass('inactive')) return false; var $that = $(this); //non looped slider if($(this).parents('.swiper-container').attr('data-loop') != 'true') { if( $(this).parents('.swiper-container').find('.swiper-slide-active').index()+1 == 1 && !$('html').hasClass('no-video')){ //make sure the animation is complete var $timeout; clearTimeout($timeout); $timeout = setTimeout(function(){ $that.removeClass('inactive'); } ,700); $(this).parents('.swiper-container').find('.swiper-wrapper').stop(true,false).css('transition','none').animate({ 'left' : parseInt($(this).parents('.swiper-container').find('.swiper-wrapper').css('left')) + 20 },200,function(){ $(this).parents('.swiper-container').find('.swiper-wrapper').stop(true,false).css('transition','left,top'); $nectarSliders[i].swipeReset(); }); $(this).addClass('inactive'); } } e.preventDefault(); $nectarSliders[i].swipePrev(); }); //next $('#'+$(this).attr('id')+' .slider-next').click(function(e) { if($(this).hasClass('inactive')) return false; var $that = $(this); var $slideNum = $(this).parents('.swiper-container').find('.swiper-wrapper > div').length; //non looped slider if($(this).parents('.swiper-container').attr('data-loop') != 'true') { if( $(this).parents('.swiper-container').find('.swiper-slide-active').index()+1 == $slideNum && !$('html').hasClass('no-video')) { //make sure the animation is complete var $timeout; clearTimeout($timeout); $timeout = setTimeout(function(){ $that.removeClass('inactive'); } ,700); $(this).parents('.swiper-container').find('.swiper-wrapper').stop(true,false).css('transition','none').animate({ 'left' : parseInt($(this).parents('.swiper-container').find('.swiper-wrapper').css('left')) - 20 },200,function(){ $(this).parents('.swiper-container').find('.swiper-wrapper').stop(true,false).css('transition','left,top'); $nectarSliders[i].swipeReset(); }); $(this).addClass('inactive'); } } e.preventDefault(); $nectarSliders[i].swipeNext(); }); } //Clickable pagination if($bullets != null && $('#'+$(this).attr('id') +' .swiper-wrapper > div').length > 1 ){ $('#'+$(this).attr('id')+' .slider-pagination .swiper-pagination-switch').click(function(){ $nectarSliders[i].swipeTo($(this).index()); }); } }); //add class to first video slide $('.swiper-wrapper').each(function(){ if($(this).find('.swiper-slide:nth-child(2) video').length > 0) $(this).find('.swiper-slide:nth-child(2)').addClass('first_video_slide'); }); //initial slide load $('.nectar-slider-wrap').each(function(i){ var $sliderWrapCount = $('.nectar-slider-wrap').length; var $that = $(this); if($(this).find('.swiper-slide-active video').length > 0){ if(!$('html').hasClass('no-video')){ $(this).find('.swiper-slide-active:first video').get(0).addEventListener('canplay',function(){ showSliderControls(); resizeToCover(); sliderLoadIn($that); captionTransition($nectarSliders[i]); }); } //ie8 else { showSliderControls(); resizeToCover(); sliderLoadIn($that); captionTransition($nectarSliders[i]); } } else { var $firstBg = $(this).find('.swiper-slide-active').attr('style'); var pattern = /url\(["']?([^'")]+)['"]?\)/; var match = pattern.exec($firstBg); if (match) { var slideImg = new Image(); slideImg.src = match[1]; $(slideImg).load(function(){ showSliderControls(); sliderLoadIn($that); captionTransition($nectarSliders[i]); }); } } //mobile check if(navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)){ captionTransition($nectarSliders[i]); showSliderControls(); resizeToCover(); $('.nectar-slider-wrap').find('.nectar-slider-loading').fadeOut(800,'easeInOutExpo'); $('.nectar-slider-wrap .mobile-video-image').show(); $('.nectar-slider-wrap .video-wrap').remove(); } }); var $animating = false; //fullscreen height fullscreenSlider(); function fullscreenSlider(){ var $adminBarHeight = ($('#wpadminbar').length > 0) ? 28 : 0 ; $('.nectar-slider-wrap').each(function(){ if($(this).attr('data-fullscreen') == 'true' && $(this).attr('data-full-width') == 'true') { //first slider on page if($(this).hasClass('first-section') && $(this).index() == 0){ $(this).find('.swiper-container').attr('data-height',$(window).height() - $(this).offset().top + 2); } //first parallax slider on page else if($(this).parents('.parallax_slider_outer').length > 0 && $(this).parents('#full_width_portfolio').length == 0){ $(this).find('.swiper-container').attr('data-height',$(window).height() - $(this).parent().offset().top + 2); } //first portfolio slider on page else if($(this).parents('#full_width_portfolio').length > 0 && $(this).attr('data-parallax') != 'true' && $(this).index() == 0){ $(this).find('.swiper-container').attr('data-height',$(window).height() - $(this).offset().top + 2); } //first portfolio parallax slider on page else if($(this).parents('#full_width_portfolio').length > 0 && $(this).attr('data-parallax') == 'true'){ $(this).find('.swiper-container').attr('data-height',$(window).height() - $(this).offset().top + 2 ); } //all others else { $(this).find('.swiper-container').attr('data-height',$(window).height()); } } }); } $(window).resize(fullscreenSlider); //responsive slider var $sliderHeights = []; var $existingSliders = []; ////get slider heights $('.swiper-container').each(function(i){ $sliderHeights[i] = parseInt($(this).attr('data-height')); $existingSliders[i] = $(this).parent().attr('id'); }); ////helper function function sliderColumnDesktopWidth(parentCol) { var $parentColWidth = 1100; var $columnNumberParsed = $(parentCol).attr('class').match(/\d+/); if($columnNumberParsed == '2') { $parentColWidth = 170 } else if($columnNumberParsed == '3') { $parentColWidth = 260 } else if($columnNumberParsed == '4') { $parentColWidth = 340 } else if($columnNumberParsed == '6') { $parentColWidth = 530 } else if($columnNumberParsed == '8') { $parentColWidth = 700 } else if($columnNumberParsed == '9') { $parentColWidth = 805 } else if($columnNumberParsed == '10') { $parentColWidth = 916.3 } else if($columnNumberParsed == '12') { $parentColWidth = 1100 } return $parentColWidth; } sliderSize(); $(window).resize(sliderSize); function sliderSize(){ //check for mobile first if( window.innerWidth < 1000 && window.innerWidth > 690 ) { //fullwidth sliders $('.nectar-slider-wrap[data-full-width="true"]:not([data-fullscreen="true"])').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); $(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/1.4 ) }); //column sliders $('.nectar-slider-wrap[data-full-width="false"]').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); var $currentSliderHeight = $sliderHeights[currentKey]; var $parentCol = ($(this).parents('.wpb_column').length > 0) ? $(this).parents('.wpb_column') : $(this).parents('.col') ; if($parentCol.length == 0) $parentCol = $('.main-content'); var $parentColWidth = sliderColumnDesktopWidth($parentCol); var $aspectRatio = $currentSliderHeight/$parentColWidth; $(this).find('.swiper-container').attr('data-height',$aspectRatio*$parentCol.width()); }); //boxed sliders $('.nectar-slider-wrap[data-full-width="boxed-full-width"]').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); $(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/1.9 ) }); } else if( window.innerWidth <= 690 ) { //fullwidth sliders $('.nectar-slider-wrap[data-full-width="true"]:not([data-fullscreen="true"])').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); $(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/2.7 ) }); //column sliders $('.nectar-slider-wrap[data-full-width="false"]').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); var $currentSliderHeight = $sliderHeights[currentKey]; var $parentCol = ($(this).parents('.wpb_column').length > 0) ? $(this).parents('.wpb_column') : $(this).parents('.col') ; if($parentCol.length == 0) $parentCol = $('.main-content'); var $parentColWidth = sliderColumnDesktopWidth($parentCol); var $aspectRatio = $currentSliderHeight/$parentColWidth; $(this).find('.swiper-container').attr('data-height',$aspectRatio*$parentCol.width()); }); //boxed sliders $('.nectar-slider-wrap[data-full-width="boxed-full-width"]').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); $(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/2.9 ) }); } else if( window.innerWidth < 1300 && window.innerWidth >= 1000 ) { //fullwidth sliders $('.nectar-slider-wrap[data-full-width="true"]:not([data-fullscreen="true"])').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); $(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/1.2 ) }); //column sliders $('.nectar-slider-wrap[data-full-width="false"]').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); var $currentSliderHeight = $sliderHeights[currentKey]; var $parentCol = ($(this).parents('.wpb_column').length > 0) ? $(this).parents('.wpb_column') : $(this).parents('.col') ; if($parentCol.length == 0) $parentCol = $('.main-content'); var $parentColWidth = sliderColumnDesktopWidth($parentCol); var $aspectRatio = $currentSliderHeight/$parentColWidth; $(this).find('.swiper-container').attr('data-height',$aspectRatio*$parentCol.width()); }); //boxed sliders $('.nectar-slider-wrap[data-full-width="boxed-full-width"]').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); $(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/1.2 ) }); } else { //fullwidth sliders $('.nectar-slider-wrap[data-full-width="true"]:not([data-fullscreen="true"])').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); $(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey] ) }); //boxed sliders $('.nectar-slider-wrap[data-full-width="false"], .nectar-slider-wrap[data-full-width="boxed-full-width"]').each(function(i){ currentKey = $existingSliders.getKeyByValue($(this).attr('id')); $(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey] ) }); } } //slider height var min_w = 1500; // minimum video width allowed var vid_w_orig; // original video dimensions var vid_h_orig; vid_w_orig = 1280; vid_h_orig = 720; var $headerHeight = $('header').height()-1; $(window).resize(function () { resizeToCover(); slideContentPos(); }); $(window).trigger('resize'); function resizeToCover() { $('.nectar-slider-wrap').each(function(i){ //width resize if($('body > #boxed').length == 0 && $('.nectar-slider-wrap[data-full-width="true"]').parent().attr('id') != 'portfolio-extra' && $(this).parents('#post-area:not(".span_12")').length == 0){ $('.nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .nectar-slider-wrap').css('left', -(($(window).width()-$smoothSrollWidth)/2 - $('.main-content').width()/2))+'px'; $('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$(window).width()); } else if( $('.nectar-slider-wrap[data-full-width="true"]').parent().attr('id') == 'portfolio-extra' && $('#full_width_portfolio').length != 0){ $('.nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .nectar-slider-wrap').css('left', -(($(window).width()-$smoothSrollWidth)/2 - $('.main-content').width()/2))+'px'; $('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$(window).width()); } else { var $container = ($('body > #boxed').length == 0) ? '#post-area' : '.container-wrap'; //backup incase only slider is used with nothing else in boxed mode if($($container).width() == '0' && $('body > #boxed').length > 0) $container = '#boxed'; $('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$($container).width()); } var $sliderHeight = parseInt($(this).find('.swiper-container').attr('data-height')); var isFullWidthCompatible = ($(this).attr('data-full-width') == 'true') ? 'true' : 'false'; if($(this).parent().attr('id') == 'portfolio-extra' && $('#full_width_portfolio').length == 0 || $(this).parents('#post-area').length > 0) { isFullWidthCompatible = 'false'; }; var $sliderWidth = (isFullWidthCompatible == 'true') ? $(window).width()-$smoothSrollWidth : $(this).width(); $(this).parents('.parallax_slider_outer').css('height',$sliderHeight); $(this).css('height',$sliderHeight); $(this).find('.swiper-container, .swiper-slide').css({'height':$sliderHeight+2, 'top':'-1px'}); $(this).find('.swiper-container').css('width', $sliderWidth); //$(this).find('.swiper-slide').css('width', $sliderWidth); // set the video viewport to the window size $(this).find('.video-wrap').width($sliderWidth+2); $(this).find('.video-wrap').height($sliderHeight+2); // use largest scale factor of horizontal/vertical var scale_h = $sliderWidth / vid_w_orig; var scale_v = ($sliderHeight - $headerHeight) / vid_h_orig; var scale = scale_h > scale_v ? scale_h : scale_v; //update minium width to never allow excess space min_w = 1280/720 * ($sliderHeight+20); // don't allow scaled width < minimum video width if (scale * vid_w_orig < min_w) {scale = min_w / vid_w_orig;} // now scale the video $(this).find('video, .mejs-overlay, .mejs-poster').width(Math.ceil(scale * vid_w_orig +2)); $(this).find('video, .mejs-overlay, .mejs-poster').height(Math.ceil(scale * vid_h_orig +2)); // and center it by scrolling the video viewport $(this).find('.video-wrap').scrollLeft(($(this).find('video').width() - $sliderWidth) / 2); $(this).find('.swiper-slide').each(function(){ //video alignment if($(this).find('.video-wrap').length > 0){ //align middle if($(this).attr('data-bg-alignment') == 'center'){ $(this).find('.video-wrap, .mejs-overlay, .mejs-poster').scrollTop(($(this).find('video').height() - ($sliderHeight)) / 2); } //align bottom else if($(this).attr('data-bg-alignment') == 'bottom'){ $(this).find('.video-wrap').scrollTop(($(this).find('video').height() - ($sliderHeight+2))); } //align top else { $(this).find('.video-wrap').scrollTop(0); } } }); }); }; //caption transitions function captionTransition(obj){ resizeToCover(); var $containerClass; (typeof obj == 'undefined') ? $containerClass = 'div[id^=ns-id-]' : $containerClass = '#'+$(obj.container).parents('.nectar-slider-wrap').attr('id'); ; var fromLeft = Math.abs(parseInt($($containerClass+' .swiper-wrapper').css('left'))); var currentSlide = Math.round(fromLeft/$($containerClass+' .swiper-slide').width()); var $slideNum = $($containerClass+':first .swiper-wrapper > div').length; if(isNaN(currentSlide)) currentSlide = 0; //make sure user isn't going back to same slide if( $($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').find('.content *').length > 0 ) { if($($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').find('.content *').css('opacity') != '0' && !$('html').hasClass('no-video')) { //play video if there's one playVideoBG(currentSlide + 1, $containerClass); if(!$($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').hasClass('autorotate-shown')) { return false; } else { $($containerClass+' .swiper-slide').removeClass('autorotate-shown'); } } } //hide all if(!$('html').hasClass('no-video')) { $($containerClass+' .swiper-slide .content p, '+$containerClass+' .swiper-slide .content h2, '+$containerClass+' .swiper-slide .content .buttons').stop(true,true).animate({'opacity':0, 'padding-top': 25},1); } //pause video if there's one $($containerClass+' .swiper-slide').each(function(){ if($(this).find('.video-wrap video').length > 0 && !$('html').hasClass('no-video')) { $(this).find('.video-wrap video').get(0).pause(); } }); $($containerClass+' .swiper-slide:not(".swiper-slide-active")').each(function(){ if($(this).find('.video-wrap video').length > 0) { if($(this).find('.video-wrap video').get(0).currentTime != 0 ) $(this).find('.video-wrap video').get(0).currentTime = 0; } }); if($($containerClass +' .swiper-container').attr('data-loop') == 'true') { //webkit video fix if( $($containerClass+' .swiper-slide-active').index()+1 == 2 && $($containerClass+' .swiper-slide-active video').length > 0 && !$('html').hasClass('no-video')) { $($containerClass+' .swiper-slide:last-child').find('.video-wrap video').get(0).play(); $($containerClass+' .swiper-slide:last-child').find('.video-wrap video').get(0).pause(); } if( $($containerClass+' .swiper-slide-active').index()+1 == $slideNum-1 && $($containerClass+' .swiper-slide-active video').length > 0 && !$('html').hasClass('no-video')) { $($containerClass+' .swiper-slide:first-child').find('.video-wrap video').get(0).play(); $($containerClass+' .swiper-slide:first-child').find('.video-wrap video').get(0).pause(); } if($($containerClass+' .swiper-slide-active').index()+1 != 2 && $($containerClass+' .swiper-slide:nth-child(2) video').length > 0 && !$('html').hasClass('no-video')) { $($containerClass+' .swiper-slide:last-child').find('.video-wrap video').get(0).play(); $($containerClass+' .swiper-slide:last-child').find('.video-wrap video').get(0).pause(); $($containerClass+' .swiper-slide:nth-child(2) video').get(0).pause(); if($($containerClass+' .swiper-slide:nth-child(2) video').get(0).currentTime != 0 ) $($containerClass+' .swiper-slide:nth-child(2) video').get(0).currentTime = 0; } //also show duplicate slide if applicable ////first if( $($containerClass+' .swiper-slide-active').index()+1 == $slideNum-1 ){ $($containerClass+' .swiper-slide:nth-child(1)').find('.content').children().each(function(i){ $(this).stop().delay(i*90).animate({ 'opacity' : 1, 'padding-top' : 0 },{ duration: 400, easing: 'easeOutQuad'}); }); } ////last if( $($containerClass+' .swiper-slide-active').index()+1 == 2 ){ $($containerClass+' .swiper-slide:nth-child('+ ($slideNum) + ')').find('.content').children().each(function(i){ $(this).stop().delay(i*90).animate({ 'opacity' : 1, 'padding-top' : 0 },{ duration: 400, easing: 'easeOutQuad'}); }); } }//if using loop //play video if there's one playVideoBG(currentSlide + 1, $containerClass); //fadeIn active slide $($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').find('.content').children().each(function(i){ $(this).stop().delay(i*90).animate({ 'opacity' : 1, 'padding-top' : 0 },{ duration: 400, easing: 'easeOutQuad'}); }); //light and dark controls if($($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').attr('data-color-scheme') == 'dark') { $($containerClass).find('.slider-pagination').addClass('dark-cs'); $($containerClass).find('.slider-prev, .slider-next').addClass('dark-cs'); } else { $($containerClass).find('.slider-pagination').removeClass('dark-cs'); $($containerClass).find('.slider-prev, .slider-next').removeClass('dark-cs'); } $captionTrans++; if($captionTrans == $('.swiper-wrapper').length) { $('div.first_video_slide').addClass('nulled') } } //used in caption transition function playVideoBG(nthChild, containerClass){ if($(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.video-wrap video').length > 0){ if(!$('html').hasClass('no-video')) $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.video-wrap video').get(0).play(); if(!$(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-overlay.mejs-overlay-play').hasClass('playing') && $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-overlay.mejs-overlay-play').hasClass('mobile-played')) { $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-overlay.mejs-overlay-play').addClass('playing'); } if(!$(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-poster').hasClass('playing') && $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-poster').hasClass('mobile-played')) $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-poster').addClass('playing'); var $that = $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-overlay.mejs-overlay-play'); var $that2 = $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-poster'); if($that.hasClass('playing') && $that.hasClass('mobile-played')) { setTimeout(function(){ $that.addClass('behind-buttons'); $that2.addClass('behind-buttons');},200); } else { $that.removeClass('behind-buttons'); $that2.removeClass('behind-buttons'); } } } var $startingSlide = null; function slideContentPos(){ $('.swiper-wrapper').each(function(){ //etxra space if first slider in section var $extraHeight = ($(this).parents('.nectar-slider-wrap').hasClass('first-section') || $(this).parents('.parallax_slider_outer').hasClass('first-section')) ? 30 : 0; var $sliderHeight = parseInt($(this).parents('.swiper-container').attr('data-height')); $(this).find('.swiper-slide').each(function(){ var $contentHeight = $(this).find('.content').height(); var $contentItems = $(this).find('.content > *').length; if($(this).find('.content > *').css('padding-top') == '25px') $contentHeight = $contentHeight - 25*$contentItems; if($(this).attr('data-y-pos') == 'top'){ var $topHeight = ($contentHeight/2) < (($sliderHeight/4) - 30) ? (($sliderHeight/4) - ($contentHeight/2)) + 20 : $sliderHeight/8; $(this).find('.content').css('top', $topHeight + 'px'); } else if($(this).attr('data-y-pos') == 'middle') { $(this).find('.content').css('top', ($sliderHeight/2) - ($contentHeight/2) + 'px'); } else { if($contentHeight > 180) { $(this).find('.content').css('top', ($sliderHeight/2) - ($contentHeight/10) + 'px'); } else { $(this).find('.content').css('top', ($sliderHeight/2) + ($contentHeight/9) + 'px'); } } }); }); } function showSliderControls() { $('.swiper-container .slider-prev, .swiper-container .slider-next, .slider-pagination').animate({'opacity':1},550,'easeOutSine'); } var sliderLength = $('.swiper-container').length; var sliderLoadedLength = 0; function sliderLoadIn(slider) { slider.find('.nectar-slider-loading').fadeOut(800,'easeInOutExpo'); ///make sure to init smooth scrolling after slider height exists var $smoothActive = $('body').attr('data-smooth-scrolling'); if( $smoothActive == 1 && $(window).width() > 690 && $('body').outerHeight(true) > $(window).height() && $('#ascrail2000').length == 0 && !navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)){ niceScrollInit(); resizeToCover(); } //check for sliders in tabbed sliderLoadedLength++; if($('.tabbed').find('.swiper-container').length > 0 && sliderLoadedLength == sliderLength) { setTimeout(function(){ $('.tabbed > ul li:first-child a').click(); }, 200); } } //play video user is hovering over $('.swiper-slide').mouseover(function(){ if($(this).find('video').length > 0 && $(this).find('video').get(0).paused == true && $animating == false){ $(this).find('video').get(0).play(); } }); //mobile play event $('body').on('click', '.mejs-overlay.mejs-overlay-play',function(){ $(this).toggleClass('playing'); $(this).addClass('mobile-played'); $(this).parent().find('.mejs-poster').toggleClass('playing'); $(this).parent().find('.mejs-poster').addClass('mobile-played'); var $that = $(this); var $that2 = $(this).parent().find('.mejs-poster'); if($(this).hasClass('playing') && $(this).hasClass('mobile-played')) { setTimeout(function(){ $that.addClass('behind-buttons'); $that2.addClass('behind-buttons'); },200); } else { setTimeout(function(){ $that.removeClass('behind-buttons'); $that2.removeClass('behind-buttons'); },1); } }); //autoplay var autoplay = []; var sliderAutoplayCount = -1; var $sliderHeight = parseInt($(this).find('.swiper-container').attr('data-height')); var portfolioHeaderHeight = ($('.project-title.parallax-effect').length > 0) ? 100 : 0; $('.nectar-slider-wrap').each(function(i){ var $autoplayVal = $(this).attr('data-autorotate'); var $that = $(this); var $sliderNum = i; if(typeof $autoplayVal !='undefined' && $autoplayVal.length != '0' && parseInt($autoplayVal)) { nectarSlideRotateInit($that,$autoplayVal,$sliderNum); } }); function nectarSlideRotateInit(slider,interval,sliderNum){ autoplay[sliderAutoplayCount] = setInterval(function(){ nectarSlideRotate(slider, sliderNum); } ,interval); $('#'+slider.attr('id')).attr('autoplay-id',sliderAutoplayCount); $('#'+slider.attr('id') + ' a.slider-prev, #'+slider.attr('id') + ' a.slider-next, #' + slider.attr('id') + ' .slider-pagination span').click(function(e){ if(typeof e.clientY != 'undefined'){ clearInterval(autoplay[$('#'+slider.attr('id')).attr('autoplay-id')]); } }); sliderAutoplayCount++; } function nectarSlideRotate(slider, sliderNum){ if($nectarSliders[sliderNum].activeIndex + 1 < $(slider).find('.swiper-wrapper > div.swiper-slide').length){ $nectarSliders[sliderNum].swipeNext(); } else { $nectarSliders[sliderNum].swipeTo(0,800); } } function clearAutoplay(e){ var $autoplayVal = $('#'+$(e.container).parent().attr('id')).attr('data-autorotate'); if(typeof $autoplayVal !='undefined' && $autoplayVal.length != '0' && parseInt($autoplayVal)) { clearInterval(autoplay[$('#'+$(e.container).parent().attr('id')).attr('autoplay-id')]); } } var animationQueue = null; function sliderArrowCount(e){ //cache slider obj var $obj = e; $animating = true; var $slideNum = $($obj.container).find('.swiper-wrapper > div').length; $activeIndex = ($($obj.container).attr('data-loop') == 'true') ? $obj.activeIndex : $obj.activeIndex + 1; //add slide counts $($obj.container).find('.slider-prev .slide-count .slide-current').html( $activeIndex ); $($obj.container).find('.slider-next .slide-count .slide-current').html( $activeIndex ); if($($obj.container).attr('data-loop') == 'true'){ //duplicate first slide if( $($obj.container).find('.swiper-slide-active').index()+1 == 1) { $($obj.container).find('.slider-next .slide-count .slide-current, .slider-prev .slide-count .slide-current').html( $slideNum - 2 ); } //duplicate last slide else if( $($obj.container).find('.swiper-slide-active').index()+1 == $slideNum) { $($obj.container).find('.slider-next .slide-count .slide-current, .slider-prev .slide-count .slide-current').html( 1 ); } } if($obj.activeIndex >= 10) { $($obj.container).find('.slider-next .slide-count .slide-current').addClass('double-digits'); } else { $($obj.container).find('.slider-next .slide-count .slide-current').removeClass('double-digits'); } $($obj.container).find('.swiper-slide:not(".swiper-slide-active")').each(function(){ if($(this).find('.video-wrap video').length > 0) { if($(this).find('.video-wrap video').get(0).currentTime != 0 ) $(this).find('.video-wrap video').get(0).currentTime = 0; } }); //don't allow swiping on duplicate transition if($($obj.container).attr('data-loop') == 'true'){ if($obj.previousIndex == 1 && $obj.activeIndex == 0 || $obj.previousIndex == $slideNum - 2 && $obj.activeIndex == $slideNum - 1 ){ $('.swiper-slide').addClass('duplicate-transition'); } } clearTimeout(animationQueue); animationQueue = setTimeout(function(){ $animating = false; $('.swiper-slide').removeClass('duplicate-transition'); },800) } //functions to add or remove slider for webkit parallax fix function hideSlider() { if( $(window).scrollTop()/($sliderHeight + portfolioHeaderHeight + 125) >= 1){ $('.parallax_slider_outer .nectar-slider-wrap, .project-title.parallax-effect').css('visibility','hidden').hide(); $(window).bind('scroll',showSlider); $(window).unbind('scroll',hideSlider); } } function showSlider() { if( $(window).scrollTop()/($sliderHeight + portfolioHeaderHeight + 125) <= 1){ $('.parallax_slider_outer .nectar-slider-wrap, .project-title.parallax-effect').css('visibility','visible').show(); slideContentPos(); resizeToCover(); //show content on current slide - could have been hidden from autorotate when slider was hidden if($('.parallax_slider_outer').length > 0) { var fromLeft = Math.abs(parseInt($('.parallax_slider_outer .nectar-slider-wrap .swiper-wrapper').css('left'))); var currentSlide = Math.round(fromLeft/$('.parallax_slider_outer .nectar-slider-wrap .swiper-slide').width()); $('.parallax_slider_outer .swiper-wrapper .swiper-slide:eq(' + currentSlide + ')').find('.content').children().each(function(i){ $(this).stop(true,true).css({ 'opacity' : 1, 'padding-top' : 0 }); }); $('.parallax_slider_outer .swiper-wrapper .swiper-slide:eq(' + currentSlide + ')').addClass('autorotate-shown'); } $(window).bind('scroll',hideSlider); $(window).unbind('scroll',showSlider); } } function sliderCorrectDisplayCheck() { if( $(window).scrollTop()/($sliderHeight + portfolioHeaderHeight + 125) >= 1){ hideSlider(); } $(window).unbind('scroll',sliderCorrectDisplayCheck); } var $sliderHeight = parseInt($('.parallax_slider_outer.first-section .swiper-container').attr('data-height')); var $adminBarHeight = ($('#wpadminbar').length > 0) ? 28 : 0; function sliderParallaxInit() { if($('#portfolio-extra').length > 0 && $('#full_width_portfolio').length == 0) { return false; } $(window).scroll(function(){ if($('#boxed').length == 0) { if(navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) { return false; } $('.parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"]').stop(true,true).transition({ y: $(window).scrollTop()*-.2 },0); $('.parallax_slider_outer.first-section .swiper-slide:not(".static"):not(".caption-no-fade") .content, .parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"] .swiper-container .slider-next, .parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"] .swiper-container .slider-prev').stop(true,true).transition({ y: $(window).scrollTop()*-.14 },0); $('#full_width_portfolio .project-title.parallax-effect').transition({ y: $(window).scrollTop()*-.2 },0); $('.parallax_slider_outer.first-section .swiper-slide:not(".caption-no-fade") .content, .parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"] .swiper-container .slider-next, .parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"] .swiper-container .slider-prev').css('opacity', 1-($(window).scrollTop()/($sliderHeight-120)) ); } }); //hide slider to not mess up parallax section var portfolioHeaderHeight = ($('.project-title.parallax-effect').length > 0) ? 100 : 0; function displayParallaxSliderInit() { if( $(window).scrollTop()/($sliderHeight + portfolioHeaderHeight + 90) >= 1){ $(window).bind('scroll', hideSlider); $(window).unbind('scroll',showSlider); } else { $(window).bind('scroll', showSlider); $(window).unbind('scroll', hideSlider); } } displayParallaxSliderInit(); $(window).bind('scroll',sliderCorrectDisplayCheck); $('.page-header-no-bg, #page-header-wrap, #page-header-bg').remove(); $('.project-title').addClass('parallax-effect').css({ 'top': $('#header-space').outerHeight() + $adminBarHeight + 'px' }); //caption alignment if portfolio fullwidth parallax if($('.project-title.parallax-effect').length > 0) { $('.parallax_slider_outer.first-section .swiper-slide .content, .nectar-slider-wrap.first-section .swiper-slide .content').css('margin-top','0px'); $('.swiper-container .slider-prev, .swiper-container .slider-next').css('margin-top','-28px'); } //if using wooCommerce sitewide notice if($('.demo_store').length > 0) $('.project-title.parallax-effect').css('margin-top','-25px'); if($('#full_width_portfolio').length > 0){ $('.parallax_slider_outer.first-section').css('margin-top','93px'); } $(window).resize(function(){ $sliderHeight = parseInt($('.parallax_slider_outer.first-section .swiper-container').attr('data-height')); $('.project-title').css({ 'top': $('#header-space').outerHeight() + $adminBarHeight + 'px' }); }); } //parallax if($('.parallax_slider_outer').length > 0 && !navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)){ sliderParallaxInit(); } else if($('.parallax_slider_outer').length > 0 && navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)) { $('.project-title').addClass('parallax-effect').css({ 'top': $('#header-space').outerHeight() + $adminBarHeight + 'px' }); } function niceScrollInit(){ $("html").niceScroll({ scrollspeed: 60, mousescrollstep: 40, cursorwidth: 15, cursorborder: 0, cursorcolor: '#2D3032', cursorborderradius: 6, autohidemode: false, horizrailenabled: false }); if($('#boxed').length == 0){ $('body, body #header-outer, body #header-secondary-outer, body #search-outer').css('padding-right','16px'); } $('html').addClass('no-overflow-y'); } //pause video backgrounds if popup video player is started $('.portfolio-items a.pp:contains(Video), .swiper-container .buttons a.pp').click(function(){ $('.swiper-slide').each(function(){ if($(this).find('.video-wrap video').length > 0) { $(this).find('.video-wrap video').get(0).pause(); } }); }); //solid button hover effect $.cssHooks.backgroundColor = { get: function(elem) { if (elem.currentStyle) var bg = elem.currentStyle["backgroundColor"]; else if (window.getComputedStyle) var bg = document.defaultView.getComputedStyle(elem, null).getPropertyValue("background-color"); if (bg.search("rgb") == -1) return bg; else { bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]); } } } function shadeColor(color, shade) { var colorInt = parseInt(color.substring(1),16); var R = (colorInt & 0xFF0000) >> 16; var G = (colorInt & 0x00FF00) >> 8; var B = (colorInt & 0x0000FF) >> 0; R = R + Math.floor((shade/255)*R); G = G + Math.floor((shade/255)*G); B = B + Math.floor((shade/255)*B); var newColorInt = (R<<16) + (G<<8) + (B); var newColorStr = "#"+newColorInt.toString(16); return newColorStr; } $('.swiper-slide').each(function(){ $(this).find('.solid_color').each(function(){ var $currentColor = $(this).find('a').css('background-color'); var $hoverColor = shadeColor($currentColor, -16); $(this).find('a').hover(function(){ $(this).attr('style','background-color:'+$hoverColor+'!important;'); },function(){ $(this).attr('style',''); }); }); }); function prettyPhotoInit(){ $(".nectar-slider-wrap a[rel^='prettyPhoto']").prettyPhoto({ theme: 'dark_rounded', allow_resize: true, default_width: 690, opacity: 0.85, animation_speed: 'normal', default_height: 388, social_tools: '', markup: '<div class="pp_pic_holder"> \ <div class="ppt">&nbsp;</div> \ <div class="pp_details"> \ <div class="pp_nav"> \ <a href="#" class="pp_arrow_previous"> <i class="icon-salient-left-arrow-thin icon-default-style"></i> </a> \ <a href="#" class="pp_arrow_next"> <i class="icon-salient-right-arrow-thin icon-default-style"></i> </a> \ <p class="currentTextHolder">0/0</p> \ </div> \ <a class="pp_close" href="#">Close</a> \ </div> \ <div class="pp_content_container"> \ <div class="pp_left"> \ <div class="pp_right"> \ <div class="pp_content"> \ <div class="pp_fade"> \ <div class="pp_hoverContainer"> \ </div> \ <div id="pp_full_res"></div> \ </div> \ </div> \ </div> \ </div> \ </div> \ </div> \ <div class="pp_loaderIcon"></div> \ <div class="pp_overlay"></div>' }); } });
calebcauthon/twoshakesofhappy_www
wp-content/themes/salient/js/nectar-slider.js
JavaScript
gpl-2.0
143,574
//>>built define("dojox/grid/enhanced/nls/nb/EnhancedGrid",{singleSort:"Enkel sortering",nestedSort:"Nestet sortering",ascending:"Klikk for \u00e5 sortere stigende",descending:"Klikk for \u00e5 sortere synkende",sortingState:"${0} - ${1}",unsorted:"Ikke sorter denne kolonnen",indirectSelectionRadio:"Rad ${0}, enkeltvalg, valgknapp",indirectSelectionCheckBox:"Rad ${0}, flervalg, avmerkingsboks",selectAll:"Velg alle"}); //@ sourceMappingURL=EnhancedGrid.js.map
joshuacoddingyou/php
public/scripts/dojox/grid/enhanced/nls/nb/EnhancedGrid.js
JavaScript
gpl-2.0
462
(function($){ "use strict"; // wpb_el_type_position $('.wpb-element-edit-modal .ewf-position-box div').click(function(){ // e.preventDefault(); $(this).closest('.ewf-position-box').find('div').removeClass('active'); $(this).addClass('active'); console.log('execute param position shit!'); var value = 'none'; if ($(this).hasClass('ewf-pb-top')) { value = 'top'; } if ($(this).hasClass('ewf-pb-top-right')) { value = 'top-right'; } if ($(this).hasClass('ewf-pb-top-left')) { value = 'top-left'; } if ($(this).hasClass('ewf-pb-bottom')) { value = 'bottom'; } if ($(this).hasClass('ewf-pb-bottom-right')) { value = 'bottom-right'; } if ($(this).hasClass('ewf-pb-bottom-left')) { value = 'bottom-left'; } if ($(this).hasClass('ewf-pb-left')) { value = 'left'; } if ($(this).hasClass('ewf-pb-right')) { value = 'right'; } $(this).closest('.edit_form_line').find('input.wpb_vc_param_value').val(value); }); })(window.jQuery);
narendra-addweb/SwitchedOn
wp-content/themes/sapphire-wp/framework/composer/params/ewf-param-position/ewf-param-position.js
JavaScript
gpl-2.0
1,050
import React, { useContext, useEffect, Fragment } from "react" import { Typography } from "@material-ui/core" import EventsContext from "../context/EventsContext" import TitleContext from "../context/TitleContext" import Box from "@material-ui/core/Box" import Button from "@material-ui/core/Button" import FacebookIcon from '@material-ui/icons/Facebook'; import TwitterIcon from '@material-ui/icons/Twitter'; import FileCopyIcon from '@material-ui/icons/FileCopy'; import makeStyles from "@material-ui/core/styles/makeStyles" import { graphql, useStaticQuery } from "gatsby" const ucfirst = (string) => string[0].toUpperCase() + string.slice(1) const Sentence = () => { const useStyles = makeStyles(theme => ( { sentence: { fontSize: '1.8em', }, sharing: { fontFamily: 'Raleway,sans-serif', display: 'flex', justifyContent: 'space-between', margin: '0 auto', marginTop: '50px', maxWidth: '300px' }, button: { fontFamily: theme.typography.body1.fontFamily, fontWeight: 'bold', textTransform: 'none' } })) const classes = useStyles() const titleContext = useContext(TitleContext) const eventsContext = useContext(EventsContext) const { site } = useStaticQuery( graphql` query { site { siteMetadata { title description author url app_id } } } ` ) let testo = "" let sharingText = "" let url = site.siteMetadata.url if( typeof window !== 'undefined' ) { url = window.location.href } if (eventsContext.events.length === 0) { testo = "" } if (eventsContext.events.length === 1) { testo = eventsContext.events[0].precisediff + " ago: <br/>" + eventsContext.events[0].name sharingText = eventsContext.events[0].precisediff + " ago: " + eventsContext.events[0].name + " #closerintime" } if (eventsContext.events.length === 2) { let evento1 = eventsContext.events[0] let evento2 = eventsContext.events[1] let verb = parseInt(evento2.plural) ? " are " : " is " if (evento1.diff > evento2.diff) { testo = ucfirst(evento2.name) + verb + "closer in time to us than to " + evento1.name + "." sharingText = ucfirst(evento2.name) + verb + "#closerintime to us than to " + evento1.name + "." } else if (evento1.diff < evento2.diff) { testo = ucfirst(evento2.name) + verb + "closer in time to " + evento1.name + " than to us." sharingText = ucfirst(evento2.name) + verb + "#closerintime to " + evento1.name + " than to us." } else { testo = ucfirst(evento2.name) + verb + "exactly halfway between " + evento1.name + " and us." sharingText = ucfirst(evento2.name) + verb + "exactly halfway between " + evento1.name + " and us. #closerintime" } } if (eventsContext.events.length === 3) { let evento1 = eventsContext.events[0] let evento2 = eventsContext.events[1] let evento3 = eventsContext.events[2] if (evento1.diff > evento3.diff) { testo = "More time passed between " + evento1.name + " and " + evento2.name + " than between " + evento3.name + " and us." sharingText = "More time passed between " + evento1.name + " and " + evento2.name + " than between " + evento3.name + " and us. #closerintime" } else if (evento1.diff < evento3.diff) { testo = "More time passed between " + evento3.name + " and us than between " + evento1.name + " and " + evento2.name + "." sharingText = "More time passed between " + evento3.name + " and us than between " + evento1.name + " and " + evento2.name + ". #closerintime" } else { testo = "The same amount time passed between " + evento1.name + " and " + evento2.name + " as it did between " + evento3.name + " and us." sharingText = "The same amount time passed between " + evento1.name + " and " + evento2.name + " as it did between " + evento3.name + " and us. #closerintime" } } useEffect(() => { titleContext.setTitle(testo) }, [testo]) const copyToClipboard = (text, href) => { var textArea = document.createElement("textarea"); textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; textArea.style.width = '2em'; textArea.style.height = '2em'; textArea.style.padding = 0; textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; textArea.style.background = 'transparent'; textArea.value = text+' '+href; document.body.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copying text command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } document.body.removeChild(textArea); } return (<Fragment> <Typography className={classes.sentence} variant={"h1"} align={"center"} dangerouslySetInnerHTML={{ __html: testo }}></Typography> {(sharingText) && <Box className={classes.sharing} > <Button component={"a"} className={classes.button} target={"_blank"} href={"https://twitter.com/intent/tweet?text=" + encodeURIComponent(sharingText) + "&url=" + encodeURIComponent(url)} startIcon={<TwitterIcon/>}> Tweet </Button> <Button component={"a"} className={classes.button} target={"_blank"} href={"https://www.facebook.com/dialog/share?app_id=" + site.siteMetadata.app_id + "&href=" + encodeURIComponent(url) + "&quote=" + encodeURIComponent(sharingText) + "&hashtag=%23closerintime"} startIcon={<FacebookIcon/>}> Share </Button> <Button component={"a"} className={classes.button} onClick={() => copyToClipboard(sharingText,url)} startIcon={<FileCopyIcon/>}> Copy </Button> </Box>} </Fragment>) } export default Sentence
enricobattocchi/closerintime
src/components/Sentence.js
JavaScript
gpl-2.0
6,042
/** * All Tax meta class * * JS used for the custom fields and other form items. * * Copyright 2012 Ohad Raz ([email protected]) * @since 1.0 */ var $ =jQuery.noConflict(); function update_repeater_fields(){ /** * Datepicker Field. * * @since 1.0 */ $('.at-date').each( function() { var $this = $(this), format = $this.attr('rel'); $this.datepicker( { showButtonPanel: true, dateFormat: format } ); }); /** * Timepicker Field. * * @since 1.0 */ $('.at-time').each( function() { var $this = $(this), format = $this.attr('rel'); $this.timepicker( { showSecond: true, timeFormat: format } ); }); /** * Colorpicker Field. * * @since 1.0 */ /* /** * Select Color Field. * * @since 1.0 */ $('.at-color-select').click( function(){ var $this = $(this); var id = $this.attr('rel'); $(this).siblings('.at-color-picker').farbtastic("#" + id).toggle(); return false; }); /** * Add Files. * * @since 1.0 */ $('.at-add-file').click( function() { var $first = $(this).parent().find('.file-input:first'); $first.clone().insertAfter($first).show(); return false; }); /** * Delete File. * * @since 1.0 */ $('.at-upload').delegate( '.at-delete-file', 'click' , function() { var $this = $(this), $parent = $this.parent(), data = $this.attr('rel'); $.post( ajaxurl, { action: 'at_delete_file', data: data }, function(response) { response == '0' ? ( alert( 'File has been successfully deleted.' ), $parent.remove() ) : alert( 'You do NOT have permission to delete this file.' ); }); return false; }); /** * Reorder Images. * * @since 1.0 */ $('.at-images').each( function() { var $this = $(this), order, data; $this.sortable( { placeholder: 'ui-state-highlight', update: function (){ order = $this.sortable('serialize'); data = order + '|' + $this.siblings('.at-images-data').val(); $.post(ajaxurl, {action: 'at_reorder_images', data: data}, function(response){ response == '0' ? alert( 'Order saved!' ) : alert( "You don't have permission to reorder images." ); }); } }); }); /** * Thickbox Upload * * @since 1.0 */ $('.at-upload-button').click( function() { var data = $(this).attr('rel').split('|'), post_id = data[0], field_id = data[1], backup = window.send_to_editor; // backup the original 'send_to_editor' function which adds images to the editor // change the function to make it adds images to our section of uploaded images window.send_to_editor = function(html) { $('#at-images-' + field_id).append( $(html) ); tb_remove(); window.send_to_editor = backup; }; // note that we pass the field_id and post_id here tb_show('', 'media-upload.php?post_id=' + post_id + '&field_id=' + field_id + '&type=image&TB_iframe=true'); return false; }); } jQuery(document).ready(function($) { /** * repater Field * @since 1.1 */ /*$( ".at-repeater-item" ).live('click', function() { var $this = $(this); $this.siblings().toggle(); }); jQuery(".at-repater-block").click(function(){ jQuery(this).find('table').toggle(); }); */ //edit $(".at-re-toggle").live('click', function() { $(this).prev().toggle('slow'); }); /** * Datepicker Field. * * @since 1.0 */ $('.at-date').each( function() { var $this = $(this), format = $this.attr('rel'); $this.datepicker( { showButtonPanel: true, dateFormat: format } ); }); /** * Timepicker Field. * * @since 1.0 */ $('.at-time').each( function() { var $this = $(this), format = $this.attr('rel'); $this.timepicker( { showSecond: true, timeFormat: format } ); }); /** * Colorpicker Field. * * @since 1.0 * better handler for color picker with repeater fields support * which now works both when button is clicked and when field gains focus. */ $('.at-color').live('focus', function() { var $this = $(this); $(this).siblings('.at-color-picker').farbtastic($this).toggle(); }); $('.at-color').live('focusout', function() { var $this = $(this); $(this).siblings('.at-color-picker').farbtastic($this).toggle(); }); /** * Add Files. * * @since 1.0 */ $('.at-add-file').click( function() { var $first = $(this).parent().find('.file-input:first'); $first.clone().insertAfter($first).show(); return false; }); /** * Delete File. * * @since 1.0 */ $('.at-upload').delegate( '.at-delete-file', 'click' , function() { var $this = $(this), $parent = $this.parent(), data = $this.attr('rel'); $.post( ajaxurl, { action: 'at_delete_file', data: data }, function(response) { response == '0' ? ( alert( 'File has been successfully deleted.' ), $parent.remove() ) : alert( 'You do NOT have permission to delete this file.' ); }); return false; }); /** * Thickbox Upload * * @since 1.0 */ $('.at-upload-button').click( function() { var data = $(this).attr('rel').split('|'), post_id = data[0], field_id = data[1], backup = window.send_to_editor; // backup the original 'send_to_editor' function which adds images to the editor // change the function to make it adds images to our section of uploaded images window.send_to_editor = function(html) { $('#at-images-' + field_id).append( $(html) ); tb_remove(); window.send_to_editor = backup; }; // note that we pass the field_id and post_id here tb_show('', 'media-upload.php?post_id=' + post_id + '&field_id=' + field_id + '&type=image&TB_iframe=true'); return false; }); /** * Helper Function * * Get Query string value by name. * * @since 1.0 */ function get_query_var( name ) { var match = RegExp('[?&]' + name + '=([^&#]*)').exec(location.href); return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); } //new image upload field function load_images_muploader(){ jQuery(".mupload_img_holder").each(function(i,v){ if (jQuery(this).next().next().val() != ''){ if (!jQuery(this).children().size() > 0){ jQuery(this).append('<img src="' + jQuery(this).next().next().val() + '" style="height: 150px;width: 150px;" />'); jQuery(this).next().next().next().val("Delete"); jQuery(this).next().next().next().removeClass('at-upload_image_button').addClass('at-delete_image_button'); } } }); } load_images_muploader(); //delete img button jQuery('.at-delete_image_button').live('click', function(e){ var field_id = jQuery(this).attr("rel"); var at_id = jQuery(this).prev().prev(); var at_src = jQuery(this).prev(); var t_button = jQuery(this); data = { action: 'at_delete_mupload', _wpnonce: $('#nonce-delete-mupload_' + field_id).val(), post_id: get_query_var('tag_ID'), field_id: field_id, attachment_id: jQuery(at_id).val() }; $.getJSON(ajaxurl, data, function(response) { if ('success' == response.status){ jQuery(t_button).val("Upload Image"); jQuery(t_button).removeClass('at-delete_image_button').addClass('at-upload_image_button'); //clear html values jQuery(at_id).val(''); jQuery(at_src).val(''); jQuery(at_id).prev().html(''); load_images_muploader(); }else{ alert(response.message); } }); return false; }); //upload button var formfield1; var formfield2; jQuery('.at-upload_image_button').live('click',function(e){ formfield1 = jQuery(this).prev(); formfield2 = jQuery(this).prev().prev(); tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true'); //store old send to editor function window.restore_send_to_editor = window.send_to_editor; //overwrite send to editor function window.send_to_editor = function(html) { imgurl = jQuery('img',html).attr('src'); img_calsses = jQuery('img',html).attr('class').split(" "); att_id = ''; jQuery.each(img_calsses,function(i,val){ if (val.indexOf("wp-image") != -1){ att_id = val.replace('wp-image-', ""); } }); jQuery(formfield2).val(att_id); jQuery(formfield1).val(imgurl); load_images_muploader(); tb_remove(); //restore old send to editor function window.send_to_editor = window.restore_send_to_editor; } return false; }); });
FeGHeidelberg/wp_feg-heidelberg_de
wp-content/themes/churchope/backend/js/tax-meta-clss.js
JavaScript
gpl-2.0
8,497
/* Google HTML5 slides template Authors: Luke Mahé (code) Marcin Wichary (code and design) Dominic Mazzoni (browser compatibility) Charles Chen (ChromeVox support) URL: http://code.google.com/p/html5slides/ */ var PERMANENT_URL_PREFIX = 'https://magni.me/presentation-pugbo-php54/'; var SLIDE_CLASSES = ['far-past', 'past', 'current', 'next', 'far-next']; var PM_TOUCH_SENSITIVITY = 15; var curSlide; /* ---------------------------------------------------------------------- */ /* classList polyfill by Eli Grey * (http://purl.eligrey.com/github/classList.js/blob/master/classList.js) */ if (typeof document !== "undefined" && !("classList" in document.createElement("a"))) { (function (view) { var classListProp = "classList" , protoProp = "prototype" , elemCtrProto = (view.HTMLElement || view.Element)[protoProp] , objCtr = Object strTrim = String[protoProp].trim || function () { return this.replace(/^\s+|\s+$/g, ""); } , arrIndexOf = Array[protoProp].indexOf || function (item) { for (var i = 0, len = this.length; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; } // Vendors: please allow content code to instantiate DOMExceptions , DOMEx = function (type, message) { this.name = type; this.code = DOMException[type]; this.message = message; } , checkTokenAndGetIndex = function (classList, token) { if (token === "") { throw new DOMEx( "SYNTAX_ERR" , "An invalid or illegal string was specified" ); } if (/\s/.test(token)) { throw new DOMEx( "INVALID_CHARACTER_ERR" , "String contains an invalid character" ); } return arrIndexOf.call(classList, token); } , ClassList = function (elem) { var trimmedClasses = strTrim.call(elem.className) , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [] ; for (var i = 0, len = classes.length; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.className = this.toString(); }; } , classListProto = ClassList[protoProp] = [] , classListGetter = function () { return new ClassList(this); } ; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { token += ""; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function (token) { token += ""; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); this._updateClassName(); } }; classListProto.remove = function (token) { token += ""; var index = checkTokenAndGetIndex(this, token); if (index !== -1) { this.splice(index, 1); this._updateClassName(); } }; classListProto.toggle = function (token) { token += ""; if (checkTokenAndGetIndex(this, token) === -1) { this.add(token); } else { this.remove(token); } }; classListProto.toString = function () { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter , enumerable: true , configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true if (ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } }(self)); } /* ---------------------------------------------------------------------- */ /* Slide movement */ function getSlideEl(no) { if ((no < 0) || (no >= slideEls.length)) { return null; } else { return slideEls[no]; } }; function updateSlideClass(slideNo, className) { var el = getSlideEl(slideNo); if (!el) { return; } if (className) { el.classList.add(className); } for (var i in SLIDE_CLASSES) { if (className != SLIDE_CLASSES[i]) { el.classList.remove(SLIDE_CLASSES[i]); } } }; function updateSlides() { for (var i = 0; i < slideEls.length; i++) { switch (i) { case curSlide - 2: updateSlideClass(i, 'far-past'); break; case curSlide - 1: updateSlideClass(i, 'past'); break; case curSlide: updateSlideClass(i, 'current'); break; case curSlide + 1: updateSlideClass(i, 'next'); break; case curSlide + 2: updateSlideClass(i, 'far-next'); break; default: updateSlideClass(i); break; } } triggerLeaveEvent(curSlide - 1); triggerEnterEvent(curSlide); window.setTimeout(function() { // Hide after the slide disableSlideFrames(curSlide - 2); }, 301); enableSlideFrames(curSlide - 1); enableSlideFrames(curSlide + 2); if (isChromeVoxActive()) { speakAndSyncToNode(slideEls[curSlide]); } updateHash(); }; function buildNextItem() { var toBuild = slideEls[curSlide].querySelectorAll('.to-build'); if (!toBuild.length) { return false; } toBuild[0].classList.remove('to-build', ''); if (isChromeVoxActive()) { speakAndSyncToNode(toBuild[0]); } return true; }; function prevSlide() { if (curSlide > 0) { curSlide--; updateSlides(); } }; function nextSlide() { if (buildNextItem()) { return; } if (curSlide < slideEls.length - 1) { curSlide++; updateSlides(); } }; /* Slide events */ function triggerEnterEvent(no) { var el = getSlideEl(no); if (!el) { return; } var onEnter = el.getAttribute('onslideenter'); if (onEnter) { new Function(onEnter).call(el); } var evt = document.createEvent('Event'); evt.initEvent('slideenter', true, true); evt.slideNumber = no + 1; // Make it readable el.dispatchEvent(evt); }; function triggerLeaveEvent(no) { var el = getSlideEl(no); if (!el) { return; } var onLeave = el.getAttribute('onslideleave'); if (onLeave) { new Function(onLeave).call(el); } var evt = document.createEvent('Event'); evt.initEvent('slideleave', true, true); evt.slideNumber = no + 1; // Make it readable el.dispatchEvent(evt); }; /* Touch events */ function handleTouchStart(event) { if (event.touches.length == 1) { touchDX = 0; touchDY = 0; touchStartX = event.touches[0].pageX; touchStartY = event.touches[0].pageY; document.body.addEventListener('touchmove', handleTouchMove, true); document.body.addEventListener('touchend', handleTouchEnd, true); } }; function handleTouchMove(event) { if (event.touches.length > 1) { cancelTouch(); } else { touchDX = event.touches[0].pageX - touchStartX; touchDY = event.touches[0].pageY - touchStartY; } }; function handleTouchEnd(event) { var dx = Math.abs(touchDX); var dy = Math.abs(touchDY); if ((dx > PM_TOUCH_SENSITIVITY) && (dy < (dx * 2 / 3))) { if (touchDX > 0) { prevSlide(); } else { nextSlide(); } } cancelTouch(); }; function cancelTouch() { document.body.removeEventListener('touchmove', handleTouchMove, true); document.body.removeEventListener('touchend', handleTouchEnd, true); }; /* Preloading frames */ function disableSlideFrames(no) { var el = getSlideEl(no); if (!el) { return; } var frames = el.getElementsByTagName('iframe'); for (var i = 0, frame; frame = frames[i]; i++) { disableFrame(frame); } }; function enableSlideFrames(no) { var el = getSlideEl(no); if (!el) { return; } var frames = el.getElementsByTagName('iframe'); for (var i = 0, frame; frame = frames[i]; i++) { enableFrame(frame); } }; function disableFrame(frame) { frame.src = 'about:blank'; }; function enableFrame(frame) { var src = frame._src; if (frame.src != src && src != 'about:blank') { frame.src = src; } }; function setupFrames() { var frames = document.querySelectorAll('iframe'); for (var i = 0, frame; frame = frames[i]; i++) { frame._src = frame.src; disableFrame(frame); } enableSlideFrames(curSlide); enableSlideFrames(curSlide + 1); enableSlideFrames(curSlide + 2); }; function setupInteraction() { /* Clicking and tapping */ var el = document.createElement('div'); el.className = 'slide-area'; el.id = 'prev-slide-area'; el.addEventListener('click', prevSlide, false); document.querySelector('section.slides').appendChild(el); var el = document.createElement('div'); el.className = 'slide-area'; el.id = 'next-slide-area'; el.addEventListener('click', nextSlide, false); document.querySelector('section.slides').appendChild(el); /* Swiping */ document.body.addEventListener('touchstart', handleTouchStart, false); } /* ChromeVox support */ function isChromeVoxActive() { if (typeof(cvox) == 'undefined') { return false; } else { return true; } }; function speakAndSyncToNode(node) { if (!isChromeVoxActive()) { return; } cvox.ChromeVox.navigationManager.switchToStrategy( cvox.ChromeVoxNavigationManager.STRATEGIES.LINEARDOM, 0, true); cvox.ChromeVox.navigationManager.syncToNode(node); cvox.ChromeVoxUserCommands.finishNavCommand(''); var target = node; while (target.firstChild) { target = target.firstChild; } cvox.ChromeVox.navigationManager.syncToNode(target); }; function speakNextItem() { if (!isChromeVoxActive()) { return; } cvox.ChromeVox.navigationManager.switchToStrategy( cvox.ChromeVoxNavigationManager.STRATEGIES.LINEARDOM, 0, true); cvox.ChromeVox.navigationManager.next(true); if (!cvox.DomUtil.isDescendantOfNode( cvox.ChromeVox.navigationManager.getCurrentNode(), slideEls[curSlide])){ var target = slideEls[curSlide]; while (target.firstChild) { target = target.firstChild; } cvox.ChromeVox.navigationManager.syncToNode(target); cvox.ChromeVox.navigationManager.next(true); } cvox.ChromeVoxUserCommands.finishNavCommand(''); }; function speakPrevItem() { if (!isChromeVoxActive()) { return; } cvox.ChromeVox.navigationManager.switchToStrategy( cvox.ChromeVoxNavigationManager.STRATEGIES.LINEARDOM, 0, true); cvox.ChromeVox.navigationManager.previous(true); if (!cvox.DomUtil.isDescendantOfNode( cvox.ChromeVox.navigationManager.getCurrentNode(), slideEls[curSlide])){ var target = slideEls[curSlide]; while (target.lastChild){ target = target.lastChild; } cvox.ChromeVox.navigationManager.syncToNode(target); cvox.ChromeVox.navigationManager.previous(true); } cvox.ChromeVoxUserCommands.finishNavCommand(''); }; /* Hash functions */ function getCurSlideFromHash() { var slideNo = parseInt(location.hash.substr(1)); if (slideNo) { curSlide = slideNo - 1; } else { curSlide = 0; } }; function updateHash() { location.replace('#' + (curSlide + 1)); }; /* Event listeners */ function handleBodyKeyDown(event) { switch (event.keyCode) { case 39: // right arrow case 13: // Enter case 32: // space case 34: // PgDn nextSlide(); event.preventDefault(); break; case 37: // left arrow case 8: // Backspace case 33: // PgUp prevSlide(); event.preventDefault(); break; case 40: // down arrow if (isChromeVoxActive()) { speakNextItem(); } else { nextSlide(); } event.preventDefault(); break; case 38: // up arrow if (isChromeVoxActive()) { speakPrevItem(); } else { prevSlide(); } event.preventDefault(); break; } }; function addEventListeners() { document.addEventListener('keydown', handleBodyKeyDown, false); }; /* Initialization */ function addPrettify() { var els = document.querySelectorAll('pre'); for (var i = 0, el; el = els[i]; i++) { if (!el.classList.contains('noprettyprint')) { el.classList.add('prettyprint'); } } var el = document.createElement('script'); el.type = 'text/javascript'; el.src = PERMANENT_URL_PREFIX + 'js/prettify.js'; el.onload = function() { prettyPrint(); } document.body.appendChild(el); }; function addFontStyle() { var el = document.createElement('link'); el.rel = 'stylesheet'; el.type = 'text/css'; el.href = 'https://fonts.googleapis.com/css?family=' + 'Open+Sans:regular,semibold,italic,italicsemibold|Droid+Sans+Mono'; document.body.appendChild(el); }; function addGeneralStyle() { var el = document.createElement('link'); el.rel = 'stylesheet'; el.type = 'text/css'; el.href = PERMANENT_URL_PREFIX + 'styles/styles.css'; document.body.appendChild(el); var el = document.createElement('meta'); el.name = 'viewport'; el.content = 'width=1100,height=750'; document.querySelector('head').appendChild(el); var el = document.createElement('meta'); el.name = 'apple-mobile-web-app-capable'; el.content = 'yes'; document.querySelector('head').appendChild(el); }; function makeBuildLists() { for (var i = curSlide, slide; slide = slideEls[i]; i++) { var items = slide.querySelectorAll('.build > *'); for (var j = 0, item; item = items[j]; j++) { if (item.classList) { item.classList.add('to-build'); } } } }; function handleDomLoaded() { slideEls = document.querySelectorAll('section.slides > article'); setupFrames(); addFontStyle(); addGeneralStyle(); addPrettify(); addEventListeners(); updateSlides(); setupInteraction(); makeBuildLists(); document.body.classList.add('loaded'); }; function initialize() { getCurSlideFromHash(); if (window['_DEBUG']) { PERMANENT_URL_PREFIX = '../'; } if (window['_DCL']) { handleDomLoaded(); } else { document.addEventListener('DOMContentLoaded', handleDomLoaded, false); } } // If ?debug exists then load the script relative instead of absolute if (!window['_DEBUG'] && document.location.href.indexOf('?debug') !== -1) { document.addEventListener('DOMContentLoaded', function() { // Avoid missing the DomContentLoaded event window['_DCL'] = true }, false); window['_DEBUG'] = true; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = '../slides.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script, s); // Remove this script s.parentNode.removeChild(s); } else { initialize(); }
ilbonzo/presentation-pugbo-php54
js/slides.js
JavaScript
gpl-2.0
14,822
//>>built define("dojox/embed/flashVars",["dojo"],function(f){f.deprecated("dojox.embed.flashVars","Will be removed in 2.0","2.0");var e={serialize:function(g,b){var e=function(a){"string"==typeof a&&(a=a.replace(/;/g,"_sc_"),a=a.replace(/\./g,"_pr_"),a=a.replace(/\:/g,"_cl_"));return a},h=dojox.embed.flashVars.serialize,d="";if(f.isArray(b)){for(var c=0;c<b.length;c++)d+=h(g+"."+c,e(b[c]))+";";return d.replace(/;{2,}/g,";")}if(f.isObject(b)){for(c in b)d+=h(g+"."+c,e(b[c]))+";";return d.replace(/;{2,}/g,";")}return g+ ":"+b}};f.setObject("dojox.embed.flashVars",e);return e}); //@ sourceMappingURL=flashVars.js.map
joshuacoddingyou/php
public/scripts/dojox/embed/flashVars.js
JavaScript
gpl-2.0
621
showWord(["n. ","Boutik, magazen, kote yo vann. Nan ri sa a, gen anpil konmès." ])
georgejhunt/HaitiDictionary.activity
data/words/konm~es_k~om~es_.js
JavaScript
gpl-2.0
83
tinyMCE.addI18n("ru.len-slider",{ title : "Шорткод для вставки LenSlider" });
gritz99/SOAP
wp-content/plugins/len-slider/js/langs/ru.js
JavaScript
gpl-2.0
97
// $Id: ahah.js,v 1.1.2.1 2009/03/21 19:43:51 mfer Exp $ /** * Provides AJAX-like page updating via AHAH (Asynchronous HTML and HTTP). * * AHAH is a method of making a request via Javascript while viewing an HTML * page. The request returns a small chunk of HTML, which is then directly * injected into the page. * * Drupal uses this file to enhance form elements with #ahah[path] and * #ahah[wrapper] properties. If set, this file will automatically be included * to provide AHAH capabilities. */ /** * Attaches the ahah behavior to each ahah form element. */ Drupal.behaviors.ahah = function(context) { for (var base in Drupal.settings.ahah) { if (!$('#'+ base + '.ahah-processed').size()) { var element_settings = Drupal.settings.ahah[base]; $(element_settings.selector).each(function() { element_settings.element = this; var ahah = new Drupal.ahah(base, element_settings); }); $('#'+ base).addClass('ahah-processed'); } } }; /** * AHAH object. */ Drupal.ahah = function(base, element_settings) { // Set the properties for this object. this.element = element_settings.element; this.selector = element_settings.selector; this.event = element_settings.event; this.keypress = element_settings.keypress; this.url = element_settings.url; this.wrapper = '#'+ element_settings.wrapper; this.effect = element_settings.effect; this.method = element_settings.method; this.progress = element_settings.progress; this.button = element_settings.button || { }; if (this.effect == 'none') { this.showEffect = 'show'; this.hideEffect = 'hide'; this.showSpeed = ''; } else if (this.effect == 'fade') { this.showEffect = 'fadeIn'; this.hideEffect = 'fadeOut'; this.showSpeed = 'slow'; } else { this.showEffect = this.effect + 'Toggle'; this.hideEffect = this.effect + 'Toggle'; this.showSpeed = 'slow'; } // Record the form action and target, needed for iFrame file uploads. var form = $(this.element).parents('form'); this.form_action = form.attr('action'); this.form_target = form.attr('target'); this.form_encattr = form.attr('encattr'); // Set the options for the ajaxSubmit function. // The 'this' variable will not persist inside of the options object. var ahah = this; var options = { url: ahah.url, data: ahah.button, beforeSubmit: function(form_values, element_settings, options) { return ahah.beforeSubmit(form_values, element_settings, options); }, success: function(response, status) { // Sanity check for browser support (object expected). // When using iFrame uploads, responses must be returned as a string. if (typeof(response) == 'string') { response = Drupal.parseJson(response); } return ahah.success(response, status); }, complete: function(response, status) { if (status == 'error' || status == 'parsererror') { return ahah.error(response, ahah.url); } }, dataType: 'json', type: 'POST' }; // Bind the ajaxSubmit function to the element event. $(element_settings.element).bind(element_settings.event, function() { $(element_settings.element).parents('form').ajaxSubmit(options); return false; }); // If necessary, enable keyboard submission so that AHAH behaviors // can be triggered through keyboard input as well as e.g. a mousedown // action. if (element_settings.keypress) { $(element_settings.element).keypress(function(event) { // Detect enter key. if (event.keyCode == 13) { $(element_settings.element).trigger(element_settings.event); return false; } }); } }; /** * Handler for the form redirection submission. */ Drupal.ahah.prototype.beforeSubmit = function (form_values, element, options) { // Disable the element that received the change. $(this.element).addClass('progress-disabled').attr('disabled', true); // Insert progressbar or throbber. if (this.progress.type == 'bar') { var progressBar = new Drupal.progressBar('ahah-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback)); if (this.progress.message) { progressBar.setProgress(-1, this.progress.message); } if (this.progress.url) { progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500); } this.progress.element = $(progressBar.element).addClass('ahah-progress ahah-progress-bar'); this.progress.object = progressBar; $(this.element).after(this.progress.element); } else if (this.progress.type == 'throbber') { this.progress.element = $('<div class="ahah-progress ahah-progress-throbber"><div class="throbber">&nbsp;</div></div>'); if (this.progress.message) { $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>') } $(this.element).after(this.progress.element); } }; /** * Handler for the form redirection completion. */ Drupal.ahah.prototype.success = function (response, status) { var wrapper = $(this.wrapper); var form = $(this.element).parents('form'); // Manually insert HTML into the jQuery object, using $() directly crashes // Safari with long string lengths. http://dev.jquery.com/ticket/1152 var new_content = $('<div></div>').html(response.data); // Restore the previous action and target to the form. form.attr('action', this.form_action); this.form_target ? form.attr('target', this.form_target) : form.removeAttr('target'); this.form_encattr ? form.attr('target', this.form_encattr) : form.removeAttr('encattr'); // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } $(this.element).removeClass('progress-disabled').attr('disabled', false); // Add the new content to the page. Drupal.freezeHeight(); if (this.method == 'replace') { wrapper.empty().append(new_content); } else { wrapper[this.method](new_content); } // Immediately hide the new content if we're using any effects. if (this.showEffect != 'show') { new_content.hide(); } // Determine what effect use and what content will receive the effect, then // show the new content. if ($('.ahah-new-content', new_content).size() > 0) { $('.ahah-new-content', new_content).hide(); new_content.show(); $(".ahah-new-content", new_content)[this.showEffect](this.showSpeed); } else if (this.showEffect != 'show') { new_content[this.showEffect](this.showSpeed); } // Attach all javascript behaviors to the new content, if it was successfully // added to the page, this if statement allows #ahah[wrapper] to be optional. if (new_content.parents('html').length > 0) { Drupal.attachBehaviors(new_content); } Drupal.unfreezeHeight(); }; /** * Handler for the form redirection error. */ Drupal.ahah.prototype.error = function (response, uri) { alert(Drupal.ahahError(response, uri)); // Resore the previous action and target to the form. $(this.element).parent('form').attr( { action: this.form_action, target: this.form_target} ); // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } // Undo hide. $(this.wrapper).show(); // Re-enable the element. $(this.element).removeClass('progess-disabled').attr('disabled', false); };
punithagk/mpm
profiles/uberdrupal/modules/jquery_update/replace/ahah.js
JavaScript
gpl-2.0
7,824
(function($){ if (typeof UxU.utils !== 'undefined') { $('.uxu-ticket-status-festival-length').html(UxU.utils.durationFromVisitors(info.tickets_sold)); } })(jQuery);
j0n/uxu-prototype
wp-content/plugins/uxu-tickets/js/uxu-tickets.js
JavaScript
gpl-2.0
173
'use strict'; const { expect } = require('chai'); const { getParsedSql } = require('./util'); describe('common table expressions', () => { it('should support single CTE', () => { const sql = ` WITH cte AS (SELECT 1) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.equal('WITH "cte" AS (SELECT 1) SELECT * FROM "cte"'); }); it('should support multiple CTE', () => { const expected = 'WITH "cte1" AS (SELECT 1), "cte2" AS (SELECT 2) ' + 'SELECT * FROM "cte1" UNION SELECT * FROM "cte2"'; const sql = ` WITH cte1 AS (SELECT 1), cte2 AS (SELECT 2) SELECT * FROM cte1 UNION SELECT * FROM cte2 `.trim(); expect(getParsedSql(sql)).to.equal(expected) }); it('should support CTE with column', () => { const sql = ` WITH cte (col1) AS (SELECT 1) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.contain('(col1)'); }); it('should support CTE with multiple columns', () => { const sql = ` WITH cte (col1, col2) AS (SELECT 1, 2) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.contain('(col1, col2)'); }); it('should support recursive CTE', () => { const sql = ` WITH RECURSIVE cte(n) AS ( SELECT 1 UNION SELECT n + 1 FROM cte WHERE n < 5 ) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.match(/^WITH RECURSIVE/); }); });
godmodelabs/flora-sql-parser
test/ast2sql/cte.js
JavaScript
gpl-2.0
1,628
"use strict"; /*** * critical element webgl demo by Silke Rohn and Benedikt Klotz * Source is the Basis applikation. * Added and changed functionalities: * @Benedikt: Objects, Lighting, particle systems, shader, blending and face culling * @Silke: particle system, changes to particle systems (Elements) */ var webgl = { gl: null, objects: [], time: 0.0, life: 250, objectAngle: 0, debug: true, maxAge: 5.0, /** * @author: Silke Rohn **/ elements: { HYDRO: -15, KALIUM: -15, TITAN: 35, FERRUM: 10, URAN: -15, CARBON: 10, MAGNESIUM: -20, OXID: -5, select: function() { var select = document.getElementById("select"); var value = select.selectedIndex; var objects = webgl.objects[2] switch(value) { case 0: webgl.life += this.FERRUM; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; if (objects.colors[0] <= 0.9) { for (var i = 0; i < objects.colors.length;i+=4) { objects.colors[i] += 0.01; objects.colors[i+1] += 0.01; } changed = true; } if(changed) { webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER,objects.colorObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.colors)); } break; case 1: webgl.life += this.OXID; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; if (objects.colors[0] <= 0.9) { for (var i = 0; i < objects.colors.length;i+=4) { objects.colors[i+1] += 0.1; } changed = true; } webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.colorObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.colors)); break; case 2: webgl.life += this.HYDRO; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; for (var i = 0; i < objects.velocities.length;i+=3) { objects.velocities[i] += 0.01; objects.velocities[i+1] += 0.01; } changed = true; webgl.maxAge += 0.5; webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.velocityObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.velocities)); break; case 3: webgl.life += this.URAN; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; for (var i = 0; i < objects.colors.length;i+=3) { objects.velocities[i] -= 0.01; objects.velocities[i+2] -= 0.01; } changed = true; if (webgl.maxAge <0.5){ window.alert("Die kritische Masse ist verschwunden!!!"); } webgl.maxAge -= 0.5; webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.velocityObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.velocities)); break; case 4: webgl.life += this.CARBON; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; for (var i = 0; i < objects.velocities.length;i+=3) { objects.velocities[i] -= 0.01; objects.velocities[i+1] -= 0.01; } changed = true; if (webgl.maxAge <0.5){ window.alert("Die kritische Masse ist verschwunden!!!"); } webgl.maxAge -= 0.5; webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.velocityObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.velocities)); break; case 5: webgl.life += this.TITAN; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; if (objects.colors[2] >= 0.1) { for (var i = 0; i < objects.colors.length;i+=4) { objects.colors[i+2] -= 0.1; } changed = true; } webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.colorObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.colors)); break; case 6: webgl.life += this.MAGNESIUM; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; if ((objects.colors[0] >= 0.1) && (objects.colors[1] >= 0.1)) { for (var i = 0; i < objects.colors.length;i+=4) { objects.colors[i] -= 0.1; objects.colors[i+1] -= 0.1; } changed = true; } webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.colorObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.colors)); break; case 7: webgl.life += this.KALIUM; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; for (var i = 0; i < webgl.objects[2].velocities.length;i+=3) { objects.velocities[i] += 0.01;//Math.random()*.1; objects.velocities[i+1] += 0.01;//Math.random()*.1; objects.velocities[i+2] += 0.01;//Math.random()*.1; } changed = true; if (webgl.maxAge <0.5){ window.alert("Die kritische Masse ist verschwunden!!!"); } webgl.maxAge -= 0.5; webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.velocityObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.velocities)); break; default: console.log("Error: unknown element"); } }, }, /** * Encapsulates Projection and Viewing matrix and some helper functions. **/ matrices: { projection: new J3DIMatrix4(), viewing: new J3DIMatrix4(), viewingTranslate: { x: 0, y: 0, z: 0 }, viewingRotations: { x: 0, y: 0, z: 0 }, /** * Initializes the Projection and the Viewing matrix. * Projection uses perspective projection with fove of 30.0, aspect of 1.0, near 1 and far 10000. * Viewing is set up as a translate of (0, 10, -50) and a rotate of 20 degrees around x and y axis. **/ init: function () { this.projection.perspective(30, 1.0, 1, 10000); this.viewingTranslate = { x: 0, y: 0, z: -5 }; this.viewingRotations = { x: 50, y: 0, z: 0 }; this.updateViewing.call(this); }, updateViewing: function() { var t = this.viewingTranslate; this.viewing = new J3DIMatrix4(); this.viewing.translate(t.x, t.y, t.z); var r = this.viewingRotations; this.viewing.scale(1.0,1.0,1.0) // 2.0,1.5,10.0 this.viewing.rotate(r.x, 1, 0, 0); this.viewing.rotate(r.y, 0, 1, 0); this.viewing.rotate(r.z, 0, 0, 1); }, zoomIn: function() { this.viewingTranslate.z -= 1; this.updateViewing(); }, zoomOut: function() { this.viewingTranslate.z += 1; this.updateViewing(); }, moveLeft: function() { this.viewingTranslate.x += 1; this.updateViewing(); }, moveRight: function() { this.viewingTranslate.x -= 1; this.updateViewing(); }, moveUp: function() { this.viewingTranslate.y += 1; this.updateViewing(); }, moveDown: function() { this.viewingTranslate.y -= 1; this.updateViewing(); }, rotateXAxis: function(offset) { this.viewingRotations.x = (this.viewingRotations.x + offset) % 360; this.updateViewing(); }, rotateYAxis: function(offset) { this.viewingRotations.y = (this.viewingRotations.y + offset) % 360; this.updateViewing(); }, rotateZAxis: function(offset) { this.viewingRotations.z = (this.viewingRotations.z + offset) % 360; this.updateViewing(); }, reset: function() { this.projection = new J3DIMatrix4(); this.viewing = new J3DIMatrix4(); this.init(); }, rotateObjectsLeft: function() { webgl.objectAngle = (webgl.objectAngle - 1) % 360; }, rotateObjectsRight: function() { webgl.objectAngle = (webgl.objectAngle + 1) % 360; }, }, /** * This message checks whether one of the error flags is set and * logs it to the console. If @p message is provided the message * is printed together with the error code. This allows to track * down an error by adding useful debug information to it. * * @param message Optional message printed together with the error. **/ checkError: function (message) { var errorToString = function(error) { switch (error) { case gl.NO_ERROR: return "NO_ERROR"; case gl.INVALID_ENUM: return "INVALID_ENUM"; case gl.INVALID_VALUE: return "INVALID_VALUE"; case gl.INVALID_OPERATION: return "INVALID_OPERATION"; case gl.OUT_OF_MEMORY: return "OUT_OF_MEMORY"; } return "UNKNOWN ERROR: " + error; }; var gl = webgl.gl; var error = gl.getError(); while (error !== gl.NO_ERROR) { if (message) { console.log(message + ": " + errorToString(error)); } else { console.log(errorToString(error)); } error = gl.getError(); } }, /** * This method logs information about the system: * @li VERSION * @li RENDERER * @li VENDOR * @li UNMASKED_RENDERER_WEBGL (Extension WEBGL_debug_renderer_info) * @li UNMASKED_VENDOR_WEBGL (Extension WEBGL_debug_renderer_info) * @li supportedExtensions **/ systemInfo: function () { var gl = webgl.gl; console.log("Version: " + gl.getParameter(gl.VERSION)); console.log("Renderer: " + gl.getParameter(gl.RENDERER)); console.log("Vendor: " + gl.getParameter(gl.VENDOR)); var extensions = gl.getSupportedExtensions(); for (var i = 0; i < extensions.length; i++) { if (extensions[i] == "WEBGL_debug_renderer_info") { var renderInfo = gl.getExtension("WEBGL_debug_renderer_info"); if (renderInfo) { console.log("Unmasked Renderer: " + gl.getParameter(renderInfo.UNMASKED_RENDERER_WEBGL)); console.log("Unmasked Vendor: " + gl.getParameter(renderInfo.UNMASKED_VENDOR_WEBGL)); } } } console.log("Extensions: "); console.log(extensions); }, /** * Creates a shader program out of @p vertex and @p fragment shaders. * * In case the linking of the shader program fails the programInfoLog is * logged to the console. * * @param vertex The compiled and valid WebGL Vertex Shader * @param fragment The compiled and valid WebGL Fragment Shader * @returns The linked WebGL Shader Program **/ createProgram: function (vertex, fragment) { var gl = webgl.gl; var shader = gl.createProgram(); gl.attachShader(shader, vertex); gl.attachShader(shader, fragment); gl.linkProgram(shader); gl.validateProgram(shader); var log = gl.getProgramInfoLog(shader); if (log != "") { console.log(log); } webgl.checkError("create Program"); return shader; }, /** * Generic method to render any @p object with any @p shader as TRIANGLES. * * This method can enable vertex, normal and texCoords depending on whether they * are defined in the @p object and @p shader. Everything is added in a completely * optional way, so there is no chance that an incorrect VertexAttribArray gets * enabled. * * Changes by: Benedikt Klotz * * The @p object can provide the following elements: * @li loaded: boolean indicating whether the object is completely loaded * @li blending: boolean indicating whether blending needs to be enabled * @li texture: texture object to bind if valid * @li vertexObject: ARRAY_BUFFER with three FLOAT values (x, y, z) * @li normalObject: ARRAY_BUFFER with three FLOAT values (x, y, z) * @li texCoordObject: ARRAY_BUFFER with two FLOAT values (s, t) * @li indexObject: ELEMENT_ARRAY_BUFFER * @li numIndices: Number of indices in indexObject * @li indexSize: The type of the index, must be one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT or GL_UNSIGNED_INT * * The @p shader can provide the following elements: * @li vertexLocation: attribute location for the vertexObject * @li normalLocation: attribute location for the normalObject * @li texCoordsLocation: attribute location for the texCoordsLocation * * It is expected that the shader program encapsulated in @p shader is already in use. **/ drawObject: function (gl, object, shader) { if (object.loaded === false) { // not yet loaded, don't render return; } // Set Time if(object.particle == true) { gl.uniform1f(shader.timeLocation, this.time); gl.uniform1f(shader.ageLocation, this.maxAge); } if (object.texture !== undefined) { gl.bindTexture(gl.TEXTURE_2D, object.texture); } if (shader.vertexLocation !== undefined && object.vertexObject !== undefined) { gl.enableVertexAttribArray(shader.vertexLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.vertexObject); gl.vertexAttribPointer(shader.vertexLocation, 3, gl.FLOAT, false, 0, 0); } // start: Particle System related Attributes if (shader.colorLocation !== undefined && object.colorObject !== undefined) { gl.enableVertexAttribArray(shader.colorLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.colorObject); gl.vertexAttribPointer(shader.colorLocation, 4, gl.FLOAT, false, 0, 0); } if (shader.velocityLocation !== undefined && object.velocityObject !== undefined) { gl.enableVertexAttribArray(shader.velocityLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.velocityObject); gl.vertexAttribPointer(shader.velocityLocation, 3, gl.FLOAT, false, 0, 0); } if (shader.startTimeLocation !== undefined && object.startTimeObject !== undefined) { gl.enableVertexAttribArray(shader.startTimeLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.startTimeObject); gl.vertexAttribPointer(shader.startTimeLocation, 1, gl.FLOAT, false, 0, 0); } if(object.particle == true) { gl.drawArrays(gl.POINTS, 0, object.particleObject.length); } // End: Particle System related Attributes if (shader.normalLocation !== undefined && object.normalObject !== undefined) { gl.enableVertexAttribArray(shader.normalLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.normalObject); gl.vertexAttribPointer(shader.normalLocation, 3, gl.FLOAT, false, 0, 0); } if (shader.texCoordsLocation !== undefined && object.texCoordObject !== undefined) { gl.enableVertexAttribArray(shader.texCoordsLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.texCoordObject); gl.vertexAttribPointer(shader.texCoordsLocation, 2, gl.FLOAT, false, 0, 0); } // Activate blending if (object.blending !== undefined && object.blending === true) { gl.blendFunc(gl.SRC_ALPHA, gl.ONE); // gl.enable(gl.BLEND); gl.uniform1f(shader.alphaLocation, 0.8); gl.disable(gl.DEPTH_TEST); // Set Alpha if blending for object is not activated } else{ gl.uniform1f(shader.alphaLocation, 1.0); } // Activate culling if(object.culling !== undefined && object.culling === true) { gl.enable(gl.CULL_FACE); gl.cullFace(gl.FRONT); } if (object.indexObject !== undefined && object.numIndices !== undefined && object.indexSize !== undefined) { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, object.indexObject); gl.drawElements(gl.TRIANGLES, object.numIndices, object.indexSize, 0); } gl.bindTexture(gl.TEXTURE_2D, null); // Disbale Culling and enable Depth Test if (object.blending !== undefined && object.blending === true) { gl.enable(gl.DEPTH_TEST); gl.disable(gl.BLEND); } // Disable Culling if(object.culling !== undefined && object.culling === true) { gl.disable(gl.CULL_FACE); } }, repaintLoop: { frameRendering: false, setup: function() { var render = function(){ if (webgl.repaintLoop.frameRendering) { return; } webgl.repaintLoop.frameRendering = true; webgl.angle = (webgl.angle + 1) % 360; for (var i = 0; i < webgl.objects.length; i++) { var object = webgl.objects[i]; if (object.update === undefined) { continue; } object.update.call(object); } webgl.time += 16/1000; webgl.displayFunc.call(webgl); webgl.repaintLoop.frameRendering = false; window.requestAnimFrame(render); }; window.requestAnimFrame(render); render(); }, }, createShader: function (gl, type, source) { var shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); var log = gl.getShaderInfoLog(shader); if (log != "") { console.log(log); } webgl.checkError("create shader " + source); return shader; }, /** * Create a texture shader with Lighting enabled * * @author: Benedikt Klotz **/ createObjectShader: function() { var gl = this.gl; var shader = { program: -1, loaded: false, mvpLocation: -1, textureLocation: -1, vertexLocation: -1, texCoordsLocation: -1, lightDirLocation: -1, create: function() { if (this.vertexShader === undefined || this.fragmentShader === undefined) { return; } var program = webgl.createProgram(this.vertexShader, this.fragmentShader); this.program = program; this.use(); // resolve locations this.normalMatrixLocation = gl.getUniformLocation(program, "u_normalMatrix"), this.lightDirLocation = gl.getUniformLocation(program, "u_lightDir"), this.mvpLocation = gl.getUniformLocation(program, "modelViewProjection"), this.textureLocation = gl.getUniformLocation(program, "u_texture"), this.vertexLocation = gl.getAttribLocation(program, "vertex"), this.texCoordsLocation = gl.getAttribLocation(program, "texCoords"), this.alphaLocation = gl.getUniformLocation(program, "uAlpha"); // set uniform gl.uniform1i(this.textureLocation, 0); gl.uniform3f(this.lightDirLocation, 1.0, 1.0, 1.0); this.loaded = true; }, use: function () { gl.useProgram(this.program); } }; $.get("shaders/texture/vertex.glsl", function(data, response) { shader.vertexShader = webgl.createShader(webgl.gl, webgl.gl.VERTEX_SHADER, data); shader.create.call(shader); }, "html"); $.get("shaders/texture/fragment.glsl", function(data, response) { shader.fragmentShader = webgl.createShader(webgl.gl, webgl.gl.FRAGMENT_SHADER, data); shader.create.call(shader); }, "html"); return shader; }, /** * Create a special shader for the Particle System * * @author: Benedikt Klotz **/ createParticleShader: function () { var gl = this.gl; var shader = { program: -1, loaded: false, mvpLocation: -1, vertexLocation: -1, dirLocation: -1, create: function() { if (this.vertexShader === undefined || this.fragmentShader === undefined) { return; } var program = webgl.createProgram(this.vertexShader, this.fragmentShader); this.program = program; this.use(); var shader = {}; // resolve locations this.mvpLocation = gl.getUniformLocation(program, "modelViewProjection"), this.timeLocation = gl.getUniformLocation(program, "u_time"), this.vertexLocation = gl.getAttribLocation(program, "vertex"), this.ageLocation = gl.getUniformLocation(program, "maxAlter"); this.colorLocation = gl.getAttribLocation(program, "initialColor"), this.velocityLocation = gl.getAttribLocation(program, "velocity"), this.startTimeLocation = gl.getAttribLocation(program, "startTime"), this.sizeLocation = gl.getAttribLocation(program, "size"), this.loaded = true; }, use: function () { gl.useProgram(this.program); } }; $.get("shaders/particle/vertex.glsl", function(data) { shader.vertexShader = webgl.createShader(webgl.gl, webgl.gl.VERTEX_SHADER, data); shader.create.call(shader); }, "html"); $.get("shaders/particle/fragment.glsl", function(data) { shader.fragmentShader = webgl.createShader(webgl.gl, webgl.gl.FRAGMENT_SHADER, data); shader.create.call(shader); }, "html"); return shader; }, setupKeyHandler: function() { var m = this.matrices; $("body").keydown(function (event) { switch (event.keyCode) { case 107: m.zoomOut.call(m); break; case 109: m.zoomIn.call(m); break; case 39: if (event.shiftKey) { m.rotateZAxis.call(m, 1); } else { m.moveLeft.call(m); /** disabled * m.rotateObjectsLeft.call(m); **/ } break; case 37: if (event.shiftKey) { m.rotateZAxis.call(m, -1); } else { m.moveRight.call(m); /** disabled * m.rotateObjectsRight.call(m); **/ } break; case 38: if (event.shiftKey) { m.rotateXAxis.call(m, 1); } else { m.moveUp.call(m); } break; case 40: if (event.shiftKey) { m.rotateXAxis.call(m, -1); } else { m.moveDown.call(m); } break; case 82: m.reset.call(m); break; } }); }, /** * Create ground object * * @author: Benedikt Klotz */ makeGround: function (gl){ var buffer = { }; // vertices array var vertices = [ -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1 ]; // normal array var normals = [ 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0 ]; // texCoord array var texCoords = [ 0, 0, 1, 0, 1, 1, 0, 1 ]; // index array var indices = [ 0, 1, 2, 0, 2, 3 ]; buffer.vertexObject = this.createBuffer_f32(gl, vertices); buffer.texCoordObject = this.createBuffer_f32(gl, texCoords); buffer.normalObject = this.createBuffer_f32(gl,normals); buffer.indexObject = this.createBuffer_ui8(gl, indices); buffer.numIndices = indices.length; return buffer; }, /** * create an upwards open box * * @author: Benedikt Klotz **/ makeOpenBox: function (gl){ var buffer = { }; // vertices array var vertices = [ 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1, // v0-v1-v2-v3 front 1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1, // v0-v3-v4-v5 right 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0-v5-v6-v1 top -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1, // v1-v6-v7-v2 left -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1, // v7-v4-v3-v2 bottom 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 ]; // v4-v7-v6-v5 back // normal array var normals = [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0-v1-v2-v3 front 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0-v3-v4-v5 right 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0-v5-v6-v1 top -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1-v6-v7-v2 left 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7-v4-v3-v2 bottom 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 ]; // v4-v7-v6-v5 back // texCoord array var texCoords = [ 1, 1, 0, 1, 0, 0, 1, 0, // v0-v1-v2-v3 front 0, 1, 0, 0, 1, 0, 1, 1, // v0-v3-v4-v5 right 1, 0, 1, 1, 0, 1, 0, 0, // v0-v5-v6-v1 top 1, 1, 0, 1, 0, 0, 1, 0, // v1-v6-v7-v2 left 0, 0, 1, 0, 1, 1, 0, 1, // v7-v4-v3-v2 bottom 0, 0, 1, 0, 1, 1, 0, 1 ]; // v4-v7-v6-v5 back // index array var indices = [ 0, 1, 2, 0, 2, 3, // front 4, 5, 6, 4, 6, 7, // right 12,13,14, 12,14,15, // left 16,17,18, 16,18,19, // bottom 20,21,22, 20,22,23 ]; // back buffer.vertexObject = this.createBuffer_f32(gl, vertices); buffer.texCoordObject = this.createBuffer_f32(gl, texCoords); buffer.normalObject = this.createBuffer_f32(gl,normals); buffer.indexObject = this.createBuffer_ui8(gl, indices); buffer.numIndices = indices.length; return buffer; }, /** * * Create Buffer Objects in Bit Size 8 and 32 in float and unsigned int. * The function with a d is used for dynamic draws * * @author: Benedikt Klotz **/ createBuffer_f32: function (gl, data) { var vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); return vbo; }, createBuffer_f32_d: function (gl, data) { var vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); return vbo; }, createBuffer_ui8: function (gl, data) { var vbo = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, vbo); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array(data), gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); return vbo; }, /** * Create a particle system, whose particle are black and are going in all directions * * @author: Benedikt Klotz, Silke Rohn **/ createParticle: function (dir) { var particle = {}; particle.position = [1, 1, 1]; switch(dir) { case 0: particle.velocity = [Math.random()*.1, Math.random()*.1, Math.random()*.1]; break; case 1: particle.velocity = [-Math.random()*.1, Math.random()*.1, Math.random()*.1]; break; case 2: particle.velocity = [Math.random()*.1, -Math.random()*.1, Math.random()*.1]; break; case 3: particle.velocity = [Math.random()*.1, Math.random()*.1, -Math.random()*.1]; break; case 4: particle.velocity = [-Math.random()*.1, -Math.random()*.1, Math.random()*.1]; break; case 5: particle.velocity = [-Math.random()*.1, Math.random()*.1, -Math.random()*.1]; break; case 6: particle.velocity = [Math.random()*.1, -Math.random()*.1, -Math.random()*.1]; break; case 7: particle.velocity = [-Math.random()*.1, -Math.random()*.1, -Math.random()*.1]; break; default: console.log("Error - particle creation: Unknown Direction - " + dir); break; } // start with black particles particle.color = [0.0, 0.0, 0.0, 1.0]; particle.startTime = Math.random() * 10 + 1; return particle; }, createParticelSystem: function(gl) { var particles = []; for (var i=0, dir=0; i<100000; i++, dir++) { if(dir == 8) { dir=0; } particles.push(this.createParticle(dir)); } var vertices = []; var velocities = []; var colors = []; var startTimes = []; var dirs = []; for (i=0; i<particles.length; i++) { var particle = particles[i]; vertices.push(particle.position[0]); vertices.push(particle.position[1]); vertices.push(particle.position[2]); velocities.push(particle.velocity[0]); velocities.push(particle.velocity[1]); velocities.push(particle.velocity[2]); colors.push(particle.color[0]); colors.push(particle.color[1]); colors.push(particle.color[2]); colors.push(particle.color[3]); startTimes.push(particle.startTime); dirs.push(particle.dir); } // create gl Buffer for particles var buffer = { }; buffer.particleObject = particles; buffer.vertexObject = this.createBuffer_f32(gl, vertices); buffer.velocityObject = this.createBuffer_f32_d(gl, velocities); buffer.colorObject = this.createBuffer_f32_d(gl, colors); buffer.startTimeObject = this.createBuffer_f32_d(gl, startTimes); buffer.dirObject = this.createBuffer_f32(gl, dirs); // save object properties for update later buffer.velocities = velocities; buffer.startTimes = startTimes; buffer.colors = colors; buffer.particle = true; return buffer; }, loadTexture: function(gl, path, object) { var texture = gl.createTexture(); var image = new Image(); g_loadingImages.push(image); image.onload = function() { webgl.doLoadTexture.call(webgl, gl, image, texture, object) } image.src = path; return texture; }, doLoadTexture: function(gl, image, texture, object) { g_loadingImages.splice(g_loadingImages.indexOf(image), 1); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); // Set Texture Parameter gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.bindTexture(gl.TEXTURE_2D, null); // Set texture loaded object.loaded = true; }, /** * Initialize all systems and objects * * @author: Benedikt Klotz **/ init: function (canvasName, vertexShaderName, fragmentShaderName) { var canvas, gl; // Setup Error reporting $(document).ajaxError(function(e,xhr,opt){ console.log("Error requesting " + opt.url + ": " + xhr.status + " " + xhr.statusText); }); // setup the API canvas = document.getElementById(canvasName); gl = canvas.getContext("experimental-webgl",{premultipliedAlpha:false}); this.gl = gl; gl.viewport(0, 0, canvas.width, canvas.height); // make background blue gl.clearColor(0.0, 0.0, 0.5, 0.6); gl.enable(gl.DEPTH_TEST); this.systemInfo(); // create the projection matrix this.matrices.init.call(this.matrices); // ground objects var object = this.makeGround.call(this, gl) object.indexSize = gl.UNSIGNED_BYTE; object.name = "ground"; object.blending = false; // Enable Front Face Culling object.culling = true; object.texture = this.loadTexture.call(this, gl, "textures/metall.jpg", object); object.shader = this.createObjectShader(); object.model = function() { var model = new J3DIMatrix4(); model.scale(1.6,1.2,1.8) model.rotate(this.objectAngle, 0.0, 1.0, 0.0); return model }; this.objects[this.objects.length] = object; // create a open box object = this.makeOpenBox.call(this, gl); object.indexSize = gl.UNSIGNED_BYTE; object.name = "box"; // enable object blending object.blending = true; object.texture = this.loadTexture.call(this, gl, "textures/glas.jpg", object); object.shader = this.createObjectShader(); object.model = function() { var model = new J3DIMatrix4(); model.scale(0.5,0.5,0.5) model.translate(0,-1.39,0); model.rotate(this.objectAngle, 0.0, 1.0, 0.0); return model; }; this.objects[this.objects.length] = object; // particle objects var object = this.createParticelSystem(gl) object.shader = this.createParticleShader(); object.loaded = true; object.blending = true; object.model = function() { var model = new J3DIMatrix4(); model.translate(-1.0,-1.7,-1.0); model.rotate(this.objectAngle, 0.0, 1.0, 0.0); return model; }; // Reset particle startTime if there are discarded setInterval(function() { var particles = object.particleObject; var changed = false; for (var i=0; i<particles.length; i++) { if(object.startTimes[i] + 7.0 <= webgl.time) { object.startTimes[i] = webgl.time + 3.0*Math.random(); changed = true; } } if(changed) { gl.bindBuffer(gl.ARRAY_BUFFER,object.startTimeObject); gl.bufferSubData(gl.ARRAY_BUFFER, 0, new Float32Array(object.startTimes)); } }, 1000); this.objects[this.objects.length] = object; // setup animation this.repaintLoop.setup.call(this); if(this.debug) { // setup handlers this.setupKeyHandler(); } }, displayFunc: function () { var gl = this.gl; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); for (var i = 0; i < this.objects.length; i++) { var object, shader, modelView, normalMatrix, modelViewProjection; object = this.objects[i]; if (object.shader === undefined) { // no shader is set, cannot render continue; } if (object.shader.loaded !== undefined && object.shader.loaded === false) { // shader not yet loaded continue; } shader = object.shader; shader.use(); // create the matrices modelViewProjection = new J3DIMatrix4(this.matrices.projection); modelView = new J3DIMatrix4(this.matrices.viewing); if (object.model !== undefined) { modelView.multiply(object.model.call(this)); } modelViewProjection.multiply(modelView); if (shader.mvpLocation !== undefined) { modelViewProjection.setUniform(gl, shader.mvpLocation, false); } if (shader.normalMatrixLocation) { normalMatrix = new J3DIMatrix4(); normalMatrix.load(modelView); normalMatrix.invert(); normalMatrix.transpose(); normalMatrix.setUniform(gl, shader.normalMatrixLocation, false) } this.drawObject(gl, object, shader); this.checkError("drawObject: " + i); } this.checkError("displayFunc"); } };
Streamstormer/webGL-project
js/webgl.js
JavaScript
gpl-2.0
37,180
import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; const StyledTag = styled.span` color: ${props => props.color}; background: ${props => props.bgcolor}; padding: ${props => props.padding}; margin: ${props => props.margin}; border-radius: 3px; border: ${props => `1px solid ${props.border}`}; max-width: ${props => props.maxWidth}; word-break: break-all; line-height: 20px; `; const Tag = ({ text, size = "medium", color = { bgcolor: "#fafafa", border: "#d9d9d9", color: "rgba(0,0,0,0.65)" }, margin = "", maxWidth = "300px" }) => { const getPaddingBySize = size => { const choices = { small: "0px 5px", medium: "1px 6px", large: "5px 10px" }; return choices[size]; }; return ( <StyledTag bgcolor={color.bgcolor} border={color.border} color={color.color} padding={getPaddingBySize(size)} margin={margin} maxWidth={maxWidth} > {text} </StyledTag> ); }; Tag.propTypes = { color: PropTypes.shape({ bgcolor: PropTypes.string, border: PropTypes.string, color: PropTypes.string }), text: PropTypes.string, size: PropTypes.string, margin: PropTypes.string, maxWidth: PropTypes.string }; export default Tag;
pamfilos/data.cern.ch
ui/cap-react/src/components/partials/Tag.js
JavaScript
gpl-2.0
1,314
showWord(["n. ","1. Gwo dan dèyè nan macha mamifè yo ki adapte pou moulen manje. Moun gen douz dan molè, sis nan chak machwa (twa chak bò). 2. Molèt, pati posteryè nan janm yon moun, ant jenou ak cheviy. Lè li kouri, molè li fè l mal. 3. a. Nan domèn chimi li vle di ki gen relasyon ak mol (yon solisyon ki gen yon mol solite dilye pou bay yon lit solisyon)" ])
georgejhunt/HaitiDictionary.activity
data/words/mol~e.js
JavaScript
gpl-2.0
372
/*! jQuery UI - v1.10.2 - 2013-03-14 * http://jqueryui.com * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function (e) { e.datepicker.regional.ms = {closeText: "Tutup", prevText: "&#x3C;Sebelum", nextText: "Selepas&#x3E;", currentText: "hari ini", monthNames: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"], monthNamesShort: ["Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"], dayNames: ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu"], dayNamesShort: ["Aha", "Isn", "Sel", "Rab", "kha", "Jum", "Sab"], dayNamesMin: ["Ah", "Is", "Se", "Ra", "Kh", "Ju", "Sa"], weekHeader: "Mg", dateFormat: "dd/mm/yy", firstDay: 0, isRTL: !1, showMonthAfterYear: !1, yearSuffix: ""}, e.datepicker.setDefaults(e.datepicker.regional.ms) });
KsenZ/cirm
js/jqueryui/ui/minified/i18n/jquery.ui.datepicker-ms.min.js
JavaScript
gpl-2.0
884
/* global FullCalendar, FullCalendarLocales, FullCalendarInteraction */ var GLPIPlanning = { calendar: null, dom_id: "", all_resources: [], visible_res: [], drag_object: null, last_view: null, display: function(params) { // get passed options and merge it with default ones var options = (typeof params !== 'undefined') ? params: {}; var default_options = { full_view: true, default_view: 'timeGridWeek', height: GLPIPlanning.getHeight, plugins: ['dayGrid', 'interaction', 'list', 'timeGrid', 'resourceTimeline', 'rrule'], license_key: "", resources: [], now: null, rand: '', header: { left: 'prev,next,today', center: 'title', right: 'dayGridMonth, timeGridWeek, timeGridDay, listFull, resourceWeek' }, }; options = Object.assign({}, default_options, options); GLPIPlanning.dom_id = 'planning'+options.rand; var window_focused = true; var loaded = false; var disable_qtip = false; var disable_edit = false; // manage visible resources this.all_resources = options.resources; this.visible_res = Object.keys(this.all_resources).filter(function(index) { return GLPIPlanning.all_resources[index].is_visible; }); // get more space for planning if (options.full_view) { $('#'+GLPIPlanning.dom_id).closest('.ui-tabs').width('98%'); } this.calendar = new FullCalendar.Calendar(document.getElementById(GLPIPlanning.dom_id), { plugins: options.plugins, height: options.height, timeZone: 'UTC', theme: true, weekNumbers: options.full_view ? true : false, defaultView: options.default_view, timeFormat: 'H:mm', eventLimit: true, // show 'more' button when too mmany events minTime: CFG_GLPI.planning_begin, maxTime: CFG_GLPI.planning_end, schedulerLicenseKey: options.license_key, resourceAreaWidth: '15%', editable: true, // we can drag / resize items droppable: false, // we cant drop external items by default nowIndicator: true, now: options.now,// as we set the calendar as UTC, we need to reprecise the current datetime listDayAltFormat: false, agendaEventMinHeight: 13, header: options.header, //resources: options.resources, resources: function(fetchInfo, successCallback) { // Filter resources by whether their id is in visible_res. var filteredResources = []; filteredResources = options.resources.filter(function(elem, index) { return GLPIPlanning.visible_res.indexOf(index.toString()) !== -1; }); successCallback(filteredResources); }, views: { listFull: { type: 'list', titleFormat: function() { return ''; }, visibleRange: function(currentDate) { var current_year = currentDate.getFullYear(); return { start: (new Date(currentDate.getTime())).setFullYear(current_year - 5), end: (new Date(currentDate.getTime())).setFullYear(current_year + 5) }; } }, resourceWeek: { type: 'resourceTimeline', buttonText: 'Timeline Week', duration: { weeks: 1 }, //hiddenDays: [6, 0], groupByDateAndResource: true, slotLabelFormat: [ { week: 'short' }, { weekday: 'short', day: 'numeric', month: 'numeric', omitCommas: true }, function(date) { return date.date.hour; } ] }, }, resourceRender: function(info) { var icon = ""; var itemtype = info.resource._resource.extendedProps.itemtype || ""; switch (itemtype.toLowerCase()) { case "group": case "group_user": icon = "users"; break; case "user": icon = "user"; } $(info.el) .find('.fc-cell-text') .prepend('<i class="fas fa-'+icon+'"></i>&nbsp;'); if (info.resource._resource.extendedProps.itemtype == 'Group_User') { info.el.style.backgroundColor = 'lightgray'; } }, eventRender: function(info) { var event = info.event; var extProps = event.extendedProps; var element = $(info.el); var view = info.view; // append event data to dom (to re-use they in clone behavior) element.data('myevent', event); var eventtype_marker = '<span class="event_type" style="background-color: '+extProps.typeColor+'"></span>'; element.append(eventtype_marker); var content = extProps.content; var tooltip = extProps.tooltip; if (view.type !== 'dayGridMonth' && view.type.indexOf('list') < 0 && event.rendering != "background" && !event.allDay){ element.append('<div class="content">'+content+'</div>'); } // add icon if exists if ("icon" in extProps) { var icon_alt = ""; if ("icon_alt" in extProps) { icon_alt = extProps.icon_alt; } element.find(".fc-title, .fc-list-item-title") .append("&nbsp;<i class='"+extProps.icon+"' title='"+icon_alt+"'></i>"); } // add classes to current event var added_classes = ''; if (typeof event.end !== 'undefined' && event.end !== null) { var now = new Date(); var end = event.end; added_classes = end.getTime() < now.getTime() ? ' event_past' : ''; added_classes+= end.getTime() > now.getTime() ? ' event_future' : ''; added_classes+= end.toDateString() === now.toDateString() ? ' event_today' : ''; } if (extProps.state != '') { added_classes+= extProps.state == 0 ? ' event_info' : extProps.state == 1 ? ' event_todo' : extProps.state == 2 ? ' event_done' : ''; } if (added_classes != '') { element.addClass(added_classes); } // add tooltip to event if (!disable_qtip) { // detect ideal position var qtip_position = { target: 'mouse', adjust: { mouse: false }, viewport: $(window) }; if (view.type.indexOf('list') >= 0) { // on central, we want the tooltip on the anchor // because the event is 100% width and so tooltip will be too much on the right. qtip_position.target= element.find('a'); } // show tooltips element.qtip({ position: qtip_position, content: tooltip, style: { classes: 'qtip-shadow qtip-bootstrap' }, show: { solo: true, delay: 100 }, hide: { fixed: true, delay: 100 }, events: { show: function(event) { if (!window_focused) { event.preventDefault(); } } } }); } // context menu element.on('contextmenu', function(e) { // prevent display of browser context menu e.preventDefault(); // get offset of the event var offset = element.offset(); // remove old instances $('.planning-context-menu').remove(); // create new one var context = $('<ul class="planning-context-menu" data-event-id=""> \ <li class="clone-event"><i class="far fa-clone"></i>'+__("Clone")+'</li> \ <li class="delete-event"><i class="fas fa-trash"></i>'+__("Delete")+'</li> \ </ul>'); // add it to body and place it correctly $('body').append(context); context.css({ left: offset.left + element.outerWidth() / 4, top: offset.top }); // get properties of event for context menu actions var extprops = event.extendedProps; var resource = {}; var actor = {}; if (typeof event.getresources === "function") { resource = event.getresources(); } // manage resource changes if (resource.length === 1) { actor = { itemtype: resource[0].extendedProps.itemtype || null, items_id: resource[0].extendedProps.items_id || null, }; } // context menu actions // 1- clone event $('.planning-context-menu .clone-event').click(function() { $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'clone_event', event: { old_itemtype: extprops.itemtype, old_items_id: extprops.items_id, actor: actor, start: event.start.toISOString(), end: event.end.toISOString(), } }, success: function() { GLPIPlanning.refresh(); } }); }); // 2- delete event (manage serie/instance specific events) $('.planning-context-menu .delete-event').click(function() { var ajaxDeleteEvent = function(instance) { instance = instance || false; $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'delete_event', event: { itemtype: extprops.itemtype, items_id: extprops.items_id, day: event.start.toISOString().substring(0, 10), instance: instance ? 1 : 0, } }, success: function() { GLPIPlanning.refresh(); } }); }; if (!("is_recurrent" in extprops) || !extprops.is_recurrent) { ajaxDeleteEvent(); } else { $('<div title="'+__("Make a choice")+'"></div>') .html(__("Delete the whole serie of the recurrent event") + "<br>" + __("or just add an exception by deleting this instance?")) .dialog({ resizable: false, height: "auto", width: "auto", modal: true, buttons: [ { text: $("<div/>").html(__("Serie")).text(), // html/text method to remove html entities icon: "ui-icon-trash", click: function() { ajaxDeleteEvent(false); $(this).dialog("close"); } }, { text: $("<div/>").html(__("Instance")).text(), // html/text method to remove html entities icon: "ui-icon-trash", click: function() { ajaxDeleteEvent(true); $(this).dialog("close"); } } ] }); } }); }); }, datesRender: function(info) { var view = info.view; // force refetch events from ajax on view change (don't refetch on first load) if (loaded) { GLPIPlanning.refresh(); } else { loaded = true; } // attach button (planning and refresh) in planning header $('#'+GLPIPlanning.dom_id+' .fc-toolbar .fc-center h2') .after( $('<i id="refresh_planning" class="fa fa-sync pointer"></i>') ).after( $('<div id="planning_datepicker"><a data-toggle><i class="far fa-calendar-alt fa-lg pointer"></i></a>') ); // specific process for full list if (view.type == 'listFull') { // hide datepick on full list (which have virtually no limit) if ($('#planning_datepicker').length > 0 && "_flatpickr" in $('#planning_datepicker')[0]) { $('#planning_datepicker')[0]._flatpickr.destroy(); } $('#planning_datepicker').hide(); // hide control buttons $('#planning .fc-left .fc-button-group').hide(); } else { // reinit datepicker $('#planning_datepicker').show(); GLPIPlanning.initFCDatePicker(new Date(view.currentStart)); // show controls buttons $('#planning .fc-left .fc-button-group').show(); } // set end of day markers for timeline GLPIPlanning.setEndofDays(info.view); }, viewSkeletonRender: function(info) { var view_type = info.view.type; GLPIPlanning.last_view = view_type; // inform backend we changed view (to store it in session) $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'view_changed', view: view_type } }); // set end of day markers for timeline GLPIPlanning.setEndofDays(info.view); }, events: { url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', extraParams: function() { var view_name = GLPIPlanning.calendar ? GLPIPlanning.calendar.state.viewType : options.default_view; var display_done_events = 1; if (view_name.indexOf('list') >= 0) { display_done_events = 0; } return { 'action': 'get_events', 'display_done_events': display_done_events, 'view_name': view_name }; }, success: function(data) { if (!options.full_view && data.length == 0) { GLPIPlanning.calendar.setOption('height', 0); } }, failure: function(error) { console.error('there was an error while fetching events!', error); } }, // EDIT EVENTS eventResize: function(info) { var event = info.event; var exprops = event.extendedProps; var is_recurrent = exprops.is_recurrent || false; if (is_recurrent) { $('<div></div>') .dialog({ modal: true, title: __("Recurring event resized"), width: 'auto', height: 'auto', buttons: [ { text: __("Serie"), click: function() { $(this).remove(); GLPIPlanning.editEventTimes(info); } }, { text: __("Instance"), click: function() { $(this).remove(); GLPIPlanning.editEventTimes(info, true); } } ] }).text(__("The resized event is a recurring event. Do you want to change the serie or instance ?")); } else { GLPIPlanning.editEventTimes(info); } }, eventResizeStart: function() { disable_edit = true; disable_qtip = true; }, eventResizeStop: function() { setTimeout(function(){ disable_edit = false; disable_qtip = false; }, 300); }, eventDragStart: function() { disable_qtip = true; }, // event was moved (internal element) eventDrop: function(info) { disable_qtip = false; var event = info.event; var exprops = event.extendedProps; var is_recurrent = exprops.is_recurrent || false; if (is_recurrent) { $('<div></div>') .dialog({ modal: true, title: __("Recurring event dragged"), width: 'auto', height: 'auto', buttons: [ { text: __("Serie"), click: function() { $(this).remove(); GLPIPlanning.editEventTimes(info); } }, { text: __("Instance"), click: function() { $(this).remove(); GLPIPlanning.editEventTimes(info, true); } } ] }).text(__("The dragged event is a recurring event. Do you want to move the serie or instance ?")); } else { GLPIPlanning.editEventTimes(info); } }, eventClick: function(info) { var event = info.event; var editable = event.extendedProps._editable; // do not know why editable property is not available if (event.extendedProps.ajaxurl && editable && !disable_edit) { var start = event.start; var ajaxurl = event.extendedProps.ajaxurl+"&start="+start.toISOString(); info.jsEvent.preventDefault(); // don't let the browser navigate $('<div></div>') .dialog({ modal: true, width: 'auto', height: 'auto', close: function() { GLPIPlanning.refresh(); } }) .load(ajaxurl, function() { $(this).dialog({ position: { my: 'center', at: 'center', viewport: $(window), of: $('#page'), collision: 'fit' } }); }); } }, // ADD EVENTS selectable: true, select: function(info) { var itemtype = (((((info || {}) .resource || {}) ._resource || {}) .extendedProps || {}) .itemtype || ''); var items_id = (((((info || {}) .resource || {}) ._resource || {}) .extendedProps || {}) .items_id || 0); // prevent adding events on group users if (itemtype === 'Group_User') { GLPIPlanning.calendar.unselect(); return false; } var start = info.start; var end = info.end; $('<div></div>').dialog({ modal: true, width: 'auto', height: 'auto', open: function () { $(this).load( CFG_GLPI.root_doc+"/ajax/planning.php", { action: 'add_event_fromselect', begin: start.toISOString(), end: end.toISOString(), res_itemtype: itemtype, res_items_id: items_id, }, function() { $(this).dialog({ position: { my: 'center', at: 'center', viewport: $(window), of: $('#page'), collision: 'fit' } }); } ); }, close: function() { $(this).dialog("close"); $(this).remove(); }, position: { my: 'center', at: 'center top', viewport: $(window), of: $('#page') } }); GLPIPlanning.calendar.unselect(); } }); var loadedLocales = Object.keys(FullCalendarLocales); if (loadedLocales.length === 1) { GLPIPlanning.calendar.setOption('locale', loadedLocales[0]); } $('.planning_on_central a') .mousedown(function() { disable_qtip = true; $('.qtip').hide(); }) .mouseup(function() { disable_qtip = false; }); window.onblur = function() { window_focused = false; }; window.onfocus = function() { window_focused = true; }; //window.calendar = calendar; // Required as object is not accessible by forms callback GLPIPlanning.calendar.render(); $('#refresh_planning').click(function() { GLPIPlanning.refresh(); }); // attach the date picker to planning GLPIPlanning.initFCDatePicker(); // force focus on the current window $(window).focus(); // remove all context menus on document click $(document).click(function() { $('.planning-context-menu').remove(); }); }, refresh: function() { if (typeof(GLPIPlanning.calendar.refetchResources) == 'function') { GLPIPlanning.calendar.refetchResources(); } GLPIPlanning.calendar.refetchEvents(); GLPIPlanning.calendar.rerenderEvents(); window.displayAjaxMessageAfterRedirect(); }, // add/remove resource (like when toggling it in side bar) toggleResource: function(res_name, active) { // find the index of current resource to find it in our array of visible resources var index = GLPIPlanning.all_resources.findIndex(function(current) { return current.id == res_name; }); if (index !== -1) { // add only if not already present if (active && GLPIPlanning.visible_res.indexOf(index.toString()) === -1) { GLPIPlanning.visible_res.push(index.toString()); } else if (!active) { GLPIPlanning.visible_res.splice(GLPIPlanning.visible_res.indexOf(index.toString()), 1); } } }, setEndofDays: function(view) { // add a class to last col of day in timeline view // to visualy separate days if (view.constructor.name === "ResourceTimelineView") { // compute the number of hour slots displayed var time_beg = CFG_GLPI.planning_begin.split(':'); var time_end = CFG_GLPI.planning_end.split(':'); var int_beg = parseInt(time_beg[0]) * 60 + parseInt(time_beg[1]); var int_end = parseInt(time_end[0]) * 60 + parseInt(time_end[1]); var sec_inter = int_end - int_beg; var nb_slots = Math.ceil(sec_inter / 60); // add class to day list header $('#planning .fc-time-area.fc-widget-header table tr:nth-child(2) th') .addClass('end-of-day'); // add class to hours list header $('#planning .fc-time-area.fc-widget-header table tr:nth-child(3) th:nth-child('+nb_slots+'n)') .addClass('end-of-day'); // add class to content bg (content slots) $('#planning .fc-time-area.fc-widget-content table td:nth-child('+nb_slots+'n)') .addClass('end-of-day'); } }, planningFilters: function() { $('#planning_filter a.planning_add_filter' ).on( 'click', function( e ) { e.preventDefault(); // to prevent change of url on anchor var url = $(this).attr('href'); $('<div></div>').dialog({ modal: true, open: function () { $(this).load(url); }, position: { my: 'top', at: 'center', of: $('#planning_filter') } }); }); $('#planning_filter .filter_option').on( 'click', function() { $(this).children('ul').toggle(); }); $(document).click(function(e){ if ($(e.target).closest('#planning_filter .filter_option').length === 0) { $('#planning_filter .filter_option ul').hide(); } }); $('#planning_filter .delete_planning').on( 'click', function() { var deleted = $(this); var li = deleted.closest('ul.filters > li'); $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'delete_filter', filter: deleted.attr('value'), type: li.attr('event_type') }, success: function() { li.remove(); GLPIPlanning.refresh(); } }); }); var sendDisplayEvent = function(current_checkbox, refresh_planning) { var current_li = current_checkbox.parents('li'); var parent_name = null; if (current_li.parent('ul.group_listofusers').length == 1) { parent_name = current_li .parent('ul.group_listofusers') .parent('li') .attr('event_name'); } var event_name = current_li.attr('event_name'); var event_type = current_li.attr('event_type'); var checked = current_checkbox.is(':checked'); return $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'toggle_filter', name: event_name, type: event_type, parent: parent_name, display: checked }, success: function() { GLPIPlanning.toggleResource(event_name, checked); if (refresh_planning) { // don't refresh planning if event triggered from parent checkbox GLPIPlanning.refresh(); } } }); }; $('#planning_filter li:not(li.group_users) input[type="checkbox"]') .on( 'click', function() { sendDisplayEvent($(this), true); }); $('#planning_filter li.group_users > span > input[type="checkbox"]') .on('change', function() { var parent_checkbox = $(this); var parent_li = parent_checkbox.parents('li'); var checked = parent_checkbox.prop('checked'); var event_name = parent_li.attr('event_name'); var chidren_checkboxes = parent_checkbox .parents('li.group_users') .find('ul.group_listofusers input[type="checkbox"]'); chidren_checkboxes.prop('checked', checked); var promises = []; chidren_checkboxes.each(function() { promises.push(sendDisplayEvent($(this), false)); }); GLPIPlanning.toggleResource(event_name, checked); // refresh planning once for all checkboxes (and not for each) // after theirs promises done $.when.apply($, promises).then(function() { GLPIPlanning.refresh(); }); }); $('#planning_filter .color_input input').on('change', function() { var current_li = $(this).parents('li'); var parent_name = null; if (current_li.length >= 1) { parent_name = current_li.eq(1).attr('event_name'); current_li = current_li.eq(0); } $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'color_filter', name: current_li.attr('event_name'), type: current_li.attr('event_type'), parent: parent_name, color: $(this).val() }, success: function() { GLPIPlanning.refresh(); } }); }); $('#planning_filter li.group_users .toggle').on('click', function() { $(this).parent().toggleClass('expanded'); }); $('#planning_filter_toggle > a.toggle').on('click', function() { $('#planning_filter_content').animate({ width:'toggle' }, 300, 'swing', function() { $('#planning_filter').toggleClass('folded'); $('#planning_container').toggleClass('folded'); }); }); }, // send ajax for event storage (on event drag/resize) editEventTimes: function(info, move_instance) { move_instance = move_instance || false; var event = info.event; var revertFunc = info.revert; var extProps = event.extendedProps; var old_itemtype = null; var old_items_id = null; var new_itemtype = null; var new_items_id = null; // manage moving the events between resources (users, groups) if ("newResource" in info && info.newResource !== null) { var new_extProps = info.newResource._resource.extendedProps; new_itemtype = new_extProps.itemtype; new_items_id = new_extProps.items_id; } if ("oldResource" in info && info.oldResource !== null) { var old_extProps = info.oldResource._resource.extendedProps; old_itemtype = old_extProps.itemtype; old_items_id = old_extProps.items_id; } var start = event.start; var end = event.end; if (typeof end === 'undefined' || end === null) { end = new Date(start.getTime()); if (event.allDay) { end.setDate(end.getDate() + 1); } else { end.setHours(end.getHours() + 2); } } var old_event = info.oldEvent || {}; var old_start = old_event.start || start; $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'update_event_times', start: start.toISOString(), end: end.toISOString(), itemtype: extProps.itemtype, items_id: extProps.items_id, move_instance: move_instance, old_start: old_start.toISOString(), new_actor_itemtype: new_itemtype, new_actor_items_id: new_items_id, old_actor_itemtype: old_itemtype, old_actor_items_id: old_items_id, }, success: function(html) { if (!html) { revertFunc(); } GLPIPlanning.refresh(); }, error: function() { revertFunc(); } }); }, // datepicker for planning initFCDatePicker: function(currentDate) { $('#planning_datepicker').flatpickr({ defaultDate: currentDate, onChange: function(selected_date) { // convert to UTC to avoid timezone issues var date = new Date( Date.UTC( selected_date[0].getFullYear(), selected_date[0].getMonth(), selected_date[0].getDate() ) ); GLPIPlanning.calendar.gotoDate(date); } }); }, // set planning height getHeight: function() { var _newheight = $(window).height() - 272; if ($('#debugajax').length > 0) { _newheight -= $('#debugajax').height(); } if (CFG_GLPI.glpilayout == 'vsplit') { _newheight = $('.ui-tabs-panel').height() - 30; } //minimal size var _minheight = 300; if (_newheight < _minheight) { _newheight = _minheight; } return _newheight; }, };
smartcitiescommunity/Civikmind
js/planning.js
JavaScript
gpl-2.0
34,622
define(['jquery','config','base','ajax','checkInput','serializeJson'],function($,config,base,AjaxFunUtils){ var defaultAddr = ''; var init = function(){ getAddress(defaultAddr); }; //加载模板 var loadhtml = function(){ var telhtml = '<div id="addressbox" class="addressbox">'+ '<form id="addressform" method="post">'+ '<div id="add_headerbox" class="headerbox">'+ '<div class="rowbox searchbox">'+ '<div class="top_l"> <a href="javascript:void(0);" id="back-address" class="back-address rel" data-level="0"> <span class="b_ico ico-back-h"></span> </a> </div>'+ '<div class="row-flex1 text-center h2_title">收货地址管理</div>'+ '</div>'+ '<div id="address_cont" class="address_cont">'+ '<ul id="addressedit" class="jsbox f16 color-333 jsbox_mt0" style="display:none">'+ '<li id="address_row" class="rowbox">'+ '<div class="row-flex1">'+ '<p id="add_str_text">广东省广州市天河区</p>'+ '<p class="f12 color-999 edit_text">所在地区</p>'+ '<input id="add_str" name="add_str" type="hidden" />'+ '<input id="add_ids" name="add_ids" type="hidden" />'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li id="townSelRow" class="rowbox">'+ '<div class="row-flex1">'+ '<input id="add_str_2" class="noborder edit_input" name="add_str_2" type="text" placeholder="请选择街道" style="padding-left:0" readonly />'+ '<p class="f12 color-999 edit_text">街道</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox li_edit">'+ '<div class="row-flex1">'+ '<input id="add_more" name="add_more" type="text" value="" placeholder="请输入详细地址" class="noborder edit_input" style="padding-left:0" data-validate="isempty" />'+ '<p class="f12 color-999 edit_text">详细地址</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox li_edit">'+ '<div class="row-flex1">'+ '<input id="addressee" name="addressee" type="text" value="" placeholder="请输入收货人姓名" class="noborder edit_input" style="padding-left:0" data-validate="isempty" />'+ '<p class="f12 color-999 edit_text">收货人姓名</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox li_edit">'+ '<div class="row-flex1">'+ '<input type="text" id="cellphone" name="cellphone" value="" placeholder="请输入收货人手机号码" class="noborder edit_input" style="padding-left:0" data-validate="Mobile" />'+ '<p class="f12 color-999 edit_text">收货人手机号码</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox li_edit">'+ '<div class="row-flex1">'+ '<input type="text" id="zip" name="zip" value="" placeholder="请输入邮编" class="noborder edit_input" style="padding-left:0" />'+ '<p class="f12 color-999 edit_text">邮编</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox" for="sedefault">'+ '<div class="row-flex1">'+ '<label><input type="checkbox" name="sedefault" id="sedefault" style="width:20px;padding:0; margin-bottom:-10px"/>设置为默认收货地址</label>'+ '<p class="f12 color-999 edit_text">默认收货地址</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '</ul>'+ '<ul id="townSelRow_list" class="jsbox jsbox_mt0" style="display:none"></ul>'+ '<div id="divsionSelect" style="display:none">'+ '<ul id="selected" class="jsbox jsbox_mt0" style="display:none"></ul>'+ '<ul id="forselect" class="jsbox jsbox_mt0"></ul>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="footerbox rowbox" style="padding:10px 0;z-index:99999">'+ '<input id="addrid_edt" name="addrid" type="hidden" />'+ '<div class="row-flex1 text-left">'+ '<button id="delBtn" type="button" class="btn w150">删除</button>'+ '</div>'+ '<div class="row-flex1 text-right">'+ '<button type="button" class="btn btn-danger w150 address_sub_btn">保存</button>'+ '</div>'+ '</div>'+ '</form>'+ '</div>'; $("body").append(telhtml); var bodyh=config.base.getHeightBody(); $("#add_headerbox").css({"height":bodyh,"z-index":99998}); $("#address_cont").css({"height":bodyh-60}); }; //添加,编辑,删除收货地址 var addedtAddress = function(opt){ //加载模板 loadhtml(); //加载,编辑地址 if(opt.act == 'add'){ $("#add_headerbox").addClass("address_add"); //省级地址获取 siondatalist(); //提交绑定 subaddress({act:opt.act}); }else{ $("#add_headerbox").addClass("address_edt"); //编辑提取数据 edtaddress({ act:opt.act, addrid:opt.addrid, callback:function(res3){ //提交绑定 subaddress({act:'edt'}); } }); } //被选中li selectedclik(); //所在地区行click address_row(); //街道选择 townSelRow(); //详细地址,收货人姓名等 $("#addressedit").on("click",".li_edit",function(){ $(this).addClass("li_edit_current"); $(this).siblings(".li_edit").removeClass("li_edit_current"); $(this).find(".edit_input").focus(); }); //关闭地址弹框 $("#back-address").on("click",function(){ var level = $(this).attr("data-level"); var stateid = $(this).attr("data-state"); var cityid = $(this).attr("data-city"); if(level == 0 || level == 3){ $("#addressbox").remove(); }else if(level == 1){ if(opt.act == 'add'){ //省级地址获取 siondatalist(); $(this).attr("data-level",0); $("#selected").html('').hide(); }else{ $(this).attr("data-level",0); $("#addressedit").show(); $("#divsionSelect").hide(); } }else if(level == 2){ $(this).attr("data-level",1); $("#selected").find(".li_click").each(function(index, element) { var li_level = $(this).attr("data-level"); if(li_level == 2){ $(this).remove(); } }); //市级地址获取 getcityaddress({thisId:stateid}); } }); }; var selectedclik = function(){ //被选中li $("#selected").on("click",'.li_click',function(){ var parentid = $(this).attr("data-parentid"); var level = $(this).attr("data-level"); $("#back-address").attr("data-level",level-1); if(parentid > 0){ getcityaddress({thisId:parentid}); $(this).remove(); }else{ siondatalist(); $("#selected").html('').hide(); } $("#add_str_2").attr("data-id",''); $("#add_str_2").val(''); $("#townSelRow_list").hide(); $("#divsionSelect").show(); $("#addressedit").hide(); }) }; //所在地区行click var address_row = function(){ //所在地区行click $("#address_row").off("click").on("click",function(){ var state = $(this).attr("data-state"); var city = $(this).attr("data-city"); var county = $(this).attr("data-county"); $("#back-address").attr("data-level",2); if(state > 0){ $("#selected").html(''); getdataaddress({ callback:function(res3){ $.each(res3.data,function(index,ooo){ if(ooo.id == state){ var lihtml3 = '<li class="li_click" data-level="'+ooo.level+'" data-name="'+ooo.name+'" data-id="'+ooo.id+'" data-parentid="0">'+ooo.name+'</li>' $("#selected").append(lihtml3); return; } }); getdataaddress({ upid:state, callback:function(res3){ $.each(res3.data,function(index,ooo){ if(ooo.id == city){ var lihtml3 = '<li class="li_click" data-level="'+ooo.level+'" data-name="'+ooo.name+'" data-id="'+ooo.id+'" data-parentid="'+state+'">'+ooo.name+'</li>' $("#selected").append(lihtml3); return; } }); getdataaddress({ upid:city, callback:function(res3){ if(res3.data.length<=0){ $("#forselect").hide(); }else{ $("#forselect").show(); } var lihtml3 = ''; $.each(res3.data,function(index,ooo){ lihtml3 += '<li class="li_click" data-level="'+ooo.level+'" data-name="'+ooo.name+'" data-id="'+ooo.id+'" data-parentid="'+city+'">'+ooo.name+'</li>' }); $("#forselect").html(lihtml3); } }); } }); } }) $("#divsionSelect,#selected").show(); $("#addressedit").hide(); forselectclick(); }else{ //省级地址获取 siondatalist(); //提交绑定 subaddress({act:'edt'}); } }) }; //街道选择 var townSelRow = function(){ //街道click $("#townSelRow").off("click").on("click",function(e){ var upid = $(this).attr("data-townid"); if(upid<=0){ return false; } getdataaddress({ upid:upid, callback:function(res){ var lihtml = ''; $.each(res.data,function(index,o){ lihtml += '<li class="li_click" data-level="'+o.level+'" data-name="'+o.name+'" data-id="'+o.id+'" data-isleaf="0">'+o.name+'</li>'; }); $("#townSelRow_list").html(lihtml).show(); $("#divsionSelect").hide(); $("#addressedit").hide(); $("#townSelRow_list").off("click").on("click",'.li_click',function(){ var thisname = $(this).attr("data-name"); var thisid = $(this).attr("data-id"); $("#add_str_2").attr("data-id",thisid); $("#add_str_2").val(thisname); var newadd_ids = $("#address_row").attr("data-state")+"_"+$("#address_row").attr("data-city")+"_"+$("#address_row").attr("data-county")+"_"+thisid; $("#add_ids").val(newadd_ids); $("#townSelRow_list").hide(); $("#divsionSelect").hide(); $("#addressedit").show(); }); } }); }); }; //准备选择li var forselectclick = function(){ $("#forselect").off("click").on('click','.li_click',function(){ var thisId = $(this).attr("data-id"); var thislevel = $(this).attr("data-level"); var thisname = $(this).attr("data-name"); var $this = $(this); $("#back-address").attr("data-level",thislevel); if(thislevel == 1){ $("#address_row,#back-address").attr("data-state",thisId); }else if(thislevel == 2){ $("#address_row,#back-address").attr("data-city",thisId); }else if(thislevel == 3){ $("#address_row,#back-address").attr("data-county",thisId); $("#add_str_2").val(''); $("#add_str_2").attr("data-id",''); } getcityaddress({ thisId:thisId, thislevel:thislevel, callback:function(resin){ if(resin.data.length <=0 || thislevel>2){ $("#divsionSelect").hide(); $("#addressedit").show(); var add_str_text = ''; var add_str_id = ''; $("#selected").find("li").each(function(index, element) { var thisinname = $(this).attr("data-name"); var thisinid = $(this).attr("data-id"); add_str_text += thisinname; add_str_id += thisinid+'_'; }); add_str_text += thisname; add_str_id += thisId+'_' $("#townSelRow").attr("data-townid",thisId); $("#add_ids").val(add_str_id); $("#add_str_text,#add_str").text(add_str_text); $("#add_str").val(add_str_text); if(resin.data.length <=0){ $("#forselect").hide(); $("#townSelRow").hide(); }else{ $("#forselect").show(); $("#townSelRow").show(); } }else{ $("#selected").append($this).show(); } } }); }); } //获取省级数据 var siondatalist = function(opt){ getdataaddress({ callback:function(res){ if(res.status == 1){ var lihtml = ''; $.each(res.data,function(index,o){ lihtml += '<li class="li_click" data-level="'+o.level+'" data-name="'+o.name+'" data-id="'+o.id+'" data-parentid="0" data-isleaf="0">'+o.name+'</li>'; }); $("#forselect").html(lihtml).show(); $("#divsionSelect").show(); $("#addressedit").hide(); forselectclick(); }else{ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+res.msg+'</div>', w:"96%", type:0 }); } } }); }; //获取省级以下数据列表 var getcityaddress = function(opt){ getdataaddress({ upid:opt.thisId, callback:function(res){ var lihtml = ''; $.each(res.data,function(index,o){ lihtml += '<li class="li_click" data-level="'+o.level+'" data-name="'+o.name+'" data-id="'+o.id+'" data-parentid="'+opt.thisId+'" data-isleaf="0">'+o.name+'</li>'; }); $("#forselect").html(lihtml).show(); if(opt.callback){ opt.callback(res); } } }); }; //统一获取地址 var getdataaddress = function(opt){ AjaxFunUtils.ajaxInit({ "url":"/common/district_son.html", "params":{upid:opt.upid}, "callback":function (res) { if(opt.callback){ opt.callback(res); } } }); }; //编辑地址,获取当前编辑地址数据 var edtaddress = function(optin){ AjaxFunUtils.ajaxInit({ url:"/myorder/address.html", params:{act:"get",addrid:optin.addrid}, callback:function(resin){ if(resin.status == 1){ $("#addressedit").show(); $("#addrid_edt").val(optin.addrid); $("#addressee").val(resin.data.addressee); $("#add_str_text").text(resin.data.address1); $("#add_str").val(resin.data.address1); $("#add_ids").val(resin.data.state+'_'+resin.data.city+'_'+resin.data.county+'_'+resin.data.town); $("#add_more").val(resin.data.more); $("#zip").val(resin.data.zip); $("#cellphone").val(resin.data.cellphone); if(resin.data.town){ $("#add_str_2").val(resin.data.address2); }else{ $("#townSelRow").hide(); } if(resin.data.addrid == defaultAddr){ $("#sedefault").attr("checked","checked"); } $("#address_row").attr("data-state",resin.data.state); $("#address_row").attr("data-city",resin.data.city); $("#address_row").attr("data-county",resin.data.county); $("#townSelRow").attr("data-townid",resin.data.county); //删除地址 $("#delBtn").show().unbind("click").bind("click",function(){ AjaxFunUtils.ajaxInit({ url:"/myorder/address.html", params:{act:"del",addrid:optin.addrid}, callback:function (result) { if(result.status == 1){ getAddress();//删除完成刷新地址列表 config.tip.tips({ htmlmsg:'<div style="padding:30px">'+result.msg+'</div>', w:"96%", type:0 }); $("#addressbox").remove(); }else{ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+result.msg+'</div>', w:"96%", type:0 }); } } }); }); if(optin.callback){ optin.callback(resin); } } } }); }; //获取送货地址 var getAddress = function(odz){ AjaxFunUtils.ajaxInit({ url:"/myorder/address.html", params:{act:'list' }, callback:function(res){ var addresslist = res.data; if(addresslist.length<=0){ $("#addrid").html('<p id="newaddress" class="addAddressBtn" data-address="0" data-act="add" style="padding:0 5px; margin:5px 0">请填写收货人信息</p>'); addAddressBtn(); return false; } var html = ''; $.each(addresslist,function(index,o){ var newaddress = o.address1+' '+o.address2 + ' ' + o.more + ' ' + o.addressee + ' ' + o.cellphone; var checked = ''; if(o.default == 1){ checked = 'checked="checked"'; defaultAddr = o.addrid; } var addVal = '<li class="rowbox mt-5"><div class="row-flex1 rowbox"><input name="addrid" id="'+o.addrid+'" type="radio" value="'+o.addrid+'" '+checked+'><label style="line-height:20px" for="'+o.addrid+'">'+newaddress+'</label></div><div class="w100 text-right"><a href="javascript:void(0);" class="addAddressBtn" data-address="1" data-addrid="'+o.addrid+'" data-act="edt">编辑<div class="ico ico-jt ml-5"></div></a></div></li>'; html +=addVal; }); $("#addrid").html(html); addAddressBtn(); } }); }; //提交添加,编辑地址 var subaddress = function(opt){ $("#addressform").checkInput({ button:'.address_sub_btn', submitBtnFn: function (from) { var dataFrom = from.serializeJson(); dataFrom.act = opt.act; AjaxFunUtils.ajaxInit({ "url":"/myorder/address.html", "params":dataFrom, "callback":function (res) { if(res.status == 1){ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+res.msg+'</div>', w:"96%", type:0, callback:function(){ getAddress();//添加,编辑完成刷新地址列表 $("#addressbox").remove(); } }); }else{ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+res.msg+'</div>', w:"96%", type:0 }); } } }); } }); }; //增加地址,编辑地址绑定 var addAddressBtn = function(){ $(".addAddressBtn").unbind("click").bind("click",function(){ var typeId = $(this).attr("data-address"); var thisaddrid = $(this).attr("data-addrid"); var act = $(this).attr("data-act"); addedtAddress({act:act,addrid:thisaddrid}); }); //获取微信地址 $(".wxAddressBtn").unbind("click").bind("click",function(){ var thisaddrid = $(this).attr("data-addrid"); AjaxFunUtils.ajaxInit({ "url":"/myorder/address.html?act=weixin_sign", "params":{}, "callback":function (res) { if(res.status == 1){ var sign_info = res.data.sign_info; get_addres(); //获取微信地址 function get_addresinfo(){ WeixinJSBridge.invoke( 'editAddress', sign_info, function(res){ var resData = {}; resData.act = "add"; resData.nickname = res.username; resData.cellphone = res.telNumber; resData.zip = res.addressPostalCode; resData.address1 = res.addressCitySecondStageName +" "+res.addressCountiesThirdStageName+" "+res.addressDetailInfo; AjaxFunUtils.ajaxInit({ "url":"/myorder/address.html", "params":resData, "callback":function (res3) { if(res3.status == 1){ if($("#sedefault").attr("checked")){ //defaultAddr = thisaddrid; } //address.getAddress();//添加,编辑完成刷新地址s列表 }else{ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+res3.msg+'</div>', w:"96%", type:0 }); } } }); } ); }; function get_addres(){ if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', get_addresinfo, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', get_addresinfo); document.attachEvent('onWeixinJSBridgeReady', get_addresinfo); } }else{ get_addresinfo(); } }; } } }); }); }; return {init:init,getAddress:getAddress}; });
38695248/require-gulp
moblie/require/js/address.js
JavaScript
gpl-2.0
19,264
// ** I18N Calendar._DN = new Array ("Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"); Calendar._MN = new Array ("Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"); // tooltips Calendar._TT = {}; Calendar._TT["TOGGLE"] = "Skifta första veckodag"; Calendar._TT["PREV_YEAR"] = "Förra året (tryck för meny)"; Calendar._TT["PREV_MONTH"] = "Förra månaden (tryck för meny)"; Calendar._TT["GO_TODAY"] = "Gå till dagens datum"; Calendar._TT["NEXT_MONTH"] = "Nästa månad (tryck för meny)"; Calendar._TT["NEXT_YEAR"] = "Nästa år (tryck för meny)"; Calendar._TT["SEL_DATE"] = "Välj dag"; Calendar._TT["DRAG_TO_MOVE"] = "Flytta fönstret"; Calendar._TT["PART_TODAY"] = " (idag)"; Calendar._TT["MON_FIRST"] = "Visa Måndag först"; Calendar._TT["SUN_FIRST"] = "Visa Söndag först"; Calendar._TT["CLOSE"] = "Stäng fönstret"; Calendar._TT["TODAY"] = "Idag"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "y-mm-dd"; Calendar._TT["TT_DATE_FORMAT"] = "DD, d MM y"; Calendar._TT["WK"] = "wk";
Fightmander/Hydra
lib/calendar/lang/calendar-sw.js
JavaScript
gpl-2.0
1,143
{"filter":false,"title":"media-uploader.js","tooltip":"/wp-content/themes/openmind/inc/js/media-uploader.js","undoManager":{"mark":-1,"position":-1,"stack":[]},"ace":{"folds":[],"scrolltop":540,"scrollleft":0,"selection":{"start":{"row":12,"column":0},"end":{"row":12,"column":0},"isBackwards":false},"options":{"guessTabSize":true,"useWrapMode":false,"wrapToView":true},"firstLineState":{"row":31,"state":"start","mode":"ace/mode/javascript"}},"timestamp":1427120528270,"hash":"5de74553de66f4852bfca961734b9c895644dc21"}
ashrafeme/drprize
.c9/metadata/workspace/wp-content/themes/openmind/inc/js/media-uploader.js
JavaScript
gpl-2.0
521
/* Malaysian initialisation for the jQuery UI date picker plugin. */ /* Written by Mohd Nawawi Mohamad Jamili ([email protected]). */ jQuery(function ($) { $.datepicker.regional['ms'] = { closeText: 'Tutup', prevText: '&#x3c;Sebelum', nextText: 'Selepas&#x3e;', currentText: 'hari ini', monthNames: ['Januari', 'Februari', 'Mac', 'April', 'Mei', 'Jun', 'Julai', 'Ogos', 'September', 'Oktober', 'November', 'Disember'], monthNamesShort: ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ogo', 'Sep', 'Okt', 'Nov', 'Dis'], dayNames: ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'], dayNamesShort: ['Aha', 'Isn', 'Sel', 'Rab', 'kha', 'Jum', 'Sab'], dayNamesMin: ['Ah', 'Is', 'Se', 'Ra', 'Kh', 'Ju', 'Sa'], weekHeader: 'Mg', dateFormat: 'dd/mm/yy', firstDay: 0, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['ms']); });
parksandwildlife/parkstay
jomres/javascript/jquery-ui-cal-localisation/jquery.ui.datepicker-ms.js
JavaScript
gpl-2.0
932
/* * linksync commander -- Command line interface to LinkSync * Copyright (C) 2016 Andrew Duncan * * This package is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * found in the file LICENSE that should have accompanied this file. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const crawler = require('simplecrawler').Crawler, fs = require('node-fs'), path = require('path'), q = require('q'), request = require('request'), url = require('url'), linklib = require('./links'), settings = require('./settings'); var self = module.exports = { crawler: new crawler(), init_crawler: function() { self.crawler.cache = new crawler.cache(settings.get('syncroot')); self.crawler.interval = 250; self.crawler.maxConcurrency = 5; self.crawler.userAgent = "LinkSync version " + settings.get('version'); self.crawler.maxDepth = 1; self.crawler.ignoreInvalidSSL = true; }, download_url: function(id, weburl, callback) { var mask = parseInt('0755', 8); var parsed_url = url.parse(weburl); var root_id = id; self.crawler = new crawler(parsed_url.hostname); self.init_crawler(); self.crawler.queueURL(weburl); self.crawler.on("fetchcomplete", function(queue_item, response_buffer, response) { console.log("Fetched: %s", queue_item.url); var parsed_url = url.parse(queue_item.url); if (parsed_url.pathname === "/") { parsed_url.pathname = "/index.html"; } var output_directory = path.join(settings.get('syncroot') + root_id + '/', parsed_url.hostname); var dirname = output_directory + parsed_url.pathname.replace(/\/[^\/]+$/, ""); var filepath = output_directory + parsed_url.pathname; console.log('%s : %s : %s', output_directory, dirname, filepath); fs.exists(dirname, function(exists) { if (exists) { fs.writeFile(filepath, response_buffer, function() {}); } else { fs.mkdir(dirname, mask, true, function() { fs.writeFile(filepath, response_buffer, function() {}); }); } }); console.log("%s (%d bytes) / %s", queue_item.url, response_buffer.length, response.headers["content-type"]); }); self.crawler.on("fetcherror", function(error) { console.log("Error syncing url (%s): %s", weburl, error); }); self.crawler.on("complete", function() { callback(); }); self.crawler.start(); }, sync: function(id) { linklib.get_link(id).then(function(link) { console.log('Syncing %s ...', link.url); self.download_url(id, link.url, function() { console.log("Finished syncing %s", link.url); }); }); } }
lakesite/linksync-commander
lib/sync.js
JavaScript
gpl-2.0
3,119
describe('autocomplete', function () { beforeEach(function () { browser.get('/bonita/preview/page/no-app-selected/autocomplete/'); }); describe('simple list', function() { var input, p; beforeEach(function() { input = $('.test-simple input'); p = $('.test-simple p'); }); it('should allow to pick a suggestion dropdownlist and update the value', function() { input.sendKeys('n'); var values = $$('.dropdown-menu a'); expect(values.count()).toBe(2); values.get(0).click(); expect(p.getText()).toContain('London'); }); }); describe('Object list', function() { var input, p; beforeEach(function() { input = $('.test-object input'); p = $('.test-object p'); }); it('should display the correct value', function() { expect(p.getText()).toContain('{ "name": "Paul" }'); expect(input.getAttribute('value')).toContain('Paul'); }); it('should display the correct suggestions', function() { input.clear().sendKeys('a'); var values = $$('.dropdown-menu a'); var labels = values.map(function(item) { return item.getText(); }); expect(values.count()).toBe(3); expect(labels).toEqual(['Paul', 'Hokusai', 'Pablo']); }); it('should update the value when select a suggestion', function() { input.clear().sendKeys('a'); var values = $$('.dropdown-menu a'); values.get(1).click(); expect(p.getText()).toContain('Hokusai'); }); }); const labels = () => { return $$('.dropdown-menu a') .map(function (item) { return item.getText(); }); }; describe('async', () => { // see https://bonitasoft.atlassian.net/browse/BS-16696 it('should display the right suggestions', () => { const input = $('.test-async input'); input.clear().sendKeys('walt'); expect(labels()).toEqual([ 'walter.bates' ]); input.sendKeys(protractor.Key.BACK_SPACE); expect(labels()).toEqual([ 'walter.bates', 'thomas.wallis' ]); }); it('should return the returned key of selection', () => { const input = $('.test-async-with-returnedKey input'); input.clear().sendKeys('walter'); var values = $$('.dropdown-menu a'); values.get(0).click(); var p = $('.test-async-with-returnedKey p'); expect(p.getText()).toContain('4'); }); it('should return the full selected object if there is no returned key', () => { const input = $('.test-async-without-returnedKey input'); input.clear().sendKeys('walter'); var values = $$('.dropdown-menu a'); values.get(0).click(); var p = $('.test-async-without-returnedKey p'); expect(p.getText()).toContain('walter.bates'); expect(p.getText()).toContain('4'); }); }); });
bonitasoft/bonita-ui-designer
tests/src/test/spec/pages/autoComplete.spec.js
JavaScript
gpl-2.0
2,839
// config/ptv.js module.exports.ptv = { devId: 'xxx', devSecret: 'xxx', };
vuongngo/catchup
config/ptv.js
JavaScript
gpl-2.0
78
/** * Created by kliu on 10/10/2015. */ var jsonschema = require("jsonschema"); var utils = {}; utils.validateJSON = function(schema, json){ var result = jsonschema.validate(json, schema); if(result.errors.length == 0){ return json; }else{ throw new Error("message not valid, " + result.errors.join()); } }; utils.validateRawString = function(schema, message){ var self = this; var json = JSON.parse(message); return self.validateJSON(json, schema); }; /** * load and initial an object from specified path, and check the function exists in this object * @param filePath * @param checkFuncs * @constructor */ utils.loadAndCheck = function(filePath, checkFuncs){ var loadCls = require(filePath); var loadObj = new loadCls(); checkFuncs.forEach(function(checkFunc){ if (typeof(loadObj[checkFunc]) != "function") { throw new Error(filePath + " doesn't have " + checkFunc + "()") } }); return loadObj; }; module.exports = utils;
adleida/adx-nodejs
utils.js
JavaScript
gpl-2.0
1,027
/* global Ext, ViewStateManager, App */ Ext.define( 'App.ux.StatefulTabPanel', { extend: 'Ext.tab.Panel', alias: 'widget.statefultabpanel', initComponent: function() { this.iconCls = this.iconCls || this.itemId; this.on( 'afterrender', this.onAfterRender, this); this.callParent( arguments); }, setActiveTab: function( tab, dontUpdateHistory) { this.callParent( arguments); if (!dontUpdateHistory) { ViewStateManager.change( tab.itemId); } }, addViewState: function( tab, path) { var i, item, newPath; for (i = 0; i < tab.items.length; i++) { item = tab.items.get( i); newPath = Ext.Array.clone( path); newPath.push( item); ViewStateManager.add( item.itemId, newPath); if (item instanceof App.ux.StatefulTabPanel) { this.addViewState( item, newPath); } } tab.viewStateDone = true; }, onAfterRender: function( tab) { if (!tab.viewStateDone) { if (tab.ownerCt instanceof App.ux.StatefulTabPanel) { tab = tab.ownerCt; } this.addViewState( tab, []); } } });
liancastellon/cellstore-admin
web/app/ux/StatefulTabPanel.js
JavaScript
gpl-2.0
1,141
$(function(){ $('.home .bxslider').bxSlider({ auto: true, mode: 'fade' }); /** * QUICK REFERENCE */ // check if the window bindings should be applied (only if the element is present) var $reference = $('.reference-wrap'); if($reference.length > 0){ // toggle the menu $('.reference-wrap h3').click(function() { $('.reference-content').slideToggle(300); }); // scroll to the elements $('.reference-content a').click(function(){ $('.reference-content').slideToggle(300); var id = $(this).html(); $('html, body').animate({ scrollTop: $('#' + id).offset().top - 20 }, 300); return false; }); $(window).bind('scroll resize', positionQuickReference); } // check if .reference-wrap should be sticky function positionQuickReference(){ var windowTop = $(window).scrollTop(); if(windowTop >= 112){ $reference.css({ position: 'fixed', top: 20, right: $(window).width() > 700 ? $(window).width() - ($('#primary h1').offset().left + $('#primary').width()) : 20 }); }else{ $reference.css({ position: 'absolute', top: 0, right: $(window).width() > 1040 ? 0 : 20 }); } } /** * SIDEBAR */ $('.btn-donate').click(function() { $('#frm-paypal').submit(); return false; }); $('.block-signup form').submit(function() { var email = $('#mce-EMAIL').val(); if(!isValidEmailAddress(email)){ $('.block-signup .error').show(); return false; } }); }); function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); return pattern.test(emailAddress); }; // (function(){ // var bsa = document.createElement('script'); // bsa.type = 'text/javascript'; // bsa.async = true; // bsa.src = '//s3.buysellads.com/ac/bsa.js'; // (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa); // })(); /** * Create a cookie */ function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; }; /** * Get a cookie */ function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start, c_end)); } } return ""; };
naka211/tellusavokater
html/js/scripts.js
JavaScript
gpl-2.0
3,481
var express = require('express'); var reload = require('reload'); var fs = require('fs'); var wss = new require('ws').Server({port: 3030}); var app = express(); var Chopper = require('./lib/Chopper'); app.set('port', process.env.PORT || 3000); app.set('view engine', 'ejs'); app.use(require('./routes/index')); app.use(require('./routes/visual')); app.use(require('./routes/d3')); app.use(require('./routes/control')); app.use(require('./routes/config')); app.use(require('./routes/api')); app.use('/jquery', express.static('./node_modules/jquery/dist')); app.use(express.static('./public')); // global vars for the EJS (Embedded JavaScript) framework app.locals.siteTitle = 'CS'; // Control Systems title var server = app.listen(app.get('port'), function () { console.log('Example app listening on port: ' + app.get('port') + '!'); }); reload(server, app); wss.on('connection', function (ws) { ws.send('Welcome to cyber chat'); ws.on('message', function (msg) { if (msg == 'exit') { ws.close(); } }) }); var chop = new Chopper(); chop.on('ready', function() { console.log('Chopper ready'); app.set('chopper', chop); }); chop.on('change', function(value) { wss.clients.forEach(function (ws, index, list) { ws.send(JSON.stringify(value)); }) }); chop.on('data', function(type, data) { fs.writeFile(type + Date.now() + '.csv', data, function (err) { console.log(`${type} data saved`); }); });
gjgjwmertens/LedBlinkJohhny5
exp_app.js
JavaScript
gpl-3.0
1,517
export { AbilityScoresViewModel } from './ability_scores'; export { ActionsToolbarViewModel } from './actions_toolbar'; export { ArmorViewModel } from './armor'; export { CharacterNameViewModel } from './character_name'; export { CharacterPortraitModel } from './character_portrait'; export { CharacterStatusLineViewModel } from './character_status_line'; export { BackgroundViewModel } from './background'; export { FeatsViewModel } from './feats'; export { FeaturesViewModel } from './features'; export { ItemsViewModel } from './items'; export { MagicItemsViewModel } from './magic_items'; export { ProficienciesViewModel } from './proficiencies'; export { ProfileViewModel } from './profile'; export { CharacterRootViewModel } from './root'; export { SkillsViewModel } from './skills'; export { SpellSlotsViewModel } from './spell_slots'; export { SpellStatsViewModel } from './spell_stats'; export { SpellbookViewModel } from './spells'; export { StatsViewModel } from './stats'; export { TrackerViewModel } from './tracker'; export { TraitsViewModel } from './traits'; export { WealthViewModel } from './wealth'; export { WeaponsViewModel } from './weapons'; export { OtherStatsViewModel } from './other_stats';
adventurerscodex/adventurerscodex
src/charactersheet/viewmodels/character/index.js
JavaScript
gpl-3.0
1,218
var index = require('express').Router(); var Member = require('../models/Member'); var sitemap = require('../middlewares/sitemap'); var utils = require('../middlewares/utils'); index.get('/', function (req, res) { res.redirect('/article'); }); index.get('/lang', function (req, res) { var setLang; if (req.cookies.lang == undefined || req.cookies.lang == 'zh-cn') { setLang = 'en-us'; } else { setLang = 'zh-cn'; } res.cookie('lang', setLang); res.redirect('/'); }); index.get('/lib/contact-us', function (req, res) { res.render('contactUs', { description: '身为工大学子的你,如果对软件开发或是产品设计有兴趣,欢迎向我们投递简历。' }); }); index.get('/lib/sitemap.xml', function (req, res) { sitemap.createXml(function (xml) { res.contentType('text/xml'); res.send(xml); res.end(); }); }); module.exports = index;
hfut-xcsoft/xcsoft.hfut.edu.cn
routes/default.js
JavaScript
gpl-3.0
901
'use strict'; const Stack = require('./_Stack'); const baseIsEqual = require('./_baseIsEqual'); /** Used to compose bitmasks for comparison styles. */ const UNORDERED_COMPARE_FLAG = 1; const PARTIAL_COMPARE_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { let index = matchData.length; const length = index; const noCustomizer = !customizer; let data; if ((object === null || object === undefined)) { return !length; } object = Object(object); while (index--) { data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; const key = data[0]; const objValue = object[key]; const srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { const stack = new Stack(); let result; if (customizer) { result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch;
rafa1231518/CommunityBot
lib/xml2js-req/xmlbuilder/lodash/_baseIsMatch.js
JavaScript
gpl-3.0
1,805
module.exports = publish var url = require('url') var semver = require('semver') var Stream = require('stream').Stream var assert = require('assert') var fixer = require('normalize-package-data').fixer var concat = require('concat-stream') var ssri = require('ssri') function escaped (name) { return name.replace('/', '%2f') } function publish (uri, params, cb) { assert(typeof uri === 'string', 'must pass registry URI to publish') assert(params && typeof params === 'object', 'must pass params to publish') assert(typeof cb === 'function', 'must pass callback to publish') var access = params.access assert( (!access) || ['public', 'restricted'].indexOf(access) !== -1, "if present, access level must be either 'public' or 'restricted'" ) var auth = params.auth assert(auth && typeof auth === 'object', 'must pass auth to publish') if (!(auth.token || (auth.password && auth.username && auth.email))) { var er = new Error('auth required for publishing') er.code = 'ENEEDAUTH' return cb(er) } var metadata = params.metadata assert( metadata && typeof metadata === 'object', 'must pass package metadata to publish' ) try { fixer.fixNameField(metadata, {strict: true, allowLegacyCase: true}) } catch (er) { return cb(er) } var version = semver.clean(metadata.version) if (!version) return cb(new Error('invalid semver: ' + metadata.version)) metadata.version = version var body = params.body assert(body, 'must pass package body to publish') assert(body instanceof Stream, 'package body passed to publish must be a stream') var client = this var sink = concat(function (tarbuffer) { putFirst.call(client, uri, metadata, tarbuffer, access, auth, cb) }) sink.on('error', cb) body.pipe(sink) } function putFirst (registry, data, tarbuffer, access, auth, cb) { // optimistically try to PUT all in one single atomic thing. // If 409, then GET and merge, try again. // If other error, then fail. var root = { _id: data.name, name: data.name, description: data.description, 'dist-tags': {}, versions: {}, readme: data.readme || '' } if (access) root.access = access if (!auth.token) { root.maintainers = [{ name: auth.username, email: auth.email }] data.maintainers = JSON.parse(JSON.stringify(root.maintainers)) } root.versions[ data.version ] = data var tag = data.tag || this.config.defaultTag root['dist-tags'][tag] = data.version var tbName = data.name + '-' + data.version + '.tgz' var tbURI = data.name + '/-/' + tbName var integrity = ssri.fromData(tarbuffer, { algorithms: ['sha1', 'sha512'] }) data._id = data.name + '@' + data.version data.dist = data.dist || {} // Don't bother having sha1 in the actual integrity field data.dist.integrity = integrity['sha512'][0].toString() // Legacy shasum support data.dist.shasum = integrity['sha1'][0].hexDigest() data.dist.tarball = url.resolve(registry, tbURI) .replace(/^https:\/\//, 'http://') root._attachments = {} root._attachments[ tbName ] = { 'content_type': 'application/octet-stream', 'data': tarbuffer.toString('base64'), 'length': tarbuffer.length } var fixed = url.resolve(registry, escaped(data.name)) var client = this var options = { method: 'PUT', body: root, auth: auth } this.request(fixed, options, function (er, parsed, json, res) { var r409 = 'must supply latest _rev to update existing package' var r409b = 'Document update conflict.' var conflict = res && res.statusCode === 409 if (parsed && (parsed.reason === r409 || parsed.reason === r409b)) { conflict = true } // a 409 is typical here. GET the data and merge in. if (er && !conflict) { client.log.error('publish', 'Failed PUT ' + (res && res.statusCode)) return cb(er) } if (!er && !conflict) return cb(er, parsed, json, res) // let's see what versions are already published. client.request(fixed + '?write=true', { auth: auth }, function (er, current) { if (er) return cb(er) putNext.call(client, registry, data.version, root, current, auth, cb) }) }) } function putNext (registry, newVersion, root, current, auth, cb) { // already have the tardata on the root object // just merge in existing stuff var curVers = Object.keys(current.versions || {}).map(function (v) { return semver.clean(v, true) }).concat(Object.keys(current.time || {}).map(function (v) { if (semver.valid(v, true)) return semver.clean(v, true) }).filter(function (v) { return v })) if (curVers.indexOf(newVersion) !== -1) { return cb(conflictError(root.name, newVersion)) } current.versions[newVersion] = root.versions[newVersion] current._attachments = current._attachments || {} for (var i in root) { switch (i) { // objects that copy over the new stuffs case 'dist-tags': case 'versions': case '_attachments': for (var j in root[i]) { current[i][j] = root[i][j] } break // ignore these case 'maintainers': break // copy default: current[i] = root[i] } } var maint = JSON.parse(JSON.stringify(root.maintainers)) root.versions[newVersion].maintainers = maint var uri = url.resolve(registry, escaped(root.name)) var options = { method: 'PUT', body: current, auth: auth } this.request(uri, options, cb) } function conflictError (pkgid, version) { var e = new Error('cannot modify pre-existing version') e.code = 'EPUBLISHCONFLICT' e.pkgid = pkgid e.version = version return e }
lyy289065406/expcodes
java/01-framework/dubbo-admin/incubator-dubbo-ops/dubbo-admin-frontend/node/node_modules/npm/node_modules/npm-registry-client/lib/publish.js
JavaScript
gpl-3.0
5,905
pref('devcache.debug', false); pref('devcache.enabled', true); pref('devcache.patterns', '');
essentialed/DevCache
defaults/preferences/prefs.js
JavaScript
gpl-3.0
97
/* UTILIZZO DEL MODULO: var mailer = require('percorso/per/questoFile.js'); mailer.inviaEmail(nome, cognome, emailDestinatario, oggetto, corpoInHtml); OPPURE mailer.inviaEmail(opzioniEmail); dove opzioniEmail è un oggetto JSON formato così: { from: '"Nome Visualizzato" <[email protected]>', // mail del mittente to: '[email protected]', // email destinatario, eventualmente può essere una lista con elementi separati da virgole subject: 'Oggetto', // l'oggetto dell'email text: 'Ciao', // email solo testo html: '<h3>Ciao</h3>' // email HTML } L'indirizzo email usato per l'invio nel primo caso è quello del gruppo dei developer (creato ad hoc per il progetto) , ovvero [email protected] Eventualmente basta cambiare i settaggi nel transporter Un futuro lavoro potrebbe essere quello di fare in modo che anche il transporter sia settabile a piacimento dall'applicazione stessa */ 'use strict'; const nodemailer = require('nodemailer'); var jsonfile = require('jsonfile') var file = './server/config/mailSettings.json'; var fs = require('fs'); var transporter; //var passwords = require('../config/passwords'); var scriviFileDummy = function() { var settaggi = { host: 'smtp.example.org', port: 465, secure: 'true', user: '[email protected]', pass: 'passwordExample' }; // scrivo il file dummy jsonfile.writeFileSync(file, settaggi); return settaggi; }; var impostaTransporter = function() { var settaggi = leggiPrivate(); // svuoto il vecchio transporter e lo ricreo transporter = null; transporter = nodemailer.createTransport({ host: settaggi.host, port: settaggi.port, secure: settaggi.secure, auth: { user: settaggi.user, pass: settaggi.pass } }); console.log('transporter impostato'); } var leggiPrivate = function() { if (fs.existsSync(file)) { console.log('File exists'); return jsonfile.readFileSync(file) } else { // file does not exist return scriviFileDummy(); } } exports.leggiSettaggi = function() { console.log('chiamata dalla api al mailer') if (fs.existsSync(file)) { console.log('File exists'); return jsonfile.readFileSync(file) } else { // file does not exist return scriviFileDummy(); } } exports.scriviSettaggi = function(obj) { // se non ci sono settaggi li creo dummy if (obj === null) scriviFileDummy() else jsonfile.writeFile(file, obj, function(err) { if (err) return console.log('ERRORE NELLA SCRITTURA DEI SETTAGGI EMAIL'); impostaTransporter(); }); } exports.inviaEmail = function(opzioniEmail) { if (transporter === null || transporter === undefined) { // lo popolo al volo impostaTransporter(); } transporter.sendMail(opzioniEmail, (error, info) => { if (error) { return console.log(error); } console.log('Message %s sent: %s', info.messageId, info.response); }) } exports.inviaEmail = function(nome, cognome, emailDestinatario, oggetto, corpoInHtml) { /* FORMA JSON DELLE OPZIONI: { from: '"Fred Foo 👻" <[email protected]>', // indirizzo mittente to: '[email protected], [email protected]', // lista riceventi subject: 'Hello ✔', // Intestazione text: 'Hello world ?', // email con testo normale html: '<b>Hello world ?</b>' // email con testo in html } */ if (transporter === null || transporter === undefined) { // lo popolo al volo impostaTransporter(); } var opzioniEmail = { from: '"Sito Tranquillo" <[email protected]>', to: emailDestinatario, subject: oggetto, html: corpoInHtml } transporter.sendMail(opzioniEmail, (error, info) => { if (error) { return console.log(error); } console.log('Message %s sent: %s', info.messageId, info.response); }) }
ecommerce-unicam/Sito-Tranquillo
server/utilities/mailer.js
JavaScript
gpl-3.0
4,054
/** * Class: Webgl * Description: Her goes description */ import {m, utils} from '../../js/main'; import * as THREE from './three.min.js' import dat from './dat.gui.min.js' import Detector from './Detector.js' // GLOBAL var EightBitMode = false; export default class Webgl { /** * @param {number} param this is param. * @return {number} this is return. */ constructor(config) { // put in defaults here //defaults this.config = $.extend({ el:'#snow' },config); this.$el = $(this.config.el); this.renderer, this.scene, this.camera, this.cameraRadius = 50.0, this.cameraTarget, this.cameraX = 0, this.cameraY = 0, this.cameraZ = this.cameraRadius, this.particleSystem, this.particleSystemHeight = 100.0, this.wind = 2.5, this.clock, this.controls, this.parameters, this.onParametersUpdate, this.texture, this.loader; this.init(); } init() { var self = this; this.renderer = new THREE.WebGLRenderer( { alpha: true, antialias: true } ); this.renderer.setSize( window.innerWidth, window.innerHeight ); this.renderer.setClearColor( 0x000000, 0 ); this.renderer.sortObjects = false; this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); this.cameraTarget = new THREE.Vector3( 0, 0, 0 ); this.loader = new THREE.TextureLoader(); this.loader.crossOrigin = ''; this.texture = this.loader.load( '../assets/textures/snowflake.png', // Resource is loaded function ( texture ) { // create the particles with the texture self.createParticles( texture ); }, // Download progress function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // Download errors function ( xhr ) { console.log( 'An error happened during the loading of the texture ' ); } ); } createParticles( tex ) { var numParticles = 2000, width = 70, height = this.particleSystemHeight, depth = 80, parameters = { // color: 0xffffff, color: 0xffffff, height: this.particleSystemHeight, radiusX: this.wind, radiusZ: 2.5, size: 100, scale: 4.0, opacity: 1, speedH: 1.0, speedV: 1.0 }, systemGeometry = new THREE.Geometry(), systemMaterial = new THREE.ShaderMaterial({ uniforms: { color: { type: 'c', value: new THREE.Color( parameters.color ) }, height: { type: 'f', value: parameters.height }, elapsedTime: { type: 'f', value: 0 }, radiusX: { type: 'f', value: parameters.radiusX }, radiusZ: { type: 'f', value: parameters.radiusZ }, size: { type: 'f', value: parameters.size }, scale: { type: 'f', value: parameters.scale }, opacity: { type: 'f', value: parameters.opacity }, texture: { type: 't', value: tex }, speedH: { type: 'f', value: parameters.speedH }, speedV: { type: 'f', value: parameters.speedV } }, vertexShader: document.getElementById( 'snow_vs' ).textContent, fragmentShader: document.getElementById( 'snow_fs' ).textContent, blending: THREE.AdditiveBlending, transparent: true, depthTest: false }); // Less particules for mobile if( this.isMobileDevice ) { numParticles = 200; } for( var i = 0; i < numParticles; i++ ) { var vertex = new THREE.Vector3( this.rand( width ), Math.random() * height, this.rand( depth ) ); systemGeometry.vertices.push( vertex ); } this.particleSystem = new THREE.Points( systemGeometry, systemMaterial ); this.particleSystem.position.y = -height/2; this.scene.add( this.particleSystem ); this.clock = new THREE.Clock(); document.getElementById("snow").appendChild( this.renderer.domElement ); this.bindEvents(); } // Events -------------------------------------------------------------------------- bindEvents() { // bind your events here. var self = this; document.addEventListener( 'mousemove', function( e ) { var mouseX = e.clientX, mouseY = e.clientY, width = window.innerWidth, halfWidth = width >> 1, height = window.innerHeight, halfHeight = height >> 1; var targetX = self.cameraRadius * ( mouseX - halfWidth ) / halfWidth; self.cameraX = targetX / 10; //self.cameraY = self.cameraRadius * ( mouseY - halfHeight ) / halfHeight; }, false ); // Activat e8 bit mode button document.getElementById("eightbitmodebutton").addEventListener( 'click', this.activateEightBitMode, false ); // handle resize this.handleWindowResize(); // Animate snow this.animate(); } activateEightBitMode() { var self = this; if( !EightBitMode ){ EightBitMode = true; $('#activate-text').html("DEACTIVATE</br>X-MAS MODE"); emitter = new EightBit_Emitter().init(); } else { EightBitMode = false; $('#activate-text').html("ACTIVATE</br>X-MAS MODE"); $('#eightbits').empty(); } } handleWindowResize() { this.renderer.setSize(window.innerWidth, window.innerHeight); this.camera.aspect = window.innerWidth / window.innerHeight; this.camera.updateProjectionMatrix(); } animate() { requestAnimationFrame( this.animate.bind(this) ); if( EightBitMode ) { var delta = this.clock.getDelta(), elapsedTime = this.clock.getElapsedTime(); this.particleSystem.material.uniforms.elapsedTime.value = elapsedTime * 10; this.camera.position.set( this.cameraX, this.cameraY, this.cameraZ ); this.camera.lookAt( this.cameraTarget ); this.renderer.clear(); this.renderer.render( this.scene, this.camera ); } else { this.renderer.clear(); } } // Getters / Setters -------------------------------------------------------------------------- addWind() { this.particleSystem.material.uniforms.radiusX.value = this.wind; m.TweenMax.from( this.particleSystem.material.uniforms.radiusX, 3, { value:30, ease:Quad.easeOut } ); } // Utils -------------------------------------------------------------------------- rand( v ) { return (v * (Math.random() - 0.5)); } // easy mobile device detection isMobileDevice() { if ( navigator === undefined || navigator.userAgent === undefined ) { return true; } var s = navigator.userAgent; if ( s.match( /iPhone/i ) || s.match( /iPod/i ) || s.match( /webOS/i ) || s.match( /BlackBerry/i ) || ( s.match( /Windows/i ) && s.match( /Phone/i ) ) || ( s.match( /Android/i ) && s.match( /Mobile/i ) ) ) { return true; } return false; } } /////////////////////////////////////////////////////////////////////////////// // 8 Bit Xmas Mode /////////////////////////////////////////////////////////////////////////////// var indexes = 2500; var prefix = '/assets/textures/'; var bitmaps = [ { type:'moose', img:'moose.gif', w:64, h:64 }, { type:'santa', img:'santa.gif', w:100, h:100 }, { type:'mistletoe', img:'mistletoe1.png', w:109, h:99 }, { type:'mistletoe', img:'mistletoe2.png', w:123, h:114 }, { type:'gift', img:'kdo1.png', w:64, h:67 }, { type:'gift', img:'kdo2.png', w:64, h:67 }, { type:'gift', img:'kdo3.png', w:64, h:67 }, { type:'mistletoe', img:'mistletoe1.png', w:109, h:99 }, { type:'mistletoe', img:'mistletoe2.png', w:123, h:114 }, ]; var emitter; class EightBit_Emitter { constructor( $selector = '#eightbits', maxParticles=10 ) { this.$emitter = document.querySelector($selector); this.maxParticles = maxParticles; } init() { var self = this; this.newParticle(); } newParticle() { var self = this; var timing = Math.floor( Math.random() * 5000 + 1000 ); // Element caracteristics var pRand = Math.floor( Math.random() * bitmaps.length ); var life = Math.floor( Math.random() * 10 + 15 ); var particle = new EightBit_Particle( pRand, life ); // check if we are still on EightBit mode if( EightBitMode ) { // Wait if too many guys on the floor if( $('#eightbits .particle').length <= this.maxParticles ) { setTimeout( self.newParticle.bind( this ), timing ); } } } handleWindowResize(){ var wWidth = window.innerWidth; var wHeight = window.innerHeight; } } class EightBit_Particle { constructor( idx, life ) { this.idx = idx; this.life = life; this._create(); } _create() { var self = this; var wWidth = window.innerWidth; var wHeight = window.innerHeight; var pic = '<div class="particle" id="p-' + indexes + '"><img src="' + prefix + bitmaps[this.idx].img + '"></div>'; $('#eightbits').append( pic ); var part = $('#p-' + indexes); indexes++; var tweenObject; if( this.idx <= 1 ) { // Moose & Santa part.css({ top: ( wHeight - bitmaps[this.idx].h ) + "px", left: ( wWidth + 100 ) + "px", 'z-index':indexes }); tweenObject = { left:-100, // easing:Linear.easeNone, onComplete:function(){ $(part).remove(); }, onCompleteParams:[part] } } else if ( this.idx > 1 ) { // falling stuff part.css({ top: "-100px", left: Math.floor( Math.random() * ( wWidth - 100 ) + 100 ) + "px", 'z-index':indexes }); tweenObject = { top:wHeight + 100, // easing:Linear.easeNone, // rotation:Math.floor( Math.random() * 90 ), onComplete:function(){ $(part).remove(); }, onCompleteParams:[part] } } m.TweenMax.to( part, self.life, tweenObject ); } }
GreatWorksCopenhagen/gw-xmascard
src/modules/webgl/webgl.js
JavaScript
gpl-3.0
10,063
"use strict"; var os = require("os"); var fs = require('fs'); var settings = require("../config.js").settings; exports.module = function() { this.onCommand_help = function(nick, command) { var chan = this.channel; fs.readFile('./package.json', 'utf-8', function(err, data) { if (!err) { chan.say(settings.globalNick + " v" + JSON.parse(data).version + " by Dirbaio, Nina, LifeMushroom, and AlphaTech. Running on Node.js " + process.versions.node + " (" + os.type() + " " + os.release() + " " + os.arch() + ")."); chan.say("For a list of available commands, check http://v.gd/TheBotCommands"); } else { console.err("Error opening ./package.js... Did you delete it?") } }); }; };
bitspill/Modular-Node.js-IRC-Bot
modules/help.js
JavaScript
gpl-3.0
708
/* eslint-env node */ import { JSDOM } from 'jsdom'; const html = `<body> <div id="test_player" data-vimeo-id="2"></div> <div class="multiple"> <iframe class="two" src="https://player.vimeo.com/video/2"></iframe> <iframe class="one" src="https://player.vimeo.com/video/76979871"></iframe> </div> </body>`; global.window = new JSDOM(html).window; global.document = window.document; global.navigator = window.navigator; global.window.jQuery = global.jQuery = require('jquery');
Yunfeng/h5buk
public/assets/vendor/player.js/test/helpers/browser-env.js
JavaScript
gpl-3.0
485
Vue.component('snackbar', require('./components/material/snackbar.vue')); Vue.component('show-snackbar', require('./components/material/show-snackbar.vue'));
authv/authv
resources/assets/js/authv.js
JavaScript
gpl-3.0
159
function changeQueryStr(name, value) { var query = window.location.search.substring(1), newQuery = '?', notFound = true, vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair == '' || pair[0] == 'page') continue; if (pair[0] == name) { notFound = false; pair[1] = value; } if (pair[1].length > 0) { newQuery += pair[0] + '=' + pair[1] + '&'; } } if (notFound && value.length > 0) { newQuery += name + '=' + value; } else if (newQuery.length == 1) { newQuery = ''; } else { newQuery = newQuery.slice(0,-1); } var loc = window.location, ajaxurl = '/ajax' + loc.pathname + newQuery, newurl = loc.protocol + "//" + loc.host + loc.pathname + newQuery; $.get(ajaxurl).done(function(data){ $('#ajax-content').html(data); init_pagination(); }); window.history.pushState({path:newurl},'',newurl); } function init_filtering_stories(jQuery) { $('#filtering input').change(function(){ var input = $(this), name = input[0].name, value=input.val(); changeQueryStr(name, value); }); } function init_pagination(jQuery) { $('.pager a').on('click', function(e){ e.preventDefault(); var value = $(this).closest('li').data('pageNum'); if (value) changeQueryStr('page', String(value)); }); } $(document).ready(init_filtering_stories); $(document).ready(init_pagination);
RomanOsadchuk/GoStory
general/static/general/js/list_filtering.js
JavaScript
gpl-3.0
1,490
import Route from '@ember/routing/route' import resetScroll from 'radio4000/mixins/reset-scroll' export default Route.extend(resetScroll, {})
internet4000/radio4000
app/channels/route.js
JavaScript
gpl-3.0
143
/* Copyright 2010-2012 Infracom & Eurotechnia ([email protected]) This file is part of the Webcampak project. Webcampak 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. Webcampak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 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 Webcampak. If not, see http://www.gnu.org/licenses/. */ console.log('Log: Load: Webcampak.view.dashboard.sourcepicturesizes.SourcesList'); //var rowEditing = Ext.create('Ext.grid.plugin.RowEditing'); Ext.define('Webcampak.view.dashboard.sourcepicturesizes.SourcesList' ,{ extend: 'Ext.form.ComboBox', alias : 'widget.statssourceslistpicturesizes', store: 'permissions.sources.Sources', name: 'source', valueField: 'id', displayField: 'name', typeAhead: true, emptyText: i18n.gettext('Select another source...'), style: 'text-align: center;', width: 315 });
Webcampak/v2.0
src/www/interface/dev/app/view/dashboard/sourcepicturesizes/SourcesList.js
JavaScript
gpl-3.0
1,232
global.should = require('should'); global.Breadboard = require('../lib');
palra/breadboard
test/globalHooks.js
JavaScript
gpl-3.0
73
function PingPongPaddle(x, y, z, radius) { this.x = x; this.y = y; this.z = z; this.radius = radius; } PingPongPaddle.prototype = { rotation: new THREE.Vector3(0, 0, 0), init: function(scene) { var tableImage = THREE.ImageUtils.loadTexture('images/paddle_texture.jpg'); //var geometry = new THREE.CubeGeometry(this.radius, this.radius, .1); var geometry = new THREE.CylinderGeometry(this.radius, this.radius, .1, 16, 1); this.paddle = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ map: tableImage, transparent: true, opacity: .5 })); //this.paddle.doubleSided = true; this.rotate(Math.PI / 2, 0, 0); this.paddle.position.x = this.x; this.paddle.position.y = this.y; this.paddle.position.z = this.z; scene.add(this.paddle); }, update: function() { if (this.paddle.position.y > 20) { direction = -1; } else if (this.paddle.position.y < -20) { direction = 1; } this.paddle.position.y += direction * .1; }, hitPaddle: function(x, y, z, radius) { if (Math.abs(this.paddle.position.x - x) < radius) { return isBetween(y, this.paddle.position.y + this.radius / 2, this.paddle.position.y - this.radius / 2) && isBetween(z, this.paddle.position.z + this.radius / 2, this.paddle.position.z - this.radius / 2); } }, rotate: function(x, y, z) { this.paddle.rotateOnAxis(new THREE.Vector3(1, 0, 0), x); this.rotation.x += x; this.paddle.rotateOnAxis(new THREE.Vector3(0, 1, 0), y); this.rotation.y += y; this.paddle.rotateOnAxis(new THREE.Vector3(0, 0, 1), z); this.rotation.z += z; } } var direction = 1; function isBetween(x, x1, x2) { return (x <= x1 && x >= x2) || (x >= x1 && x <= x2); }
mryan23/PingPongServer
war/js/ping_pong_paddle.js
JavaScript
gpl-3.0
1,903
function InstrumentSelector(list) { this.instruments = list; this.currentInstrument; this.updateInstrumentView(); } InstrumentSelector.prototype.addInstrument = function (type, url, colorCode) { var l = this.instruments.push(new Instrument(type, url, colorCode)); this.createInstrumentView(l-1); } InstrumentSelector.prototype.removeInstrument = function (type, url, colorCode) { this.instruments.push(new Instrument(type, url, colorCode)); this.updateInstrumentView(); } InstrumentSelector.prototype.createInstrumentView = function (index) { var bar = document.getElementById("instrumentBar"); var img = document.createElement("span"); img.className = "instrumentContainer"; img.id = this.instruments[index].instrumentName; img.style.backgroundImage = "url(" + this.instruments[index].imgURL + ")"; img.style.backgroundColor = this.instruments[index].color; // img.style.backgroundImage = "url(images/"+this.instruments[index]+".png)"; bar.appendChild(img); } InstrumentSelector.prototype.updateInstrumentView = function () { var bar = document.getElementById("instrumentBar"); // first clear all the children. var len = bar.children.length; for (var a=0; a<len; a++) { bar.removeChild(bar.children[a]); } // then add all for (var i=0; i < this.instruments.length; i++) { this.createInstrumentView(i); } } InstrumentSelector.prototype.setActiveInstrument = function (instrumentName) { this.currentInstrument = this.getInstrument(instrumentName); this.updateSelected(); } InstrumentSelector.prototype.getInstrument = function (instrumentName) { for (var i=0; i<this.instruments.length; i++) { // alert(this.instruments[i].instrumentName + " " + instrumentName); if (this.instruments[i].instrumentName == instrumentName) { return this.instruments[i]; } } return null; } InstrumentSelector.prototype.updateSelected = function () { for (var i=0; i<this.instruments.length; i++) { var sel = document.getElementById(this.instruments[i].instrumentName); sel.className = sel.className.replace(" instrumentSelected",""); } var sel = document.getElementById(this.currentInstrument.instrumentName); sel.className = sel.className + " instrumentSelected"; }
mqtlam/cloud-composer
release/beta_0.3/include/InstrumentSelector.js
JavaScript
gpl-3.0
2,208
function glitch_frame(frame) { // bail out if we have no motion vectors let mvs = frame["mv"]; if ( !mvs ) return; // bail out if we have no forward motion vectors let fwd_mvs = mvs["forward"]; if ( !fwd_mvs ) return; // clear horizontal element of all motion vectors for ( let i = 0; i < fwd_mvs.length; i++ ) { // loop through all rows let row = fwd_mvs[i]; for ( let j = 0; j < row.length; j++ ) { // loop through all macroblocks let mv = row[j]; // THIS IS WHERE THE MAGIC HAPPENS mv[0] = 0; // this sets the horizontal motion vector to zero // mv[1] = 0; // you could also change the vertical motion vector } } }
JC-Morph/alghemy
lib/alghemy/scripts/mv_sink.js
JavaScript
gpl-3.0
805
/* | Copyright 2015 Pispidikis john | | Licensed under the GNU GENERAL PUBLIC LICENSE Version 3 | you may not use this file except in compliance with the License. | | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ function addworkspace() { var selectionlayer = document.getElementById('selectedlayer'); var selection = document.getElementById('selectedworkspace'); var selectionstore = document.getElementById('selectedstore'); var geoserverurl=$("#geoserverurl").val(); if(geoserverurl=="") { messagealert("There is no URL input","ATTENTION!"); }//if(geoserverurl=="") else { $.get(geoserverurl+"rest/workspaces.json").done(function(response) { var workspaces=response.workspaces.workspace; selectionstore.innerHTML = ""; selectionstore.add(new Option("-", "-")); selectionlayer.innerHTML = ""; selectionlayer.add(new Option("-", "-")); selection.innerHTML = ""; selection.add(new Option("Select Workspace", "Select Workspace")); //var obj = JSON.parse(response); for (var key in workspaces){ // alert(obj['workspaces']['workspace']); selection.add(new Option(workspaces[key].name, workspaces[key].name)); }// for (var key in response) })//done(function() .fail(function() { selection.innerHTML = ""; selection.add(new Option("-", "-")); selectionstore.innerHTML = ""; selectionstore.add(new Option("-", "-")); messagealert("Connection Fail","ATTENTION!"); }//fail(function() ); //$.get('geoserverurl'+"rest/workspaces.json").then(function(response) }//else }//function addworkspace() function Geoserverchangevalueofworkspace(sel) { var selectionstore = document.getElementById('selectedstore'); var selectionlayer = document.getElementById('selectedlayer'); var geoserverurl=$("#geoserverurl").val(); if(geoserverurl=="") { messagealert("There is no URL input","ATTENTION!"); }//if(geoserverurl=="") else { $.get(geoserverurl+"rest/workspaces/"+sel.value+"/datastores.json").done(function(response) { var stores=response.dataStores.dataStore; selectionstore.innerHTML = ""; selectionstore.add(new Option("Select Store", "Select Store")); for (var key in stores){ // alert(obj['workspaces']['workspace']); selectionstore.add(new Option(stores[key].name, stores[key].name)); }// for (var key in response) }).fail(function() { selectionstore.innerHTML = ""; selectionstore.add(new Option("-", "-")); selectionlayer.innerHTML = ""; selectionlayer.add(new Option("-", "-")); messagealert("Connection Fail","ATTENTION!"); }); }//else }//function Geoserverchangevalueofstores(sel) function Geoserverchangevalueofstore(sel) {// var selectionworkspace=$('#selectedworkspace').val(); var selectionlayer = document.getElementById('selectedlayer'); var selectionstore = $('#selectedstore').val(); var geoserverurl=$("#geoserverurl").val(); if(geoserverurl=="") { messagealert("There is no URL input","ATTENTION!"); }//if(geoserverurl=="") else { $.get(geoserverurl+"rest/workspaces/"+selectionworkspace+"/datastores/"+sel.value+"/featuretypes.json").done(function(response) { var layers=response.featureTypes.featureType; selectionlayer.innerHTML = ""; selectionlayer.add(new Option("Select Layer", "Select Layer")); for (var key in layers){ // alert(obj['workspaces']['workspace']); selectionlayer.add(new Option(layers[key].name, layers[key].name)); }// for (var key in response) }).fail(function() { selectionlayer.innerHTML = ""; selectionlayer.add(new Option("-", "-")); messagealert("Connection Fail","ATTENTION!"); }); }//else }//function Geoserverchangevalueoflayer(sel) function AddOgcLayers(geoserverurl,workspace,store,layer,ogc){ if(ogc=="WMS") { //checkname var checking=false; var checkname="WMS_"+workspace+'_'+layer; //alert(buildings.length); for(var i=0;i<userConfig.overlayer.length;i++) { if(userConfig.overlayer[i].get("title")===checkname) { checking=true; } }//for(var i=0;i<userConfig.overlayer.length;i++) if(checking==true) { for(var j=0;j<userConfig.overlayer.length;j++) { if(userConfig.overlayer[j].get("title")==checkname) { $("#tr"+j).css('display','block'); zoomtocurrentlayer(j); if(document.getElementById("checkbox"+j).checked==true) { userConfig.overlayer[j].setVisible(true); } } } }//if(checking==true) ///////////////// if(checking==false) { var mylayer= new ol.layer.Tile({ title:"WMS_"+workspace+'_'+layer, // extent: [23.7558830002859,37.9693964210029,23.7566755911988,37.9699165146207], source: new ol.source.TileWMS(/** @type {olx.source.TileWMSOptions} */ ({ url: geoserverurl+workspace+'/wms', params: { 'VERSION': '1.1.1','LAYERS': workspace+':'+layer, 'TILED': true /*"version":"1.1.1", "format":"application/vnd.google-earth.kml+xml", "layers":"myworkspace:examplecitydb", //"height":"2048", // "width":"2048" "transparent":"true", "srs":"EPSG:4326", "format_options":"AUTOFIT:true;KMATTR:true;KMPLACEMARK:true;KMSCORE:100;MODE:refresh;SUPEROVERLAY:true;"*/ }, serverType: 'geoserver' })) }); ol2d.addLayer(mylayer); userConfig.overlayer.push(mylayer); var data=$('#data').html(); html=addnewoverlayerWMS(userConfig.overlayer.length-1,true); // configureOverlayers(); if(data!=="no data") { $('#data').append(html); } else { $('#data').html(html); } }// if(checking==false) }//if(ogc=="WMS") else if(ogc=="WFS") { //checkname var checking=false; var checkname="WFS_"+workspace+'_'+layer; //alert(buildings.length); for(var i=0;i<userConfig.overlayer.length;i++) { if(userConfig.overlayer[i].get("title")===checkname) { checking=true; } }//for(var i=0;i<userConfig.overlayer.length;i++) if(checking==true) { for(var j=0;j<userConfig.overlayer.length;j++) { if(userConfig.overlayer[j].get("title")==checkname) { $("#tr"+j).css('display','block'); zoomtocurrentlayer(j); if(document.getElementById("checkbox"+j).checked==true) { userConfig.overlayer[j].setVisible(true); } } } }//if(checking==true) ///////////////// if(checking==false) { // $.ajax(geoserverurl+workspace+'/ows?service=WFS&version=1.1.0&request=GetFeature&typeName='+workspace+':'+layer+'&outputFormat=application/json').then(function(response) { // format used to parse WFS GetFeature responses var geojsonFormat = new ol.format.GeoJSON(); var vectorSource = new ol.source.Vector({ loader: function(extent, resolution, projection) { var url = geoserverurl+workspace+'/wfs?service=WFS&' + 'version=1.1.0&request=GetFeature&typename='+workspace+':'+layer+'&' + 'outputFormat=text/javascript&format_options=callback:loadFeatures' + '&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857'; // use jsonp: false to prevent jQuery from adding the "callback" // parameter to the URL $.ajax({url: url, dataType: 'jsonp', jsonp: false}); }, strategy: ol.loadingstrategy.tile(ol.tilegrid.createXYZ({ maxZoom: 19 })) }); /** * JSONP WFS callback function. * @param {Object} response The response object. */ window.loadFeatures = function(response) { //vectorSource.clear(); vectorSource.addFeatures(geojsonFormat.readFeatures(response)); }; var vector = new ol.layer.Vector({ title: "WFS_"+workspace+'_'+layer, source: vectorSource, style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'rgba(0, 0, 255, 1.0)', width: 2 }) }) }); ol2d.addLayer(vector); // var layer = findBy(ol2d.getLayerGroup(),citydbname); userConfig.overlayer.push(vector); var data=$('#data').html(); html=addnewoverlayerWMS(userConfig.overlayer.length-1,true); // configureOverlayers(); if(data!=="no data") { $('#data').append(html); } else { $('#data').html(html); } }//if(checking==false) }//else if(ogc=="WFs }//function AddOgcLayers(geoserverurl,workspace,store,layer,ogc){ function addnewoverlayerWMS(i,check) { var html='<table>'; html+='<tr id="tr'+i+'" fillcolor="ffcc33" strokecolor="000000">'; html+="<td>"; if(check==true) { html+='<input type="checkbox" id="checkbox'+i+'" name="checkbox" value="'+i+'" checked="checked" onchange="overlayercheck('+i+')" />'; html+='<img id="hover'+i+'" src="images/hover.jpg" style="WIDTH: 12px; HEIGHT: 12px; cursor:pointer" onmouseover="changestyleoverhover('+i+')"'; html+='onmouseout="changestyleouthover('+i+')""></img>'; } else { html+='<input type="checkbox" id="checkbox'+i+'" name="checkbox" value="'+i+'" onchange="overlayercheck('+i+')" />'; html+='<img id="hover'+i+'" src="images/hover.jpg" style="WIDTH: 12px; HEIGHT: 12px; cursor:pointer;visibility:hidden;" onmouseover="changestyleoverhover('+i+')"'; html+='onmouseout="changestyleouthover('+i+')""></img>'; } html+='</td>'; html+="<td style='min-width: 250px;'>"; html+=userConfig.overlayer[i].get("title"); html+="<br>"; var layer = findBy(ol2d.getLayerGroup(), userConfig.overlayer[i].get("title")); if(check==true) { html+= '<input class="opacity'+userConfig.overlayer[i].get("title")+'" style="display:block;" type="range" min="0" max="1" step="0.01" value="1" onchange="changeopacity('+i+')"/>'; } else { html+= '<input class="opacity'+userConfig.overlayer[i].get("title")+'" style="display:none;" type="range" min="0" max="1" step="0.01" value="1" onchange="changeopacity('+i+')"/>'; } html+='</td>'; html+="<td>"; /* //zoom to currentlayer html+=' <button class="mapButton" title="zoot to: '+userConfig.overlayer[i].get("title")+'" id="'+userConfig.overlayer[i].get("title")+'" onclick="zoomtocurrentlayer('+i+')" style="cursor: pointer"><img src="images/search16.png" style="WIDTH: 9px; HEIGHT: 9px"></img></button>'; html+='</td>'; //change color html+="<td>"; html+='<button class="mapButton" title="change style to: '+userConfig.overlayer[i].get("title")+'" id="'+userConfig.overlayer[i].get("title")+'" onclick="changestyle('+i+')" style="cursor: pointer"><img src="images/draw.png" style="WIDTH: 9px; HEIGHT: 9px"></img></button>'; html+='</td>'; */ //remove button html+="<td>"; html+='<button class="mapButton" title="remove layer: '+userConfig.overlayer[i].get("title")+'" id="'+userConfig.overlayer[i].get("title")+'" onclick="removecurrentlayer('+i+')" style="cursor: pointer"><img src="images/remove16.png" style="WIDTH: 9px; HEIGHT: 9px"></img></button>'; html+='</td>'; //zoomtocurrentlayer('+i+')//mapfunction.js ///////end zoom to current layer //slideropacity // html+="<td>"; //html+='</td>'; html+="</tr>"; html+="</table>"; //html+='<br />'; //ol2d.addLayer(userConfig.overlayer[i]); return html; }//function addnewoverlayerWMS(i,check)
pispidikisj/Topo3DcityDBPS
lib/OGCfunction.js
JavaScript
gpl-3.0
13,602
'use strict'; const {Application} = require('backbone.marionette'); const Geppetto = require('backbone.geppetto'); const debug = require( 'debug' )( 'dpac:app', '[Context]' ); const eventLog = require( 'debug' )( 'dpac:core.events', '\u2709' ); const app = module.exports = new Application(); const AppContext = Geppetto.Context.extend( { initialize: function( config ){ debug( "#initialize" ); Geppetto.setDebug( true ); this.vent.on( 'all', function( eventName, event ){ eventLog( eventName ); } ); this.wireValue( 'appContext', this ); this.wireValue( 'app', app ); this.wireCommand( "app:startup:requested", require( './controllers/BootstrapModule' ) ); } } ); app.on( 'start', function(){ debug( 'App#start' ); const app = this; app.context = new AppContext(); app.context.dispatch( 'app:startup:requested' ); } );
d-pac/d-pac.client
src/scripts/core/App.js
JavaScript
gpl-3.0
957
jQuery(document).ready(function(jQuery){ jQuery('.smile-upload-media').click(function(e) { _wpPluploadSettings['defaults']['multipart_params']['admin_page']= 'customizer'; var button = jQuery(this); var id = 'smile_'+button.attr('id'); var uid = button.data('uid'); var rmv_btn = 'remove_'+button.attr('id'); var img_container = button.attr('id')+'_container'; //Extend wp.media object var uploader = wp.media.frames.file_frame = wp.media({ title: 'Select or Upload Image', button: { text: 'Choose Image' }, library: { type: 'image' }, multiple: false, }); uploader.on('select', function(props, attachment){ attachment = uploader.state().get('selection').first().toJSON(); var data = attachment.id+"|"+attachment.url; var sz = jQuery(".cp-media-"+uid).val(); var alt = attachment.alt;//console.log(id); var val = attachment.id+"|"+sz+"|"+alt; var a = jQuery("#"+id); var name = jQuery("#"+id).attr('name'); a.val(val); a.attr('value',val); jQuery(".cp-media-"+uid).attr('data-id',attachment.id); jQuery(".cp-media-"+uid).attr('data-alt',attachment.alt); jQuery(".cp-media-"+uid).parents(".cp-media-sizes").removeClass("hide-for-default"); jQuery("."+img_container).html('<img src="'+attachment.url+'"/>'); jQuery("#"+rmv_btn).show(); button.text('Change Image'); // Partial Refresh // - Apply background, background-color, color etc. var css_preview = a.attr('data-css-preview') || ''; var selector = a.attr('data-css-selector') || ''; var property = a.attr('data-css-property') || ''; var unit = a.attr('data-unit') || 'px'; var url = attachment.url; partial_refresh_image( css_preview, selector, property, unit, url ); jQuery(document).trigger('cp-image-change', [name,url, val] ); jQuery("#"+id).trigger('change'); }); uploader.open(button); return false; }); jQuery('.smile-remove-media').on('click', function(e){ e.preventDefault(); var button = jQuery(this); var id = button.attr('id').replace("remove_","smile_"); var upload = button.attr('id').replace("remove_",""); var img_container = button.attr('id').replace("remove_","")+'_container'; jQuery("#"+id).attr('value',''); // Partial Refresh // - Apply background, background-color, color etc. var a = jQuery("#"+id); var css_preview = a.attr('data-css-preview') || ''; var selector = a.attr('data-css-selector') || ''; var property = a.attr('data-css-property') || ''; var unit = a.attr('data-unit') || 'px'; var value = ''; // Empty the background image var name = jQuery("#"+id).attr('name'); partial_refresh_image( css_preview, selector, property, unit, value ); var html = '<p class="description">No Image Selected</p>'; jQuery("."+img_container).html(html); button.hide(); jQuery("#"+upload).text('Select Image'); jQuery(document).trigger('cp-image-remove', [name,value] ); jQuery("#"+id).trigger('change'); }); jQuery('.smile-default-media').on('click', function(e){ e.preventDefault(); var button = jQuery(this); var id = button.attr('id').replace("default_","smile_"); var upload = button.attr('id').replace("default_",""); var img_container = button.attr('id').replace("default_","")+'_container'; var container = jQuery(this).parents('.content'); var default_img = jQuery(this).data('default'); jQuery("#"+id).attr('value',default_img); // Partial Refresh // - Apply background, background-color, color etc. var a = jQuery("#"+id); var css_preview = a.attr('data-css-preview') || ''; var selector = a.attr('data-css-selector') || ''; var property = a.attr('data-css-property') || ''; var unit = a.attr('data-unit') || 'px'; var value = default_img; // Empty the background image var name = jQuery("#"+id).attr('name'); partial_refresh_image( css_preview, selector, property, unit, value ); var html = '<p class="description">No Image Selected</p>'; jQuery("."+img_container).html('<img src="'+default_img+'"/>'); jQuery(document).trigger('cp-image-default', [name,value] ); jQuery("#"+id).trigger('change'); container.find(".cp-media-sizes").hide().addClass('hide-for-default'); }); jQuery(".cp-media-size").on("change", function(e){ var img_id = jQuery(this).attr('data-id'); var alt = jQuery(this).attr('data-alt'); var input = 'smile_'+jQuery(this).parents('.cp-media-sizes').data('name'); var val = ""; if( img_id !== '' ) { val = img_id+"|"+jQuery(this).val(); } if( alt !== '' ) { val = val+"|"+alt; } jQuery("#"+input).val(val); jQuery("#"+input).attr('value',val); }); function partial_refresh_image( css_preview, selector, property, unit, value ) { // apply css by - inline if( css_preview != 1 || null == css_preview || 'undefined' == css_preview ) { var frame = jQuery("#smile_design_iframe").contents(); switch( property ) { case 'src': frame.find( selector ).attr( 'src' , value ); break; default: frame.find( selector ).css( property , 'url(' + value + ')' ); break; } } // apply css by - after css generation jQuery(document).trigger('updated', [css_preview, selector, property, value, unit]); } });
emergugue/emergugue_wp_theme
wp-content/plugins/convertplug/framework/lib/fields/media/media.js
JavaScript
gpl-3.0
5,553
// Copyright © 2016 Gary W. Hudson Esq. // Released under GNU GPL 3.0 var lzwh = (function() {var z={ Decode:function(p) {function f(){--h?k>>=1:(k=p.charCodeAt(q++)-32,h=15);return k&1}var h=1,q=0,k=0,e=[""],l=[],g=0,m=0,c="",d,a=0,n,b; do{m&&(e[g-1]=c.charAt(0));m=a;l.push(c);d=0;for(a=g++;d!=a;)f()?d=(d+a>>1)+1:a=d+a>>1;if(d)c=l[d]+e[d],e[g]=c.charAt(0) else{b=1;do for(n=8;n--;b*=2)d+=b*f();while(f());d&&(c=String.fromCharCode(d-1),e[g]="")}}while(d);return l.join("")}, Encode:function(p) {function f(b){b&&(k|=e);16384==e?(q.push(String.fromCharCode(k+32)),e=1,k=0):e<<=1}function h(b,d){for(var a=0,e,c=l++;a!=c;) e=a+c>>1,b>e?(a=e+1,f(1)):(c=e,f(0));if(!a){-1!=b&&(a=d+1);do{for(c=8;c--;a=(a-a%2)/2)f(a%2);f(a)}while(a)}}for(var q=[],k=0, e=1,l=0,g=[],m=[],c=0,d=p.length,a,n,b=0;c<d;)a=p.charCodeAt(c++),g[b]?(n=g[b].indexOf(a),-1==n?(g[b].push(a),m[b].push(l+1), c-=b?1:0,h(b,a),b=0):b=m[b][n]):(g[b]=[a],m[b]=[l+1],c-=b?1:0,h(b,a),b=0);b&&h(b,0);for(h(-1,0);1!=e;)f(0);return q.join("")} };return z})(); if(typeof define==='function'&&define.amd)define(function(){return lzw}) else if(typeof module!=='undefined'&&module!=null)module.exports=lzw;
GWHudson/lzwh
lzwhutf16-min.js
JavaScript
gpl-3.0
1,186
ManageIndexes = { GridPanel : function(config) { config.autoExpandColumn = 'columns'; config.viewConfig = { forceFit: true }; ManageIndexes.GridPanel.superclass.constructor.call(this, config); }, gridPanelStore : function(data) { var store = new Ext.data.SimpleStore( { fields : data.fields }); store.loadData(data.data); return store; }, gridPanelColumnModel : function(data) { for ( var i = 0; i < data.models.length; i++) { var curr = data.models[i]; if (curr.id == 'unique' || curr.id == 'fullText') { curr.renderer = function(v) { //return '<div class="x-grid3-check-col' + (v ? '-on' : '') + '"> </div>'; return '<input type="checkbox" '+(v?'checked="checked"':'')+' disabled="disabled" />'; }; } } var cm = new Ext.grid.ColumnModel( { columns : data.models }); return cm; }, closeManageIndexesWindow : function() { Ext.getCmp('manage_indexes_window').close(); }, showDeleteIndexConfirmation : function() { // Get the selected row(s) var indexesGrid = Ext.getCmp('manage_indexes_grid'); var selModel = indexesGrid.getSelectionModel(); var rows = selModel.getSelections(); // If no rows are selected, alert the user. if (!rows.length) { var msg = "Please select index(s) to delete!"; Dbl.Utils.showErrorMsg(msg, ''); // Ext.MessageBox.alert('No Index(es) Selected', // 'Please select the index(es) to delete'); return; } ManageIndexes.indexesForDeletion = []; for ( var i = 0; i < rows.length; i++) { ManageIndexes.indexesForDeletion.push(rows[i].data.indexName); } // Get confirmation from the user var title = 'Are you sure?'; var message = 'Are you sure you want to delete the selected index(es)?'; var handleConfirmation = function(btn) { if (btn == "yes") { // Send the delete index command to server Server.sendCommand('delete_indexes', { indexes : ManageIndexes.indexesForDeletion, table : Explorer.selectedDbTable }, function(data) { // var msg = "Index(s) deleted successfully"; Dbl.Utils.showInfoMsg(Messages.getMsg('index_deletion_success')); // Ext.MessageBox.alert('Success!!', // 'Index(es) deleted successfully'); ManageIndexes.refreshGrid(); // Server.sendCommand('get_min_table_indexes', { // parent_database : Explorer.selectedDatabase, // table : Explorer.selectedDbTable // }, function(data) { // var store = ManageIndexes.gridPanelStore(data); // var cm = ManageIndexes.gridPanelColumnModel(data); // Ext.getCmp('manage_indexes_grid') // .reconfigure(store, cm); // // }); }); } }; Ext.MessageBox.confirm(title, message, handleConfirmation); }, indexesForDeletion : [], refreshGrid: function() { Server.sendCommand('get_min_table_indexes', { parent_database : Explorer.selectedDatabase, table : Explorer.selectedDbTable }, function(data) { var store = ManageIndexes.gridPanelStore(data); var cm = ManageIndexes.gridPanelColumnModel(data); Ext.getCmp('manage_indexes_grid').reconfigure(store, cm); }); }, showEditIndexWindow: function() { var selectionCount = Ext.getCmp('manage_indexes_grid').getSelectionModel().getCount(); if(!selectionCount) { // var msg = "Please select an index to edit!"; Dbl.Utils.showErrorMsg(Messages.getMsg('edit_index_required')); } else if(selectionCount > 1) { // var msg = "Please select a single index to edit!"; Dbl.Utils.showErrorMsg(Messages.getMsg('edit_index_single')); } else { Server.sendCommand('get_min_table_columns', { table : Explorer.selectedDbTable }, function(data) { data.editMode = true; ManageIndexes.addIndexWin = new ManageIndexes.AddIndexWindow(data); ManageIndexes.addIndexWin.show(); }); } }, showAddIndexWindow : function(editMode) { Server.sendCommand('get_min_table_columns', { table : Explorer.selectedDbTable }, function(data) { ManageIndexes.addIndexWin = new ManageIndexes.AddIndexWindow(data); ManageIndexes.addIndexWin.show(); }); }, AddIndexWindow : function(data) { var gridPanel = new ManageIndexes.AddIndexGrid(data); var form = new ManageIndexes.AddIndexForm(); if(data.editMode) { var index = Ext.getCmp('manage_indexes_grid').getSelectionModel().getSelected().data; var indexName = index.indexName; var formObj = form.getForm(); formObj.findField('add_index_form_index_name').setValue(indexName); formObj.findField('add_index_form_original_name').setValue(indexName); //form.originalIndexName = indexName; var indexType; if(indexName == 'PRIMARY') indexType = 'primary'; else if(index.unique == true) indexType = 'unique'; else if(index.fullText == true) indexType = 'fullText'; else indexType = 'none'; var cmpId = 'add_index_form_index_type_'+indexType; Ext.getCmp('options_group').setValue(cmpId,true); var columns = index.columns.split(',').reverse(); for(var i=0; i<columns.length; i++) { var recIndex = gridPanel.getStore().find('Name',columns[i]); var rec = gridPanel.getStore().getAt(recIndex); rec.set('included', true); gridPanel.getStore().remove(rec); gridPanel.getStore().insert(0, rec); } } ManageIndexes.AddIndexWindow.superclass.constructor.call(this, { title : "Add New Index", id : "add_index_window", headerAsText : true, width : 350, resizable : false, modal : true, plain : true, stateful : true, shadow : false, onEsc : function() { }, closeAction : 'destroy', items : [ form, gridPanel ], buttons : [ { text: data.editMode ? 'submit' : 'add', handler: data.editMode?ManageIndexes.editIndex:ManageIndexes.createAndAddIndex }, { text: 'cancel', handler: ManageIndexes.closeAddIndexWindow }] }); }, AddIndexGrid : function(data) { var includedModel = new Ext.ux.CheckColumn({ header: ' ', checkOnly: true, dataIndex: 'included', width: 20}); for(var i=0; i<data.fields.length; i++) { if(data.fields[i] == "included") { data.fields[i].type = 'bool'; data.models[i] = includedModel; } } ManageIndexes.AddIndexGrid.superclass.constructor.call(this, { fields : data.fields, data : data.data, models : data.models, autoExpandColumn: 'Name', viewConfig: { forceFit: true }, id : 'add_index_grid', height: 180, //width: 333, autoScroll: true, fbar: [Messages.getMsg('edit_index_footer')], enableDragDrop: true, ddGroup: 'mygridDD', plugins: [includedModel], listeners: { "render": { scope: this, fn: function(grid) { var ddrow = new Ext.dd.DropTarget(grid.container, { ddGroup : 'mygridDD', copy: false, notifyDrop : function(dd, e, data){ //Ext.getCmp('reorder_columns_window').reorderButton.enable(); var ds = grid.store; var sm = grid.getSelectionModel(); var rows = sm.getSelections(); //var rows = this.currentRowEl; if(dd.getDragData(e)) { var cindex=dd.getDragData(e).rowIndex; if(typeof(cindex) != "undefined") { for(i = 0; i < rows.length; i++) { ds.remove(ds.getById(rows[i].id)); } ds.insert(cindex,data.selections); sm.clearSelections(); } } } }); } } } }); }, AddIndexForm: function(data) { var radioGroupItems = [ { boxLabel: 'Unique', name: 'add_index_form_index_type', id: 'add_index_form_index_type_unique', inputValue: 'unique' }, { boxLabel: 'Full Text', name: 'add_index_form_index_type', id: 'add_index_form_index_type_fullText', inputValue: 'fullText' }, { boxLabel: 'Primary', name: 'add_index_form_index_type', id: 'add_index_form_index_type_primary', inputValue: 'primary', listeners: { 'check': { fn: function() { var form = Ext.getCmp('add_index_form').getForm().getValues(false); var indexName = Ext.getCmp('add_index_form_index_name'); if(form.add_index_form_index_type == 'primary') { indexName.prevValue = form.add_index_form_index_name; indexName.setValue('PRIMARY'); indexName.disable(); } else { indexName.setValue(indexName.prevValue); indexName.enable(); } } } } }, { boxLabel: 'None', name: 'add_index_form_index_type', id: 'add_index_form_index_type_none', inputValue: 'none', checked: true }]; ManageIndexes.AddIndexForm.superclass.constructor.call(this, { id: 'add_index_form', labelAlign: 'top', frame: true, bodyStyle: "padding: 5px", defaults: { anchor: '100%' }, items:[ { xtype: 'textfield', fieldLabel: 'Index Name', name: 'add_index_form_index_name', id: 'add_index_form_index_name', blankText: 'Index name is required', allowBlank: false }, { xtype: 'hidden', name: 'add_index_form_original_name', id: 'add_index_form_original_name' }, { xtype: 'radiogroup', rows: 1, id: 'options_group', defaults: { anchor: '100%' }, bodyStyle: "padding: 0px; margin: 0px", items: radioGroupItems, fieldLabel: 'Index Options' }] }); }, editIndex: function() { ManageIndexes.createAndAddIndex(true); }, createAndAddIndex: function(editMode) { var form = Ext.getCmp('add_index_form').getForm(); if(!form.isValid()) { return; } var values = form.getValues(); var store = Ext.getCmp('add_index_grid').getStore(); var indexes = []; var selectedRows = 0; for(var i=0; i<store.getCount(); i++) { var record = store.getAt(i); if(record.get('included') == true) { indexes.push(record.get('Name')); selectedRows++; } } if(selectedRows < 1) { // var msg = 'Please select at least one column'; Dbl.Utils.showErrorMsg(Messages.getMsg('add_index_column_req')); //Ext.MessageBox.alert('No Columns Selected', 'Please Select atleast one column'); return; } Server.sendCommand( 'create_indexes', { table: Explorer.selectedDbTable, type: values.add_index_form_index_type, name: values.add_index_form_index_name, indexes: indexes, originalName: values.add_index_form_original_name }, function(data) { if(data.success) { ManageIndexes.refreshGrid(); ManageIndexes.closeAddIndexWindow(); // var msg = 'Index added successfully'; Dbl.Utils.showInfoMsg(Messages.getMsg('index_addition_success')); } else if(!data.success) { var msg = data.msg ? data.msg : data; Dbl.Utils.showErrorMsg(data.msg, ''); } }, function(data){ Dbl.Utils.showErrorMsg(data.msg, ''); }); }, closeAddIndexWindow: function() { Ext.getCmp('add_index_window').close(); } }; Ext.onReady(function() { Ext.extend(ManageIndexes.GridPanel, Dbl.ListViewPanel, { hello : function(str) { } }); Ext.extend(ManageIndexes.AddIndexWindow, Ext.Window, { }); Ext.extend(ManageIndexes.AddIndexGrid, Dbl.ListViewPanel, {}); Ext.extend(ManageIndexes.AddIndexForm, Ext.FormPanel, {}); });
manusis/dblite
app/js/dblite/manageindexes.js
JavaScript
gpl-3.0
11,797
'use strict'; var winston = require('winston'), loggerUtils = require('alien-node-winston-utils'); module.exports = { port : 3000, // TODO this isnt setup for nginx yet server : { // Ports on which to run node instances. Should be n-1 instances, where n is the number of cores. enabledPorts : [3000] }, mysql : { connectionLimit : 10, host : 'localhost', user : process.env.MYSQL_USER, password : process.env.MYSQL_PASS, database : 'club540' }, // // Email configuration // email : { // smtp : { // host : "smtp.mailgun.org", // port : 465, // sender : "[email protected]", // username : "[email protected]", // password : "Playlist123" // } // }, redis : { host : 'localhost', port : 6379, password : '' }, logging : { winston : { transports : [ { name : 'console', level : 'debug', timestamp : loggerUtils.getDateString, colorize : true, transportType : 'console' } // TODO: allow parallel logging strategies // using this strategy will disable console logging of errors // { // name : 'file', // level : 'debug', // timestamp : loggerUtils.getTimestamp, // colorize : true, // transportType : 'file', // filename : 'logs/activity.log', // json : false, // required for formatter to work // formatter : loggerUtils.getFormatter, // handleExceptions : true, // datePattern : '.yyyy-MM-dd' // dictates how logs are rotated - more specific pattern rotates more often // } ], strategies : { console : winston.transports.Console, file : winston.transports.DailyRotateFile } } }, errors : { db : { NO_RESULTS : { code : 6000, message : 'No results' } } } };
SeanCannon/club540
config/production.js
JavaScript
gpl-3.0
2,188
'use strict'; const path = require('path'); const os = require('os'); const fs = require('fs-extra'); const fieHome = require('fie-home'); const debug = require('debug')('core-report'); const fieUser = require('fie-user'); const execSync = require('child_process').execSync; const spawn = require('cross-spawn'); const cache = require('fie-cache'); /** * 环境变量获取 */ const cacheEnvGetter = { fieVersion() { return ( process.env.FIE_VERSION || execSync('npm view fie version') .toString() .replace(/[\nv]/g, '') ); }, email() { return fieUser.getEmail(); }, nodeVersion() { return execSync('node -v') .toString() .replace(/[\nv]/g, ''); }, npmVersion() { try { return execSync('npm -v') .toString() .replace('\n', ''); } catch (e) { return null; } }, tnpmVersion() { try { return execSync('tnpm -v') .toString() .split('\n')[0] .match(/\d+\.\d+\.\d+/)[0]; } catch (ex) { // 外网无tnpm return null; } }, system() { return `${os.platform()} ${os.release()}`; }, }; /** * 获取当前分支版本 * @param cwd * @returns {string} */ exports.getCurBranch = function(cwd) { const headerFile = path.join(cwd, '.git/HEAD'); let version = ''; if (fs.existsSync(headerFile)) { const gitVersion = fs.readFileSync(headerFile, { encoding: 'utf8' }); const arr = gitVersion.split(/refs[\\\/]heads[\\\/]/g); if (arr && arr.length > 1) { version = arr[1]; } } return version.trim(); }; /** * 获取项目URL * @returns {*} */ exports.getProjectUrl = function() { let url; try { url = ( spawn .sync('git', ['config', '--get', 'remote.origin.url'], { silent: true }) .stdout.toString() || '' ).trim(); // 有些git的url是http开头的,需要格式化为git@格式,方便统一处理 const match = url.match(/http:\/\/gitlab.alibaba-inc.com\/(.*)/); if (match && match[1]) { url = `[email protected]:${match[1]}`; } } catch (err) { debug('git config 错误:', err.message); } return url; }; /** * 获取项目相关环境 */ exports.getProjectInfo = function(cwd) { const branch = exports.getCurBranch(cwd); const pkgPath = path.join(cwd, 'package.json'); const CONFIG_FILE = process.env.FIE_CONFIG_FILE || 'fie.config.js'; const fiePath = path.join(cwd, CONFIG_FILE); // 这里不能使用fieConfig这个包,会循环引用 let pkg; let fie; let repository = exports.getProjectUrl(); // 判断pkg是否存在 if (fs.existsSync(pkgPath)) { pkg = fs.readJsonSync(pkgPath, { throws: false }); } // 判断fie.config.js是否存在 if (fs.existsSync(fiePath)) { delete require.cache[fiePath]; try { fie = require(fiePath); } catch (e) { fie = null; } } // 如果git中没有则尝试从pkg中获取 if (pkg && pkg.repository && pkg.repository.url) { repository = pkg.repository.url; } return { cwd, branch, pkg, fie, repository, }; }; /** * 获取项目的环境信息 * @param force 为true时 则获取实时信息,否则读取缓存 * 对 tnpm, node 版本等重新获取,一般在报错的时候才传入 true * @returns {*} */ exports.getProjectEnv = function(force) { let cacheEnv = cache.get('reportEnvCache'); if (!cacheEnv || force) { cacheEnv = {}; const cacheEnvKeys = Object.keys(cacheEnvGetter); cacheEnvKeys.forEach(item => { cacheEnv[item] = cacheEnvGetter[item](); }); // 缓存三天 cache.set('reportEnvCache', cacheEnv, { expires: 259200000 }); } return cacheEnv; }; /** * 获取当前执行的命令,移除用户路径 */ exports.getCommand = function(arg) { let argv = arg || process.argv; argv = argv.map(item => { const match = item.match(/\\bin\\(((?!bin).)*)$|\/bin\/(.*)/); // mac if (match && match[3]) { // 一般 node fie -v 这种方式则不需要显示 node return match[3] === 'node' ? '' : match[3]; } else if (match && match[1]) { // 一般 node fie -v 这种方式则不需要显示 node return match[1] === 'node.exe' ? '' : match[1]; } else if (!match && item.indexOf('node.exe') !== -1) { // fix如果C:\\node.exe 这种不带bin的路径 // TODO 当然这里的正则可以再优化兼容一下 return ''; } return item; }); return argv.join(' ').trim(); }; /** * 获取模块的类型和版本 */ exports.getFieModuleVersion = function(mod) { const modPkgPath = path.join(fieHome.getModulesPath(), mod, 'package.json'); let pkg = {}; if (fs.existsSync(modPkgPath)) { pkg = fs.readJsonSync(modPkgPath, { throws: false }) || {}; } return pkg.version; };
fieteam/fie
packages/fie-report/lib/utils.js
JavaScript
gpl-3.0
4,841
module.exports = { 'extends': ['google', 'plugin:react/recommended'], 'parserOptions': { 'ecmaVersion': 6, 'sourceType': 'module', 'ecmaFeatures': { 'jsx': true } }, 'env': { 'browser': true, }, 'plugins': [ 'react' ] };
BadgerTek/mern-skeleton
.eslintrc.client.js
JavaScript
gpl-3.0
293
/** * Client. * @module client */ /** * View configuration. * @class ViewConfig */ function ViewConfig(resources) { this.playAnimations = true; this.resources = resources; } /** * Should we play animations? * @method setPlayAnimations */ ViewConfig.prototype.setPlayAnimations = function(value) { this.playAnimations = value; } /** * Should we play animations? * @method getPlayAnimations */ ViewConfig.prototype.getPlayAnimations = function() { return this.playAnimations; } /** * Scale animation time. * @method scaleAnimationTime */ ViewConfig.prototype.scaleAnimationTime = function(millis) { if (this.playAnimations) return millis; return 1; } /** * Get resources. * @method getResources */ ViewConfig.prototype.getResources = function() { return this.resources; } module.exports = ViewConfig;
limikael/netpoker
src/client/resources/ViewConfig.js
JavaScript
gpl-3.0
832
var com = com || {}; com.hiyoko = com.hiyoko || {}; com.hiyoko.component = com.hiyoko.component || {}; com.hiyoko.component.UlList = function($html){}; com.hiyoko.util.extend(com.hiyoko.component.ApplicationBase, com.hiyoko.component.UlList); com.hiyoko.component.UlList.prototype.renderDefaultLi = function($li, item) { if(item.type !== 'node') { var $text = $('<span></span>') $text.text(item.text); $text.addClass('com-hiyoko-component-ul-list-li-text'); $li.append($text); } $li.attr('title', item.value); return $li; } com.hiyoko.component.UlList.prototype.buildList = function(list, opt_option) { this.$html.empty(); var $ul = $('<ul></ul>'); var option = opt_option || {renderer: this.renderDefaultLi.bind(this)}; list.forEach(function(item){ var $li = $('<li></li>'); $li = option.renderer($li, item, option); if(item.type !== 'leaf') { var tmpOption = opt_option || {renderer: this.renderDefaultLi.bind(this)}; tmpOption.child = true; $li.append(this.buildList(item.list, tmpOption)); } if(option.child) { $li.addClass('com-hiyoko-component-ul-list-li-child'); } else { $li.addClass('com-hiyoko-component-ul-list-li'); } $ul.append($li); }.bind(this)); this.$html.append($ul); return $ul; }; com.hiyoko.component.UlList.prototype.getValueLi = function($li) { var result = {}; var text = $li.children('.com-hiyoko-component-ul-list-li-text').text(); result.text = text; var $ul = $li.children('ul'); if($ul.length) { result.list = this.getValue($ul); } if(result.text && result.list) { result.type = 'namednode'; } else if(result.list) { result.type = 'node'; } else { result.type = 'leaf'; } return result; }; com.hiyoko.component.UlList.prototype.getValue = function(opt_$html) { if(opt_$html) { var $html = $(opt_$html); var result = []; $.each($html.children('li'), function(i, v){ result.push(this.getValueLi($(v))); }.bind(this)); return result; } else { return this.getValue(this.$html.children('ul')); } };
Shunshun94/shared
jquery/com/hiyoko/components/v1/UlList.js
JavaScript
gpl-3.0
2,032
Fox.define('language', [], function () { var Language = function (cache) { this.cache = cache || null; this.data = {}; }; _.extend(Language.prototype, { data: null, cache: null, url: 'I18n', has: function (name, category, scope) { if (scope in this.data) { if (category in this.data[scope]) { if (name in this.data[scope][category]) { return true; } } } }, get: function (scope, category, name) { if (scope in this.data) { if (category in this.data[scope]) { if (name in this.data[scope][category]) { return this.data[scope][category][name]; } } } if (scope == 'Global') { return name; } return false; }, translate: function (name, category, scope) { scope = scope || 'Global'; category = category || 'labels'; var res = this.get(scope, category, name); if (res === false && scope != 'Global') { res = this.get('Global', category, name); } return res; }, translateOption: function (value, field, scope) { var translation = this.translate(field, 'options', scope); if (typeof translation != 'object') { translation = {}; } return translation[value] || value; }, loadFromCache: function () { if (this.cache) { var cached = this.cache.get('app', 'language'); if (cached) { this.data = cached; return true; } } return null; }, clearCache: function () { if (this.cache) { this.cache.clear('app', 'language'); } }, storeToCache: function () { if (this.cache) { this.cache.set('app', 'language', this.data); } }, load: function (callback, disableCache) { this.once('sync', callback); if (!disableCache) { if (this.loadFromCache()) { this.trigger('sync'); return; } } this.fetch(); }, fetch: function (sync) { var self = this; $.ajax({ url: this.url, type: 'GET', dataType: 'JSON', async: !(sync || false), success: function (data) { self.data = data; self.storeToCache(); self.trigger('sync'); } }); }, }, Backbone.Events); return Language; });
ilovefox8/zhcrm
client/src/language.js
JavaScript
gpl-3.0
3,025
/** * Copyright 2014 IBM Corp. * * 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. **/ // If you use this as a template, update the copyright with your own name. // Sample Node-RED node file module.exports = function(RED) { "use strict"; // require any external libraries we may need.... //var foo = require("foo-library"); // The main node definition - most things happen in here function mobileactuatorNode(n) { // Create a RED node RED.nodes.createNode(this,n); // Store local copies of the node configuration (as defined in the .html) this.topic = n.topic; this.mobile_type = n.mobile_type; this.mobile_port = n.mobile_port; // copy "this" object in case we need it in context of callbacks of other functions. var node = this; // Do whatever you need to do in here - declare callbacks etc // Note: this sample doesn't do anything much - it will only send // this message once at startup... // Look at other real nodes for some better ideas of what to do.... var msg = {}; msg.topic = this.topic; msg.payload = "Hello world !" // send out the message to the rest of the workspace. // ... this message will get sent at startup so you may not see it in a debug node. //this.send(msg); // respond to inputs.... this.on('input', function (msg) { //node.warn("I saw a payload: "+msg.payload); // in this example just send it straight on... should process it here really if (msg.payload[0] == this.mobile_type && msg.payload[1] == 0){ msg.payload = msg.payload.substr(2) node.send(msg); } }); this.on("close", function() { // Called when the node is shutdown - eg on redeploy. // Allows ports to be closed, connections dropped etc. // eg: node.client.disconnect(); }); } RED.nodes.registerType("mobile actuator",mobileactuatorNode); }
lemio/w-esp
w-esp-node-red/nodes/94-mobile_actuator.js
JavaScript
gpl-3.0
2,532
function parseCategory(aCategory, aFunction) { if(document.location.host == '' || document.location.host == 'localhost' ) var url = 'test.html'; else var url = categoryGetURLPrivate(aCategory); $.ajax({ type: "GET", url: url, dataType:'html', success: function(responseText) { var aData = {}; aData.categories = []; aData.alternative = []; aData.related = []; aData.sitesCooled = []; aData.sites = []; aData.alphabar = []; aData.groups = []; aData.editors = []; aData.moz = ''; var tmp = 0; //subcategories and links $(responseText).find('.dir-1').each(function() { aData.categories[tmp] = []; $(this).find('li').each(function() { aData.categories[tmp][aData.categories[tmp].length] = $(this).html().replace(/href="/, 'href="#/Top'); }) aData.categories[tmp].sort(ODPy.sortLocale); tmp++; }); //alternative languages $(responseText).find('.language').find('li').each(function() { aData.alternative[aData.alternative.length] = $(this).html().replace(/href="/, 'href="#/Top'); }); aData.alternative = aData.alternative.sort(ODPy.sortLocale); //related categories $(responseText).find('fieldset.fieldcap .directory').find('li').each(function() { aData.related[aData.related.length] = $(this).html().replace(/href="/, 'href="#/Top'); }); aData.related.sort(ODPy.sortLocale); //sites cooled $(responseText).find('.directory-url').find('li.star').each(function() { aData.sitesCooled[aData.sitesCooled.length] = $(this).html().replace(/href="/, ' target="_blank" href="'); }); //alert(aData.sitesCooled.toString()); aData.sitesCooled.sort(ODPy.sortLocale); //sites not cooled $(responseText).find('.directory-url').find('li:not(.star)').each(function() { aData.sites[aData.sites.length] = $(this).html().replace(/href="/, ' target="_blank" href="'); }); aData.sites.sort(ODPy.sortLocale); //alphabar $(responseText).find('.alphanumeric a').each(function() { aData.alphabar[aData.alphabar.length] = $(this).html(); }); aData.alphabar.sort(ODPy.sortLocale); //groups $(responseText).find('.fieldcapRn .float-l li:first').each(function() { var item = $(this).html(); if(item.indexOf('search') != -1){} else aData.groups[aData.groups.length] = item; return; }); aData.groups.sort(ODPy.sortLocale); //editors $(responseText).find('.volEditN a').each(function() { if(trim(stripTags($(this).html()))) aData.editors[aData.editors.length] = '<a href="http://editors.dmoz.org/public/profile?editor='+$(this).html()+'">'+$(this).html()+'</a>'; }); //mozzie if(responseText.indexOf('img/moz') != -1) { try { aData.moz = responseText.split('/img/moz/')[1].split('"')[0]; } catch(e){} } //aData.editors.sort(ODPy.sortLocale); aFunction(aCategory, aData); }, error :function() { ODPy.statusSet('Error category "'+categoryTitle(aCategory)+'" no exists'); ODPy.statusHide(); } }); }
titoBouzout/ODPy
lib/ODP/categoryParser.js
JavaScript
gpl-3.0
3,590
Ext.define('User', { extend: 'Ext.data.Model', fields: [ {name: 'name', type: 'string', convert: function(value,record) { return record.get('name')+' the barbarian'); } }, {name: 'age', type: 'int'}, {name: 'phone', type: 'string'}, {name: 'alive', type: 'boolean', defaultValue: true} ], });
veltzer/demos-javascript
src/extjs/examples/model/model_change.js
JavaScript
gpl-3.0
316
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const cordova_config_1 = require("../utils/cordova-config"); function LabAppView(req, res) { return res.sendFile('index.html', { root: path.join(__dirname, '..', '..', 'lab') }); } exports.LabAppView = LabAppView; function ApiCordovaProject(req, res) { cordova_config_1.buildCordovaConfig((err) => { res.status(400).json({ status: 'error', message: 'Unable to load config.xml' }); }, (config) => { res.json(config); }); } exports.ApiCordovaProject = ApiCordovaProject;
Rob2B/Cherry-enseirb
app/node_modules/@ionic/cli-plugin-ionic1/dist/serve/lab.js
JavaScript
gpl-3.0
652