var Altius = function() {
var token;
var postForm;
var initOnce=function() {
var postLink = function(link) {
var form = $('
', {action:$(link).attr('href'), method:'post'}).appendTo('body');
var m = $("meta[name=_token]");
$(document.createElement('input')).attr('type', 'hidden').attr('name', '_token').attr('value', m.attr('content')).appendTo(form);
form.submit();
Metronic.blockUI({
boxed: true
});
};
var sheet = document.createElement('style');
document.body.appendChild(sheet);
sheet=sheet.sheet;
$('.search-btn:not(.show-search-icon)').click(function () {
$('#search_input').focus().select();
});
$(document).on('click','a[data-postajax]',function(e) {
e.preventDefault();
var a = $(e.currentTarget);
var submit = function(t) {
t.trigger('ajax:before');
$.ajax( {
url: t.attr('href'),
type: 'POST',
dataType: 'json',
success: function(data,text) {
t.trigger('ajax:success',data);
Altius.executeFormActions(data);
}
});
};
var message = a.attr('data-postajax');
if(message.length) {
a.trigger('ajax:confirm');
bootbox.confirm(message,function(r) {
if(r)
submit(a);
else
a.trigger('ajax:cancel');
});
} else
submit(a);
});
$('a[data-postajax]').css('pointer-events','auto');
/* This is way better than having to scan all the data-posts. */
$(document).on('click','a[data-post]',function(e) {
e.preventDefault();
var message = $(this).data('post');
var context=this;
if(message.length) {
bootbox.confirm(message,function(res) {
if(res)
postLink(context);
});
} else {
postLink(context);
}
});
sheet.insertRule("a[data-post] { pointer-events: auto; }", 0);
};
var initElement = function(el) {
el = el || $(document);
// console.log('doinit',el);
initForms(el);
initDisplayName(el);
initLinks(el);
initAcl(el);
initTabs(el);
initDates(el);
// initHelp(el);
};
var initDates=function(el) {
el.find('[data-datetimelocal]').each(function(e) {
var el = $(this);
var datetimelocal = el.attr('data-datetimelocal');
var timezone = el.attr('data-timezone');
var format = 'D MMM YYYY HH:mm';
var event = moment.tz(datetimelocal, timezone);
var browser;
var browserTZ= (typeof Intl !== 'undefined') ? Intl.DateTimeFormat().resolvedOptions().timeZone : null;
if(browserTZ) {
browser = event.clone().tz(browserTZ);
} else {
browser = event.clone().tz('UTC').subtract((new Date()).getTimezoneOffset(),'m');
}
el.html( '' + event.format(format) + '
' +
'' + browser.format(format) + '
' +
'' + event.fromNow()
).attr('title',event.fromNow());
});
};
var initHelp=function(el) {
if(window.SnappyWidget === undefined) {
return;
}
el.find('[data-help-topic]').each(function(e) {
var topic= $(this).attr('data-help-topic')*1;
if(topic===0)
return;
var q=$('').appendTo(document.body);
q.css({
top: $(this).offset().top + 'px',
left: $(this).offset().left + $(this).width()+ 'px'
});
q.click(function(e) {
e.preventDefault();
e.stopPropagation();
SnappyWidget.open({topicId: topic});
});
return;
});
el.find('[data-help-question]').each(function(e) {
var question = $(this).attr('data-help-question')*1;
if(question===0)
return;
var q=$('').appendTo(document.body);
q.css({
top: $(this).offset().top + 'px',
left: $(this).offset().left + $(this).width()+ 'px'
});
q.click(function(e) {
e.preventDefault();
e.stopPropagation();
SnappyWidget.open({id: question});
});
});
};
var initTabs = function(el) {
el= el || document;
var pills = $(el).find('ul.nav.nav-pills');
pills.each(function(e) {
if($(this).find('li.active').length>0)
return;
var data = $(this).siblings('div.tab-content');
var tab = data.find('div.tab-pane').not('.empty').first(); // find first not empty
if(tab.length===0) // find
tab = data.find('div.tab-pane').first();
if(tab)
$(this).find('a[href="#' + tab.attr('id') + '"]').tab('show');
});
};
var focusFirst = function(el) {
el= el || document;
var first = $(el).find('.focusFirst,input[type=text],input[type=email],input[type=number],textarea,select,input[type=checkbox],input[type=password]').not('[tabindex="-1"]').not('[disabled]').filter(':visible:first');
if(document.activeElement.tagName!='BODY')
return;
if(first) {
first.focus();
first.select();
}
else {
first = $(el).find('button').not('[tabindex="-1"]').not('[disabled]').filter(':visible:first');
if(first)
first.focus();
}
};
var displayNotifications = function(n) {
toastr.options.positionClass = "toast-top-left";
$.each(n,function(i,v) {
switch(v.type) {
case 'success':
toastr.success(v.message,"Success",{timeOut: 5000, closeButton: true});
break;
case 'info':
toastr.info(v.message,"Information",{timeOut: 5000, closeButton: true});
break;
case 'warning':
toastr.warning(v.message,"Warning",{timeOut: 5000, extendedTimeOut: 30000, closeButton: true});
break;
case 'danger':
toastr.error(v.message,"Danger",{timeOut: 5000, extendedTimeOut: 30000, closeButton: true});
break;
default:
break;
}
});
};
var firstName = function(n) {
n = n.trim().split(' ');
return n[0];
};
var compoundName = function(s,capitalize) {
var words = s.trim().split(' ');
var name = [];
var compound = ['ah','al','di','da','de','del','den','della','der','di','du','el','le','la','pietro','st.','st','ter','van','vanden','vere','von','\'t'];
$.each(words,function(k,w) {
if(w.length) {
if(capitalize) {
if(w.toLowerCase() == w) { // all lowercase
name.push(w);
} else {
name.push(w.toUpperCase());
}
}
else {
name.push(w);
}
if(compound.indexOf(w.toLowerCase())==-1)
return false;
}
});
return name.join(' ');
};
var initDisplayName = function(el) {
el.find("input[name='displayname']").each(function(e) {
// https://github.com/joshfraser/PHP-Name-Parser/blob/master/parser.php
var displayCalc=function() {
return (compoundName(surnames.val(),true) + ' ' + firstName(givennames.val())).trim();
};
var tvCalc=function() {
return (firstName(givennames.val()) + ' ' + compoundName(surnames.val(),false)).trim();
};
var updateStyles=function() {
if(displayName.length)
displayName.toggleClass('defaultName',displayName.val().trim() == displayCalc(surnames.val(),givennames.val()));
if(mediaName.length)
mediaName.toggleClass('defaultName',mediaName.val().trim() == tvCalc(surnames.val(),givennames.val()));
};
var calcNames= function() {
if(displayName.hasClass('defaultName')) {
displayName.val(displayCalc(surnames.val(),givennames.val()));
}
if(mediaName.hasClass('defaultName')) {
mediaName.val(tvCalc(surnames.val(),givennames.val()));
}
};
var displayName= $(this);
var form = displayName.closest('form').first();
var surnames = form.find("input[name='surnames']").first();
var givennames = form.find("input[name='givennames']").first();
var mediaName = form.find("input[name='medianame']").first();
if(surnames.length && givennames.length) {
surnames.on('change input paste keyup',calcNames);
givennames.on('change input paste keyup',calcNames);
displayName.on('change input paste keyup',updateStyles);
mediaName.on('change input paste keyup',updateStyles);
updateStyles();
}
});
};
// forms
var executeFormActions = function(data,target) {
var ret=null;
if(target) {
if(data.errors) {
Altius.Form.addAllErrors(target,data.errors);
}
if(data.contentInner) {
target.html(data.contentInner);
Altius.initElement(target);
// target.effect('highlight');
}
}
if(data.content) {
if(target) {
ret = $(data.content);
target.replaceWith(ret);
Altius.initElement(ret.parent());
}
}
if(data.notifications)
displayNotifications(data.notifications);
if(data.redirect) {
Metronic.blockUI();
window.location.href = data.redirect;
}
return ret;
};
var createModal= function(size) {
size = size ||'md';
// modal-full
// modal-lg
// modal-md
// modal-sm
var modal = $('');
$("body").append(modal);
modal.on('shown.bs.modal', function (e) {
Mousetrap.pause();
});
modal.on('hidden.bs.modal', function (e) {
$(modal).remove();
Mousetrap.unpause();
});
modal.find('div.modal-content').html ('
Loading... ');
modal.on("ajax:success","form[data-ajax]",function(e,data) {
if(data.replace) {
modal.modal('hide');
if(modal.replace) {
var p = $(data.replace);
modal.replace.replaceWith(p);
Altius.initElement(p);
}
}
if(data.id) {
modal.modal('hide');
$('#'+ modal.target.data('select2')).select2("val",data.id,true).select2('focus').parent().find('a.select2-choice').effect('highlight',{'duration':2000});
}
if(data.refresh) {
modal.modal('hide');
Metronic.blockUI();
window.location.reload();
}
});
return modal;
};
var initForms = function(el) {
// signature
var sigContainer = el.find('.eSignature');
var sig = sigContainer.find('.jSignature').jSignature();
sig.bind('change',function(e) {
$(this).siblings('[name="signature"]').val($(this).jSignature("getData","svgbase64"));
});
sig.closest('form').find('input[type="password"]').on('keyup',function(e) {
if($(this).val().length) {
sig.jSignature('clear');
Metronic.blockUI({
target: sigContainer,
ignoreIfBlocked: true,
textOnly: true,
message:'eSignature not required with password.'
});
} else {
Metronic.unblockUI(sigContainer);
}
});
sigContainer.find('a').bind('click',function(e) {
$(this).siblings('.jSignature').jSignature('clear');
$(this).siblings('[name="signature"]').val('');
});
el.find('select[data-selectsplitter-selector]').selectsplitter();
el.find('[data-set-value]').on('click',function() {
var el=$(this);
Altius.Form.setValue(el.closest('form'),el.attr('data-target'),el.attr('data-set-value'),true);
});
el.find('.checkall').on('click',function() {
$(this).closest('form').find(':checkbox.checkalltarget').prop('checked',this.checked);
if(this.checked)
$(this).closest('form').find(':checkbox.checkalltarget').parent('span').addClass('checked');
else
$(this).closest('form').find(':checkbox.checkalltarget').parent('span').removeClass('checked');
});
el.find('.select2datalist').each(function(e) {
var attr = $(this).attr('data-list');
$(this).select2({
dropdownCssClass: "bigdrop",
openOnEnter: false,
placeholder: ' ',
allowClear: true,
createSearchChoice: function (term, data) {
var match=term;
if ($(data).filter(function () {
match=this.text.substring(0,term.length);
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: match,
text: match
};
}
},
data: JSON.parse(attr)
});
});
el.find('select.select2simple').select2({
// dropdownCssClass: "bigdrop",
placeholder: ' ',
openOnEnter: false,
allowClear: true,
// matcher: function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())>=0; } // default
matcher: function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())===0; } // start
});
el.find('select').on('keydown',function(e) {
if(e.keyCode===13) {
e.preventDefault();
e.stopPropagation();
$(this).closest("form").submit();
}
});
el.find('.select2-focusser').on('keydown', function (e) {
if(e.keyCode===13) {
e.preventDefault();
e.stopPropagation();
$(this).closest("form").submit();
}
});
var links = el.find('a[data-modalsize]');
// add modal management.
links.each(function(e) {
$(this).click(function(e) {
e.preventDefault();
var modal = createModal($(this).data('modalsize'));
if($(this).data('replace')) {
modal.replace=$(this).parent($(this).data('replace'));
}
modal.target=$(this);
modal.modal({ "keyboard": true});
modal.find('div.modal-content').load($(this).attr('href'),function() {
Altius.initElement(modal);
});
}).css('pointer-events','auto');
});
el.find('.geolocation-picker').each(function(e){
// console.log('a',$(this));
var context = $(this);
var search = $('#'+context.attr('id') + 'search');
var altitude = $('#'+context.attr('id') + 'altitude');
var timezone = $('#'+context.attr('id') + 'timezone');
search.keydown(function(e) {
if(e.keyCode==13) {
e.preventDefault();
return false;
}
});
context.locationpicker( {
location: { latitude: context.data('latitude') || 51.5073509 , longitude: context.data('longitude') || -0.1277583},
radius: context.data('radius') || 0,
zoom: context.data('zoom') || 14,
enableAutocomplete: true,
inputBinding: {
locationNameInput: search,
latitudeInput: $('#'+context.attr('id') + 'latitude'),
longitudeInput: $('#'+context.attr('id') + 'longitude'),
radiusInput: $('#'+context.attr('id') + 'radius')
},
onchanged: function(currentLocation, radius, isMarkerDropped) {
var loc = $(this).locationpicker('map').location;
if($(this).attr('data-bindaddress'))
Altius.Form.setValue(context.closest('form'),$(this).attr('data-bindaddress'),loc.formattedAddress,true);
var elevator = new google.maps.ElevationService();
var location =new google.maps.LatLng(currentLocation.latitude, currentLocation.longitude);
if(altitude.length)
elevator.getElevationForLocations( { locations: [ location] }, function(results,status) {
if(status=="OK") {
altitude.val(results[0].elevation).parent('td').effect('highlight');
} else
altitude.val('').parent('td').effect('highlight');
});
if(timezone.length)
$.get(
'/corsproxy?get=' + encodeURIComponent('https://maps.googleapis.com/maps/api/timezone/json'),
{location: currentLocation.latitude + ',' + currentLocation.longitude, timestamp: Math.round(Date.now()/1000)},function(e){
if(e.status=="OK") {
timezone.val(e.timeZoneId).attr('title',e.timeZoneName).parent('td').effect('highlight');
} else {
timezone.val('').attr('title','Not Found').parent('td').effect('highlight');
}
},'json');
}
});
});
if(jQuery().datepicker)
el.find('.date-picker').datepicker({
rtl: false,
autoclose: true,
orientation: 'left'
});
el.find('.filepicker').filepicker( {
});
if(jQuery().timepicker) {
el.find('.timepicker').timepicker({
minuteStep: 5,
template: false,
showSeconds: false,
showMeridian: false,
defaultTime:false
});
}
focusFirst(el);
el.find('button[data-confirm]').each(function(e) {
var button = $(this);
button.click(function(e,from) {
if(from==null) {
e.preventDefault();
bootbox.confirm(button.attr('data-confirm'),function(res) {
if(res)
button.trigger('click',333);
});
}
});
});
el.find('form[data-confirm]').each(function(e) {
var form = $(this);
form.find('button').click(function(e) {
e.preventDefault();
bootbox.confirm(form.attr('data-confirm'),function(res) {
if(res)
form.submit();
});
});
});
el.find('form[data-ajax]').each(function(e) {
var form = $(this);
form.find('button[data-submit]').click(function(e) {
form.find('input[name="_submit"]').attr('value',$(this).attr('data-submit'));
});
$(this).submit(function(e){
e.preventDefault();
var data= form.serializeArray();
var url = form.attr("action");
Metronic.blockUI({ target: form });
$.ajax(
{
url : url,
type: "POST",
data : data,
dataType: 'json',
success:function(data, textStatus, jqXHR)
{
Metronic.unblockUI(form);
form.trigger("ajax:success",data);
Altius.executeFormActions(data,form);
Altius.focusFirst(form);
},
error: function(request, textStatus, errorThrown)
{
var json = request.responseJSON;
Metronic.unblockUI(form);
switch(request.status) {
case 403:
toastr.error(json.message || 'You are not authorized to complete this action.',"Error",{timeOut: 5000, extendedTimeOut: 30000, closeButton: true, positionClass: "toast-top-left"});
break;
case 404:
toastr.error(json.message || 'We cannot find this page.',"Error",{timeOut: 5000, extendedTimeOut: 30000, closeButton: true, positionClass: "toast-top-left"});
break;
case 422:
Altius.Form.addAllErrors(form,json);
Altius.Form.focusFirst(form);
break;
default:
toastr.error('We have encountered an unexpected error:
' + json.message + '',"Error",{timeOut: 5000, extendedTimeOut: 30000, closeButton: true, positionClass: "toast-top-left"});
break;
}
}
});
});
});
};
var initLinks = function(el) {
var postLink = function(link) {
var form = $('', {action:$(link).attr('href'), method:'post'}).appendTo('body');
var m = $("meta[name=_token]");
$(document.createElement('input')).attr('type', 'hidden').attr('name', '_token').attr('value', m.attr('content')).appendTo(form);
form.submit();
Metronic.blockUI({
boxed: true
});
};
el.find('.popovers').popover();
el.find('a[data-postajax]').css('pointer-events','auto');
// sends get as an ajax request. No follow up
el.find('[data-ajax]').css('pointer-events','auto');
$('body').on('click','a[data-ajax]',function(e){
var a = $(this);
e.preventDefault();
a.addClass('ajaxsubmitting ');
a.append(' ');
$.ajax({
type: "GET",
url: a.attr('href'),
success: function(data,status) {
a.removeClass('ajaxsubmitting ');
a.find('i.fa-spinner.fa-spin').remove();
a.trigger("ajax:success",data);
Altius.executeFormActions(data,$(a.attr('data-target')));
}
}).fail(function( msg ) {
console.log(msg,a);
});
});
};
var initAcl = function(el) {
el.find('[data-acl-hidden]').css('display','none').removeAttr("href");
el.find('[data-acl-visible]').each(function(e) {
$(this).data('placement','top')
.data('trigger','hover')
.data('container','body')
.data('content',$(this).data('content-acl'))
.data('html',true);
$(this).popover();
});
el.find('[data-acl-disabled]').each(function(e) {
// for all elements we
// Add class disabled
// Add attribute disabled
// Wrap with
// options
//
// the stuff below tested for a tags
$(this).addClass('disabled');
$(this).attr('disabled',1);
$(this).data('placement','top')
.data('trigger','hover')
.data('container','body')
.data('content',$(this).data('content-acl'))
.data('html',true);
$(this).css('pointer-events','all');
$(this).popover();
// for a records
if($(this).prop('tagName').toLowerCase() == 'a') {
$(this).removeAttr("href");
// disable li elements that are parents.
$(this).parent('li').addClass('disabled').attr('disabled',1);
// $(this).prepend(' ');//
}
});
};
var playAudio=function(x) {
var sound=document.getElementById('sound_' +x);
if(sound===null) {
sound=document.createElement("audio");
document.body.appendChild(sound);
sound.setAttribute('id','sound_' +x);
sound.setAttribute('src',"/sounds/" + x + ".wav");
}
sound.currentTime=0;
sound.play();
};
return {
//main function to initiate the application
init: function () {
initElement(); // implies document
initOnce();
Altius.Hockey.init();
// Altius.Inline.init();
// initAddModal();
// initEditModal();
},
playAudio: playAudio,
createModal: createModal,
initHelp: initHelp,
initElement: initElement,
focusFirst: focusFirst,
executeFormActions: executeFormActions,
token: $("meta[name=_token]").attr('content')
};
}();
snappyReady = function () {
Altius.initHelp($(document));
// alert('sna;');
};
RealTime = ( function() {
var trackRecord = function(table,id,params) {
params = params||{};
var track={
record:null
};
fetchRecord(table,id,params,track,'record');
return track;
};
var fetchRecord=function(table,id,params,object,attribute) {
// there are really three choices here
// There is no data: fetch from API and parse
// Object is an array: Fetch from array, push and parse
// There is data and no embeds. Stop here!
//
$.get('/rt/' + table + '/'+ id,params,function(data) {
if(attribute===null) { // this is an array
attribute = object.push(data)-1;
} else {
object[attribute]=data;
}
parseRecordEmbeds(object,attribute,params.embeds);
});
};
var parseArrayEmbeds=function(parent, attribute, embeds) {
// console.log('parseArrayEmbeds',parent, attribute,embeds);
bindArray(parent,attribute,embeds);
$.each(parent[attribute],function(i) {
parseRecordEmbeds(parent[attribute],i,embeds);
});
}
var parseRecordEmbeds=function(object,attribute,embeds) {
var record=object[attribute];
bindRecord(object,attribute);
if(embeds.length===0)
return;
object[attribute]._embeds=embeds
var em = embedsToObject(embeds);
for(var attrib in em) {
if($.isArray(record[attrib])) {
parseArrayEmbeds(record,attrib,em[attrib]);
}
else
if(typeof(record[attrib])==='object') {
parseRecordEmbeds(record,attrib,em[attrib]);
}
}
}
var markBind=function(obj,bind) {
if(! obj._bind)
obj._bind=bind;
else
obj._bind +=', ' +bind;
}
// Record Management
var unbindArray=function(arr) {
alert('unbind array');
};
var unbindObject=function(object) {
if(!object)
return;
$.each(object,function(i,el) {
if(typeof(el)==='object') {
unbindObject(el);
}
});
if(object._bindings) {
var channel= pusherSubscribe(object._bindings.channel);
$.each(object._bindings,function(i,func) {
if(i!='channel')
channel.unbind(i,func);
});
}
}
var bindRecord=function(object,attribute) {
var channel =object[attribute].type+ '-' + object[attribute].id;
object[attribute]._bindings ={ channel : channel};
channel = pusherSubscribe( channel);
var updated = function(data) {
recordSync(object,attribute,data.record);
};
var deleted = function(data) {
if($.isArray(object)) {
arrayRemoveRecord(object,data.record);
} else {
unbindObject(object[attribute]);
object[attribute]=null;
}
};
channel.bind('updated',updated);
channel.bind('deleted',deleted);
object[attribute]._bindings.updated=updated;
object[attribute]._bindings.deleted=deleted;
}
var bindArray=function(parent,attribute,embeds) {
var channel = parent.type + '-' + parent.id + '-' + attribute;
parent[attribute]._bindings={channel:channel};
channel = pusherSubscribe(channel);
var created = function(data) {
if(embeds.length) {
fetchRecord(data.record.type, data.record.id,{embeds:embeds}, parent[attribute],null);
return;
} else {
var id = parent[attribute].push(data.record);
bindRecord(parent[attribute],id-1);
}
};
channel.bind('created',created);
parent[attribute]._bindings.created=created;
};
var recordSync=function(object,attribute,source) {
var dest=object[attribute];
if(dest._embeds) {
var em = embedsToObject(dest._embeds);
console.log(em);
for(var name in em) {
var id = name+'_id';
console.log(name,id);
if(dest[id] || source[id]) {
if(source[id]===null) {
unbindObject(dest[name]);
delete dest[name];
}
if(source[id] !==dest[id]) {
unbindObject(dest[name]);
fetchRecord(dest.type,dest.id,{embeds:dest._embeds},object,attribute);
return;
}
}
}
}
$.each(source,function(i) {
dest[i]=source[i];
});
}
var arrayRemoveRecord=function(arr,record) {
$.each(arr,function(i) {
if(arr[i].id===record.id) {
unbindObject(arr[i]);
arr.splice(i,1);
return false;
}
});
}
var embedsToObject=function(embeds) {
if(embeds.length===0)
return {};
var list = embeds.split(',');
var ret = {};
for(var i in list) {
var els = list[i].split('.');
var first = els.shift();
if(ret[first]) {
ret[first]+= ',' +els.join('.');
}
else {
ret[first]= els.join('.');
}
}
console.log('embedsToObject',embeds,ret);
return ret;
};
var pusherSubscriptions={};
var pusherSubscribe = function(channel) {
if(! pusherSubscriptions[channel]) {
pusherSubscriptions[channel] = pusher.subscribe(pusher.prefix + channel);
}
return pusherSubscriptions[channel];
}
return {
trackRecord: trackRecord
}
}) ();
$.widget('custom.filepicker', {
_create: function() {
var c=this;
this.element.wrap('');
this.element.after('');
this.element.parent().find('a').click(function(e) {
c._open();
});
},
_open: function() {
// create modal if it doesn't exist
// set the value within the modal
// display the modal!
this._openModal(this.element.val());
},
_modal:null,
_fm: null,
_openModal: function(val) {
if(this._modal) {
this._fm.filemanager('val',val);
this._modal.modal({ "keyboard": true});
return;
}
var c=this;
var footer = '';
this._modal=$( '').appendTo(document.body);
this._fm=
this._modal.find('#filemanager').filemanager({
selectionChange: function(e,data) {
c._updateUI(data);
}
});
this.select = this._modal.find('button[data-select]');
this.select.on('click',function() {
c.element.val(c._selection.files[0]);
});
this._fm.filemanager('val',val);
this._modal.modal({ "keyboard": true});
},
_selection:{},
_updateUI: function(data) {
this._selection=data;
this.select.toggleClass( 'disabled',((data.folders.length>0) || (data.files.length!=1)));
}
});
$.widget( "custom.filemanager", {
_path: '',
_sort: '',
_dir: '',
_https: '',
_image: null,
_create: function() {
this.element.css('min-height','300px');
this._image= new Image();
this._setupEvents();
if(this.options.value)
this._action('open',this.options.value);
else
this._action('open','');
// console.log(this.options);
},
val: function(data) {
this.element.html('');
this._action('open',data);
// alert('c');
// console.log('val',data);
},
getSelection: function() {
var rows = this.element.find('table tr.info');
var ret={
folders : [],
files : []
};
var c=this;
rows.each(function(i,v){
if($(v).attr('data-type')=='dir')
ret.folders.push(c._path + '/' + $(v).attr('data-basename'));
else
ret.files.push(c._path + '/' + $(v).attr('data-basename'));
});
return ret;
},
_setupEvents : function() {
var c= this;
this._image.onload=function() {
c.element.find('#filemanage_image_dims').html( c._image.width + ' x ' + c._image.height);
};
this.element.on('click','a[data-open]',function(e) {
e.preventDefault();
var a = $(e.currentTarget);
Metronic.blockUI({ target: c.element });
c._action('open',a.attr('data-open'));
});
this.element.on('click','a[data-view]',function(e) {
e.preventDefault();
e.stopPropagation();
c._view($(e.currentTarget));
});
this.element.on('click','table.table-select tr',function(e) {
$(e.currentTarget).toggleClass('info');
c._updateButtons();
});
this.element.on('click','#filemanage-foldernew',function(e) {
e.preventDefault();
c._createNewFolder();
});
this.element.on('click','#filemanage-rename',function(e) {
e.preventDefault();
c._rename();
});
this.element.on('click','#filemanage-delete',function(e) {
e.preventDefault();
c._delete();
});
},
_updateButtons: function() {
var count = this.element.find('table tr.info').length;
this.element.find('#filemanage-rename').toggleClass('disabled',count!=1);
this.element.find('#filemanage-delete').toggleClass('disabled',count<1);
this._trigger('selectionChange',null,this.getSelection());
},
_view: function(a) {
// open preview tab
a.closest('tr').addClass('info').siblings().removeClass('info');
this._updateButtons();
var full = this._https + a.attr('data-view');
this.element.find('#filemanage_image_dims').html('');
this.element.find('#filemanage_filename').html(full);
this.element.find('#filemanage_image').attr('src',full);
this.element.find('#filemanage_open').attr('href',full);
this.element.find('#filemanage_download').attr('href',full);
this.element.find('a[href=#preview]').tab('show');
this._image.src=full;
},
_delete: function(a) {
var rows = this.element.find('table tr.info');
var names=[];
rows.each(function(i,v) {
names.push($(v).attr('data-basename'));
});
var c=this;
bootbox.confirm( "Delete the following items?
', function(res) {
if(res) {
c._action('delete',names);
}
// row.removeClass('danger');
});
},
_rename: function(a) {
var row = this.element.find('table tr.info').first();
// row.addClass('warning');
var c=this;
bootbox.prompt( {
title: "Rename",
value: row.attr('data-basename'),
callback: function(r) {
if(r!==null) {
c._action('rename',{ existing: row.attr('data-basename'), rename: r});
} else
row.removeClass('warning');
}
});
setTimeout( function() {
$('form.bootbox-form input.bootbox-input').select();
},200);
},
_createNewFolder:function() {
var c=this;
bootbox.prompt( {
title: "Create a new folder",
value: "New Folder",
callback: function(r) {
if(r!==null) {
c._action('newfolder',r);
}
}
});
setTimeout( function() {
$('form.bootbox-form input.bootbox-input').select();
},200);
},
_action: function(action,value) {
var c=this;
$.ajax('/admin/files/action', {
method: "POST",
data: {
action: action,
value: value,
path: c._path,
sort: c._sort,
dir : c._dir ,
_token: Altius.token
},
success: function(data) {
Altius.executeFormActions(data,c.element);
if(data.contentInner) {
$("#mydropzone").dropzone({ maxFilesize: 1 });
c._path=c.element.find('div.tab-content').attr('data-path');
c._sort=c.element.find('div.tab-content').attr('data-sort');
c._dir =c.element.find('div.tab-content').attr('data-dir');
c._https =c.element.find('div.tab-content').attr('data-https');
if(c.options.selectFile>0)
c.element.find('div.modal-footer').show();
else
c.element.find('div.modal-footer').hide();
c._updateButtons();
Metronic.unblockUI();
}
}
});
}
});
Altius.Form = function() {
var focusFirst = function(el) {
el= el || document;
var first = $(el).find('.focusFirst,input[type=text],input[type=email],input[type=number],textarea,select,input[type=checkbox],input[type=password]').not('[tabindex="-1"]').not('[disabled]').filter(':visible:first');
if(document.activeElement.tagName!='BODY')
return;
if(first) {
first.focus();
first.select();
}
};
var setupForm = function(form) {
form.find('[name]').on('change',function(e){
clearError(form,$(this).attr('name'));
});
};
var addFormError = function(form,message) {
form.find('div.alert-danger').html(message).slideDown();
};
var addError= function(form,field,message) {
var fieldObj=form.find('[name="' + field + '"]');
fieldObj.closest('.form-group').addClass('has-error').find('.help-block').html(message);
};
var clearError = function(form,field) {
var fieldObj=form.find('[name="' + field + '"]');
fieldObj.closest('.form-group').removeClass('has-error').find('.help-block').html('');
};
var addAllErrors = function(form,json) {
clearAllErrors(form);
if(json.message)
addFormError(form,json.message);
if(json.errors) {
$.each(json.errors,function(name,msg) {
addError(form,name,msg.join('
'));
});
} else { // legacy way
$.each(json,function(name,msg) {
if(name=='_form') {
addFormError(form,msg.join('
'));
}
else {
addError(form,name,msg.join('
'));
}
});
}
};
var clearAllErrors = function(form) {
form.find('div.alert-danger').hide();
form.find('.form-group').removeClass('has-error');
form.find('.help-block').html('');
};
var setValue = function(form,field,value,highlight) {
var fieldObj=form.find('[name="' + field + '"]:not(.noset)');
// console.log('set',field,fieldObj,value);
if(fieldObj.hasClass('form-control-static')) {
fieldObj.html(value);
}
else
if(fieldObj.hasClass('select2-offscreen')) {
fieldObj.select2("val",value,true);
if(highlight)
fieldObj.select2('container').find('a.select2-choice').effect('highlight',{ 'duration' : 2000});
} else {
if(fieldObj.attr('type')=='checkbox') {
if(value)
fieldObj.parent().addClass('checked');
else
fieldObj.parent().removeClass('checked');
fieldObj.prop('checked',value);
if(highlight)
fieldObj.closest('.input-group').effect('highlight',{ 'duration' : 2000});
}
else {
fieldObj.val(value);
if(highlight)
fieldObj.effect('highlight',{ 'duration' : 2000});
}
}
};
var setAllValues = function(form,values) {
$.each(values,function(name,value) {
setValue(form,name,value);
});
};
return {
//main function to initiate the application
setupForm: setupForm,
addError: addError,
clearError: clearError,
clearAllErrors: clearAllErrors,
addAllErrors: addAllErrors,
addFormError: addFormError,
setValue: setValue,
setAllValues: setAllValues,
focusFirst: focusFirst
};
}();
$.widget( "custom.clock", {
_data: {}, // from server.
_elapsed:0,
_plus: 0,
_peerConn: null,
_pusherChannel:null,
_ablyChannel: null,
_create: function() {
Altius.serverTime(1);
this._data = JSON.parse(this.element.attr('data-clock'));
/*
var peer = new Peer({key: 'werd3q88ltk2o6r'});
this._peerConn = peer.connect("match-" + this._data.id + "-scoreboard");
console.log('peercon',this._peerConn);
*/
// this._ablyChannel = ably.channels.get( pusher.prefix + 'matches-' + this._data.id);
this._pusherChannel = pusher.subscribe('private-' + pusher.prefix + 'matches-' + this._data.id);
this._plus=this._calcElapsed();
if(this.element.attr('data-start')) {
if(this._data.started)
$('#audioStart')[0].play();
else
$('#audioStop')[0].play();
}
/*
if(this._data.started)
$('#audioStart')[0].play();
else
$('#audioStop')[0].play();
*/
this._setupEvents();
this._paintOnce();
},
_setupEvents: function() {
var c=this;
setInterval(function() {
c._paintRepeat();
},100);
c.element.find('button.countdown').on('click',function() {
c._edit();
});
c.element.find('button.action').on('click',function(e) {
e.preventDefault();
e.stopPropagation();
c._clockChange();
});
c.element.find('#match_period ul a').click(function(e) {
e.preventDefault();
var period = $(e.target).attr('data-period');
c._sendClockAction('period', Altius.serverTime(),period);
});
c.element.find('button.countdown40').on('click',function() {
c._sendClockAction('countdown',Altius.serverTime());
});
c.element.find('button.shootout').on('click',function() {
c._sendClockAction('shootoutStart',Altius.serverTime());
});
},
_edit:function() {
var c = this;
bootbox.prompt( {
title: "Enter a new time",
value: this._formatTime(this._data.finish*60-this._elapsed,true),
callback: function(r) {
if(r!==null) {
var seconds = Math.floor(r/100)*60 + r % 100;
c._sendClockAction('edit', Altius.serverTime(),seconds);
}
}
});
$('div.bootbox-prompt input.bootbox-input').select();
},
getSeconds: function() {
return this._elapsed;
},
getMinute:function() {
return Math.ceil(this._elapsed/60);
},
getMinuteText:function(){
return Math.ceil(this._elapsed/60) +
( (this._plus && (this._data.start != this._data.finish)) ? '+':'' );
},
toggle: function() {
this._clockChange();
// console.log('space');
},
_clockChange:function() {
if(this._plus) {
this._sendClockAction('next');
if(this._data.nextminutes>0)
$('#audioStart')[0].play();
}
else if(this._data.started)
this._clockStop();
else
this._clockStart();
},
_clockStop:function() {
if(this._started===0)
return;
var ts = Altius.serverTime();
this._data.elapsed = this._data.elapsed + ts - this._data.started;
this._data.started = 0;
this._paintOnce();
this._sendClockAction('stop',ts);
$('#audioStop')[0].play();
},
_clockStart:function() {
if(this._data.started>0)
return;
var ts = Altius.serverTime();
this._data.started = ts;
this._paintOnce();
this._sendClockAction('start',ts);
$('#audioStart')[0].play();
},
_clockPlus: function() {
this._plus=true;
this._paintOnce();
if(this._data.finish > this._data.start)
$('#audioEnd')[0].play();
},
_sendClockAction: function(action,ts,value) {
this._calcElapsed();
var data = { timestamp: ts, elapsed: this._elapsed, started: this._data.started };
/*
if(this._peerConn)
this._peerConn.send(data);
*/
if(this._pusherChannel.subscribed) {
if(( action=='start') || (action=='stop') ) {
data.source='pusher';
this._pusherChannel.trigger('client-clockAction', { action: action, data : data});
}
if (action=='shootoutStart') {
this._pusherChannel.trigger('client-clockAction', { action: action, data : data});
return;
}
}
/* skip ably for now
if(this._ablyChannel) {
if(( action=='start') || (action=='stop') ) {
data.source='ably';
this._ablyChannel.publish('client-clockAction',{ action: action, data : data});
console.log('ably publish',data);
}
}
*/
var c=this;
$.post('/admin/matchmanage/' + this._data.id + '/clock',
{
action: action,
value:value,
timestamp: ts || Altius.serverTime(),
_token: Altius.token
},
function(data, textStatus) {
c._setClockJson(data);
},'json'
);
},
_setClockJson: function (data) {
this._plus=false;
this._data=data;
this._paintOnce();
},
_calcElapsed: function() {
if(this._data.started) {
this._elapsed = this._data.elapsed + Altius.serverTime() - this._data.started;
} else {
this._elapsed = this._data.elapsed;
}
this._elapsed = Math.max(this._elapsed, this._data.start*60);
this._elapsed = Math.min(this._elapsed, this._data.finish*60);
return (this._elapsed == this._data.finish*60);
// return the plus value
},
//always countdown
_formatTime: function(seconds,clean) {
if(clean) {
seconds = Math.ceil(seconds);
return Math.floor(seconds/60).toFixed(0) + ((seconds%60 < 10) ? '0' : '') + seconds%60;
}
if(seconds < 59.9) { // Ceiling to nearest 10th second and then return with 1 decimal
seconds = Math.ceil(seconds*10)/10;
return seconds.toFixed(1);
}
// Ceiling to nearest second.
seconds = Math.ceil(seconds);
return Math.floor(seconds/60) + ':' + (( seconds%60 < 10)? '0':'') + seconds%60 ;
},
_paintOnce: function() {
this._paintRepeat();
this.element.find('button.countdown').addClass( (this._data.started && !this._plus) ?'green':'red').removeClass((this._data.started && !this._plus)?'red':'green');
this.element.find('button.period').html(this._data.period);
this.element.find('div#match_period ul li a i').removeClass('fa-check');
this.element.find('div#match_period ul li a[data-period="' + this._data.period+'"] i').addClass('fa-check');
this.element.find('div.final').hide();
this.element.find('button.action').attr('disabled',false);
if(this._elapsed == this._data.finish*60) {
if(this._data.nextminutes>0)
this.element.find('button.action').html('Start: ' + this._data.next);
else {
if(this._data.next===null) {
this.element.find('button.action').html('Next').attr('disabled',true);
this.element.find('div.final').show();
}
else {
this.element.find('button.action').html('Next: ' + this._data.next);
}
}
}
else if(this._data.started)
this.element.find('button.action').html('Stop');
else
this.element.find('button.action').html('Start');
},
_paintRepeat: function() {
if(this._calcElapsed() && ! this._plus) {
this._clockPlus();
}
if(this._data.start == this._data.finish) {
this.element.find('button.countdown').html(this._formatTime(this._data.nextminutes*60));
} else {
this.element.find('button.countdown').html(this._formatTime(this._data.finish*60-this._elapsed));
}
// 40 s clock
var top = 40;
var countdown = Math.min(top,Math.ceil(top + this._data.countdown - Altius.serverTime())); // calculate countdown.
if(countdown<-1) // display for 2 extra seconds
countdown=top;
countdown=Math.max(countdown,0); // display 0 for negatives
this.element.find('button.countdown40').html(countdown);
this.element.find('button.minute').html(this.getMinuteText());
}
});
Altius.Hockey = function() {
var container;
var baseUrl;
var modals={};
var clock=false;
var initClock = function(div) {
if(div.length)
clock = div.clock();
console.log('clock',clock);
};
var initMatchManage = function() {
container = $('#match_manage2').first();
if(container.length===0) {
return;
}
bootbox.setDefaults({animate:false});
initClock(container.find('#match_clock'));
modals.sub = $('#match_sub_modal');
modals.goal = $('#match_goal_modal');
modals.card = $('#match_card_modal');
modals.gksub = $('#match_gksub_modal');
modals.timeout = $('#match_timeout_modal');
modals.shootout = $('#match_shootout_modal');
modals.extra = $('#match_extra_modal');
modals.notes = $('#match_notes_modal');
Altius.Form.setupForm(modals.sub);
Altius.Form.setupForm(modals.goal);
Altius.Form.setupForm(modals.card);
Altius.Form.setupForm(modals.gksub);
Altius.Form.setupForm(modals.timeout);
Altius.Form.setupForm(modals.shootout);
Altius.Form.setupForm(modals.notes);
modals.goal.on('hidden.bs.modal',function(e) {
$('#match_goals_table').find('tr').removeClass('warning');
});
modals.card.on('hidden.bs.modal',function(e) {
$('#match_cards_table').find('tr').removeClass('warning');
});
modals.shootout.on('hidden.bs.modal',function(e) {
$('#match_shootouts_table').find('tr').removeClass('warning');
});
$('div.modal').on('shown.bs.modal', function (e) {
Mousetrap.pause();
});
$('div.modal').on('hidden.bs.modal', function (e) {
Mousetrap.unpause();
});
var s = modals.card.find('select[name="type"]');
var d = modals.card.find('input[name="duration"]');
var p = modals.card.find('input[name="penaltypoints"]');
var sel =s.attr('data-mode')=='select';
var min =s.attr('data-mode')=='minute';
if(min) {
d.on('change',function(e){
p.val(d.val());
});
}
s.on('change',function(e) {
d.prop('min',null).prop('max',null).prop('readonly',true).prop('placeholder','Duration');
p.prop('min',null).prop('max',null).prop('readonly',true).prop('placeholder',min? 'Auto Points':'No Points');
switch(s.select2('val')) {
case 'G':
d.val(d.attr('data-G'));
if(sel)
p.val(p.attr('data-G'));
if(min)
p.val(d.val());
break;
case 'Y':
d.prop('min',d.attr('data-Y'))
.prop('max',d.attr('data-Y')*4)
.prop('readonly',false)
.val(d.attr('data-Y'));
if(sel)
p.prop('min',p.attr('data-Y-min'))
.prop('max',p.attr('data-Y-max'))
.prop('readonly',false)
.val(p.attr('data-Y-min'));
if(min)
p.val(d.val());
break;
case 'R':
d.val(null)
.prop('placeholder','Full Match');
if(sel)
p.val(p.attr('data-R'));
if(min)
p.val(p.attr('data-R'));
break;
default:
d.val(null);
p.val(null);
}
});
// data-toggle="dropdown"
// container.find('tr[data-playermenu] i').attr('data-toggle','dropdown').attr('data-target','#hockey_player_menu').addClass('dropdown');
$(document).click(function () {
$('#hockey_player_menu').hide();
});
container.find('tr[data-playermenu] ').on('click',function(e) {
e.preventDefault();
e.stopPropagation();
var tr = $(this);
$('#hockey_player_menu').show()
.css({
position: "absolute",
left: e.clientX + $(window)['scrollLeft'](),
top: e.clientY + $(window)['scrollTop']()
}
)
.off('click')
.on('click',function(e) {
$(this).hide();
var a = $(e.target);
// var playerMenu = function(table,type,team,player) {
playerMenu(a.attr('data-table'),a.attr('data-type'),tr.attr('data-team'),tr.attr('data-player'));
console.log('Event',tr.attr('data-team'),tr.attr('data-player'));
console.log('Event',a.attr('data-table'),a.attr('data-type'));
});
});
if(container) {
baseUrl='/admin/matchmanage/' + container.attr('data-match');
initKeystrokes();
// generic delete.
container.on('ajax:confirm','table a',function(e) {
var a = $(e.currentTarget);
a.closest('tr').addClass('danger');
});
container.on('ajax:cancel','table a',function(e) {
var a = $(e.currentTarget);
a.closest('tr').removeClass('danger');
});
container.on('ajax:success','table a',function(e,data) {
var a = $(e.currentTarget);
if(data.deleted) {
a.closest('table').find('tr[data-id="' + data.deleted + '"]').hide('fade');
}
if(data.scoreline)
updateScoreline(data.scoreline);
});
container.on('click','input.reserve',reserveClick);
// substitution!
container.on('click','a.substitute',subClick);
container.find('#match_sub_modal').find('form').on('ajax:success',subFormSuccess);
// goals
container.on('click','#match_goal_add',goalAdd);
container.on('click','a.match_goal_edit',goalEdit);
container.find('#match_goal_modal').find('form').on('ajax:success',goalFormSuccess);
// cards
container.on('click','#match_card_add',cardAdd);
container.on('click','a.match_card_edit',cardEdit);
container.find('#match_card_modal').find('form').on('ajax:success',cardFormSuccess);
container.on('click','#match_shootout_add',shootoutAdd);
container.on('click','a.match_shootout_edit',shootoutEdit);
container.find('#match_shootout_modal').find('form').on('ajax:success',shootoutFormSuccess);
// extra
container.on('click','#match_extra_add',extraAdd);
container.on('click','a.match_extra_edit',extraEdit);
container.find('#match_extra_modal').find('form').on('ajax:success',extraFormSuccess);
// notes
container.on('click','.match_notes_edit',notesEdit);
container.find('#match_notes_modal').find('form').on('ajax:success',notesFormSuccess);
container.on('click','.match_reasons_edit',reasonsEdit);
// change team.
container.find('select.select2simple[name="team_id"]').on('change',teamChange);
}
};
var reasonsEdit=function () {
var modal = Altius.createModal();
modal.modal({ "keyboard": true});
modal.find('div.modal-content').load(baseUrl + '/reasons',function() {
Altius.initElement(modal);
});
};
var updateScoreline=function(scoreline) {
$('h3.panel-title.scoreline').html(scoreline).parent().effect('highlight');
};
var notesEdit = function() {
Altius.Form.clearAllErrors(modals.notes);
// clear values
Altius.Form.setAllValues( modals.notes,{
notes: container.find('#match_notes').text()
});
modals.notes.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.notes);
};
var notesFormSuccess=function(e,data) {
if(data.success) {
modals.notes.modal('hide');
container.find('#match_notes').html(data.notes);
}
};
var cardsNarrative = function() {
alert('cards Narrative');
};
var setTeam = function(form,team) {
if(team===null)
team='blank';
form.find('.player_list.form-control').not('.team_' + team).attr('disabled',true).hide();
form.find('.player_list.form-control.team_' + team).attr('disabled',false).select2('val',0).show();
};
var teamChange=function(e) {
var s = $(this);
setTeam(s.closest('form'),s.select2("val"));
};
var playerMenu = function(table,type,team,player) {
if(table=='Goal') {
setTeam(modals.goal,team);
Altius.Form.setAllValues( modals.goal,{
id: null,
minute: clock? clock.clock('getMinuteText') : null,
team_id: team,
player_id: player,
type: type
});
modals.goal.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.goal);
return;
}
if(table=='Card') {
setTeam(modals.card,team);
Altius.Form.setAllValues( modals.card,{
id: null,
minute: clock? clock.clock('getMinuteText') : null,
team_id: team,
player_id: player,
penaltypoints: null, // Set penalty points before setting type
duration: null, // Set duration before setting type
type: type,
official_id: null,
narrative: null
});
modals.card.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.card);
return;
}
};
var goalAdd = function() {
Altius.Form.clearAllErrors(modals.goal);
// clear values
Altius.Form.setAllValues( modals.goal,{
id: null,
minute: clock? clock.clock('getMinuteText') : null,
team_id: null,
player_id: null,
type: null
});
setTeam(modals.goal,'blank');
modals.goal.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.goal);
};
var goalEdit = function(e) {
var btn = $(e.currentTarget);
btn.closest('tr').addClass('warning');
var data= JSON.parse(btn.attr('data-record'));
console.log(data);
setTeam(modals.goal,data.team_id);
Altius.Form.clearAllErrors(modals.goal);
Altius.Form.setAllValues(modals.goal, data);
modals.goal.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.goal);
};
var goalFormSuccess=function(e,data) {
if(data.success) {
modals.goal.modal('hide');
if(data.table) {
$('#match_goals_table').replaceWith(data.table);
Altius.initElement($('#match_goals_table'));
}
$('#match_goals_table').find('tr.highlight td').effect('highlight',2000);
if(data.scoreline)
updateScoreline(data.scoreline);
}
};
var cardAdd=function() {
Altius.Form.clearAllErrors(modals.card);
// clear values
Altius.Form.setAllValues( modals.card,{
id: null,
minute: clock? clock.clock('getMinuteText') : null,
team_id: null,
player_id: null,
type: null,
duration: null,
penaltypoints: null,
official_id: null,
narrative: null
});
setTeam(modals.card,'blank');
modals.card.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.card);
};
var cardEdit = function(e) {
var btn = $(e.currentTarget);
btn.closest('tr').addClass('warning');
var data= JSON.parse(btn.attr('data-record'));
setTeam(modals.card,data.team_id);
Altius.Form.clearAllErrors(modals.card);
Altius.Form.setAllValues(modals.card, data);
modals.card.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.card);
};
var cardFormSuccess=function(e,data) {
if(data.success) {
modals.card.modal('hide');
if(data.table) {
$('#match_cards_table').replaceWith(data.table);
Altius.initElement($('#match_cards_table'));
}
$('#match_cards_table').find('tr.highlight td').effect('highlight',2000);
}
};
var extraAdd=function() {
Altius.Form.clearAllErrors(modals.extra);
// clear values
Altius.Form.setAllValues( modals.extra,{
id: null,
minute: clock? clock.clock('getMinuteText') : null,
team_id: null,
type: null
});
modals.extra.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.extra);
};
var extraEdit = function(e) {
var btn = $(e.currentTarget);
btn.closest('tr').addClass('warning');
var data= JSON.parse(btn.attr('data-record'));
Altius.Form.clearAllErrors(modals.extra);
Altius.Form.setAllValues(modals.extra,data);
modals.extra.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.extra);
};
var extraFormSuccess=function(e,data) {
if(data.success) {
modals.extra.modal('hide');
if(data.table) {
$('#match_extras_table').replaceWith(data.table);
Altius.initElement($('#match_extras_table'));
}
$('#match_extras_table').find('tr.highlight td').effect('highlight',2000);
}
};
var shootoutAdd=function() {
Altius.Form.clearAllErrors(modals.shootout);
// clear values
var next = $('#match_shootouts_table').attr('data-shootout-info');
next = JSON.parse(next);
setTeam(modals.shootout,next.team);
Altius.Form.setAllValues( modals.shootout,{
id: null,
team_id: next.team,
attacker_id: null,
defender_id: next['def_' + next.team],
result: null
});
modals.shootout.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.shootout);
};
var shootoutEdit = function(e) {
var btn = $(e.currentTarget);
btn.closest('tr').addClass('warning');
var data= JSON.parse(btn.attr('data-record'));
setTeam(modals.shootout,data.team_id);
Altius.Form.clearAllErrors(modals.shootout);
Altius.Form.setAllValues(modals.shootout, data);
modals.shootout.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.shootout);
};
var shootoutFormSuccess=function(e,data) {
if(data.success) {
modals.shootout.modal('hide');
if(data.table) {
$('#match_shootouts_table').replaceWith(data.table);
Altius.initElement($('#match_shootouts_table'));
}
$('#match_shootouts_table').find('tr.highlight td').effect('highlight',2000);
if(data.scoreline)
updateScoreline(data.scoreline);
}
};
var subEdit = function(e) {
bootbox.alert('subedit');
};
var initKeystrokes=function() {
Mousetrap.bind('g', function(e) {
e.preventDefault();
container.find('a[href=#match_goals]').tab('show');
goalAdd();
});
Mousetrap.bind('c', function(e) {
e.preventDefault();
container.find('a[href=#match_cards]').tab('show');
cardAdd();
});
Mousetrap.bind('s', function(e) {
e.preventDefault();
container.find('a[href=#match_shootouts]').tab('show');
shootoutAdd();
});
Mousetrap.bind('i', function(e) {
e.preventDefault();
container.find('a[href=#match_info]').tab('show');
});
Mousetrap.bind('space', function(e) {
e.preventDefault();
e.stopPropagation();
if(clock) {
clock.clock('toggle');
}
});
};
var reserveClick = function(e) {
var a = $(e.currentTarget);
$.post(baseUrl + '/reserve',
{
status: a.prop('checked')
},
function(data,textStatus) {
Altius.executeFormActions(data);
}
);
};
var subClick= function(e) {
var a = $(e.currentTarget);
if((a.attr('data-minute') ==-1) && clock && (clock.clock('getMinute')>0)) {
$.post(baseUrl + '/subon',
{
minute: clock? clock.clock('getMinuteText') : null,
seconds: clock? clock.clock('getSeconds') : null,
player: a.attr('data-player'),
_token: Altius.token
},
function(data, textStatus) {
if(data.success) {
Altius.executeFormActions(data);
if(data.record)
updatePlayerSub(data.record);
}
}
);
} else {
Altius.Form.clearAllErrors(modals.sub);
Altius.Form.setValue(modals.sub,'player_id',a.attr('data-player'));
Altius.Form.setValue(modals.sub,'player',a.attr('title'));
Altius.Form.setValue(modals.sub,'minute',a.attr('data-minute') + (a.attr('data-minuteplus')>0?'+':''));
modals.sub.modal({ "keyboard": true});
Altius.Form.focusFirst(modals.sub);
}
};
var subFormSuccess=function(e,data) {
modals.sub.modal('hide');
updatePlayerSub(data.record);
};
// update and paint functions
var updatePlayerSub= function(record) {
var a = container.find('a.substitute[data-player="' + record.player_id + '"]');
console.log(record,a);
a.attr('data-minute',record.minute);
a.attr('data-minuteplus',record.minuteplus?1:0);
if(record.minute==-1)
a.addClass('btn-default').removeClass('btn-info');
else
a.removeClass('btn-default').addClass('btn-info');
var row = container.find('#match_player_' + record.player_id);
if(record.minute==-1) {
row.removeClass('info');
} else
row.addClass('info');
row.find('td').effect('highlight',1000);
var text='';
if(record.minute===0)
text='X';
else
if(record.minute >0) {
text=record.minute;// + "'";
if(record.minuteplus)
text+='+';
}
row.find('td').first().html( text);
// find button and update with proper text and class
// find row and update with class and minute + text
};
var lineupForm=function() {
$('#match_lineuppicker').each(function(e){
var f = $(this);
var update = function(id,val) {
var el = f.find('.' + id);
var data =el.attr('data-val')*1;
if(data) {
el.html(val + '/' + data);
el.removeClass('warning success danger');
if(val < data)
el.addClass('warning');
if(val == data)
el.addClass('success');
if(val > data)
el.addClass('danger');
} else {
el.html(val);
}
};
var count=function() {
var match=0;
var start=0;
var captain=0;
var gk=0;
var coach=0;
var manager=0;
f.find('table.table-team-lineup tr').each(function(e) {
var row = $(this);
var select = row.find('select[name^=player]').first();
if(select.val()) {
if (select.val()=='X')
start++;
if (select.val()!='DEL') {
match++;
if(row.find('span.checked input[name^=player_captain]').length)
captain++;
if(row.find('span.checked input[name^=player_goalkeeper]').length)
gk++;
}
}
});
update('match_captaincount',captain);
update('match_gkcount',gk);
f.find('select[name^=staff]').each(function(e) {
var val=$(this).val();
if(val=='Manager')
manager++;
if(val=='Coach')
coach++;
});
update('match_matchcount',match);
update('match_startcount',start);
update('match_coachcount',coach);
update('match_managercount',manager);
};
count();
f.on('change','select',null,function(e) {
count();
});
f.on('click','input',null,function(e) {
count();
});
});
};
var initElements=function(el) {
el = el || $(document);
el.find('table.recentTeam tr.teamstaff a, table.recentTeam tr.player a').on('ajax:success',function(e,data) {
if(data.success) {
var target=$('#SelectedTeamBody');
target.html(data.team);
Altius.initElement(target);
$(this).attr("disabled",'disabled');
$(this).siblings().removeAttr("disabled");
$(this).siblings('.add').attr("disabled",'disabled');
$(this).closest('tr').addClass('success');
}
});
};
return {
//main function to initiate the application
init: function() {
initMatchManage();
initElements();
},
lineupForm: lineupForm
};
}();
var Lessons = function() {
var init=function() {
// $('#activity').append('');
};
var onStart=function(tour) {
$.each(tour._options.steps,function(i,s) {
if($(s.element).length===0) {
if(s.orphan_content) {
s.content=s.orphan_content;
} else {
if(s.orphan_skip)
s.skip=true;
}
}
if( $(s.element).popover){
$(s.element).popover('destroy');
}
});
tour._direction=1;
if(tour._options.steps.length==1){
$('div.lesson button[data-role=next]').css('display','none').html('asdf');
}
};
var onHide=function(tour) {
var step = tour._options.steps[tour._current];
if(step.reflex) {
$(step.element).removeClass('pulsate');
}
$(step.element).popover();
};
var onHidden=function(tour) {
var step = tour._options.steps[tour._current];
};
var onPrev=function(tour) {
tour._direction=-1;
};
var onNext=function(tour) {
tour._direction=1;
};
var onShow=function(tour) {
};
var onShown=function(tour) {
var step = tour._options.steps[tour._current];
if(step.skip) {
if(tour._direction==-1) {
tour.prev();
} else {
tour.next();
}
}
if(step.activate) {
if(step.activate===true){
$(step.element).tab('show');
} else {
$(step.activate).tab('show');
}
}
if(tour._current == (tour._options.steps.length-1)) {
$('div.lesson button[data-role=end]').html(' Complete');
} else {
$('div.lesson button[data-role=end]').html(' Cancel');
}
if(tour._options.steps.length>1)
$("div.lesson span.progress").css('width',((tour._current+1)/tour._options.steps.length*100) + '%');
else
$("div.lesson span.progress").css('width','0');
if(tour._options.steps.length==1){
$('div.lesson button[data-role=next]').css('display','none');
$('div.lesson button[data-role=prev]').css('display','none');
}
if(step.reflex) {
$("div.lesson div.popover-navigation button[data-role=next]").attr('disabled','disabled');
$(step.element).addClass('pulsate');
}
else {
$("div.lesson div.popover-navigation button[data-role=next]").removeAttr('disabled');
}
};
var onEnd = function(tour) {
if(tour._current == (tour._options.steps.length-1)) {
$.ajax({
type: "GET",
dataType: 'json',
url: '/help/markRead',
data: {
code: tour._options.name,
type: tour._options.type,
route: tour._options.route,
step: tour._current,
total: tour._options.steps.length
},
success: function(data) {
$('#faq_completed').html(data.completed);
if(data['new']===0) {
$('#faq_completed').parent().addClass('badge-success').removeClass('badge-warning');
}
$('#' + data.id).find('span').remove();
$('#' + data.id).append('');
}
});
}
$.each(tour._options.steps,function(i,s) {
$(s.element).popover();
});
};
return {
init: init,
onStart: onStart,
onNext: onNext,
onPrev: onPrev,
onShow: onShow,
onShown: onShown,
onHide: onHide,
onHidden: onHidden,
onEnd: onEnd
};
}();
Altius.serverTime = function() {
var times = { count:0, total:0,delta:0};
var seeded=false;
var serverTime = function(debug) {
seed();
if(times.count>0) {
if(debug)
console.log( 'serverTime:',times.count,times.delta);
return $.now()/1000 + (times.delta);
}
var m = $("meta[name=_timestamp]");
if(debug)
console.log( 'serverTime',0,m.attr('content')/1000 - $.now()/1000);
return m.attr('content')/1000;
};
var seed = function() {
if(seeded)
return;
seeded=true;
// check immediately
check();
var checks = [200,3000,10000,20000];
$.each(checks,function(i,v) {
setTimeout(check,v);
});
};
var check =function() {
var start=$.now()/1000;
$.get('/time.php',null,function(data) {
times.count++;
times.total+=data/1000 - (start + $.now()/1000)/2;
times.delta=times.total/times.count;
console.log('ServerTimeCheck' ,(times.delta), $.now()/1000 + (times.delta));
});
};
return serverTime;
}();
$(document).ready(function() {
$('div.accordion.faq a').on('click', function(e,a,b) {
history.pushState(null, null, $(this).attr('href'));
});
// add a hash to the URL when the user clicks on a tab
// navigate to a tab when the history changes
$('.nav-tabs').each(function(e) {
var active = $(this).find('li.active a');
if(active.length===0)
$(this).find('a:first').tab('show');
});
$('a[data-toggle="tab"]').on('click', function(e) {
history.pushState(null, null, $(this).attr('href'));
});
return;
var activate = function(e) {
if(location.hash.length) {
var activeTab = $('[href=' + (location.hash) + ']');
if (activeTab.length) {
activeTab.tab('show');
return;
}
}
};
window.addEventListener("popstate", activate);
});
(function ( $ ) {
/**
* Holds google map object and related utility entities.
* @constructor
*/
function GMapContext(domElement, options) {
var _map = new google.maps.Map(domElement, options);
var _marker = new google.maps.Marker({
position: new google.maps.LatLng(54.19335, -3.92695),
map: _map,
title: "Drag Me",
draggable: options.draggable
});
return {
map: _map,
marker: _marker,
circle: null,
location: _marker.position,
radius: options.radius,
locationName: options.locationName,
addressComponents: {
formatted_address: null,
addressLine1: null,
addressLine2: null,
streetName: null,
streetNumber: null,
city: null,
state: null,
stateOrProvince: null
},
settings: options.settings,
domContainer: domElement,
geodecoder: new google.maps.Geocoder()
}
}
// Utility functions for Google Map Manipulations
var GmUtility = {
/**
* Draw a circle over the the map. Returns circle object.
* Also writes new circle object in gmapContext.
*
* @param center - LatLng of the center of the circle
* @param radius - radius in meters
* @param gmapContext - context
* @param options
*/
drawCircle: function(gmapContext, center, radius, options) {
if (gmapContext.circle != null) {
gmapContext.circle.setMap(null);
}
if (radius > 0) {
radius *= 1;
options = $.extend({
strokeColor: "#0000FF",
strokeOpacity: 0.35,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.20
}, options);
options.map = gmapContext.map;
options.radius = radius;
options.center = center;
gmapContext.circle = new google.maps.Circle(options);
return gmapContext.circle;
}
return null;
},
/**
*
* @param gMapContext
* @param location
* @param callback
*/
setPosition: function(gMapContext, location, callback) {
gMapContext.location = location;
gMapContext.marker.setPosition(location);
gMapContext.map.panTo(location);
this.drawCircle(gMapContext, location, gMapContext.radius, {});
if (gMapContext.settings.enableReverseGeocode) {
gMapContext.geodecoder.geocode({latLng: gMapContext.location}, function(results, status){
if (status == google.maps.GeocoderStatus.OK && results.length > 0){
gMapContext.locationName = results[0].formatted_address;
gMapContext.addressComponents =
GmUtility.address_component_from_google_geocode(results[0].address_components);
}
if (callback) {
callback.call(this, gMapContext);
}
});
} else {
if (callback) {
callback.call(this, gMapContext);
}
}
},
locationFromLatLng: function(lnlg) {
return {latitude: lnlg.lat(), longitude: lnlg.lng()}
},
address_component_from_google_geocode: function(address_components) {
var result = {};
for (var i = address_components.length-1; i>=0; i--) {
var component = address_components[i];
// Postal code
if (component.types.indexOf('postal_code') >= 0) {
result.postalCode = component.short_name;
}
// Street number
else if (component.types.indexOf('street_number') >= 0) {
result.streetNumber = component.short_name;
}
// Street name
else if (component.types.indexOf('route') >= 0) {
result.streetName = component.short_name;
}
// City
else if (component.types.indexOf('sublocality') >= 0) {
result.city = component.short_name;
}
// State \ Province
else if (component.types.indexOf('administrative_area_level_1') >= 0) {
result.stateOrProvince = component.short_name;
}
// State \ Province
else if (component.types.indexOf('country') >= 0) {
result.country = component.short_name;
}
}
result.addressLine1 = [result.streetNumber, result.streetName].join(' ').trim();
result.addressLine2 = '';
return result;
}
};
function isPluginApplied(domObj) {
return getContextForElement(domObj) != undefined;
}
function getContextForElement(domObj) {
return $(domObj).data("locationpicker");
}
function updateInputValues(inputBinding, gmapContext){
if (!inputBinding) return;
var currentLocation = GmUtility.locationFromLatLng(gmapContext.location);
if (inputBinding.latitudeInput) {
inputBinding.latitudeInput.val(currentLocation.latitude);
}
if (inputBinding.longitudeInput) {
inputBinding.longitudeInput.val(currentLocation.longitude);
}
if (inputBinding.radiusInput) {
inputBinding.radiusInput.val(gmapContext.radius);
}
if (inputBinding.locationNameInput) {
inputBinding.locationNameInput.val(gmapContext.locationName);
}
}
function setupInputListenersInput(inputBinding, gmapContext) {
if (inputBinding) {
if (inputBinding.radiusInput){
inputBinding.radiusInput.on("change", function() {
gmapContext.radius = $(this).val();
GmUtility.setPosition(gmapContext, gmapContext.location, function(context){
context.settings.onchanged.apply(gmapContext.domContainer,
[GmUtility.locationFromLatLng(context.location), context.radius, false]);
});
});
}
if (inputBinding.locationNameInput && gmapContext.settings.enableAutocomplete) {
gmapContext.autocomplete = new google.maps.places.Autocomplete(inputBinding.locationNameInput.get(0));
google.maps.event.addListener(gmapContext.autocomplete, 'place_changed', function() {
var place = gmapContext.autocomplete.getPlace();
if (!place.geometry) {
gmapContext.settings.onlocationnotfound(place.name);
return;
}
GmUtility.setPosition(gmapContext, place.geometry.location, function(context) {
updateInputValues(inputBinding, context);
context.settings.onchanged.apply(gmapContext.domContainer,
[GmUtility.locationFromLatLng(context.location), context.radius, false]);
});
});
}
if (inputBinding.latitudeInput) {
inputBinding.latitudeInput.on("change", function() {
GmUtility.setPosition(gmapContext, new google.maps.LatLng($(this).val(), gmapContext.location.lng()), function(context){
context.settings.onchanged.apply(gmapContext.domContainer,
[GmUtility.locationFromLatLng(context.location), context.radius, false]);
});
});
}
if (inputBinding.longitudeInput) {
inputBinding.longitudeInput.on("change", function() {
GmUtility.setPosition(gmapContext, new google.maps.LatLng(gmapContext.location.lat(), $(this).val()), function(context){
context.settings.onchanged.apply(gmapContext.domContainer,
[GmUtility.locationFromLatLng(context.location), context.radius, false]);
});
});
}
}
}
/**
* Initialization:
* $("#myMap").locationpicker(options);
* @param options
* @param params
* @returns {*}
*/
$.fn.locationpicker = function( options, params ) {
if (typeof options == 'string') { // Command provided
var _targetDomElement = this.get(0);
// Plug-in is not applied - nothing to do.
if (!isPluginApplied(_targetDomElement)) return;
var gmapContext = getContextForElement(_targetDomElement);
switch (options) {
case "location":
if (params == undefined) { // Getter
var location = GmUtility.locationFromLatLng(gmapContext.location);
location.radius = gmapContext.radius;
location.name = gmapContext.locationName;
return location;
} else { // Setter
if (params.radius) {
gmapContext.radius = params.radius;
}
GmUtility.setPosition(gmapContext, new google.maps.LatLng(params.latitude, params.longitude), function(gmapContext) {
updateInputValues(gmapContext.settings.inputBinding, gmapContext);
});
}
break;
case "subscribe":
/**
* Provides interface for subscribing for GoogleMap events.
* See Google API documentation for details.
* Parameters:
* - event: string, name of the event
* - callback: function, callback function to be invoked
*/
if (params == undefined) { // Getter is not available
return null;
} else {
var event = params.event;
var callback = params.callback;
if (!event || ! callback) {
console.error("LocationPicker: Invalid arguments for method \"subscribe\"")
return null;
}
google.maps.event.addListener(gmapContext.map, event, callback);
}
break;
case "map":
/**
* Returns object which allows access actual google widget and marker paced on it.
* Structure: {
* map: Instance of the google map widget
* marker: marker placed on map
* }
*/
if (params == undefined) { // Getter is not available
var locationObj = GmUtility.locationFromLatLng(gmapContext.location);
locationObj.formattedAddress = gmapContext.locationName;
locationObj.addressComponents = gmapContext.addressComponents;
return {
map: gmapContext.map,
marker: gmapContext.marker,
location: locationObj
}
} else {
return null;
}
}
return null;
}
return this.each(function() {
var $target = $(this);
// If plug-in hasn't been applied before - initialize, otherwise - skip
if (isPluginApplied(this)) return;
// Plug-in initialization is required
// Defaults
var settings = $.extend({}, $.fn.locationpicker.defaults, options );
// Initialize
var gmapContext = new GMapContext(this, {
zoom: settings.zoom,
center: new google.maps.LatLng(settings.location.latitude, settings.location.longitude),
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
disableDoubleClickZoom: false,
scrollwheel: settings.scrollwheel,
streetViewControl: false,
radius: settings.radius,
locationName: settings.locationName,
settings: settings,
draggable: settings.draggable
});
$target.data("locationpicker", gmapContext);
// Subscribe GMap events
google.maps.event.addListener(gmapContext.marker, "dragend", function(event) {
GmUtility.setPosition(gmapContext, gmapContext.marker.position, function(context){
var currentLocation = GmUtility.locationFromLatLng(gmapContext.location);
context.settings.onchanged.apply(gmapContext.domContainer, [currentLocation, context.radius, true]);
updateInputValues(gmapContext.settings.inputBinding, gmapContext);
});
});
GmUtility.setPosition(gmapContext, new google.maps.LatLng(settings.location.latitude, settings.location.longitude), function(context){
updateInputValues(settings.inputBinding, gmapContext);
context.settings.oninitialized($target);
var currentLocation = GmUtility.locationFromLatLng(gmapContext.location);
settings.onchanged.apply(gmapContext.domContainer, [currentLocation, context.radius, false]);
});
// Set up input bindings if needed
setupInputListenersInput(settings.inputBinding, gmapContext);
});
};
$.fn.locationpicker.defaults = {
location: {latitude: 40.7324319, longitude: -73.82480799999996},
locationName: "",
radius: 500,
zoom: 15,
scrollwheel: true,
inputBinding: {
latitudeInput: null,
longitudeInput: null,
radiusInput: null,
locationNameInput: null
},
enableAutocomplete: false,
enableReverseGeocode: true,
draggable: true,
onchanged: function(currentLocation, radius, isMarkerDropped) {},
onlocationnotfound: function(locationName) {},
oninitialized: function (component) {}
}
}( jQuery ));
/* mousetrap v1.4.6 craig.is/killing/mice */
(function(J,r,f){function s(a,b,d){a.addEventListener?a.addEventListener(b,d,!1):a.attachEvent("on"+b,d)}function A(a){if("keypress"==a.type){var b=String.fromCharCode(a.which);a.shiftKey||(b=b.toLowerCase());return b}return h[a.which]?h[a.which]:B[a.which]?B[a.which]:String.fromCharCode(a.which).toLowerCase()}function t(a){a=a||{};var b=!1,d;for(d in n)a[d]?b=!0:n[d]=0;b||(u=!1)}function C(a,b,d,c,e,v){var g,k,f=[],h=d.type;if(!l[a])return[];"keyup"==h&&w(a)&&(b=[a]);for(g=0;gg||h.hasOwnProperty(g)&&(p[h[g]]=g)}e=p[d]?"keydown":"keypress"}"keypress"==e&&f.length&&(e="keydown");return{key:c,modifiers:f,action:e}}function F(a,b,d,c,e){q[a+":"+d]=b;a=a.replace(/\s+/g," ");var f=a.split(" ");1":".","?":"/","|":"\\"},G={option:"alt",command:"meta","return":"enter",escape:"esc",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"},p,l={},q={},n={},D,z=!1,I=!1,u=!1;for(f=1;20>f;++f)h[111+f]="f"+f;for(f=0;9>=f;++f)h[f+96]=f;s(r,"keypress",y);s(r,"keydown",y);s(r,"keyup",y);var m={bind:function(a,b,d){a=a instanceof Array?a:[a];for(var c=0;c')
.css('left',0)
.hide();
clock.appendTo(containers[0]);
div.find('i.match_home_possession').removeClass('info');
div.find('i.match_away_possession').removeClass('info');
initAnalytics();
};
var update = function(e,html,highlight) {
highlight = highlight || false;
e.each(function(i){
r = $(this);
if(r.html() !==html) {
if(highlight) {
r.html(html).effect('highlight',{ 'duration' : 2000});
}
else {
r.html(html);
}
}
});
};
var renderDelete = function(data) {
paintHeader(data,true);
unpaintSingle(data.events[0]);
};
var renderAdd = function(data) {
console.log('add',data);
paintHeader(data,true);
paintSingle(data.events[0],true);
};
var renderEdit = function(data) {
console.log('edit',data);
paintHeader(data,true);
unpaintSingle(data.events[0]);
paintSingle(data.events[0],true);
};
var renderHead=function(data) {
match = data.match;
paintHeader(data,true);
paintClock();
console.log(data);
};
var renderAll = function(data) {
events = data.events;
match = data.match;
paintHeader(data,true);
paintClock();
setInterval(updateClock,clockInterval);
clearEvents();
paintEvents(); // was paintSlow();
};
var clearEvents=function() {
aggregation={ possession : { home: 0,
away: 0,
free: 0,
time: 0,
poss: 'free'
}};
poss = {
bars: [],
curr: 'free',
seconds: 0,
percent: 0,
home: 0,
away: 0,
free: 0
};
lastPoss = {
team: 'free',
percent: 0
};
// clear stats table
div.find('td.stattext').html('0');
div.find('td.stattext.event_posscalc').html('0%');
div.find('td.bargraph span').css({width:'50%'});
// clear timeline buckets
div.find('[data-match-period]').empty();
};
var updateClock = function() {
if(match.clockstatus=='started') {
match.seconds += clockInterval/1000;
if (match.seconds >= match.ladder[match.status].finish*60)
{
match.seconds=match.ladder[match.status].finish*60;
match.plus=true;
match.clockstatus='plus';
}
match.minute=Math.ceil(match.seconds/60);
paintClock();
addPossession(aggregation.possession.poss,match.seconds);
paintPossession(false);
}
};
var getClockPercent= function (ladder,seconds) {
return Math.max(0,Math.min(100,(seconds - ladder.start * 60) / (ladder.minutes*60) * 100));
};
var paintClock = function() {
var period = match.ladder[match.status];
// Hari. Check this. Build etc.
if(period && period.period) {
var min = match.minute + "'" + ( match.plus ? '+' : '');
clock.appendTo(containers[period.period-1])
.removeClass('plus started stopped')
.addClass(match.clockstatus)
.data('content',match.status + ' ' + min )
.css('left','calc( ' + getClockPercent(match.ladder[match.status],match.seconds)+ '% - 0.46em)')
.show();
if(clock.data('bs.popover')) {
clock.data('bs.popover').options.content=match.status + ' ' + min;
}
update(div.find('.match_minute'), min,0);
} else {
clock.hide();
update(div.find('.match_minute'), '',0);
}
};
var paintHeader = function(data,animate) {
animate=1;
if(data.match.minute>0 && (data.match.status!='Official')) {
div.find('div.hockey-stats-manager3 a').removeClass('disabled');
div.find('div.stats_enabled').hide();
} else {
div.find('div.hockey-stats-manager3 a').addClass('disabled');
div.find('div.stats_enabled').show();
}
update(div.find('.match_statusminute'), data.match.statusminute,animate);
update(div.find('.match_status'), data.match.status,animate);
update(div.find('.match_minute'), data.match.minute + "'",animate);
update(div.find('.match_scoreline'), data.match.scoreline,animate);
};
var paintPossession=function(animate) {
el = div.find('td.stattext.home.event_posscalc');
update(el,Math.round(aggregation.possession['homep']) + '%',animate);
el = div.find('td.stattext.away.event_posscalc');
update(el,Math.round(aggregation.possession['awayp']) + '%',animate);
if(animate) {
div.find('span.bargraph.event_posscalc').animate( { width: getPercent(aggregation.possession['homep'],aggregation.possession['awayp']) + '%' },500,"easeOutCubic");
}
else {
div.find('span.bargraph.event_posscalc').width( getPercent(aggregation.possession['homep'],aggregation.possession['awayp']) + '%');
}
div.find('.match_home_possession').removeClass('info');
div.find('.match_away_possession').removeClass('info');
if(aggregation.possession.poss == 'home')
div.find('.match_home_possession').addClass('info');
if(aggregation.possession.poss == 'away')
div.find('.match_away_possession').addClass('info');
};
var paintFinalPossession= function(animate) {
return;
addPossession(aggregation.possession.poss,match.seconds);
paintPossession(animate);
};
var paintEvents = function() {
$.each(events,function(i,v) {
paintSingle(v);
});
};
var paintSlow = function() {
var interval = 7*600; // 60 second intervals
var chunk = 1;
var index=0;
var timeout = setInterval( function() {
while( (events[index]) && (events[index].seconds <=interval*chunk)) {
paintSingle(events[index]);
index++;
}
chunk++;
if( !events[index] || ( interval * chunk > (match.periods * match.period_seconds)) ) {
clearInterval(timeout);
paintFinalPossession();
}
},50);
};
var addPossession = function (who,seconds) {
var ap = aggregation.possession;
if(seconds > ap.time) {
// console.log('bar',ap.poss, seconds-ap.time);
ap[ap.poss] += seconds - ap.time;
ap.time=seconds;
ap.poss = who?who:'free';
}
var den = Math.max(1,ap.home+ap.away)/100;
ap.homep = ap.home/den;
ap.awayp = ap.away/den;
};
var paintAggregation = function(event,animate) {
var code = event.event;
if(code=='shot')
code=code+'_'+event.outcome;
el = div.find('td.stattext.' + event.home_away + '.event_' + code);
update(el,aggregation[code][event.home_away],animate);
// must aggregate before
if(animate) {
div.find('span.bargraph.event_' + code).animate( { width: getPercent(aggregation[code].home,aggregation[code].away) + '%' },500,"easeOutCubic");
}
else {
div.find('span.bargraph.event_' + code).width( getPercent(aggregation[code].home,aggregation[code].away) + '%');
}
};
var unAggregate = function(event) {
var code = event.event;
if(code=='shot')
code=code+'_'+event.outcome;
if(!(aggregation[code]) )
return;
aggregation[code][event.home_away]--;
paintAggregation(event,false);
// possession
};
var unpaintSingle = function(event) {
unAggregate(event);
var id = 'event_' + event.event + '_' + event.id;
$('#' + id).remove();
};
var aggregate = function(event,animate) {
var code = event.event;
if(code=='shot')
code=code+'_'+event.outcome;
if(!(aggregation[code]) )
aggregation[code] = { home : 0,
away : 0};
aggregation[code][event.home_away]++;
paintAggregation(event,animate);
if(code=='poss') {
if( (event.seconds-poss.seconds) >0 ) {
var bar = {
team: poss.curr,
start: poss.seconds,
length: event.seconds-poss.seconds,
period: event.period
};
console.log('test',bar,event);
poss.bars.push(bar);
poss[poss.curr] += event.seconds-poss.seconds;
poss.seconds=event.seconds;
poss.curr=event.home_away?event.home_away:'free';
}
console.log('bar',bar,poss);
addPossession(event.home_away,event.seconds);
// console.log(event,poss);
}
};
var paintSingle =function(event,animate) {
animate=animate||false;
if ( (event.event!='goal') && (event.event !='card') && (event.event !='gksub')&& (event.event !='timeout') ) {
$('table.match_stats_table').slideDown();
$('div.match_timeline3 > div > div').css('height','150px');
}
aggregate(event,animate);
var target = containers[event.period-1];
var percent= ( event.percent* 100/100);
var left = 'calc( ' + percent + '% - 0.46em)';
if(target)
var id = 'event_' + event.event + '_' + event.id;
switch(event.event){
case 'shot':
if(event.outcome=='goal') {
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_shotgoal info')
.addClass(event.home_away);
} else
if(event.outcome=='wide') {
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_shotwide')
.addClass(event.home_away);
} else
if(event.outcome=='savegk') {
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_shotgoal')
.addClass(event.home_away);
} else {
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_shot')
.addClass(event.home_away);
}
break;
break;
case 'timeout':
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_timeout')
.attr('title','Timeout')
.addClass(event.home_away);
break;
case 'gksub':
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_gksub')
.attr('title','GK Substitution')
.addClass(event.home_away);
break;
case 'goal':
$('').appendTo(target)
.css('left',left)
.addClass(event.home_away)
.addClass('icon_goal')
.attr('id',id)
.data('title',event.popup_title)
.data('content',event.popup_content)
.data('placement',event.home_away=='home' ? 'top' : 'bottom');
break;
case 'card':
var icon;
switch(event.type) {
case 'G': icon=''; break;
case 'Y': icon=''; break;
case 'R': icon=''; break;
default:
icon='';
break;
}
$(icon).appendTo(target)
.css('left',left)
.addClass(event.home_away)
.addClass('icon_' + event.type)
.attr('id',id)
.data('title',event.popup_title)
.data('content',event.popup_content)
.data('placement',event.home_away=='home' ? 'top' : 'bottom');
break;
case 'pc':
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_pc')
.addClass(event.home_away);
break;
case 'ps':
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_ps')
.addClass(event.home_away);
break;
case 'circle':
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_circle')
.addClass(event.home_away);
break;
case 'shotwide':
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_shotwide')
.addClass(event.home_away);
break;
case 'shotgoal':
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_shotgoal')
.addClass(event.home_away);
break;
case 'lost2':
$('').appendTo(target)
.css('left',left)
.attr('id',id)
.addClass('icon_lost')
.addClass(event.home_away);
break;
case 'poss':
paintPossession(animate);
/*
if(lastPoss.team!='free')
$('').appendTo(target)
.css('left',lastPoss.percent + '%')
.attr('id',id)
.addClass(lastPoss.team)
.css('width',(event.percent-lastPoss.percent) + '%');
lastPoss.team=event.home_away?event.home_away:'free';
lastPoss.percent=event.percent;
*/
break;
default:
break;
}
div.find('.popovers').popover();
};
return {
init: init,
all: renderAll,
head : renderHead,
add: renderAdd,
del : renderDelete,
edit : renderEdit
};
})();
(function() {
$('[data-pusher-realtime]').each(function(e) {
var context = $(this);
var realtime = context.data('pusher-realtime');
realtime=JSON.parse(realtime);
var renderer = context.data('pusher-renderer');
renderer = rt[renderer];
renderer.init(context);
renderer[realtime.event](realtime.data);
var element = document.querySelector('meta[name="pusher:key"]');
var key= element && element.getAttribute("content");
var pusher = new Pusher(key);
var channel = pusher.subscribe(realtime.channel);
$.each(realtime.events,function(i,v) {
channel.bind(v,function(data) {
renderer[v](data);
console.log('pusherrender',v);
});
});
/*
var ablyChannel= ably.channels.get( realtime.channel);
$.each(realtime.events,function(i,v) {
ablyChannel.subscribe(v,function(data) {
console.log('render',v);
renderer[v](data.data);
});
});
*/
});
}) ();
/*
(function() {
$('[data-altius-realtime]').each(function(e) {
var context = $(this);
var realtime = context.data('altius-realtime');
realtime=JSON.parse(realtime);
// do initial render
rt[realtime.renderer](context,realtime.data);
// Create Pusher interface
var pusher = new Pusher(Altius.pusherKey);
var channel = pusher.subscribe(realtime.channel);
channel.bind(realtime.event,function(data) {
rt[realtime.renderer](context,data);
});
});
}) ();
*/
// Stats3 Panel
var stats3Panel = ( function() {
var undoActions=[];
var undoButton;
var el;
var currentMode='free';
var setMode=function(mode) {
if(mode=='right') {
el.find('div.panel.right').addClass('panel-primary').removeClass('panel-info');
el.find('div.panel.left').addClass('panel-info').removeClass('panel-primary');
el.find('div.panel.middle').addClass('panel-info').removeClass('panel-primary');
} else
if(mode=='left') {
el.find('div.panel.left').addClass('panel-primary').removeClass('panel-info');
el.find('div.panel.right').addClass('panel-info').removeClass('panel-primary');
el.find('div.panel.middle').addClass('panel-info').removeClass('panel-primary');
} else {
el.find('div.panel.left').addClass('panel-info').removeClass('panel-primary');
el.find('div.panel.right').addClass('panel-info').removeClass('panel-primary');
el.find('div.panel.middle').addClass('panel-primary').removeClass('panel-info');
}
el.find("[data-visible]").hide();
el.find("[data-visible~='" + mode + "']").show();
el.find("[data-enabled]").attr('disabled','disabled');
el.find("[data-enabled~='" + mode + "']").removeAttr('disabled');
currentMode=mode;
};
var undo=function(el,a) {
var action = undoActions.shift();
action.a.removeClass('last_clicked').effect('pulsate',{times:2});
if(undoActions.length===0) {
undoButton.find('.description').html('');
undoButton.find('.team').html('');
undoButton.attr('disabled',1);
setMode(initialPossession);
} else {
undoButton.find('.description').html(undoActions[0].a.text());
undoButton.find('.team').html(undoActions[0].team);
undoButton.removeAttr('disabled');
undoActions[0].a.addClass('last_clicked');
setMode(undoActions[0].mode);
}
};
var setUndo=function(el,a) {
el.find('a').removeClass('last_clicked');
a.addClass('last_clicked');
var panel = a.closest('div.panel');
var title = panel.find('h3.panel-title');
undoButton.find('.description').html(a.text());
var teamText = (panel.hasClass('left') ? ( ' ' + title.text()) : '') +
(panel.hasClass('right') ? ( title.text() + ' ') :'');
undoButton.find('.team').html(teamText);
undoActions.unshift({ mode: currentMode ,
team: teamText,
a : a
});
undoButton.removeAttr('disabled');
};
var initialPossession;
var
init = function(item) {
el=item;
undoButton = el.find('#match_statistics_undo a');
initialPossession=el.data('possession');
console.log('poss',initialPossession);
setMode(initialPossession);
el.find('a[data-ajax]').each(function(e) {
var a = $(this);
$(this).click(function(e) {
var a = $(this);
// things to do
// send Ajax Request
// Update UX based on mode
// Store Undo and update Undo text
if(a.data('mode'))
setMode(a.data('mode'));
if(a.hasClass('undo')) {
$('#audioStop')[0].play();
undo(el,a);
} else {
$('#audioStart')[0].play();
setUndo(el,a);
}
if($(this).is(':visible')) {
// $('#audioStart')[0].play();
console.log('nop');
}
});
});
};
return {
init: init
};
})();
(function() {
$('div.hockey-stats-manager3').each(function(e) {
var context = $(this);
stats3Panel.init($(this));
});
})();