Count the Calls group by months - javascript

Data: you can See in below image:
i want display this data like this:(how many calls are there in particular months)
Name Jan Feb March April May
Staff 0 1 1 0 0
Account 0 0 1 0 3
and i want to do this the same for all the months.
for Graph i wrote a function like this:(but i tried using same logic for table also, but that doesn't seem to work.)
Anyone can help me how to do the same thing in table
getGraphData2( data,config) {
var year = new Date().getUTCFullYear()-1;
var month = new Date().getMonth()+10;
var fullMonths = config.Filter.filter(f => f.type === "Monthly");
var monthsThisYear = config.Filter.filter(f => f.type === "Monthly" && f.key <= month && f.key > (month - 12));
var monthsLastYear = config.Filter.filter(f => f.type === "Monthly" && f.key > (12 - (12 - monthsThisYear.length)));
var months = [];
months.push(...monthsThisYear);
months.push(...monthsLastYear);
var labels = months.map(m => m.value);
var targetTypes = this.state.resultsGraph.map(m => ({Name: m.Name}));
var fData = {};
targetTypes.forEach(f => {
fData[f.Name] = { label: f.Name, data: fullMonths.map(m => 0) };
});
if (this.state.results !== null) {
for (var c = 0; c < this.state.resultsGraph.length; c++) {
var call = this.state.resultsGraph[c];
if (call !== undefined && call !== null) {
var cDate = new Date(call.Call_Date_vod__c); //ConvertToDate(call.call_Date_vod__c);
if (cDate != null && ((cDate.getMonth() + 1) <= month && cDate.getFullYear() === year) || (month < (cDate.getMonth() + 1) && cDate.getFullYear() === (year - 1))) {
var targetType = call.Name;
if (targetType !== undefined && targetType !== null) {
var actData = fData[targetType];
if (actData !== undefined && actData !== null)
actData.data[cDate.getMonth()] = actData.data[cDate.getMonth()] + 1;
else {
actData = fData["NoTarget"];
actData.data[cDate.getMonth()] = actData.data[cDate.getMonth()] + 1;
}
}
else {
var actData = fData["NoTarget"];
actData.data[cDate.getMonth()] = actData.data[cDate.getMonth()] + 1;
}
}
}
}
}
fData = Object.keys(fData).map(k => fData[k]);
fData = fData.filter(f => f.data.filter(d => d > 0).length > 0);
for (var i = 0; i < fData.length; i++) {
var fdat = fData[i];
var data = fdat.data;
fdat.data = months.map(m => data[(m.key - 1)]);
}
var ds = fData.map((m, index) => ({
label: m.label,
data: m.data,
stack: "stack1",
backgroundColor: labels.map(l => (this.props.selectGraphFilter === l) ? getCanvasPattern(config.BackgroundColor[index]) : config.BackgroundColor[index]),
hoverBackgroundColor: labels.map(l => (this.props.selectGraphFilter === l) ? getCanvasPattern(config.HoverBackgroundColor[index]) : config.HoverBackgroundColor[index]),
}));
var graphData = {
labels: labels,
datasets: ds,
};
return graphData;
}

How about to aggregate it like this?
const data = this.state.resultsGraph.reduce(
(actData, call) => {
if (actData) {
actData[call.Name][
`${call.Call_Date_vod__c.getMonth()} ${call.Call_Date_vod__c.getFullYear()}`
] =
(actData[call.Name][
`${call.Call_Date_vod__c.getMonth()} ${call.Call_Date_vod__c.getFullYear()}`
] || 0) + call.Call;
}
return actData;
},
{
Staff: {},
Account: {}
}
);

Related

How to convert from Path to XPath, given a browser event

On a MouseEvent instance, we have a property called path, it might look like this:
Does anybody know if there is a reliable way to translate this path array into an XPath? I assume that this path data is the best data to start from? Is there a library I can use to do the conversion?
This library looks promising, but it doesn't use the path property of an event: https://github.com/johannhof/xpath-dom
There's not a unique XPath to a node, so you'll have to decide what's the most appropriate way of constructing a path. Use IDs where available? Numeral position in the document? Position relative to other elements?
See getPathTo() in this answer for one possible approach.
PS: Taken from Javascript get XPath of a node
Another option is to use SelectorGadget from below link
https://dv0akt2986vzh.cloudfront.net/unstable/lib/selectorgadget.js
The actual code for the DOM path is at
https://dv0akt2986vzh.cloudfront.net/stable/lib/dom.js
Usage: on http://google.com
elem = document.getElementById("q")
predict = new DomPredictionHelper()
predict.pathOf(elem)
// gives "body.default-theme.des-mat:nth-child(2) div#_Alw:nth-child(4) form#f:nth-child(2) div#fkbx:nth-child(2) input#q:nth-child(2)"
predict.predictCss([elem],[])
// gives "#q"
CODE if link goes down
// Copyright (c) 2008, 2009 Andrew Cantino
// Copyright (c) 2008, 2009 Kyle Maxwell
function DomPredictionHelper() {};
DomPredictionHelper.prototype = new Object();
DomPredictionHelper.prototype.recursiveNodes = function(e){
var n;
if(e.nodeName && e.parentNode && e != document.body) {
n = this.recursiveNodes(e.parentNode);
} else {
n = new Array();
}
n.push(e);
return n;
};
DomPredictionHelper.prototype.escapeCssNames = function(name) {
if (name) {
try {
return name.replace(/\s*sg_\w+\s*/g, '').replace(/\\/g, '\\\\').
replace(/\./g, '\\.').replace(/#/g, '\\#').replace(/\>/g, '\\>').replace(/\,/g, '\\,').replace(/\:/g, '\\:');
} catch(e) {
console.log('---');
console.log("exception in escapeCssNames");
console.log(name);
console.log('---');
return '';
}
} else {
return '';
}
};
DomPredictionHelper.prototype.childElemNumber = function(elem) {
var count = 0;
while (elem.previousSibling && (elem = elem.previousSibling)) {
if (elem.nodeType == 1) count++;
}
return count;
};
DomPredictionHelper.prototype.pathOf = function(elem){
var nodes = this.recursiveNodes(elem);
var self = this;
var path = "";
for(var i = 0; i < nodes.length; i++) {
var e = nodes[i];
if (e) {
path += e.nodeName.toLowerCase();
var escaped = e.id && self.escapeCssNames(new String(e.id));
if(escaped && escaped.length > 0) path += '#' + escaped;
if(e.className) {
jQuery.each(e.className.split(/ /), function() {
var escaped = self.escapeCssNames(this);
if (this && escaped.length > 0) {
path += '.' + escaped;
}
});
}
path += ':nth-child(' + (self.childElemNumber(e) + 1) + ')';
path += ' '
}
}
if (path.charAt(path.length - 1) == ' ') path = path.substring(0, path.length - 1);
return path;
};
DomPredictionHelper.prototype.commonCss = function(array) {
try {
var dmp = new diff_match_patch();
} catch(e) {
throw "Please include the diff_match_patch library.";
}
if (typeof array == 'undefined' || array.length == 0) return '';
var existing_tokens = {};
var encoded_css_array = this.encodeCssForDiff(array, existing_tokens);
var collective_common = encoded_css_array.pop();
jQuery.each(encoded_css_array, function(e) {
var diff = dmp.diff_main(collective_common, this);
collective_common = '';
jQuery.each(diff, function() {
if (this[0] == 0) collective_common += this[1];
});
});
return this.decodeCss(collective_common, existing_tokens);
};
DomPredictionHelper.prototype.tokenizeCss = function(css_string) {
var skip = false;
var word = '';
var tokens = [];
var css_string = css_string.replace(/,/, ' , ').replace(/\s+/g, ' ');
var length = css_string.length;
var c = '';
for (var i = 0; i < length; i++){
c = css_string[i];
if (skip) {
skip = false;
} else if (c == '\\') {
skip = true;
} else if (c == '.' || c == ' ' || c == '#' || c == '>' || c == ':' || c == ',') {
if (word.length > 0) tokens.push(word);
word = '';
}
word += c;
if (c == ' ' || c == ',') {
tokens.push(word);
word = '';
}
}
if (word.length > 0) tokens.push(word);
return tokens;
};
DomPredictionHelper.prototype.decodeCss = function(string, existing_tokens) {
var inverted = this.invertObject(existing_tokens);
var out = '';
jQuery.each(string.split(''), function() {
out += inverted[this];
});
return this.cleanCss(out);
};
// Encode css paths for diff using unicode codepoints to allow for a large number of tokens.
DomPredictionHelper.prototype.encodeCssForDiff = function(strings, existing_tokens) {
var codepoint = 50;
var self = this;
var strings_out = [];
jQuery.each(strings, function() {
var out = new String();
jQuery.each(self.tokenizeCss(this), function() {
if (!existing_tokens[this]) {
existing_tokens[this] = String.fromCharCode(codepoint++);
}
out += existing_tokens[this];
});
strings_out.push(out);
});
return strings_out;
};
DomPredictionHelper.prototype.simplifyCss = function(css, selected_paths, rejected_paths) {
var self = this;
var parts = self.tokenizeCss(css);
var best_so_far = "";
if (self.selectorGets('all', selected_paths, css) && self.selectorGets('none', rejected_paths, css)) best_so_far = css;
for (var pass = 0; pass < 4; pass++) {
for (var part = 0; part < parts.length; part++) {
var first = parts[part].substring(0,1);
if (self.wouldLeaveFreeFloatingNthChild(parts, part)) continue;
if ((pass == 0 && first == ':') || // :nth-child
(pass == 1 && first != ':' && first != '.' && first != '#' && first != ' ') || // elem, etc.
(pass == 2 && first == '.') || // classes
(pass == 3 && first == '#')) // ids
{
var tmp = parts[part];
parts[part] = '';
var selector = self.cleanCss(parts.join(''));
if (selector == '') {
parts[part] = tmp;
continue;
}
if (self.selectorGets('all', selected_paths, selector) && self.selectorGets('none', rejected_paths, selector)) {
best_so_far = selector;
} else {
parts[part] = tmp;
}
}
}
}
return self.cleanCss(best_so_far);
};
DomPredictionHelper.prototype.wouldLeaveFreeFloatingNthChild = function(parts, part) {
return (((part - 1 >= 0 && parts[part - 1].substring(0, 1) == ':') &&
(part - 2 < 0 || parts[part - 2] == ' ') &&
(part + 1 >= parts.length || parts[part + 1] == ' ')) ||
((part + 1 < parts.length && parts[part + 1].substring(0, 1) == ':') &&
(part + 2 >= parts.length || parts[part + 2] == ' ') &&
(part - 1 < 0 || parts[part - 1] == ' ')));
};
DomPredictionHelper.prototype.cleanCss = function(css) {
return css.replace(/\>/, ' > ').replace(/,/, ' , ').replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '').replace(/,$/, '');
};
DomPredictionHelper.prototype.getPathsFor = function(arr) {
var self = this;
var out = [];
jQuery.each(arr, function() {
if (this && this.nodeName) {
out.push(self.pathOf(this));
}
})
return out;
};
DomPredictionHelper.prototype.predictCss = function(s, r) {
var self = this;
if (s.length == 0) return '';
var selected_paths = self.getPathsFor(s);
var rejected_paths = self.getPathsFor(r);
var css = self.commonCss(selected_paths);
var simplest = self.simplifyCss(css, selected_paths, rejected_paths);
// Do we get off easy?
if (simplest.length > 0) return simplest;
// Okay, then make a union and possibly try to reduce subsets.
var union = '';
jQuery.each(s, function() {
union = self.pathOf(this) + ", " + union;
});
union = self.cleanCss(union);
return self.simplifyCss(union, selected_paths, rejected_paths);
};
DomPredictionHelper.prototype.fragmentSelector = function(selector) {
var self = this;
var out = [];
jQuery.each(selector.split(/\,/), function() {
var out2 = [];
jQuery.each(self.cleanCss(this).split(/\s+/), function() {
out2.push(self.tokenizeCss(this));
});
out.push(out2);
});
return out;
};
// Everything in the first selector must be present in the second.
DomPredictionHelper.prototype.selectorBlockMatchesSelectorBlock = function(selector_block1, selector_block2) {
for (var j = 0; j < selector_block1.length; j++) {
if (jQuery.inArray(selector_block1[j], selector_block2) == -1) {
return false;
}
}
return true;
};
// Assumes list is an array of complete CSS selectors represented as strings.
DomPredictionHelper.prototype.selectorGets = function(type, list, the_selector) {
var self = this;
var result = true;
if (list.length == 0 && type == 'all') return false;
if (list.length == 0 && type == 'none') return true;
var selectors = self.fragmentSelector(the_selector);
var cleaned_list = [];
jQuery.each(list, function() {
cleaned_list.push(self.fragmentSelector(this)[0]);
});
jQuery.each(selectors, function() {
if (!result) return;
var selector = this;
jQuery.each(cleaned_list, function(pos) {
if (!result || this == '') return;
if (self._selectorGets(this, selector)) {
if (type == 'none') result = false;
cleaned_list[pos] = '';
}
});
});
if (type == 'all' && cleaned_list.join('').length > 0) { // Some candidates didn't get matched.
result = false;
}
return result;
};
DomPredictionHelper.prototype._selectorGets = function(candidate_as_blocks, selector_as_blocks) {
var cannot_match = false;
var position = candidate_as_blocks.length - 1;
for (var i = selector_as_blocks.length - 1; i > -1; i--) {
if (cannot_match) break;
if (i == selector_as_blocks.length - 1) { // First element on right.
// If we don't match the first element, we cannot match.
if (!this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position])) cannot_match = true;
position--;
} else {
var found = false;
while (position > -1 && !found) {
found = this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position]);
position--;
}
if (!found) cannot_match = true;
}
}
return !cannot_match;
};
DomPredictionHelper.prototype.invertObject = function(object) {
var new_object = {};
jQuery.each(object, function(key, value) {
new_object[value] = key;
});
return new_object;
};
DomPredictionHelper.prototype.cssToXPath = function(css_string) {
var tokens = this.tokenizeCss(css_string);
if (tokens[0] && tokens[0] == ' ') tokens.splice(0, 1);
if (tokens[tokens.length - 1] && tokens[tokens.length - 1] == ' ') tokens.splice(tokens.length - 1, 1);
var css_block = [];
var out = "";
for(var i = 0; i < tokens.length; i++) {
if (tokens[i] == ' ') {
out += this.cssToXPathBlockHelper(css_block);
css_block = [];
} else {
css_block.push(tokens[i]);
}
}
return out + this.cssToXPathBlockHelper(css_block);
};
// Process a block (html entity, class(es), id, :nth-child()) of css
DomPredictionHelper.prototype.cssToXPathBlockHelper = function(css_block) {
if (css_block.length == 0) return '//';
var out = '//';
var first = css_block[0].substring(0,1);
if (first == ',') return " | ";
if (jQuery.inArray(first, [':', '#', '.']) != -1) {
out += '*';
}
var expressions = [];
var re = null;
for(var i = 0; i < css_block.length; i++) {
var current = css_block[i];
first = current.substring(0,1);
var rest = current.substring(1);
if (first == ':') {
// We only support :nth-child(n) at the moment.
if (re = rest.match(/^nth-child\((\d+)\)$/))
expressions.push('(((count(preceding-sibling::*) + 1) = ' + re[1] + ') and parent::*)');
} else if (first == '.') {
expressions.push('contains(concat( " ", #class, " " ), concat( " ", "' + rest + '", " " ))');
} else if (first == '#') {
expressions.push('(#id = "' + rest + '")');
} else if (first == ',') {
} else {
out += current;
}
}
if (expressions.length > 0) out += '[';
for (var i = 0; i < expressions.length; i++) {
out += expressions[i];
if (i < expressions.length - 1) out += ' and ';
}
if (expressions.length > 0) out += ']';
return out;
};

Value is never used in function(JS)

I have function for filtering results
Here is code
filtered = markers.filter(function (marker) {
var getDate = marker.date.match(/\d/g).join('');
var markerDate = new Date(parseFloat(getDate));
return (markerDate => valDateStart && markerDate <= valDateEnd && (marker.imei === imei || imei === null));
});
It was refactored from this
$.each(markers, function (i,marker) {
var getDate = marker.date.match(/\d/g).join('');
var markerDate = new Date(parseFloat(getDate));
// var valDate = new Date(startValue[2], startValue[1] - 1, startValue[0]);
if (markerDate => valDateStart && markerDate <= valDateEnd && (marker.imei === imei || imei === null)) {
filtered.push(marker);
}
});
But now in this row var markerDate = new Date(parseFloat(getDate)); I have markerDate is never used
Where is problem?

Refresh Code when Infinite Scroll Is Called

How to I call a JavaScript function when Tumblr's infinite scroll loads more posts?
I figure it would have to be some sort of listener function for when tumblrAutoPager.init us called. I found the infinite scroll code online and don't really understand it.
var tumblrAutoPager = {
url: "http://proto.jp/",
ver: "0.1.7",
rF: true,
gP: {},
pp: null,
ppId: "",
LN: location.hostname,
init: function () {
if ($("autopagerize_icon") || navigator.userAgent.indexOf('iPhone') != -1) return;
var tAP = tumblrAutoPager;
var p = 1;
var lh = location.href;
var lhp = lh.lastIndexOf("/page/");
var lht = lh.lastIndexOf("/tagged/");
if (lhp != -1) {
p = parseInt(lh.slice(lhp + 6));
tAP.LN = lh.slice(7, lhp);
} else if (lht != -1) {
tAP.LN = lh.slice(7);
if (tAP.LN.slice(tAP.LN.length - 1) == "/") tAP.LN = tAP.LN.slice(0, tAP.LN.length - 1);
} else if ("http://" + tAP.LN + "/" != lh) {
return;
};
var gPFncs = [];
gPFncs[0] = function (aE) {
var r = [];
for (var i = 0, l = aE.length; i < l; i++) {
if (aE[i].className == "autopagerize_page_element") {
r = gCE(aE[i]);
break;
}
}
return r;
};
gPFncs[1] = function (aE) {
var r = [];
for (var i = 0, l = aE.length; i < l; i++) {
var arr = aE[i].className ? aE[i].className.split(" ") : null;
if (arr) {
for (var j = 0; j < arr.length; j++) {
arr[j] == "post" ? r.push(aE[i]) : null;
}
}
}
return r;
};
gPFncs[2] = function (aE) {
var r = [];
var tmpId = tAP.ppId ? [tAP.ppId] : ["posts", "main", "container", "content", "apDiv2", "wrapper", "projects"];
for (var i = 0, l = aE.length; i < l; i++) {
for (var j = 0; j < tmpId.length; j++) {
if (aE[i].id == tmpId[j]) {
r = gCE(aE[i]);
tAP.ppId = aE[i].id;
break;
}
}
}
return r;
};
for (var i = 0; i < gPFncs.length; i++) {
var getElems = gPFncs[i](document.body.getElementsByTagName('*'));
if (getElems.length) {
tAP.gP = gPFncs[i];
tAP.pp = getElems[0].parentNode;
break;
}
}
function gCE(pElem) {
var r = [];
for (var i = 0, l = pElem.childNodes.length; i < l; i++) {
r.push(pElem.childNodes.item(i))
}
return r;
}
if (!tAP.pp) {
return;
}
sendRequest.README = {
license: 'Public Domain',
url: 'http://jsgt.org/lib/ajax/ref.htm',
version: 0.516,
author: 'Toshiro Takahashi'
};
function chkAjaBrowser() {
var A, B = navigator.userAgent;
this.bw = {
safari: ((A = B.split('AppleWebKit/')[1]) ? A.split('(')[0].split('.')[0] : 0) >= 124,
konqueror: ((A = B.split('Konqueror/')[1]) ? A.split(';')[0] : 0) >= 3.3,
mozes: ((A = B.split('Gecko/')[1]) ? A.split(' ')[0] : 0) >= 20011128,
opera: ( !! window.opera) && ((typeof XMLHttpRequest) == 'function'),
msie: ( !! window.ActiveXObject) ? ( !! createHttpRequest()) : false
};
return (this.bw.safari || this.bw.konqueror || this.bw.mozes || this.bw.opera || this.bw.msie)
}
function createHttpRequest() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP')
} catch (B) {
try {
return new ActiveXObject('Microsoft.XMLHTTP')
} catch (A) {
return null
}
}
} else {
return null
}
}
};
function sendRequest(E, R, C, D, F, G, S, A) {
var Q = C.toUpperCase() == 'GET',
H = createHttpRequest();
if (H == null) {
return null
}
if ((G) ? G : false) {
D += ((D.indexOf('?') == -1) ? '?' : '&') + 't=' + (new Date()).getTime()
}
var P = new chkAjaBrowser(),
L = P.bw.opera,
I = P.bw.safari,
N = P.bw.konqueror,
M = P.bw.mozes;
if (typeof E == 'object') {
var J = E.onload;
var O = E.onbeforsetheader
} else {
var J = E;
var O = null
}
if (L || I || M) {
H.onload = function () {
J(H);
H.abort()
}
} else {
H.onreadystatechange = function () {
if (H.readyState == 4) {
J(H);
H.abort()
}
}
}
R = K(R, D);
if (Q) {
D += ((D.indexOf('?') == -1) ? '?' : (R == '') ? '' : '&') + R
}
H.open(C, D, F, S, A);
if ( !! O) {
O(H)
}
B(H);
H.send(R);
function B(T) {
if (!L || typeof T.setRequestHeader == 'function') {
T.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
}
return T
}
function K(X, V) {
var Z = [];
if (typeof X == 'object') {
for (var W in X) {
Y(W, X[W])
}
} else {
if (typeof X == 'string') {
if (X == '') {
return ''
}
if (X.charAt(0) == '&') {
X = X.substring(1, X.length)
}
var T = X.split('&');
for (var W = 0; W < T.length; W++) {
var U = T[W].split('=');
Y(U[0], U[1])
}
}
}
function Y(b, a) {
Z.push(encodeURIComponent(b) + '=' + encodeURIComponent(a))
}
return Z.join('&')
}
return H
}
function addNextPage(oj) {
if (oj.status == 404) {
tAP.remainFlg = false;
return;
}
var d = document.createElement("div");
d.innerHTML = oj.responseText;
var posts = tAP.gP(d.getElementsByTagName("*"));
if (posts.length < 2) {
tAP.rF = false;
return;
}
d = document.createElement("div");
d.className = "tumblrAutoPager_page_info";
tAP.pp.appendChild(d);
for (var i = 0; i < posts.length; i++) {
tAP.pp.appendChild(posts[i]);
}
var footer = $("footer");
footer ? footer.parentNode.appendChild(footer) : null;
tAP.rF = true;
}
watch_scroll();
function watch_scroll() {
var d = document.compatMode == "BackCompat" ? document.body : document.documentElement;
var r = d.scrollHeight - d.clientHeight - (d.scrollTop || document.body.scrollTop);
if (r < d.clientHeight * 2 && tAP.rF) {
tAP.rF = false;
p++;
sendRequest(addNextPage, "", "GET", "http://" + tAP.LN + "/page/" + p, true);
}
setTimeout(arguments.callee, 200);
};
function $(id) {
return document.getElementById(id)
};
},
switchAutoPage: function () {
this.rF = !this.rF;
var aE = document.getElementsByTagName('*');
for (var i = 0, l = aE.length; i < l; i++) {
if (aE[i].className == "tAP_switch") {
aE[i].firstChild.nodeValue = this.rF ? "AutoPage[OFF]" : "AutoPage[ON]";
}
}
}
};
window.addEventListener ? window.addEventListener('load', tumblrAutoPager.init, false) : window.attachEvent ? window.attachEvent("onload", tumblrAutoPager.init) : window.onload = tumblrAutoPager.init;

Cross date picker default date issue

hello all i am using the following js code to convert the input type date into three different text boxes for day,month and year.
js
(function () {
var sign = function(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
};
// TODO Calcular año bisiesto
var bisiesto = function(year)
{
return true;
// return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 1 : 0;
};
$.fn.insertAt = $.fn.insertAt || function(index, $parent) {
return this.each(function() {
if (index === 0) {
$parent.prepend(this);
} else {
$parent.children().eq(index - 1).after(this);
}
});
};
var Crossdp = function(e, o) {
if (e.data("cross-datepicker")) {
return this;
}
e.attr("type", "text");
o = $.extend({}, $.fn.cdp.defaults, o);
if(o.hideInput)
e.hide();
var cnt = $("<div>").addClass(o.classes.container || "").data("input", e).insertBefore(e);
// Data
var days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Read format
var d = $("<select>").addClass(o.classes.controls || "").addClass(o.classes.days || ""),
m = $("<select>").addClass(o.classes.controls || "").addClass(o.classes.months || ""),
y = $("<select>").addClass(o.classes.controls || "").addClass(o.classes.year || "");
/**
* Gets the format metadata.
*/
var getFormat = function(format) {
var f = {},
last = "",
order = 0,
elements = {
"d": d,
"m": m,
"y": y
};
for(var i = 0, of=format; i < of.length; i++) {
var c = of[i];
if(last == c) {
f[c].count ++;
}
else if(c == "d" || c == "y" || c == "m") {
f[c] = {
"count": 1,
"order": order++,
"e": elements[c]
};
elements[c].data("order", f[c].order);
last = c;
}
if(order > 3) {
throw "Invalid date format";
}
}
return f;
};
var iF = getFormat(o.inputFormat),
f = getFormat(o.format);
for(var i in f) {
f[i].e.appendTo(cnt);
}
cnt.sort(function(a, b) {
if(a.data("order") > b.data("order")) {
return 1;
}
else if(a.data("order") < b.data("order")) {
return -1;
}
else {
return 0;
}
});
// Helpers
/**
* Format a numeric day to string.
*/
var formatDay = function(day, format) {
var text = String(day),
c = format || f.d.count;
while(c > text.length) {
text = "0" + text;
}
return text;
};
/**
* Format a numeric month to string.
*/
var formatMonth = function(month, format) {
if(month > 12) {
throw "Invalid month: "+month;
}
var c = format || f.m.count,
text = String(month);
if(c == 2) {
if(text.length == 1) {
text = "0" + text;
}
}
else if(c == 3) {
text = o.months[i-1].substr(0, 3);
}
else if(c == 4) {
text = o.months[i-1];
}
else {
throw "Invalid month format";
}
return text;
};
/**
* Format a numeric month to string.
*/
var formatYear = function(year, format) {
var text = String(year),
c = format || f.y.count;
if(c == 2) {
text = text.substr(text.length-2, 2);
}
else if(c != 4) {
throw "Invalid year format";
}
return text;
};
var parseYear = function(date, format) {
// TODO
};
// Update input function
var formatDate = function(resultFormat, readFormat, years, months, days) {
var a = ["d", "m", "y"],
result = resultFormat;
if(typeof days === 'string')
days = parseInt(days);
if(typeof months === 'string')
months = parseInt(months);
if(typeof years === 'string')
years = parseInt(years);
for(var i = 0; i < a.length; i++) {
var ch = a[i], /* Example: a[0]='d' */
format = readFormat[ch], /* Example: uF['d']='dd' */
word = "",
formatted = "";
for(var j = 0; j < format.count; j++) {
word += ch;
}
if(ch == "d") {
formatted = formatDay(days, format.count);
}
else if(ch == "m") {
formatted = formatMonth(months, format.count);
}
else {
formatted = formatYear(years, format.count);
}
result = result.replace(word, formatted);
}
return result;
};
var updateInput = function() {
e.val(formatDate(o.inputFormat, iF, y.val(), m.val(), d.val()));
};
this.updateInput = function() {
updateInput();
};
var updateFromInput = function() {
// TODO
};
// Generate 3 selects
/* Days */
d.data("days", 0);
/**
* Days of determinated month.
*/
var generateDays = function(month) {
if(d.data("days") == days[month-1]) {
return;
}
var selected = parseInt(d.val() || "1");
d.html("");
if(month == 0) {
return;
}
if(o.addNullOption) {
d.append("<option value=''>"+o.nullOptionText+"</option>");
}
for(var i = 1; i <= days[month-1]; i++) {
$("<option>").attr("value", i).text(formatDay(i)).appendTo(d);
}
d.val(selected);
};
d.change(function() {
updateInput();
});
generateDays(1);
/* Months */
m.change(function() {
// Regenerate days
generateDays(parseInt($(this).val()));
updateInput();
});
if(o.addNullOption) {
m.append("<option value='0'>"+o.nullOptionText+"</option>");
}
for(var i = 1; i <= 12; i++) {
m.append("<option value='"+i+"'>"+formatMonth(i)+"</option>");
}
/* Years */
var from,
to;
if(typeof o.years[0] == 'string') {
var current = new Date().getFullYear(),
count;
if(o.years.length == 3) {
current += o.years[1];
count = o.years[2];
}
else {
count = o.years[1];
}
for(var i = current; i != current + count; i += sign(count)) {
y.append("<option value='"+i+"'>"+formatYear(i)+"</option>");
}
}
else {
for(var i = o.years[0]; i != o.years[1]; i += sign(o.years[1]-o.years[0])) {
y.append("<option value='"+i+"'>"+formatYear(i)+"</option>");
}
}
y.change(function() {
updateInput();
});
// Save
this.inputs = {
d: d,
y: y,
m: m
};
// Finish
if(e.data("initial-day")) {
$(function() {
$.fn.cdp.statics.fns.set(e, [
e.data("initial-year"),
e.data("initial-month"),
e.data("initial-day")]);
});
}
updateInput();
e.data("cross-datepicker", this);
};
$.fn.cdp = function (o, arg) {
var e = $(this);
if (e.length == 0) {
return this;
}
else if (e.length > 1) {
e.each(function () {
$(this).cdp(o);
});
return this;
}
if(!e.is("input")) {
throw "You can apply Cross-DatePicker only on an 'input' element";
}
if(typeof o === 'string') {
var st = $.fn.cdp.statics;
if(!st.fns[o]) {
console.error("Unknown function "+o);
}
st.fns[o](e, arg);
return this;
}
var cdp = new Crossdp(e, o);
return this;
}
$.fn.cdp.defaults = {
hideInput: true,
format: "d/mmm/yyyy",
inputFormat: "yyyy-mm-dd",
years: ["now", -100], // [initial year, final year] or ["now", relative years count] or ["now", relative years from, relative years count]
months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
addNullOption: false,
nullOptionText: "Select",
classes: {
container: "cdp-container",
controls: "cdp-select",
days: "cdp-d",
months: "cdp-m",
years: "cdp-y"
}
};
$.fn.cdp.statics = {
fns: {
set: function(e, arg) {
var st = $.fn.cdp.statics,
obj = e.data("cross-datepicker"),
y,m,d;
if($.isArray(arg)) {
y = arg[0];
m = arg[1];
d = arg[2];
}
else if(typeof arg === 'string') {
var array = arg.split("-");
y = parseInt(array[0]);
m = parseInt(array[1]);
d = parseInt(array[2]);
}
else {
y = arg.year || arg.y;
m = arg.month || arg.m;
d = arg.day || arg.d;
}
obj.inputs.y.val(String(y));
obj.inputs.m.val(String(m));
obj.inputs.d.val(String(d));
obj.updateInput();
}
}
};
})();
how to implement
html
<input type="date" data-initial-day="20" data-initial-year="2010" data-initial-month="64" />
<!-- Required scripts -->
<script src='https://code.jquery.com/jquery-2.1.0.min.js'></script>
<script src='../src/cross-datepicker.js'></script>
<script>
$(function() {
$("input[type='date']").cdp();
});
</script>
the problem is that the code works great when defined data-initial-year for month and day also but when i want to show the default none selected date like select day select month and select year it shows blank or 0 .
i dont know how to solve this i have tried to solve the problem by adding some text into the js file but no help .
if you can suggest me something it would be great.
The plugin code needs to check if an entry is valid before setting it.
First off, set the addNullOption to true so that a "Select" text is visible.
$(function() {
$("input[type='date']").cdp({
addNullOption : true,
nullOptionText: "Select"
});
});
Then modify the last function $.fn.cdp.statics with the "check valid" code included below (demo):
$.fn.cdp.statics = {
fns: {
set: function(e, arg) {
var st = $.fn.cdp.statics,
obj = e.data("cross-datepicker"),
y,m,d;
if($.isArray(arg)) {
y = arg[0];
m = arg[1];
d = arg[2];
}
else if(typeof arg === 'string') {
var array = arg.split("-");
y = parseInt(array[0]);
m = parseInt(array[1]);
d = parseInt(array[2]);
}
else {
y = arg.year || arg.y;
m = arg.month || arg.m;
d = arg.day || arg.d;
}
// check valid
if ( obj.inputs.y.find('option[value="' + y + '"]').length ) {
obj.inputs.y.val(String(y));
}
if ( obj.inputs.m.find('option[value="' + m + '"]').length ) {
obj.inputs.m.val(String(m));
}
if ( obj.inputs.d.find('option[value="' + d + '"]').length ) {
obj.inputs.d.val(String(d));
}
obj.updateInput();
}
}
};
To show "Select" in the other selects, I ended up adding the following code because the year select didn't have a null option:
if (o.addNullOption) {
y.append("<option value='0'>"+o.nullOptionText+"</option>");
}
and changing the "check valid" code to:
// check valid
y = obj.inputs.y.find('option[value="' + y + '"]').length ? y : 0;
obj.inputs.y.val(String(y));
m = obj.inputs.m.find('option[value="' + m + '"]').length ? m : 0;
obj.inputs.m.val(String(m));
d = obj.inputs.d.find('option[value="' + d + '"]').length ? d : 0;
obj.inputs.d.val(String(d));
Get the full code from this updated demo.

Google calendar event list jQuery formatting

I've been at it all day trying to find a good solution to displaying a google calendar in a list format on a website i'm developing. I came across this piece of code which works quite well except a few formatting problems. I'm not all that clued up on jQuery so I'm struggling with the formatting. I've done as much as I can from the CSS side but clearly some of it is in the script side. Maybe if someone could please help me remove the formatting in the script and have strictly css that would be great =) or another better solution =P
Thanks so much!
The format i'm after is 3 sections in different divs:
date('nov 12, 09:00') event('Student Night') location('Nicci Beach')
JS:
// Generated by CoffeeScript 1.4.0
(function() {
var $, gCalFlow, log, methods, pad_zero, _ref;
$ = jQuery;
if ((typeof window !== "undefined" && window !== null) && (window._gCalFlow_debug != null) && (typeof console !== "undefined" && console !== null)) {
log = console;
if ((_ref = log.debug) == null) {
log.debug = log.log;
}
} else {
log = {};
log.error = log.warn = log.log = log.info = log.debug = function() {};
}
pad_zero = function(num, size) {
var i, ret, _i, _ref1;
if (size == null) {
size = 2;
}
if (10 * (size - 1) <= num) {
return num;
}
ret = "";
for (i = _i = 1, _ref1 = size - ("" + num).length; 1 <= _ref1 ? _i <= _ref1 : _i >= _ref1; i = 1 <= _ref1 ? ++_i : --_i) {
ret = ret.concat("0");
}
return ret.concat(num);
};
gCalFlow = (function() {
gCalFlow.prototype.target = null;
gCalFlow.prototype.template = $("<div class=\"gCalFlow\">\n <div class=\"gcf-header-block\">\n <div class=\"gcf-title-block\">\n <span class=\"gcf-title\"></span>\n </div>\n </div>\n <div class=\"gcf-item-container-block\">\n <div class=\"gcf-item-block\">\n <div class=\"gcf-item-header-block\">\n <div class=\"gcf-item-date-block\">\n [<span class=\"gcf-item-daterange\"></span>]\n </div>\n <div class=\"gcf-item-title-block\">\n <strong class=\"gcf-item-title\"></strong>\n </div>\n </div>\n <div class=\"gcf-item-body-block\">\n <div class=\"gcf-item-description\">\n </div>\n <div class=\"gcf-item-location\">\n </div>\n </div>\n </div>\n </div>\n <div class=\"gcf-last-update-block\">\n LastUpdate: <span class=\"gcf-last-update\"></span>\n </div>\n</div>");
gCalFlow.prototype.opts = {
maxitem: 5,
calid: null,
mode: 'upcoming',
feed_url: null,
auto_scroll: false,
scroll_interval: 10 * 1000,
link_title: true,
link_item_title: true,
link_item_description: true,
link_target: '_blank',
item_description_in_html: false,
callback: null,
no_items_html: '',
globalize_culture: (typeof navigator !== "undefined" && navigator !== null) && (navigator.browserLanguage || navigator.language || navigator.userLanguage),
globalize_fmt_datetime: 'f',
globalize_fmt_date: 'D',
globalize_fmt_time: 't',
globalize_fmt_monthday: 'M',
date_formatter: function(d, allday_p) {
var fmtstr;
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.format != null)) {
if (allday_p) {
fmtstr = this.globalize_fmt_date;
} else {
fmtstr = this.globalize_fmt_datetime;
}
return Globalize.format(d, fmtstr);
} else {
if (allday_p) {
return "" + (d.getFullYear()) + "-" + (pad_zero(d.getMonth() + 1)) + "-" + (pad_zero(d.getDate()));
} else {
return "" + (d.getFullYear()) + "-" + (pad_zero(d.getMonth() + 1)) + "-" + (pad_zero(d.getDate())) + " " + (pad_zero(d.getHours())) + ":" + (pad_zero(d.getMinutes()));
}
}
},
daterange_formatter: function(sd, ed, allday_p) {
var endstr, ret;
ret = this.date_formatter(sd, allday_p);
if (allday_p) {
ed = new Date(ed.getTime() - 86400 * 1000);
}
endstr = '';
if (sd.getDate() !== ed.getDate() || sd.getMonth() !== ed.getMonth()) {
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.format != null)) {
endstr += Globalize.format(ed, this.globalize_fmt_monthday);
} else {
endstr += "" + (pad_zero(ed.getMonth() + 1)) + "-" + (pad_zero(ed.getDate()));
}
}
if (!allday_p && (sd.getHours() !== ed.getHours() || sd.getMinutes() !== ed.getMinutes())) {
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.format != null)) {
endstr += Globalize.format(ed, this.globalize_fmt_time);
} else {
endstr += " " + (pad_zero(ed.getHours())) + ":" + (pad_zero(ed.getMinutes()));
}
}
if (endstr) {
ret += " - " + endstr;
}
return ret;
}
};
function gCalFlow(target, opts) {
this.target = target;
target.addClass('gCalFlow');
if (target.children().size() > 0) {
log.debug("Target node has children, use target element as template.");
this.template = target;
}
this.update_opts(opts);
}
gCalFlow.prototype.update_opts = function(new_opts) {
log.debug("update_opts was called");
log.debug("old options:", this.opts);
this.opts = $.extend({}, this.opts, new_opts);
return log.debug("new options:", this.opts);
};
gCalFlow.prototype.gcal_url = function() {
if (!this.opts.calid && !this.opts.feed_url) {
log.error("Option calid and feed_url are missing. Abort URL generation");
this.target.text("Error: You need to set 'calid' or 'feed_url' option.");
throw "gCalFlow: calid and feed_url missing";
}
if (this.opts.feed_url) {
return this.opts.feed_url;
} else if (this.opts.mode === 'updates') {
return "https://www.google.com/calendar/feeds/" + this.opts.calid + "/public/full?alt=json-in-script&max-results=" + this.opts.maxitem + "&orderby=lastmodified&sortorder=descending";
} else {
return "https://www.google.com/calendar/feeds/" + this.opts.calid + "/public/full?alt=json-in-script&max-results=" + this.opts.maxitem + "&orderby=starttime&futureevents=true&sortorder=ascending&singleevents=true";
}
};
gCalFlow.prototype.fetch = function() {
var success_handler,
_this = this;
log.debug("Starting ajax call for " + (this.gcal_url()));
success_handler = function(data) {
log.debug("Ajax call success. Response data:", data);
return _this.render_data(data, _this);
};
return $.ajax({
success: success_handler,
dataType: "jsonp",
url: this.gcal_url()
});
};
gCalFlow.prototype.parse_date = function(dstr) {
var day, hour, m, min, mon, offset, ret, sec, year;
if (m = dstr.match(/^(\d{4})-(\d{2})-(\d{2})$/)) {
return new Date(parseInt(m[1], 10), parseInt(m[2], 10) - 1, parseInt(m[3], 10), 0, 0, 0);
}
offset = (new Date()).getTimezoneOffset() * 60 * 1000;
year = mon = day = null;
hour = min = sec = 0;
if (m = dstr.match(/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2}(?:\.\d+)?)(Z|([+-])(\d{2}):(\d{2}))$/)) {
year = parseInt(m[1], 10);
mon = parseInt(m[2], 10);
day = parseInt(m[3], 10);
hour = parseInt(m[4], 10);
min = parseInt(m[5], 10);
sec = parseInt(m[6], 10);
if (m[7] !== "Z") {
offset += (m[8] === "+" ? 1 : -1) * (parseInt(m[9], 10) * 60 + parseInt(m[10], 10)) * 1000 * 60;
}
} else {
log.warn("Time parse error! Unknown time pattern: " + dstr);
return new Date(1970, 1, 1, 0, 0, 0);
}
log.debug("time parse (gap to local): " + offset);
ret = new Date(new Date(year, mon - 1, day, hour, min, sec).getTime() - offset);
log.debug("time parse: " + dstr + " -> ", ret);
return ret;
};
gCalFlow.prototype.render_data = function(data) {
var ci, desc_body_method, ed, ent, et, etf, feed, ic, it, items, link, sd, st, stf, t, titlelink, _i, _len, _ref1, _ref2;
log.debug("start rendering for data:", data);
feed = data.feed;
t = this.template.clone();
titlelink = (_ref1 = this.opts.titlelink) != null ? _ref1 : "http://www.google.com/calendar/embed?src=" + this.opts.calid;
if (this.opts.link_title) {
t.find('.gcf-title').html($("<a />").attr({
target: this.opts.link_target,
href: titlelink
}).text(feed.title.$t));
} else {
t.find('.gcf-title').text(feed.title.$t);
}
t.find('.gcf-link').attr({
target: this.opts.link_target,
href: titlelink
});
t.find('.gcf-last-update').html(this.opts.date_formatter(this.parse_date(feed.updated.$t)));
it = t.find('.gcf-item-block');
it.detach();
it = $(it[0]);
log.debug("item block template:", it);
items = $();
log.debug("render entries:", feed.entry);
if (this.opts.item_description_as_html) {
desc_body_method = 'html';
} else {
desc_body_method = 'text';
}
if ((feed.entry != null) && feed.entry.length > 0) {
_ref2 = feed.entry.slice(0, +this.opts.maxitem + 1 || 9e9);
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
ent = _ref2[_i];
log.debug("formatting entry:", ent);
ci = it.clone();
if (ent.gd$when) {
st = ent.gd$when[0].startTime;
sd = this.parse_date(st);
stf = this.opts.date_formatter(sd, st.indexOf(':') < 0);
ci.find('.gcf-item-date').html(stf);
ci.find('.gcf-item-start-date').html(stf);
et = ent.gd$when[0].endTime;
ed = this.parse_date(et);
etf = this.opts.date_formatter(ed, et.indexOf(':') < 0);
ci.find('.gcf-item-end-date').html(etf);
ci.find('.gcf-item-daterange').html(this.opts.daterange_formatter(sd, ed, st.indexOf(':') < 0));
}
ci.find('.gcf-item-update-date').html(this.opts.date_formatter(this.parse_date(ent.updated.$t), false));
link = $('<a />').attr({
target: this.opts.link_target,
href: ent.link[0].href
});
if (this.opts.link_item_title) {
ci.find('.gcf-item-title').html(link.clone().text(ent.title.$t));
} else {
ci.find('.gcf-item-title').text(ent.title.$t);
}
if (this.opts.link_item_description) {
ci.find('.gcf-item-description').html(link.clone()[desc_body_method](ent.content.$t));
} else {
ci.find('.gcf-item-description')[desc_body_method](ent.content.$t);
}
ci.find('.gcf-item-location').text(ent.gd$where[0].valueString);
ci.find('.gcf-item-link').attr({
href: ent.link[0].href
});
log.debug("formatted item entry:", ci[0]);
items.push(ci[0]);
}
} else {
items = $('<div class=".gcf-no-items"></div>').html(this.opts.no_items_html);
}
log.debug("formatted item entry array:", items);
ic = t.find('.gcf-item-container-block');
log.debug("item container element:", ic);
ic.html(items);
this.target.html(t.html());
this.bind_scroll();
if (this.opts.callback) {
return this.opts.callback.apply(this.target);
}
};
gCalFlow.prototype.bind_scroll = function() {
var scroll_children, scroll_container, scroll_timer, scroller, state;
scroll_container = this.target.find('.gcf-item-container-block');
scroll_children = scroll_container.find(".gcf-item-block");
log.debug("scroll container:", scroll_container);
if (!this.opts.auto_scroll || scroll_container.size() < 1 || scroll_children.size() < 2) {
return;
}
state = {
idx: 0
};
scroller = function() {
var scroll_to;
log.debug("current scroll position:", scroll_container.scrollTop());
log.debug("scroll capacity:", scroll_container[0].scrollHeight - scroll_container[0].clientHeight);
if (typeof scroll_children[state.idx] === 'undefined' || scroll_container.scrollTop() >= scroll_container[0].scrollHeight - scroll_container[0].clientHeight) {
log.debug("scroll to top");
state.idx = 0;
return scroll_container.animate({
scrollTop: scroll_children[0].offsetTop
});
} else {
scroll_to = scroll_children[state.idx].offsetTop;
log.debug("scroll to " + scroll_to + "px");
scroll_container.animate({
scrollTop: scroll_to
});
return state.idx += 1;
}
};
return scroll_timer = setInterval(scroller, this.opts.scroll_interval);
};
return gCalFlow;
})();
methods = {
init: function(opts) {
var data;
if (opts == null) {
opts = {};
}
data = this.data('gCalFlow');
if (!data) {
return this.data('gCalFlow', {
target: this,
obj: new gCalFlow(this, opts)
});
}
},
destroy: function() {
var data;
data = this.data('gCalFlow');
data.obj.target = null;
$(window).unbind('.gCalFlow');
data.gCalFlow.remove();
return this.removeData('gCalFlow');
},
render: function() {
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.culture != null)) {
Globalize.culture(this.data('gCalFlow').obj.opts.globalize_culture);
}
return this.data('gCalFlow').obj.fetch();
}
};
$.fn.gCalFlow = function(method) {
var orig_args;
orig_args = arguments;
if (typeof method === 'object' || !method) {
return this.each(function() {
methods.init.apply($(this), orig_args);
return methods.render.apply($(this), orig_args);
});
} else if (methods[method]) {
return this.each(function() {
return methods[method].apply($(this), Array.prototype.slice.call(orig_args, 1));
});
} else if (method === 'version') {
return "1.2.5";
} else {
return $.error("Method " + method + " does not exist on jQuery.gCalFlow");
}
};
}).call(this);
HTML:
<div id="gcf-custom-template">
<div class="gcf-item-container-block">
<div class="gcf-item-block">
<div class="gcf-item-header-block">
<div class="gcf-item-title-block">
<div style="float: left; width 250px;"><a class="gcf-item-link"><span class="gcf-item-daterange">2012-02-01 09:00</span>:</a></div>
<div style="float: left; width 250px;"><a class="gcf-item-location">1-877-346-9707 w 55586#</a></div>
<div style="float: left; width 250px;"><strong><a class="gcf-item-title">Item Title of Your event</a></strong></div>
</div>
</div>
</div>
</div>
</div>
Script Call:
<script type="text/javascript">
var $ = jQuery;
$(function() {
$('#gcf-custom-template').gCalFlow({
calid: '4t0m1c.w07f#gmail.com',
maxitem: 50,
mode: 'updates',
date_formatter: function(d, allday_p) { return (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getYear().toString().substr(-2) }
});
});
</script>
Here is my solution to a similar problem, using moment.js for date formatting, markupjs for templating, and jQuery for general making life easier.
// a markup.js pipe which calls on moment.js for formatting
Mark.pipes.moment = function (date, format) {
return moment(new Date(date)).format(format);
};
// a markup.js pipe that tests if two dates are in the same month (difference between "1st-2nd december" and "30 november - 2 december")
Mark.pipes.diffmonth = function (date1, date2) {
moment1 = moment(new Date(date1));
moment2 = moment(new Date(date2));
var ret= moment1.month()!=moment2.month();
return ret;
};
// a markup.js pipe to filter an array
Mark.pipes.sift = function (arr, prop, val) {
return $.grep(arr,function(item) {
return item[prop] == val;
});
};
$(document).ready(loadCalendarData);
// this is a google calendar public full json feed (to have complete date and location information)
calendarURL = "http://www.google.com/calendar/feeds/6vv7tct80gv5tblahm5sg0vsos#group.calendar.google.com/public/full?alt=json-in-script&orderby=starttime&singleevents=true&sortorder=ascending&futureevents=true&callback=?";
function loadCalendarData() {
$.getJSON( calendarURL, applyTemplate);
}
function applyTemplate(cal_data) {
// format dates in french
moment.lang("fr");
// take cal_data, a google calendar json full feed. and extract VCALENDAR fields. Also extract a type field that distinguishes single day events from multiple day events.
var events = $.map(cal_data["feed"]["entry"], function (event) {
var url= $.grep(event["link"], function(link) {
return link["rel"]=="related";
});
return {
"summary": event["title"]["$t"],
"dtstart": event["gd$when"][0]["startTime"],
"dtend": event["gd$when"][0]["endTime"],
"url": url[0]?url[0]["href"]:"",
"location": event["gd$where"][0]["valueString"],
"type": (moment.duration(new Date(event["gd$when"][0]["endTime"])-new Date(event["gd$when"][0]["startTime"])).as("hours")<18)?"single":"multi"
};
});
// summary with url link if exists
Mark.includes.linked_summary = "{{if url}}<a href='{{url}}'>{{/if}}{{summary}}{{if url}}</a>{{/if}}";
// location in brackets if exists
Mark.includes.optional_location = "{{if location}} ({{location}}){{/if}}"
// separate list of evenings and multiple day/weeked events
var template =
"Les soirées à venir :<ul>{{events|sift>type>single}}"+
"<li>{{dtstart|moment>dddd|capcase}} {{dtstart|moment>D/M}}: {{linked_summary}}{{optional_location}}</li>"+
"{{/events}}</ul>"+
"<br>"+
"Les stages et weekends à venir (2013/2014):<ul>{{events|sift>type>multi}}"+
"<li>{{dtstart|moment>D}}{{if dtstart|diffmonth>`dtend`}}{{dtstart|moment>/M}}{{/if}}-{{dtend|moment>D/M}}: {{linked_summary}}{{optional_location}}</li>"+
"{{/events}}</ul>";
$("#web").html(Mark.up(template, {"events":events}));
}

Categories