/**
############
# # _ _ ____
# __ # | |_| |__ ___ / ___|_ __ __ _ __ _
# _/..\ # | __| '_ \ / _ \ | | '__/ _` |/ _` |
#___-/.....\ # | |_| | | | __/ |___| | | (_| | (_| |
#...........-# \__|_| |_|\___|\____|_| \__,_|\__, |
#............# |___/
############
This is for ALL js which is common to the whole site, like tooltip hovers, headline fixed behaviours
If behaviour is specific to just the area or list templates then it should be in a seperate script
*/
// ******** START DEFAULT INTERNATIONALISATION ********************
// * default values for translation keys in case they are not loaded
// * also acts as a spec for the translation keys that this file requires
if ( typeof tc_translate == "undefined" ) {
tc_translate = { keys:{} };
}
$.each({
// add the default values here
"js.common.show-more": "show more",
"js.common.hide": "hide",
"js.common.hide.label": "hide {labe}",
"process.button.log-ascent": "Log ascent(s)",
"process.button.log-ascent.one": "Log ascent",
"process.button.log-ascent.many": "Log {count} ascents",
"x":""}, function(key, val){
if ( typeof tc_translate.keys[key] == "undefined" ) {
tc_translate.keys[key] = val
}
});
// ******** END DEFAULT INTERNATIONALISATION ********************
//// ******** START getText INTERNATIONALISATION ********************
//tc_translate.getText = function (key,substitutes,options) {
// var use_key = key;
// if ( typeof options != "undefined" && typeof options['count'] != 'undefined' ) {
// var count = options['count'];
// //alert("DEBUG:A:"+count);
// var postfix = '';
// if ( count < 0 ) {
// postfix = '.negative';
// } else if ( count == 0 ) {
// postfix = '.zero';
// } else if ( count == 1 ) {
// postfix = '.one';
// } else if ( count > 1 ) {
// postfix = '.many';
// }
// var fullkey = use_key + postfix;
// //alert("DEBUG:B:"+fullkey);
// if ( typeof tc_translate.keys[fullkey] != "undefined" ) {
// use_key = fullkey;
// }
// }
// if ( typeof tc_translate.keys[use_key] == "undefined" ) {
// return '?';
// }
// //alert("DEBUG:C:"+use_key);
// var text = tc_translate.keys[use_key];
// if ( typeof substitutes != "undefined" ) {
// //alert("DEBUG:D:"+text);
// $.each(substitutes,function(k, v){
// //alert("DEBUG:X:"+text+":"+k+":"+v);
// var re = new RegExp("{"+k+"}",'g');
// text = text.replace(re,v);
// //alert("DEBUG:Y:"+text);
// });
// }
// //alert("DEBUG:F:"+text);
// return text;
//}
//// ******** END getText INTERNATIONALISATION ********************
thecrag = thecrag || {};
function getClusterRadius(count) {
// Update the scale of the whole donut
var radius = Math.log(count+1)/Math.log(10); // From 0 - 6
radius *= .25;
radius += .5;
radius *= 40;
return radius;
}
/*
* styles - array of style objects
* size - if not specified the svg will be 80x80 and the donut
* will be sized within this. If specified is will force
* the donut to that size and adapt accordingly
*/
function renderStyleDonut(stylesorig, size) {
var styles = stylesorig;
var arr = [];
if (!Array.isArray(styles)){
for (var s in styles) {
arr.push({
label: s,
total: styles[s]
});
}
styles = arr;
}
styles.sort(function(a,b) {
return b.total - a.total;
});
var total = 0;
for (var style in styles){
total += styles[style].total;
}
var scale = 1;
if (size) {
size = Math.round(size);
scale = size * .027;
} else {
size = 80;
scale = getClusterRadius(total);
}
var half = size / 2;
var html = '';
html += '';
return html;
}
// from underscore.js
var _ = {};
_.throttle = function(func, wait) {
var context, args, timeout, throttling, more, result;
var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
return function() {
context = this; args = arguments;
var later = function() {
timeout = null;
if (more) func.apply(context, args);
whenDone();
};
if (!timeout) timeout = setTimeout(later, wait);
if (throttling) {
more = true;
} else {
result = func.apply(context, args);
}
whenDone();
throttling = true;
return result;
};
};
_.debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
if (immediate && !timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
_.uniq = function(a) {
var prims = {"boolean":{}, "number":{}, "string":{}}, objs = [];
return a.filter(function(item) {
var type = typeof item;
if(type in prims)
return prims[type].hasOwnProperty(item) ? false : (prims[type][item] = true);
else
return objs.indexOf(item) >= 0 ? false : objs.push(item);
});
};
/*
* The bread crumb manager
*/
function Crumbs($el) {
this.$el = $el;
var that = this;
if ($el.length) {
$(window).on('resize', _.throttle(function(el, obj) {
that.resize();
}, 100));
this.resize();
} else {
window.console && console.warn("Crumbs has no items!");
}
}
Crumbs.prototype = {
/*
* How much space the crumb trail wants?
*
* How much it wants depends on it's current display state so
* this will change as nodes are shrunk and hidden.
*/
wants: function() {
// var w = this.$el[0].scrollWidth;
var w = this.$el.find('.crumbs__all')[0].scrollWidth;
return w;
},
/*
* How many pixels do we have to fit stuff into?
*/
has: function() {
var w = this.$el[0].clientWidth - 5; // 5px buffer for good luck
return w;
},
/*
* Returns how much room there is.
* If there is no room it is negative
*/
room: function() {
var room = this.has() - this.wants();
return room;
},
/*
* True is there is enough room
*/
fits: function() {
return this.room() >= 0;
},
/*
* Resets display state
*/
reset: function() {
var $lis = this.$el.find('.crumb');
// Reset any previous shortenings
$lis.find('.crumb_long').css('display', 'inline-block');
$lis.find('.crumb_short').css('display', 'none');
$lis.removeClass('crumb--collapsed');
// remove max widths
$lis.find('a').css('max-width', 'none');
$lis.css('display', 'inline-block');
$lis.find('.crumb__sep i').attr('class', 'icon-angle-right');
},
/*
* resize the crumb to fit the available space
*/
resize: function() {
var $lis = this.$el.find('.crumb');
var max = $lis.length;
var has = this.has();
var c;
this.reset();
// Must be after we reset to full width
var wants = this.wants();
// From right to left make sure all nodes are < 300px
var mwid = 300;
for (c=max-1; c >= 0 && !this.fits(); c--) {
$lis.eq(c).find('a').css('max-width', mwid+'px');
}
// From left to right, see if there is a short version of any nodes
for (c=1; c < max-1 && !this.fits(); c++) {
var $s = $lis.eq(c).find('.crumb__short');
if ($s.length) {
$lis.eq(c).find('.crumb__short').css('display', 'inline-block');
$lis.eq(c).find('.crumb__long').css('display', 'none');
}
}
// If we are on a screen smaller than X, and we don't fit then it's ok collapse the last node
if (!this.fits() && window.matchMedia && window.matchMedia('(max-width: 736px)').matches) { // see layout/regions.less
$lis.eq(max-1).addClass('crumb--collapsed');
}
// From left to right hide nodes but NEVER remove the last node
for (c=1; c < max-1 && !this.fits(); c++) {
$lis.eq(c).css('display', 'none');
$lis.eq(c+1).find('.crumb__sep i').attr('class', 'icon-double-angle-right')
}
// Now fine tune the size of the selected item to make it perfect
var gap = this.room();
var $sel = $lis.last().find('a');
if ($sel.css('max-width') == 'none') {
mwid = $sel.width();
}
$sel.css('max-width', (mwid + gap) + 'px');
},
/*
* replace the crumbtrail with new data. Each crumb object is identical to
* the template data but in json:
* {
* nid: 12345,
* href: '/climbing/australia',
* icon: 'world',
* label: 'Australia',
* short: 'Aus'
* }
*/
replace: function(crumbs) {
var html = '';
var c = 0;
for(c=0; c';
if (c != 0) {
html += this.render_crumb__sep(cr.nid,0);
}
html += '';
if (cr.icon) {
html += '';
}
if (cr.label) {
html += ''+cr.label+'';
}
if (cr['short']) {
html += ''+cr['short']+'';
}
html += '';
html += '';
}
this.$el.find('.crumbs__all').html(html);
this.resize();
},
render_crumb__sep: function(nid, children) {
var html = '';
var sclass = 'crumb__sep';
if (children) {
sclass += ' crumb--menu';
sclass += ' crumb--spin';
sclass += ' dropdown-menu--trigger';
}
html += '';
html += '';
return html;
}
}
thecrag.crumbs = new Crumbs($('#breadCrumbs'));
function centerTabs(){
$('.tabs').each(function(i) {
var $t = $(this);
var $s = $t.find('.tab--selected');
if ($s.length) {
$t.find('.tabs__slider').scrollLeft($s[0].offsetLeft - $t.width()/2 + $s.width()/2);
}
});
}
$(window).on('resize', _.throttle(centerTabs, 100));
window.addEventListener("orientationchange", centerTabs, false);
function initLazyJS(){
$('.js-lazy-img').lazy({
effect: "fadeIn",
effecttime: 2600,
threshold: 0
});
$('.js-lazy-img-fast').lazy();
}
(function($){
$.fn.keepVisible = function(keepInside){
// if no parent id then
var margin = {
top: 0,
bottom: 0
},
that = this,
height = this.height(),
width = this.width(),
outerHeight = this.outerHeight(),
outerWidth = this.outerWidth(),
offset = this.offset(),
slider = this,
placeHolder,
modeFlow = 0, modeTop = 1, modeBottom = 2,
mode = modeFlow,
check;
if (keepInside){
margin.top = offset.top;
margin.bottom = $(document).outerHeight() - offset.top - outerHeight;
}
// make a placeholder
placeHolder = $('')
.css({height: outerHeight, width: 10, display: 'none'})
.insertBefore(this);
// make the
check = function(){
height = that.height();
outerHeight = that.outerHeight();
//offset = that.offset();
var scrollTop = $(window).scrollTop(),
winHeight = $(window).height(),
oldMode = mode;
mode = modeFlow;
// has the slider overlapped the window frame?
if (scrollTop < offset.top + outerHeight - winHeight ){
mode |= modeBottom;
}
if (scrollTop > offset.top ){
mode |= modeTop;
}
// if both the top and bottom overlap then put it back into flow mode
if (mode === (modeTop | modeBottom)){ mode -= modeTop | modeBottom; }
if (winHeight < 400 || $(window).width() < 650){
mode = modeFlow;
}
if (outerHeight != that.outerHeight() ||
outerWidth != that.outerWidth() ){
outerHeight = that.outerHeight();
outerWidth = that.outerWidth();
} else {
if (mode === oldMode){ return; }
}
if (mode === modeFlow){
placeHolder.hide();
slider.removeClass('fixed')
return;
}
placeHolder.show().height(height);
slider.addClass('fixed');
};
$(window).scroll(check);
$(window).resize(check);
check();
};
})(jQuery);
// Follow / unfollow buttons
if ($('body').data('uid')){
$(".follow-them,.unfollow-them").click(function(e){
var $el = $(this);
var fol = $el.hasClass('follow-them');
$('body').trigger('crag.edit.start');
updateFollowing($('body').data('uid'),$el.data('uid'),fol,function(){
$('body').trigger('crag.edit.stop');
});
$el.toggleClass('follow-them btn-success', !fol);
$el.toggleClass('unfollow-them', fol);
$el.html(' ' + (fol ? 'Unfollow' : 'Follow') );
return false;
});
}
$('.link-map__pins a').on('mouseover', function(e) {
$('body').trigger('node.over', {id: $(this).data('nid') });
});
$('.link-map__pins a').on('mouseout', function(e) {
$('body').trigger('node.out', {id: $(this).data('nid') });
});
$(document).on('topotoggle', function(e,data){
var node = data.orig;
if (data.editing){
return;
}
if (node.type == 'area'){
window.location = node.url;
} else {
// Ask the page, is it selectable
var $check = $('input[type=checkbox][value='+node.id+']');
if ($check.length > 0){
// If yes, then select or deselect it
if ($check.attr('checked')){
$('body').trigger('node.deselect', {id: node.id});
} else {
$('body').trigger('node.select', {id: node.id});
}
} else {
// If not then navigate to it (eg cross area topo, or route page)
window.location = node.url;
}
}
});
$(document).on('topohover', function(e,data){
// Only code specific to topos go here's, the rest delegate to node.over
var node = data.node;
$('body').trigger('node.over', {id: node.id});
var o = data.orig;
if (o.type != 'route'){ return; }
var stars = '';
for(c=0; c★';
}
var name = '' + stars
+ ' '
+ o.name
+ ' ' + o.grade + ' '
+ o.style;
$('body')
.poshytip('enable')
.poshytip('update', name)
.poshytip('show');
});
$(document).on('topounhover', function(e,data){
// Only code specific to topos go here's, the rest delegate to node.over
$('body').trigger('node.out', {id: data.node.id});
if( !$.fn.poshytip){
return;
}
$('body').poshytip('disable').poshytip('hide');
});
function setupKeyboard(){
$("body").keydown(function(e) {
var keyMap = {
37: 'prev',
//38: 'up', // don't mess with normal scroll nav
39: 'next'
// 191: '#searchForm input' // '/' and '?' character - disabled because it stops blocks text area inputs
};
var link = keyMap[e.keyCode];
if (!link) return true;
var focus = $(e.target).is('body');
if (!focus){ return true; }
var href = $("link[rel='"+link+"']").attr('href');
if (href){
location = href;
return false;
}
var elem = $(link);
if (elem[0]){
elem.focus();
return false;
}
});
}
jQuery.expr[':'].anchas = function(a,i,m){
return jQuery(a).closest(m[3]).length == 0;
};
function setupTooltips(){
if( !$.fn.poshytip){
return;
}
// Remove things we don't want tooltips for like google maps and logos
var $t = $('[title]:not([title=""]):anchas(.js-no-tooltips)');
$t.poshytip({
className: 'tip-twitter',
content: function(callback){
var tip = $(this).data('title.poshytip');
if (tip.indexOf(' - ') != -1){
tip = '
'+tip.replace(/ - /, '
');
}
tip = tip.replace(/ - /g, ' ');
return tip;
},
fade: false,
liveEvents: true,
followCursor: true,
showTimeout: 1,
hideTimeout: 1,
slide: false,
alignX: 'center',
offsetY: 8,
allowTipHover: false,
// alignTo:'cursor'
alignTo:'target'
});
// This one is spare for topo, maps and other dynamic tooltips
$('body').poshytip({
shownnnnnOn: 'none',
className: 'tip-twitter',
fade: false,
followCursor: true,
showTimeout: 0,
showAniDuration: 0,
refreshAniDuration: 0,
slide: false,
alignX: 'center',
alignTo: 'cursor'
}).poshytip('disable');
}
/*
* This is only triggered on the first hover which
* loads data and is then removed. After that it is pure
* css hovers.
*
*/
function menuHoverHandler(e){
var $e = $(e.currentTarget);
$e.unbind('mouseenter', menuHoverHandler);
var $nid = $e.find('> [data-nid]');
if ($nid.length == 0) {
$nid = $e.parent().find('> [data-nid]');
}
var nid = $nid.data('nid');
var suffix = $e.closest('[data-suffix]').data('suffix') || '';
function menuLoadHandler ($li, data){
data = data[0];
function addItem($l, item){
var a = $('').attr('href', thecrag_index_url({
id :item[0],
'type': 'area',
urlStub: item[2],
urlAncestorStub: item[3],
trailer: suffix
} ) )
.text(item[1])
.attr('data-nid',item[0])
.attr('data-subtype',item[5].toLowerCase())
;
var $li = $('
';
$(html).hide().appendTo(elem).css({position:'absolute','z-index':1000,top:pos.top+elem.innerHeight()+1,left:pos.left}).show().find("a").bind('click',function(e){
var source = $(this).find('.tags');
var style = source.text();
callback(source);
$("#style-dynamic").remove();
updateStyle(userid,routeid,style,function(){});
e.preventDefault();
return false;
});
}
function updateStyle(accid,nodeid,style,fn) {
url = "/api/route/update";
atom={submittor:accid,node:nodeid,gearStyle:style};
data={data:atom};
json=JSON.stringify(data);
postAPI(url,json,fn);
}
function ajaxArchiveRoute(nid,uid,fn) {
url = "/api/route/update";
atom={node:nid,submittor:uid,archive:1};
data={data:atom};
json=JSON.stringify(data);
postAPI(url,json,fn);
}
function ajaxUnarchiveRoute(nid,uid,fn) {
url = "/api/route/update";
atom={node:nid,submittor:uid,archive:0};
data={data:atom};
json=JSON.stringify(data);
postAPI(url,json,fn);
}
function archiveRoute(event,element) {
event.preventDefault();
var route = element.closest('[data-nid]');
var nid = route.data('nid');
var uid = $('body').data('uid');
if ( nid>0 && uid>0 ) {
ajaxArchiveRoute(nid,uid,function(){
$('body').trigger('node.deselect', {id: nid});
route.addClass("archived");
});
}
return false;
}
function unarchiveRoute(event,element) {
event.preventDefault();
var route = element.closest('[data-nid]');
var nid = route.data('nid');
var uid = $('body').data('uid');
if ( nid>0 && uid>0 ) {
ajaxUnarchiveRoute(nid,uid,function(){
route.removeClass("archived");
route.find(".label-archived").hide();
});
}
return false;
}
function thecrag_index_url(data,ctl) {
// alert("DEBUG:thecrag_index_url:start");
ctl = ctl ? ctl : {};
var type = ctl.type ? ctl.type : (data.type ? data.type : 'area');
var trailer = ctl.trailer ? ctl.trailer : (data.trailer ? data.trailer : '' );
var def = ctl['default'] ? ctl['default'] : '';
var src = '';
if ( type.match(/^(area|route)$/) ) {
if ( data.urlStub ) {
src = '/climbing/' + data.urlStub;
} else if ( data.urlAncestorStub ) {
src = '/climbing/' + data.urlAncestorStub + '/' + type + '/' + data.id;
} else if ( def ) {
src = def;
} else {
src = '/' + type + '/' + data.id;
}
}
if ( trailer ) {
src += (trailer.match(/^[\/\?]/)? '' : '/') + trailer;
}
// alert("DEBUG:thecrag_index_url:"+src);
return src;
}
function escapeHTML(s) {
return s.replace(/&/g,"&").replace(//g,">").replace(/\"/g,""");
}
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
/*
* selected bits from https://github.com/h5bp/mobile-boilerplate
*/
(function(document) {
window.MBP = window.MBP || {};
MBP.viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]');
MBP.preventZoom = function() {
if (!!document.querySelectorAll) return;
var formFields = document.querySelectorAll('input, select, textarea');
var contentString = 'width=device-width,initial-scale=1,maximum-scale=';
var i = 0;
var fieldLength = formFields.length;
var setViewportOnFocus = function() {
MBP.viewportmeta.content = contentString + '1';
};
var setViewportOnBlur = function() {
MBP.viewportmeta.content = contentString + '10';
};
for (; i < fieldLength; i++) {
formFields[i].onfocus = setViewportOnFocus;
formFields[i].onblur = setViewportOnBlur;
}
};
MBP.autogrow = function(element, lh) {
function handler(e) {
var newHeight = this.scrollHeight;
var currentHeight = this.clientHeight;
if (newHeight > currentHeight) {
this.style.height = newHeight + 3 * textLineHeight + 'px';
}
}
var setLineHeight = (lh) ? lh : 12;
var textLineHeight = element.currentStyle ? element.currentStyle.lineHeight : getComputedStyle(element, null).lineHeight;
textLineHeight = (textLineHeight.indexOf('px') == -1) ? setLineHeight : parseInt(textLineHeight, 10);
element.style.overflow = 'hidden';
element.addEventListener ? element.addEventListener('input', handler, false) : element.attachEvent('onpropertychange', handler);
};
// If we cache this we don't need to re-calibrate everytime we call
// the hide url bar
MBP.BODY_SCROLL_TOP = false;
// So we don't redefine this function everytime we
// we call hideUrlBar
MBP.getScrollTop = function() {
var win = window;
var doc = document;
return win.pageYOffset || doc.compatMode === 'CSS1Compat' && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
};
// It should be up to the mobile
MBP.hideUrlBar = function() {
var win = window;
// if there is a hash, or MBP.BODY_SCROLL_TOP hasn't been set yet, wait till that happens
if (!location.hash && MBP.BODY_SCROLL_TOP !== false) {
win.scrollTo( 0, MBP.BODY_SCROLL_TOP === 1 ? 0 : 1 );
}
};
MBP.hideUrlBarOnLoad = function() {
var win = window;
var doc = win.document;
var bodycheck;
// If there's a hash, or addEventListener is undefined, stop here
if ( !location.hash && win.addEventListener ) {
// scroll to 1
window.scrollTo( 0, 1 );
MBP.BODY_SCROLL_TOP = 1;
// reset to 0 on bodyready, if needed
bodycheck = setInterval(function() {
if ( doc.body ) {
clearInterval( bodycheck );
MBP.BODY_SCROLL_TOP = MBP.getScrollTop();
MBP.hideUrlBar();
}
}, 15 );
win.addEventListener('load', function() {
setTimeout(function() {
// at load, if user hasn't scrolled more than 20 or so...
if (MBP.getScrollTop() < 20) {
// reset to hide addr bar at onload
MBP.hideUrlBar();
}
}, 0);
});
}
};
})(document);
MBP.preventZoom();
MBP.hideUrlBar();
function FastClick(layer) {
'use strict';
var oldOnClick, self = this;
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
if (!layer || !layer.nodeType) {
throw new TypeError('Layer must be a document node');
}
/** @type function() */
this.onClick = function() { return FastClick.prototype.onClick.apply(self, arguments); };
/** @type function() */
this.onMouse = function() { return FastClick.prototype.onMouse.apply(self, arguments); };
/** @type function() */
this.onTouchStart = function() { return FastClick.prototype.onTouchStart.apply(self, arguments); };
/** @type function() */
this.onTouchEnd = function() { return FastClick.prototype.onTouchEnd.apply(self, arguments); };
/** @type function() */
this.onTouchCancel = function() { return FastClick.prototype.onTouchCancel.apply(self, arguments); };
if (FastClick.notNeeded(layer)) {
return;
}
// Set up event handlers as required
if (this.deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
/**
* Android requires exceptions.
*
* @type boolean
*/
FastClick.prototype.deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
/**
* iOS requires exceptions.
*
* @type boolean
*/
FastClick.prototype.deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
/**
* iOS 4 requires an exception for select elements.
*
* @type boolean
*/
FastClick.prototype.deviceIsIOS4 = FastClick.prototype.deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
/**
* iOS 6.0(+?) requires the target element to be manually derived
*
* @type boolean
*/
FastClick.prototype.deviceIsIOSWithBadTarget = FastClick.prototype.deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
/**
* Determine whether a given element requires a native click.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element needs a native click
*/
FastClick.prototype.needsClick = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
// Don't send a synthetic click to disabled inputs (issue #62)
case 'button':
case 'select':
case 'textarea':
if (target.disabled) {
return true;
}
break;
case 'input':
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((this.deviceIsIOS && target.type === 'file') || target.disabled) {
return true;
}
break;
case 'label':
case 'video':
return true;
}
/*
var node = target;
do {
if ((/\bneedsclick\b/).test(node.className)) return true;
}
while (node = node.parent);
return false;
*/
return (/\bneedsclick\b/).test(target.className);
};
/**
* Determine whether a given element requires a call to focus to simulate click into element.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
*/
FastClick.prototype.needsFocus = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
case 'textarea':
case 'select':
return true;
case 'input':
switch (target.type) {
case 'button':
case 'checkbox':
case 'file':
case 'image':
case 'radio':
case 'submit':
return false;
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly;
default:
return (/\bneedsfocus\b/).test(target.className);
}
};
/**
* Send a click event to the specified element.
*
* @param {EventTarget|Element} targetElement
* @param {Event} event
*/
FastClick.prototype.sendClick = function(targetElement, event) {
'use strict';
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent('click', true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
'use strict';
var length;
if (this.deviceIsIOS && targetElement.setSelectionRange) {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
/**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
*
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.updateScrollParent = function(targetElement) {
'use strict';
var scrollParent, parentElement;
scrollParent = targetElement.fastClickScrollParent;
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
// target element was moved to another parent.
if (!scrollParent || !scrollParent.contains(targetElement)) {
parentElement = targetElement;
do {
if (parentElement.scrollHeight > parentElement.offsetHeight) {
scrollParent = parentElement;
targetElement.fastClickScrollParent = parentElement;
break;
}
parentElement = parentElement.parentElement;
} while (parentElement);
}
// Always update the scroll top tracker if possible.
if (scrollParent) {
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
}
};
/**
* @param {EventTarget} targetElement
* @returns {Element|EventTarget}
*/
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
'use strict';
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode;
}
return eventTarget;
};
/**
* On touch start, record the position and scroll offset.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchStart = function(event) {
'use strict';
var targetElement, touch, selection;
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
if (this.deviceIsIOS) {
// Only trusted events will deselect text on iOS (issue #49)
selection = window.getSelection();
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!this.deviceIsIOS4) {
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
if (touch.identifier === this.lastTouchIdentifier) {
event.preventDefault();
return false;
}
this.lastTouchIdentifier = touch.identifier;
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
// 1) the user does a fling scroll on the scrollable layer
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.updateScrollParent(targetElement);
}
}
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < 200) {
event.preventDefault();
}
return true;
};
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.touchHasMoved = function(event) {
'use strict';
var touch = event.changedTouches[0], boundary = this.touchBoundary;
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
return true;
}
return false;
};
/**
* Attempt to find the labelled control for the given label element.
*
* @param {EventTarget|HTMLLabelElement} labelElement
* @returns {Element|null}
*/
FastClick.prototype.findControl = function(labelElement) {
'use strict';
// Fast path for newer browsers supporting the HTML5 control attribute
if (labelElement.control !== undefined) {
return labelElement.control;
}
// All browsers under test that support touch events also support the HTML5 htmlFor attribute
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor);
}
// If no for attribute exists, attempt to retrieve the first labellable descendant element
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};
/**
* On touch end, determine whether to send a click event at once.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchEnd = function(event) {
'use strict';
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
// If the touch has moved, cancel the click tracking
if (this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
if (!this.trackingClick) {
return true;
}
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < 200) {
this.cancelNextClick = true;
return true;
}
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
// On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 .
if (this.deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (this.deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
if ((event.timeStamp - trackingClickStart) > 100 || (this.deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
if (!this.deviceIsIOS4 || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (this.deviceIsIOS && !this.deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
/**
* On touch cancel, stop tracking the click.
*
* @returns {void}
*/
FastClick.prototype.onTouchCancel = function() {
'use strict';
this.trackingClick = false;
this.targetElement = null;
};
/**
* Determine mouse events which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onMouse = function(event) {
'use strict';
// If a target element was never set (because a touch event was never fired) allow the event
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
// Programmatically generated events targeting a specific element should be permitted
if (!event.cancelable) {
return true;
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// unless explicitly enabled, prevent non-touch click events from triggering actions,
// to prevent ghost/doubleclicks.
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
// If the mouse event is permitted, return true for the action to go through.
return true;
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* an actual click which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onClick = function(event) {
'use strict';
var permitted;
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
this.targetElement = null;
}
// If clicks are permitted, return true for the action to go through.
return permitted;
};
/**
* Remove all FastClick's event listeners.
*
* @returns {void}
*/
FastClick.prototype.destroy = function() {
'use strict';
var layer = this.layer;
if (this.deviceIsAndroid) {
layer.removeEventListener('mouseover', this.onMouse, true);
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true);
}
layer.removeEventListener('click', this.onClick, true);
layer.removeEventListener('touchstart', this.onTouchStart, false);
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};
/**
* Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
*/
FastClick.notNeeded = function(layer) {
'use strict';
var metaViewport;
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') {
return true;
}
if ((/Chrome\/[0-9]+/).test(navigator.userAgent)) {
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
if (FastClick.prototype.deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport && metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// Chrome desktop doesn't need FastClick (issue #15)
} else {
return true;
}
}
// IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none') {
return true;
}
return false;
};
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
*/
FastClick.attach = function(layer) {
'use strict';
return new FastClick(layer);
};
// if (typeof define !== 'undefined' && define.amd) {
//
// // AMD. Register as an anonymous module.
// define(function() {
// 'use strict';
// return FastClick;
// });
// } else if (typeof module !== 'undefined' && module.exports) {
// module.exports = FastClick.attach;
// module.exports.FastClick = FastClick;
// } else {
// window.FastClick = FastClick;
// }
//
// FastClick.attach(document.body);
//
//
// ******** START GENERAL HELPER FUNCTIONS ********************
function subURLArg(url,lbl,val) {
var reg = new RegExp('([?])'+lbl+'=[^&]*&?',"g");
url = url.replace(reg,'$1');
reg = new RegExp('&'+lbl+'=[^&]*',"g");
url = url.replace(reg,'');
url = url.replace(/[?&]+$/,'');
if (typeof val !== 'undefined' ) {
if (!url.match(/[?]/)) {
url += '?';
}
if (!url.match(/[?]$/)) {
url += '&';
}
url += lbl + '=' + val;
}
return url;
}
// ******** END GENERAL HELPER FUNCTIONS ********************
// ******** START URL REPLACE EMBED ********************
var URLReplace = {
resolver: {},
functions: {},
resolve: function (resolve) {
// alert("resolve:" + resolve);
if ( 'undefined' === typeof URLReplace.resolver[resolve] ) {
URLReplace.resolver[resolve] = $.Deferred();
}
URLReplace.resolver[resolve].resolve();
},
resolveTrigger: function ($elem,ctl) {
//alert("resolveTrigger");
var resolve = $elem.data('replace-resolve');
if ( resolve && resolve.length ) {
if ( 'undefined' === typeof URLReplace.resolver[resolve] ) {
URLReplace.resolver[resolve] = $.Deferred();
}
URLReplace.resolver[resolve].done(function () {URLReplace.trigger($elem,ctl);});
} else {
URLReplace.trigger($elem,ctl);
}
},
trigger: function ($elem,ctl) {
//alert("trigger");
var control = ctl || {};
var url = $elem.data('replace-url');
if ( !url || !url.length ) {
alert("Error: no stream-url defined");
return false;
}
var cont = $elem.data('replace-container');
if ( !cont || !cont.length ) {
alert("Error: no replace-container defined");
return false;
}
var $container = $elem.closest(cont);
var embed = $elem.data('replace-content');
if ( !embed || !embed.length ) {
alert("Error: no replace-content defined");
return false;
}
var $embed = $container.find(embed);
$container.find('.replace-notification').remove();
$elem.blur()
if ('undefined' === typeof control.url) {
control.url = url;
}
var mode = $elem.data('replace-mode');
if ( mode && mode.length ) {
control.mode = mode;
} else {
control.mode = 'append';
}
var prepare = $elem.data('replace-prepare');
if ( prepare && prepare.length && 'undefined' !== typeof URLReplace.functions[prepare] ) {
control = URLReplace.functions[prepare]($elem,$container,$embed,control);
}
var func = $elem.data('replace-function');
if ( func && func.length && 'undefined' !== typeof URLReplace.functions[func] ) {
control.embedder = URLReplace.functions[func];
}
URLReplace.embed($elem,$container,$embed,control);
},
embed: function ($elem,$container,$embed,control) {
//alert("embed: "+control.url);
var waiting = '';
var indev = 0;
if ( indev ) {
niceurl = control.url
niceurl = subURLArg(niceurl,'embed','off');
$('
Embed URL debug, turn off before prod release: ' + niceurl + '