/*! Magnific Popup - v0.9.9 - 2013-11-15 * http://dimsemenov.com/plugins/magnific-popup/ * Copyright (c) 2013 Dmitry Semenov; */ ;(function($) { /*>>core*/ /** * * Magnific Popup Core JS file * */ /** * Private static constants */ var CLOSE_EVENT = 'Close', BEFORE_CLOSE_EVENT = 'BeforeClose', AFTER_CLOSE_EVENT = 'AfterClose', BEFORE_APPEND_EVENT = 'BeforeAppend', MARKUP_PARSE_EVENT = 'MarkupParse', OPEN_EVENT = 'Open', CHANGE_EVENT = 'Change', NS = 'nd', EVENT_NS = '.' + NS, READY_CLASS = 'nd-ready', REMOVING_CLASS = 'nd-removing', PREVENT_CLOSE_CLASS = 'nd-prevent-close'; /** * Private vars */ var nd, // As we have only one instance of MagnificPopup object, we define it locally to not to use 'this' MagnificPopup = function(){}, _isJQ = !!(window.jQuery), _prevStatus, _window = $(window), _body, _document, _prevContentType, _wrapClasses, _currPopupType; /** * Private functions */ var _ndOn = function(name, f) { nd.ev.on(NS + name + EVENT_NS, f); }, _getEl = function(className, appendTo, html, raw) { var el = document.createElement('div'); el.className = 'nd-'+className; if(html) { el.innerHTML = html; } if(!raw) { el = $(el); if(appendTo) { el.appendTo(appendTo); } } else if(appendTo) { appendTo.appendChild(el); } return el; }, _ndTrigger = function(e, data) { nd.ev.triggerHandler(NS + e, data); if(nd.st.callbacks) { // converts "ndEventName" to "eventName" callback and triggers it if it's present e = e.charAt(0).toLowerCase() + e.slice(1); if(nd.st.callbacks[e]) { nd.st.callbacks[e].apply(nd, $.isArray(data) ? data : [data]); } } }, _getCloseBtn = function(type) { if(type !== _currPopupType || !nd.currTemplate.closeBtn) { nd.currTemplate.closeBtn = $( nd.st.closeMarkup.replace('%title%', nd.st.tClose ) ); _currPopupType = type; } return nd.currTemplate.closeBtn; }, // Initialize Magnific Popup only when called at least once _checkInstance = function() { if(!$.magnificPopup.instance) { nd = new MagnificPopup(); nd.init(); $.magnificPopup.instance = nd; } }, // CSS transition detection, http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr supportsTransitions = function() { var s = document.createElement('p').style, // 's' for style. better to create an element if body yet to exist v = ['ms','O','Moz','Webkit']; // 'v' for vendor if( s['transition'] !== undefined ) { return true; } while( v.length ) { if( v.pop() + 'Transition' in s ) { return true; } } return false; }; /** * Public functions */ MagnificPopup.prototype = { constructor: MagnificPopup, /** * Initializes Magnific Popup plugin. * This function is triggered only once when $.fn.magnificPopup or $.magnificPopup is executed */ init: function() { var appVersion = navigator.appVersion; nd.isIE7 = appVersion.indexOf("MSIE 7.") !== -1; nd.isIE8 = appVersion.indexOf("MSIE 8.") !== -1; nd.isLowIE = nd.isIE7 || nd.isIE8; nd.isAndroid = (/android/gi).test(appVersion); nd.isIOS = (/iphone|ipad|ipod/gi).test(appVersion); nd.supportsTransition = supportsTransitions(); // We disable fixed positioned lightbox on devices that don't handle it nicely. // If you know a better way of detecting this - let me know. nd.probablyMobile = (nd.isAndroid || nd.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent) ); _body = $(document.body); _document = $(document); nd.popupsCache = {}; }, /** * Opens popup * @param data [description] */ open: function(data) { var i; if(data.isObj === false) { // convert jQuery collection to array to avoid conflicts later nd.items = data.items.toArray(); nd.index = 0; var items = data.items, item; for(i = 0; i < items.length; i++) { item = items[i]; if(item.parsed) { item = item.el[0]; } if(item === data.el[0]) { nd.index = i; break; } } } else { nd.items = $.isArray(data.items) ? data.items : [data.items]; nd.index = data.index || 0; } // if popup is already opened - we just update the content if(nd.isOpen) { nd.updateItemHTML(); return; } nd.types = []; _wrapClasses = ''; if(data.mainEl && data.mainEl.length) { nd.ev = data.mainEl.eq(0); } else { nd.ev = _document; } if(data.key) { if(!nd.popupsCache[data.key]) { nd.popupsCache[data.key] = {}; } nd.currTemplate = nd.popupsCache[data.key]; } else { nd.currTemplate = {}; } nd.st = $.extend(true, {}, $.magnificPopup.defaults, data ); nd.fixedContentPos = nd.st.fixedContentPos === 'auto' ? !nd.probablyMobile : nd.st.fixedContentPos; if(nd.st.modal) { nd.st.closeOnContentClick = false; nd.st.closeOnBgClick = false; nd.st.showCloseBtn = false; nd.st.enableEscapeKey = false; } // Building markup // main containers are created only once if(!nd.bgOverlay) { // Dark overlay nd.bgOverlay = _getEl('bg').on('click'+EVENT_NS, function() { nd.close(); }); nd.wrap = _getEl('wrap').attr('tabindex', -1).on('click'+EVENT_NS, function(e) { if(nd._checkIfClose(e.target)) { nd.close(); } }); nd.container = _getEl('container', nd.wrap); } nd.contentContainer = _getEl('content'); if(nd.st.preloader) { nd.preloader = _getEl('preloader', nd.container, nd.st.tLoading); } // Initializing modules var modules = $.magnificPopup.modules; for(i = 0; i < modules.length; i++) { var n = modules[i]; n = n.charAt(0).toUpperCase() + n.slice(1); nd['init'+n].call(nd); } _ndTrigger('BeforeOpen'); if(nd.st.showCloseBtn) { // Close button if(!nd.st.closeBtnInside) { nd.wrap.append( _getCloseBtn() ); } else { _ndOn(MARKUP_PARSE_EVENT, function(e, template, values, item) { values.close_replaceWith = _getCloseBtn(item.type); }); _wrapClasses += ' nd-close-btn-in'; } } if(nd.st.alignTop) { _wrapClasses += ' nd-align-top'; } if(nd.fixedContentPos) { nd.wrap.css({ overflow: nd.st.overflowY, overflowX: 'hidden', overflowY: nd.st.overflowY }); } else { nd.wrap.css({ top: _window.scrollTop(), position: 'absolute' }); } if( nd.st.fixedBgPos === false || (nd.st.fixedBgPos === 'auto' && !nd.fixedContentPos) ) { nd.bgOverlay.css({ height: _document.height(), position: 'absolute' }); } if(nd.st.enableEscapeKey) { // Close on ESC key _document.on('keyup' + EVENT_NS, function(e) { if(e.keyCode === 27) { nd.close(); } }); } _window.on('resize' + EVENT_NS, function() { nd.updateSize(); }); if(!nd.st.closeOnContentClick) { _wrapClasses += ' nd-auto-cursor'; } if(_wrapClasses) nd.wrap.addClass(_wrapClasses); // this triggers recalculation of layout, so we get it once to not to trigger twice var windowHeight = nd.wH = _window.height(); var windowStyles = {}; if( nd.fixedContentPos ) { if(nd._hasScrollBar(windowHeight)){ var s = nd._getScrollbarSize(); if(s) { windowStyles.marginRight = s; } } } if(nd.fixedContentPos) { if(!nd.isIE7) { windowStyles.overflow = 'hidden'; } else { // ie7 double-scroll bug $('body, html').css('overflow', 'hidden'); } } var classesToadd = nd.st.mainClass; if(nd.isIE7) { classesToadd += ' nd-ie7'; } if(classesToadd) { nd._addClassTond( classesToadd ); } // add content nd.updateItemHTML(); _ndTrigger('BuildControls'); // remove scrollbar, add margin e.t.c $('html').css(windowStyles); // add everything to DOM nd.bgOverlay.add(nd.wrap).prependTo( document.body ); // Save last focused element nd._lastFocusedEl = document.activeElement; // Wait for next cycle to allow CSS transition setTimeout(function() { if(nd.content) { nd._addClassTond(READY_CLASS); nd._setFocus(); } else { // if content is not defined (not loaded e.t.c) we add class only for BG nd.bgOverlay.addClass(READY_CLASS); } // Trap the focus in popup _document.on('focusin' + EVENT_NS, nd._onFocusIn); }, 16); nd.isOpen = true; nd.updateSize(windowHeight); _ndTrigger(OPEN_EVENT); return data; }, /** * Closes the popup */ close: function() { if(!nd.isOpen) return; _ndTrigger(BEFORE_CLOSE_EVENT); nd.isOpen = false; // for CSS3 animation if(nd.st.removalDelay && !nd.isLowIE && nd.supportsTransition ) { nd._addClassTond(REMOVING_CLASS); setTimeout(function() { nd._close(); }, nd.st.removalDelay); } else { nd._close(); } }, /** * Helper for close() function */ _close: function() { _ndTrigger(CLOSE_EVENT); var classesToRemove = REMOVING_CLASS + ' ' + READY_CLASS + ' '; nd.bgOverlay.detach(); nd.wrap.detach(); nd.container.empty(); if(nd.st.mainClass) { classesToRemove += nd.st.mainClass + ' '; } nd._removeClassFromnd(classesToRemove); if(nd.fixedContentPos) { var windowStyles = {marginRight: ''}; if(nd.isIE7) { $('body, html').css('overflow', ''); } else { windowStyles.overflow = ''; } $('html').css(windowStyles); } _document.off('keyup' + EVENT_NS + ' focusin' + EVENT_NS); nd.ev.off(EVENT_NS); // clean up DOM elements that aren't removed nd.wrap.attr('class', 'nd-wrap').removeAttr('style'); nd.bgOverlay.attr('class', 'nd-bg'); nd.container.attr('class', 'nd-container'); // remove close button from target element if(nd.st.showCloseBtn && (!nd.st.closeBtnInside || nd.currTemplate[nd.currItem.type] === true)) { if(nd.currTemplate.closeBtn) nd.currTemplate.closeBtn.detach(); } if(nd._lastFocusedEl) { $(nd._lastFocusedEl).focus(); // put tab focus back } nd.currItem = null; nd.content = null; nd.currTemplate = null; nd.prevHeight = 0; _ndTrigger(AFTER_CLOSE_EVENT); }, updateSize: function(winHeight) { if(nd.isIOS) { // fixes iOS nav bars https://github.com/dimsemenov/Magnific-Popup/issues/2 var zoomLevel = document.documentElement.clientWidth / window.innerWidth; var height = window.innerHeight * zoomLevel; nd.wrap.css('height', height); nd.wH = height; } else { nd.wH = winHeight || _window.height(); } // Fixes #84: popup incorrectly positioned with position:relative on body if(!nd.fixedContentPos) { nd.wrap.css('height', nd.wH); } _ndTrigger('Resize'); }, /** * Set content of popup based on current index */ updateItemHTML: function() { var item = nd.items[nd.index]; // Detach and perform modifications nd.contentContainer.detach(); if(nd.content) nd.content.detach(); if(!item.parsed) { item = nd.parseEl( nd.index ); } var type = item.type; _ndTrigger('BeforeChange', [nd.currItem ? nd.currItem.type : '', type]); // BeforeChange event works like so: // _ndOn('BeforeChange', function(e, prevType, newType) { }); nd.currItem = item; if(!nd.currTemplate[type]) { var markup = nd.st[type] ? nd.st[type].markup : false; // allows to modify markup _ndTrigger('FirstMarkupParse', markup); if(markup) { nd.currTemplate[type] = $(markup); } else { // if there is no markup found we just define that template is parsed nd.currTemplate[type] = true; } } if(_prevContentType && _prevContentType !== item.type) { nd.container.removeClass('nd-'+_prevContentType+'-holder'); } var newContent = nd['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, nd.currTemplate[type]); nd.appendContent(newContent, type); item.preloaded = true; _ndTrigger(CHANGE_EVENT, item); _prevContentType = item.type; // Append container back after its content changed nd.container.prepend(nd.contentContainer); _ndTrigger('AfterChange'); }, /** * Set HTML content of popup */ appendContent: function(newContent, type) { nd.content = newContent; if(newContent) { if(nd.st.showCloseBtn && nd.st.closeBtnInside && nd.currTemplate[type] === true) { // if there is no markup, we just append close button element inside if(!nd.content.find('.nd-close').length) { nd.content.append(_getCloseBtn()); } } else { nd.content = newContent; } } else { nd.content = ''; } _ndTrigger(BEFORE_APPEND_EVENT); nd.container.addClass('nd-'+type+'-holder'); nd.contentContainer.append(nd.content); }, /** * Creates Magnific Popup data object based on given data * @param {int} index Index of item to parse */ parseEl: function(index) { var item = nd.items[index], type = item.type; if(item.tagName) { item = { el: $(item) }; } else { item = { data: item, src: item.src }; } if(item.el) { var types = nd.types; // check for 'nd-TYPE' class for(var i = 0; i < types.length; i++) { if( item.el.hasClass('nd-'+types[i]) ) { type = types[i]; break; } } item.src = item.el.attr('data-nd-src'); if(!item.src) { item.src = item.el.attr('href'); } } item.type = type || nd.st.type || 'inline'; item.index = index; item.parsed = true; nd.items[index] = item; _ndTrigger('ElementParse', item); return nd.items[index]; }, /** * Initializes single popup or a group of popups */ addGroup: function(el, options) { var eHandler = function(e) { e.ndEl = this; nd._openClick(e, el, options); }; if(!options) { options = {}; } var eName = 'click.magnificPopup'; options.mainEl = el; if(options.items) { options.isObj = true; el.off(eName).on(eName, eHandler); } else { options.isObj = false; if(options.delegate) { el.off(eName).on(eName, options.delegate , eHandler); } else { options.items = el; el.off(eName).on(eName, eHandler); } } }, _openClick: function(e, el, options) { var midClick = options.midClick !== undefined ? options.midClick : $.magnificPopup.defaults.midClick; if(!midClick && ( e.which === 2 || e.ctrlKey || e.metaKey ) ) { return; } var disableOn = options.disableOn !== undefined ? options.disableOn : $.magnificPopup.defaults.disableOn; if(disableOn) { if($.isFunction(disableOn)) { if( !disableOn.call(nd) ) { return true; } } else { // else it's number if( _window.width() < disableOn ) { return true; } } } if(e.type) { e.preventDefault(); // This will prevent popup from closing if element is inside and popup is already opened if(nd.isOpen) { e.stopPropagation(); } } options.el = $(e.ndEl); if(options.delegate) { options.items = el.find(options.delegate); } nd.open(options); }, /** * Updates text on preloader */ updateStatus: function(status, text) { if(nd.preloader) { if(_prevStatus !== status) { nd.container.removeClass('nd-s-'+_prevStatus); } if(!text && status === 'loading') { text = nd.st.tLoading; } var data = { status: status, text: text }; // allows to modify status _ndTrigger('UpdateStatus', data); status = data.status; text = data.text; nd.preloader.html(text); nd.preloader.find('a').on('click', function(e) { e.stopImmediatePropagation(); }); nd.container.addClass('nd-s-'+status); _prevStatus = status; } }, /* "Private" helpers that aren't private at all */ // Check to close popup or not // "target" is an element that was clicked _checkIfClose: function(target) { if($(target).hasClass(PREVENT_CLOSE_CLASS)) { return; } var closeOnContent = nd.st.closeOnContentClick; var closeOnBg = nd.st.closeOnBgClick; if(closeOnContent && closeOnBg) { return true; } else { // We close the popup if click is on close button or on preloader. Or if there is no content. if(!nd.content || $(target).hasClass('nd-close') || (nd.preloader && target === nd.preloader[0]) ) { return true; } // if click is outside the content if( (target !== nd.content[0] && !$.contains(nd.content[0], target)) ) { if(closeOnBg) { // last check, if the clicked element is in DOM, (in case it's removed onclick) if( $.contains(document, target) ) { return true; } } } else if(closeOnContent) { return true; } } return false; }, _addClassTond: function(cName) { nd.bgOverlay.addClass(cName); nd.wrap.addClass(cName); }, _removeClassFromnd: function(cName) { this.bgOverlay.removeClass(cName); nd.wrap.removeClass(cName); }, _hasScrollBar: function(winHeight) { return ( (nd.isIE7 ? _document.height() : document.body.scrollHeight) > (winHeight || _window.height()) ); }, _setFocus: function() { (nd.st.focus ? nd.content.find(nd.st.focus).eq(0) : nd.wrap).focus(); }, _onFocusIn: function(e) { if( e.target !== nd.wrap[0] && !$.contains(nd.wrap[0], e.target) ) { nd._setFocus(); return false; } }, _parseMarkup: function(template, values, item) { var arr; if(item.data) { values = $.extend(item.data, values); } _ndTrigger(MARKUP_PARSE_EVENT, [template, values, item] ); $.each(values, function(key, value) { if(value === undefined || value === false) { return true; } arr = key.split('_'); if(arr.length > 1) { var el = template.find(EVENT_NS + '-'+arr[0]); if(el.length > 0) { var attr = arr[1]; if(attr === 'replaceWith') { if(el[0] !== value[0]) { el.replaceWith(value); } } else if(attr === 'img') { if(el.is('img')) { el.attr('src', value); } else { el.replaceWith( '' ); } } else { el.attr(arr[1], value); } } } else { template.find(EVENT_NS + '-'+key).html(value); } }); }, _getScrollbarSize: function() { // thx David if(nd.scrollbarSize === undefined) { var scrollDiv = document.createElement("div"); scrollDiv.id = "nd-sbm"; scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;'; document.body.appendChild(scrollDiv); nd.scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); } return nd.scrollbarSize; } }; /* MagnificPopup core prototype end */ /** * Public static functions */ $.magnificPopup = { instance: null, proto: MagnificPopup.prototype, modules: [], open: function(options, index) { _checkInstance(); if(!options) { options = {}; } else { options = $.extend(true, {}, options); } options.isObj = true; options.index = index || 0; return this.instance.open(options); }, close: function() { return $.magnificPopup.instance && $.magnificPopup.instance.close(); }, registerModule: function(name, module) { if(module.options) { $.magnificPopup.defaults[name] = module.options; } $.extend(this.proto, module.proto); this.modules.push(name); }, defaults: { // Info about options is in docs: // http://dimsemenov.com/plugins/magnific-popup/documentation.html#options disableOn: 0, key: null, midClick: false, mainClass: '', preloader: true, focus: '', // CSS selector of input to focus after popup is opened closeOnContentClick: false, closeOnBgClick: true, closeBtnInside: true, showCloseBtn: true, enableEscapeKey: true, modal: false, alignTop: false, removalDelay: 0, fixedContentPos: 'auto', fixedBgPos: 'auto', overflowY: 'auto', closeMarkup: '', tClose: 'Close (Esc)', tLoading: 'Loading...' } }; $.fn.magnificPopup = function(options) { _checkInstance(); var jqEl = $(this); // We call some API method of first param is a string if (typeof options === "string" ) { if(options === 'open') { var items, itemOpts = _isJQ ? jqEl.data('magnificPopup') : jqEl[0].magnificPopup, index = parseInt(arguments[1], 10) || 0; if(itemOpts.items) { items = itemOpts.items[index]; } else { items = jqEl; if(itemOpts.delegate) { items = items.find(itemOpts.delegate); } items = items.eq( index ); } nd._openClick({ndEl:items}, jqEl, itemOpts); } else { if(nd.isOpen) nd[options].apply(nd, Array.prototype.slice.call(arguments, 1)); } } else { // clone options obj options = $.extend(true, {}, options); /* * As Zepto doesn't support .data() method for objects * and it works only in normal browsers * we assign "options" object directly to the DOM element. FTW! */ if(_isJQ) { jqEl.data('magnificPopup', options); } else { jqEl[0].magnificPopup = options; } nd.addGroup(jqEl, options); } return jqEl; }; //Quick benchmark /* var start = performance.now(), i, rounds = 1000; for(i = 0; i < rounds; i++) { } console.log('Test #1:', performance.now() - start); start = performance.now(); for(i = 0; i < rounds; i++) { } console.log('Test #2:', performance.now() - start); */ /*>>core*/ /*>>inline*/ var INLINE_NS = 'inline', _hiddenClass, _inlinePlaceholder, _lastInlineElement, _putInlineElementsBack = function() { if(_lastInlineElement) { _inlinePlaceholder.after( _lastInlineElement.addClass(_hiddenClass) ).detach(); _lastInlineElement = null; } }; $.magnificPopup.registerModule(INLINE_NS, { options: { hiddenClass: 'hide', // will be appended with `nd-` prefix markup: '', tNotFound: 'Content not found' }, proto: { initInline: function() { nd.types.push(INLINE_NS); _ndOn(CLOSE_EVENT+'.'+INLINE_NS, function() { _putInlineElementsBack(); }); }, getInline: function(item, template) { _putInlineElementsBack(); if(item.src) { var inlineSt = nd.st.inline, el = $(item.src); if(el.length) { // If target element has parent - we replace it with placeholder and put it back after popup is closed var parent = el[0].parentNode; if(parent && parent.tagName) { if(!_inlinePlaceholder) { _hiddenClass = inlineSt.hiddenClass; _inlinePlaceholder = _getEl(_hiddenClass); _hiddenClass = 'nd-'+_hiddenClass; } // replace target inline element with placeholder _lastInlineElement = el.after(_inlinePlaceholder).detach().removeClass(_hiddenClass); } nd.updateStatus('ready'); } else { nd.updateStatus('error', inlineSt.tNotFound); el = $('
'); } item.inlineElement = el; return el; } nd.updateStatus('ready'); nd._parseMarkup(template, {}, item); return template; } } }); /*>>inline*/ /*>>ajax*/ var AJAX_NS = 'ajax', _ajaxCur, _removeAjaxCursor = function() { if(_ajaxCur) { _body.removeClass(_ajaxCur); } }, _destroyAjaxRequest = function() { _removeAjaxCursor(); if(nd.req) { nd.req.abort(); } }; $.magnificPopup.registerModule(AJAX_NS, { options: { settings: null, cursor: 'nd-ajax-cur', tError: 'The content could not be loaded.' }, proto: { initAjax: function() { nd.types.push(AJAX_NS); _ajaxCur = nd.st.ajax.cursor; _ndOn(CLOSE_EVENT+'.'+AJAX_NS, _destroyAjaxRequest); _ndOn('BeforeChange.' + AJAX_NS, _destroyAjaxRequest); }, getAjax: function(item) { if(_ajaxCur) _body.addClass(_ajaxCur); nd.updateStatus('loading'); var opts = $.extend({ url: item.src, success: function(data, textStatus, jqXHR) { var temp = { data:data, xhr:jqXHR }; _ndTrigger('ParseAjax', temp); nd.appendContent( $(temp.data), AJAX_NS ); item.finished = true; _removeAjaxCursor(); nd._setFocus(); setTimeout(function() { nd.wrap.addClass(READY_CLASS); }, 16); nd.updateStatus('ready'); _ndTrigger('AjaxContentAdded'); }, error: function() { _removeAjaxCursor(); item.finished = item.loadError = true; nd.updateStatus('error', nd.st.ajax.tError.replace('%url%', item.src)); } }, nd.st.ajax.settings); nd.req = $.ajax(opts); return ''; } } }); /*>>ajax*/ /*>>image*/ var _imgInterval, _getTitle = function(item) { if(item.data && item.data.title !== undefined) return item.data.title; var src = nd.st.image.titleSrc; if(src) { if($.isFunction(src)) { return src.call(nd, item); } else if(item.el) { return item.el.attr(src) || ''; } } return ''; }; $.magnificPopup.registerModule('image', { options: { markup: '
'+ '
'+ '
'+ '
'+ '
'+ '
'+ '
'+ '
'+ '
'+ '
'+ '
'+ '
', cursor: 'nd-zoom-out-cur', titleSrc: 'title', verticalFit: true, tError: 'The image could not be loaded.' }, proto: { initImage: function() { var imgSt = nd.st.image, ns = '.image'; nd.types.push('image'); _ndOn(OPEN_EVENT+ns, function() { if(nd.currItem.type === 'image' && imgSt.cursor) { _body.addClass(imgSt.cursor); } }); _ndOn(CLOSE_EVENT+ns, function() { if(imgSt.cursor) { _body.removeClass(imgSt.cursor); } _window.off('resize' + EVENT_NS); }); _ndOn('Resize'+ns, nd.resizeImage); if(nd.isLowIE) { _ndOn('AfterChange', nd.resizeImage); } }, resizeImage: function() { var item = nd.currItem; if(!item || !item.img) return; if(nd.st.image.verticalFit) { var decr = 0; // fix box-sizing in ie7/8 if(nd.isLowIE) { decr = parseInt(item.img.css('padding-top'), 10) + parseInt(item.img.css('padding-bottom'),10); } item.img.css('max-height', nd.wH-decr); } }, _onImageHasSize: function(item) { if(item.img) { item.hasSize = true; if(_imgInterval) { clearInterval(_imgInterval); } item.isCheckingImgSize = false; _ndTrigger('ImageHasSize', item); if(item.imgHidden) { if(nd.content) nd.content.removeClass('nd-loading'); item.imgHidden = false; } } }, /** * Function that loops until the image has size to display elements that rely on it asap */ findImageSize: function(item) { var counter = 0, img = item.img[0], ndSetInterval = function(delay) { if(_imgInterval) { clearInterval(_imgInterval); } // decelerating interval that checks for size of an image _imgInterval = setInterval(function() { if(img.naturalWidth > 0) { nd._onImageHasSize(item); return; } if(counter > 200) { clearInterval(_imgInterval); } counter++; if(counter === 3) { ndSetInterval(10); } else if(counter === 40) { ndSetInterval(50); } else if(counter === 100) { ndSetInterval(500); } }, delay); }; ndSetInterval(1); }, getImage: function(item, template) { var guard = 0, // image load complete handler onLoadComplete = function() { if(item) { if (item.img[0].complete) { item.img.off('.ndloader'); if(item === nd.currItem){ nd._onImageHasSize(item); nd.updateStatus('ready'); } item.hasSize = true; item.loaded = true; _ndTrigger('ImageLoadComplete'); } else { // if image complete check fails 200 times (20 sec), we assume that there was an error. guard++; if(guard < 200) { setTimeout(onLoadComplete,100); } else { onLoadError(); } } } }, // image error handler onLoadError = function() { if(item) { item.img.off('.ndloader'); if(item === nd.currItem){ nd._onImageHasSize(item); nd.updateStatus('error', imgSt.tError.replace('%url%', item.src) ); } item.hasSize = true; item.loaded = true; item.loadError = true; } }, imgSt = nd.st.image; var el = template.find('.nd-img'); if(el.length) { var img = document.createElement('img'); img.className = 'nd-img'; item.img = $(img).on('load.ndloader', onLoadComplete).on('error.ndloader', onLoadError); img.src = item.src; // without clone() "error" event is not firing when IMG is replaced by new IMG // TODO: find a way to avoid such cloning if(el.is('img')) { item.img = item.img.clone(); } if(item.img[0].naturalWidth > 0) { item.hasSize = true; } } nd._parseMarkup(template, { title: _getTitle(item), img_replaceWith: item.img }, item); nd.resizeImage(); if(item.hasSize) { if(_imgInterval) clearInterval(_imgInterval); if(item.loadError) { template.addClass('nd-loading'); nd.updateStatus('error', imgSt.tError.replace('%url%', item.src) ); } else { template.removeClass('nd-loading'); nd.updateStatus('ready'); } return template; } nd.updateStatus('loading'); item.loading = true; if(!item.hasSize) { item.imgHidden = true; template.addClass('nd-loading'); nd.findImageSize(item); } return template; } } }); /*>>image*/ /*>>zoom*/ var hasMozTransform, getHasMozTransform = function() { if(hasMozTransform === undefined) { hasMozTransform = document.createElement('p').style.MozTransform !== undefined; } return hasMozTransform; }; $.magnificPopup.registerModule('zoom', { options: { enabled: false, easing: 'ease-in-out', duration: 300, opener: function(element) { return element.is('img') ? element : element.find('img'); } }, proto: { initZoom: function() { var zoomSt = nd.st.zoom, ns = '.zoom', image; if(!zoomSt.enabled || !nd.supportsTransition) { return; } var duration = zoomSt.duration, getElToAnimate = function(image) { var newImg = image.clone().removeAttr('style').removeAttr('class').addClass('nd-animated-image'), transition = 'all '+(zoomSt.duration/1000)+'s ' + zoomSt.easing, cssObj = { position: 'fixed', zIndex: 9999, left: 0, top: 0, '-webkit-backface-visibility': 'hidden' }, t = 'transition'; cssObj['-webkit-'+t] = cssObj['-moz-'+t] = cssObj['-o-'+t] = cssObj[t] = transition; newImg.css(cssObj); return newImg; }, showMainContent = function() { nd.content.css('visibility', 'visible'); }, openTimeout, animatedImg; _ndOn('BuildControls'+ns, function() { if(nd._allowZoom()) { clearTimeout(openTimeout); nd.content.css('visibility', 'hidden'); // Basically, all code below does is clones existing image, puts in on top of the current one and animated it image = nd._getItemToZoom(); if(!image) { showMainContent(); return; } animatedImg = getElToAnimate(image); animatedImg.css( nd._getOffset() ); nd.wrap.append(animatedImg); openTimeout = setTimeout(function() { animatedImg.css( nd._getOffset( true ) ); openTimeout = setTimeout(function() { showMainContent(); setTimeout(function() { animatedImg.remove(); image = animatedImg = null; _ndTrigger('ZoomAnimationEnded'); }, 16); // avoid blink when switching images }, duration); // this timeout equals animation duration }, 16); // by adding this timeout we avoid short glitch at the beginning of animation // Lots of timeouts... } }); _ndOn(BEFORE_CLOSE_EVENT+ns, function() { if(nd._allowZoom()) { clearTimeout(openTimeout); nd.st.removalDelay = duration; if(!image) { image = nd._getItemToZoom(); if(!image) { return; } animatedImg = getElToAnimate(image); } animatedImg.css( nd._getOffset(true) ); nd.wrap.append(animatedImg); nd.content.css('visibility', 'hidden'); setTimeout(function() { animatedImg.css( nd._getOffset() ); }, 16); } }); _ndOn(CLOSE_EVENT+ns, function() { if(nd._allowZoom()) { showMainContent(); if(animatedImg) { animatedImg.remove(); } image = null; } }); }, _allowZoom: function() { return nd.currItem.type === 'image'; }, _getItemToZoom: function() { if(nd.currItem.hasSize) { return nd.currItem.img; } else { return false; } }, // Get element postion relative to viewport _getOffset: function(isLarge) { var el; if(isLarge) { el = nd.currItem.img; } else { el = nd.st.zoom.opener(nd.currItem.el || nd.currItem); } var offset = el.offset(); var paddingTop = parseInt(el.css('padding-top'),10); var paddingBottom = parseInt(el.css('padding-bottom'),10); offset.top -= ( $(window).scrollTop() - paddingTop ); /* Animating left + top + width/height looks glitchy in Firefox, but perfect in Chrome. And vice-versa. */ var obj = { width: el.width(), // fix Zepto height+padding issue height: (_isJQ ? el.innerHeight() : el[0].offsetHeight) - paddingBottom - paddingTop }; // I hate to do this, but there is no another option if( getHasMozTransform() ) { obj['-moz-transform'] = obj['transform'] = 'translate(' + offset.left + 'px,' + offset.top + 'px)'; } else { obj.left = offset.left; obj.top = offset.top; } return obj; } } }); /*>>zoom*/ /*>>iframe*/ var IFRAME_NS = 'iframe', _emptyPage = '//about:blank', _fixIframeBugs = function(isShowing) { if(nd.currTemplate[IFRAME_NS]) { var el = nd.currTemplate[IFRAME_NS].find('iframe'); if(el.length) { // reset src after the popup is closed to avoid "video keeps playing after popup is closed" bug if(!isShowing) { el[0].src = _emptyPage; } // IE8 black screen bug fix if(nd.isIE8) { el.css('display', isShowing ? 'block' : 'none'); } } } }; $.magnificPopup.registerModule(IFRAME_NS, { options: { markup: '
'+ '
'+ ''+ '
', srcAction: 'iframe_src', // we don't care and support only one default type of URL by default patterns: { youtube: { index: 'youtube.com', id: 'v=', src: '//www.youtube.com/embed/%id%?autoplay=1' }, vimeo: { index: 'vimeo.com/', id: '/', src: '//player.vimeo.com/video/%id%?autoplay=1' }, gmaps: { index: '//maps.google.', src: '%id%&output=embed' } } }, proto: { initIframe: function() { nd.types.push(IFRAME_NS); _ndOn('BeforeChange', function(e, prevType, newType) { if(prevType !== newType) { if(prevType === IFRAME_NS) { _fixIframeBugs(); // iframe if removed } else if(newType === IFRAME_NS) { _fixIframeBugs(true); // iframe is showing } }// else { // iframe source is switched, don't do anything //} }); _ndOn(CLOSE_EVENT + '.' + IFRAME_NS, function() { _fixIframeBugs(); }); }, getIframe: function(item, template) { var embedSrc = item.src; var iframeSt = nd.st.iframe; $.each(iframeSt.patterns, function() { if(embedSrc.indexOf( this.index ) > -1) { if(this.id) { if(typeof this.id === 'string') { embedSrc = embedSrc.substr(embedSrc.lastIndexOf(this.id)+this.id.length, embedSrc.length); } else { embedSrc = this.id.call( this, embedSrc ); } } embedSrc = this.src.replace('%id%', embedSrc ); return false; // break; } }); var dataObj = {}; if(iframeSt.srcAction) { dataObj[iframeSt.srcAction] = embedSrc; } nd._parseMarkup(template, dataObj, item); nd.updateStatus('ready'); return template; } } }); /*>>iframe*/ /*>>gallery*/ /** * Get looped index depending on number of slides */ var _getLoopedId = function(index) { var numSlides = nd.items.length; if(index > numSlides - 1) { return index - numSlides; } else if(index < 0) { return numSlides + index; } return index; }, _replaceCurrTotal = function(text, curr, total) { return text.replace(/%curr%/gi, curr + 1).replace(/%total%/gi, total); }; $.magnificPopup.registerModule('gallery', { options: { enabled: false, arrowMarkup: '', preload: [0,2], navigateByImgClick: true, arrows: true, tPrev: 'Previous (Left arrow key)', tNext: 'Next (Right arrow key)', tCounter: '%curr% of %total%' }, proto: { initGallery: function() { var gSt = nd.st.gallery, ns = '.nd-gallery', supportsFastClick = Boolean($.fn.ndFastClick); nd.direction = true; // true - next, false - prev if(!gSt || !gSt.enabled ) return false; _wrapClasses += ' nd-gallery'; _ndOn(OPEN_EVENT+ns, function() { if(gSt.navigateByImgClick) { nd.wrap.on('click'+ns, '.nd-img', function() { if(nd.items.length > 1) { nd.next(); return false; } }); } _document.on('keydown'+ns, function(e) { if (e.keyCode === 37) { nd.prev(); } else if (e.keyCode === 39) { nd.next(); } }); }); _ndOn('UpdateStatus'+ns, function(e, data) { if(data.text) { data.text = _replaceCurrTotal(data.text, nd.currItem.index, nd.items.length); } }); _ndOn(MARKUP_PARSE_EVENT+ns, function(e, element, values, item) { var l = nd.items.length; values.counter = l > 1 ? _replaceCurrTotal(gSt.tCounter, item.index, l) : ''; }); _ndOn('BuildControls' + ns, function() { if(nd.items.length > 1 && gSt.arrows && !nd.arrowLeft) { var markup = gSt.arrowMarkup, arrowLeft = nd.arrowLeft = $( markup.replace(/%title%/gi, gSt.tPrev).replace(/%dir%/gi, 'left') ).addClass(PREVENT_CLOSE_CLASS), arrowRight = nd.arrowRight = $( markup.replace(/%title%/gi, gSt.tNext).replace(/%dir%/gi, 'right') ).addClass(PREVENT_CLOSE_CLASS); var eName = supportsFastClick ? 'ndFastClick' : 'click'; arrowLeft[eName](function() { nd.prev(); }); arrowRight[eName](function() { nd.next(); }); // Polyfill for :before and :after (adds elements with classes nd-a and nd-b) if(nd.isIE7) { _getEl('b', arrowLeft[0], false, true); _getEl('a', arrowLeft[0], false, true); _getEl('b', arrowRight[0], false, true); _getEl('a', arrowRight[0], false, true); } nd.container.append(arrowLeft.add(arrowRight)); } }); _ndOn(CHANGE_EVENT+ns, function() { if(nd._preloadTimeout) clearTimeout(nd._preloadTimeout); nd._preloadTimeout = setTimeout(function() { nd.preloadNearbyImages(); nd._preloadTimeout = null; }, 16); }); _ndOn(CLOSE_EVENT+ns, function() { _document.off(ns); nd.wrap.off('click'+ns); if(nd.arrowLeft && supportsFastClick) { nd.arrowLeft.add(nd.arrowRight).destroyndFastClick(); } nd.arrowRight = nd.arrowLeft = null; }); }, next: function() { nd.direction = true; nd.index = _getLoopedId(nd.index + 1); nd.updateItemHTML(); }, prev: function() { nd.direction = false; nd.index = _getLoopedId(nd.index - 1); nd.updateItemHTML(); }, goTo: function(newIndex) { nd.direction = (newIndex >= nd.index); nd.index = newIndex; nd.updateItemHTML(); }, preloadNearbyImages: function() { var p = nd.st.gallery.preload, preloadBefore = Math.min(p[0], nd.items.length), preloadAfter = Math.min(p[1], nd.items.length), i; for(i = 1; i <= (nd.direction ? preloadAfter : preloadBefore); i++) { nd._preloadItem(nd.index+i); } for(i = 1; i <= (nd.direction ? preloadBefore : preloadAfter); i++) { nd._preloadItem(nd.index-i); } }, _preloadItem: function(index) { index = _getLoopedId(index); if(nd.items[index].preloaded) { return; } var item = nd.items[index]; if(!item.parsed) { item = nd.parseEl( index ); } _ndTrigger('LazyLoad', item); if(item.type === 'image') { item.img = $('').on('load.ndloader', function() { item.hasSize = true; }).on('error.ndloader', function() { item.hasSize = true; item.loadError = true; _ndTrigger('LazyLoadError', item); }).attr('src', item.src); } item.preloaded = true; } } }); /* Touch Support that might be implemented some day addSwipeGesture: function() { var startX, moved, multipleTouches; return; var namespace = '.nd', addEventNames = function(pref, down, move, up, cancel) { nd._tStart = pref + down + namespace; nd._tMove = pref + move + namespace; nd._tEnd = pref + up + namespace; nd._tCancel = pref + cancel + namespace; }; if(window.navigator.msPointerEnabled) { addEventNames('MSPointer', 'Down', 'Move', 'Up', 'Cancel'); } else if('ontouchstart' in window) { addEventNames('touch', 'start', 'move', 'end', 'cancel'); } else { return; } _window.on(nd._tStart, function(e) { var oE = e.originalEvent; multipleTouches = moved = false; startX = oE.pageX || oE.changedTouches[0].pageX; }).on(nd._tMove, function(e) { if(e.originalEvent.touches.length > 1) { multipleTouches = e.originalEvent.touches.length; } else { //e.preventDefault(); moved = true; } }).on(nd._tEnd + ' ' + nd._tCancel, function(e) { if(moved && !multipleTouches) { var oE = e.originalEvent, diff = startX - (oE.pageX || oE.changedTouches[0].pageX); if(diff > 20) { nd.next(); } else if(diff < -20) { nd.prev(); } } }); }, */ /*>>gallery*/ /*>>retina*/ var RETINA_NS = 'retina'; $.magnificPopup.registerModule(RETINA_NS, { options: { replaceSrc: function(item) { return item.src.replace(/\.\w+$/, function(m) { return '@2x' + m; }); }, ratio: 1 // Function or number. Set to 1 to disable. }, proto: { initRetina: function() { if(window.devicePixelRatio > 1) { var st = nd.st.retina, ratio = st.ratio; ratio = !isNaN(ratio) ? ratio : ratio(); if(ratio > 1) { _ndOn('ImageHasSize' + '.' + RETINA_NS, function(e, item) { item.img.css({ 'max-width': item.img[0].naturalWidth / ratio, 'width': '100%' }); }); _ndOn('ElementParse' + '.' + RETINA_NS, function(e, item) { item.src = st.replaceSrc(item, ratio); }); } } } } }); /*>>retina*/ /*>>fastclick*/ /** * FastClick event implementation. (removes 300ms delay on touch devices) * Based on https://developers.google.com/mobile/articles/fast_buttons * * You may use it outside the Magnific Popup by calling just: * * $('.your-el').ndFastClick(function() { * console.log('Clicked!'); * }); * * To unbind: * $('.your-el').destroyndFastClick(); * * * Note that it's a very basic and simple implementation, it blocks ghost click on the same element where it was bound. * If you need something more advanced, use plugin by FT Labs https://github.com/ftlabs/fastclick * */ (function() { var ghostClickDelay = 1000, supportsTouch = 'ontouchstart' in window, unbindTouchMove = function() { _window.off('touchmove'+ns+' touchend'+ns); }, eName = 'ndFastClick', ns = '.'+eName; // As Zepto.js doesn't have an easy way to add custom events (like jQuery), so we implement it in this way $.fn.ndFastClick = function(callback) { return $(this).each(function() { var elem = $(this), lock; if( supportsTouch ) { var timeout, startX, startY, pointerMoved, point, numPointers; elem.on('touchstart' + ns, function(e) { pointerMoved = false; numPointers = 1; point = e.originalEvent ? e.originalEvent.touches[0] : e.touches[0]; startX = point.clientX; startY = point.clientY; _window.on('touchmove'+ns, function(e) { point = e.originalEvent ? e.originalEvent.touches : e.touches; numPointers = point.length; point = point[0]; if (Math.abs(point.clientX - startX) > 10 || Math.abs(point.clientY - startY) > 10) { pointerMoved = true; unbindTouchMove(); } }).on('touchend'+ns, function(e) { unbindTouchMove(); if(pointerMoved || numPointers > 1) { return; } lock = true; e.preventDefault(); clearTimeout(timeout); timeout = setTimeout(function() { lock = false; }, ghostClickDelay); callback(); }); }); } elem.on('click' + ns, function() { if(!lock) { callback(); } }); }); }; $.fn.destroyndFastClick = function() { $(this).off('touchstart' + ns + ' click' + ns); if(supportsTouch) _window.off('touchmove'+ns+' touchend'+ns); }; })(); /*>>fastclick*/ _checkInstance(); })(window.jQuery || window.Zepto);