Skip to content

Instantly share code, notes, and snippets.

@kosso
Created May 17, 2013 01:32
Show Gist options
  • Save kosso/5596362 to your computer and use it in GitHub Desktop.
Save kosso/5596362 to your computer and use it in GitHub Desktop.
Some handy Ti CommonJS module functions
// Various useful functions.
function dateformat (format, timestamp) {
var that = this,
jsdate, f, formatChr = /\\?([a-z])/gi,
formatChrCb,
// Keep this here (works, but for code commented-out
// below for file size reasons)
//, tal= [],
_pad = function (n, c) {
if ((n = n + '').length < c) {
return new Array((++c) - n.length).join('0') + n;
}
return n;
},
txt_words = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
formatChrCb = function (t, s) {
return f[t] ? f[t]() : s;
};
f = {
// Day
d: function () { // Day of month w/leading 0; 01..31
return _pad(f.j(), 2);
},
D: function () { // Shorthand day name; Mon...Sun
return f.l().slice(0, 3);
},
j: function () { // Day of month; 1..31
return jsdate.getDate();
},
l: function () { // Full day name; Monday...Sunday
return txt_words[f.w()] + 'day';
},
N: function () { // ISO-8601 day of week; 1[Mon]..7[Sun]
return f.w() || 7;
},
S: function () { // Ordinal suffix for day of month; st, nd, rd, th
var j = f.j();
return j > 4 && j < 21 ? 'th' : {1: 'st', 2: 'nd', 3: 'rd'}[j % 10] || 'th';
},
w: function () { // Day of week; 0[Sun]..6[Sat]
return jsdate.getDay();
},
z: function () { // Day of year; 0..365
var a = new Date(f.Y(), f.n() - 1, f.j()),
b = new Date(f.Y(), 0, 1);
return Math.round((a - b) / 864e5) + 1;
},
// Week
W: function () { // ISO-8601 week number
var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3),
b = new Date(a.getFullYear(), 0, 4);
return _pad(1 + Math.round((a - b) / 864e5 / 7), 2);
},
// Month
F: function () { // Full month name; January...December
return txt_words[6 + f.n()];
},
m: function () { // Month w/leading 0; 01...12
return _pad(f.n(), 2);
},
M: function () { // Shorthand month name; Jan...Dec
return f.F().slice(0, 3);
},
n: function () { // Month; 1...12
return jsdate.getMonth() + 1;
},
t: function () { // Days in month; 28...31
return (new Date(f.Y(), f.n(), 0)).getDate();
},
// Year
L: function () { // Is leap year?; 0 or 1
return new Date(f.Y(), 1, 29).getMonth() === 1 | 0;
},
o: function () { // ISO-8601 year
var n = f.n(),
W = f.W(),
Y = f.Y();
return Y + (n === 12 && W < 9 ? -1 : n === 1 && W > 9);
},
Y: function () { // Full year; e.g. 1980...2010
return jsdate.getFullYear();
},
y: function () { // Last two digits of year; 00...99
return (f.Y() + "").slice(-2);
},
// Time
a: function () { // am or pm
return jsdate.getHours() > 11 ? "pm" : "am";
},
A: function () { // AM or PM
return f.a().toUpperCase();
},
B: function () { // Swatch Internet time; 000..999
var H = jsdate.getUTCHours() * 36e2,
// Hours
i = jsdate.getUTCMinutes() * 60,
// Minutes
s = jsdate.getUTCSeconds(); // Seconds
return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3);
},
g: function () { // 12-Hours; 1..12
return f.G() % 12 || 12;
},
G: function () { // 24-Hours; 0..23
return jsdate.getHours();
},
h: function () { // 12-Hours w/leading 0; 01..12
return _pad(f.g(), 2);
},
H: function () { // 24-Hours w/leading 0; 00..23
return _pad(f.G(), 2);
},
i: function () { // Minutes w/leading 0; 00..59
return _pad(jsdate.getMinutes(), 2);
},
s: function () { // Seconds w/leading 0; 00..59
return _pad(jsdate.getSeconds(), 2);
},
u: function () { // Microseconds; 000000-999000
return _pad(jsdate.getMilliseconds() * 1000, 6);
},
I: function () { // DST observed?; 0 or 1
// Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC.
// If they are not equal, then DST is observed.
var a = new Date(f.Y(), 0),
// Jan 1
c = Date.UTC(f.Y(), 0),
// Jan 1 UTC
b = new Date(f.Y(), 6),
// Jul 1
d = Date.UTC(f.Y(), 6); // Jul 1 UTC
return 0 + ((a - c) !== (b - d));
},
O: function () { // Difference to GMT in hour format; e.g. +0200
var a = jsdate.getTimezoneOffset();
return (a > 0 ? "-" : "+") + _pad(Math.abs(a / 60 * 100), 4);
},
P: function () { // Difference to GMT w/colon; e.g. +02:00
var O = f.O();
return (O.substr(0, 3) + ":" + O.substr(3, 2));
},
T: function () { // Timezone abbreviation; e.g. EST, MDT, ...
return 'UTC';
},
Z: function () { // Timezone offset in seconds (-43200...50400)
return -jsdate.getTimezoneOffset() * 60;
},
// Full Date/Time
c: function () { // ISO-8601 date.
return 'Y-m-d\\Th:i:sP'.replace(formatChr, formatChrCb);
},
r: function () { // RFC 2822
return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb);
},
U: function () { // Seconds since UNIX epoch
return jsdate.getTime() / 1000 | 0;
}
};
this.date = function (format, timestamp) {
that = this;
jsdate = ((typeof timestamp === 'undefined') ? new Date() : // Not provided
(timestamp instanceof Date) ? new Date(timestamp) : // JS Date()
new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
);
return format.replace(formatChr, formatChrCb);
};
return this.date(format, timestamp);
}
function strtotime (str, now) {
var i, match, s, strTmp = '',
parse = '';
strTmp = str;
strTmp = strTmp.replace(/\s{2,}|^\s|\s$/g, ' '); // unecessary spaces
strTmp = strTmp.replace(/[\t\r\n]/g, ''); // unecessary chars
strTmp = strTmp.replace(/T/g, ' '); // unecessary chars
strTmp = strTmp.replace(/\.000Z/g, ''); // unecessary chars
if (strTmp == 'now') {
return (new Date()).getTime() / 1000; // Return seconds, not milli-seconds
} else if (!isNaN(parse = Date.parse(strTmp))) {
return (parse / 1000);
} else if (now) {
now = new Date(now * 1000); // Accept PHP-style seconds
} else {
now = new Date();
}
strTmp = strTmp.toLowerCase();
var __is = {
day: {
'sun': 0,
'mon': 1,
'tue': 2,
'wed': 3,
'thu': 4,
'fri': 5,
'sat': 6
},
mon: {
'jan': 0,
'feb': 1,
'mar': 2,
'apr': 3,
'may': 4,
'jun': 5,
'jul': 6,
'aug': 7,
'sep': 8,
'oct': 9,
'nov': 10,
'dec': 11
}
};
var process = function (m) {
var ago = (m[2] && m[2] == 'ago');
var num = (num = m[0] == 'last' ? -1 : 1) * (ago ? -1 : 1);
switch (m[0]) {
case 'last':
case 'next':
switch (m[1].substring(0, 3)) {
case 'yea':
now.setFullYear(now.getFullYear() + num);
break;
case 'mon':
now.setMonth(now.getMonth() + num);
break;
case 'wee':
now.setDate(now.getDate() + (num * 7));
break;
case 'day':
now.setDate(now.getDate() + num);
break;
case 'hou':
now.setHours(now.getHours() + num);
break;
case 'min':
now.setMinutes(now.getMinutes() + num);
break;
case 'sec':
now.setSeconds(now.getSeconds() + num);
break;
default:
var day;
if (typeof(day = __is.day[m[1].substring(0, 3)]) != 'undefined') {
var diff = day - now.getDay();
if (diff == 0) {
diff = 7 * num;
} else if (diff > 0) {
if (m[0] == 'last') {
diff -= 7;
}
} else {
if (m[0] == 'next') {
diff += 7;
}
}
now.setDate(now.getDate() + diff);
}
}
break;
default:
if (/\d+/.test(m[0])) {
num *= parseInt(m[0], 10);
switch (m[1].substring(0, 3)) {
case 'yea':
now.setFullYear(now.getFullYear() + num);
break;
case 'mon':
now.setMonth(now.getMonth() + num);
break;
case 'wee':
now.setDate(now.getDate() + (num * 7));
break;
case 'day':
now.setDate(now.getDate() + num);
break;
case 'hou':
now.setHours(now.getHours() + num);
break;
case 'min':
now.setMinutes(now.getMinutes() + num);
break;
case 'sec':
now.setSeconds(now.getSeconds() + num);
break;
}
} else {
return false;
}
break;
}
return true;
};
match = strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(?:\s(\d{1,2}:\d{2}(:\d{2})?)?(?:\.(\d+))?)?$/);
if (match != null) {
if (!match[2]) {
match[2] = '00:00:00';
} else if (!match[3]) {
match[2] += ':00';
}
s = match[1].split(/-/g);
for (i in __is.mon) {
if (__is.mon[i] == s[1] - 1) {
s[1] = i;
}
}
s[0] = parseInt(s[0], 10);
s[0] = (s[0] >= 0 && s[0] <= 69) ? '20' + (s[0] < 10 ? '0' + s[0] : s[0] + '') : (s[0] >= 70 && s[0] <= 99) ? '19' + s[0] : s[0] + '';
return parseInt(this.strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2]) + (match[4] ? match[4] / 1000 : ''), 10);
}
var regex = '([+-]?\\d+\\s' + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?' + '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday' + '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday)' + '|(last|next)\\s' + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?' + '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday' + '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday))' + '(\\sago)?';
match = strTmp.match(new RegExp(regex, 'gi')); // Brett: seems should be case insensitive per docs, so added 'i'
if (match == null) {
return false;
}
for (i = 0; i < match.length; i++) {
if (!process(match[i].split(' '))) {
return false;
}
}
return (now.getTime() / 1000);
}
function strip_tags (str, allowed_tags) {
// http://kevin.vanzonneveld.net
var key = '', allowed = false;
var matches = [];
var allowed_array = [];
var allowed_tag = '';
var i = 0;
var k = '';
var html = '';
var replacer = function (search, replace, str) {
return str.split(search).join(replace);
};
// Build allowes tags associative array
if (allowed_tags) {
allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
}
str += '';
// Match tags
matches = str.match(/(<\/?[\S][^>]*>)/gi);
// Go through all HTML tags
for (key in matches) {
if(key){
// Save HTML tag
html = matches[key].toString();
// Is tag not in allowed list? Remove from str!
allowed = false;
// Go through all allowed tags
for (k in allowed_array) {
if(k){
// Init
allowed_tag = allowed_array[k];
i = -1;
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag) ;}
// Determine
if (i == 0) {
allowed = true;
break;
}
}
}
if (!allowed) {
str = replacer(html, "", str); // Custom replace. No regexing
}
}
}
return str;
}
function openCustomBrowser(currentWin,url, emailer, evals){
evals = null || evals;
//emailer = true || emailer; // show share via email button by default.
// curentWindow, url, [title, barcolor]
Ti.API.info('emailr : '+emailer);
if(Titanium.Platform.osname=='android'){
Ti.Platform.openURL(url);
return;
}
url = url.replace('Http://','http://');
url = url + '?from_app=true';
var current_url = url;
var w = Ti.UI.createWindow();
// w.orientationModes = [
// Titanium.UI.PORTRAIT
//];
w.tabBarHidden = true;
var top_view = Ti.UI.createView({
top:0,
left:0,
right:0,
zIndex:1,
backgroundColor:'#222',
bottom:0,
height:40
});
var logo = Ti.UI.createImageView({
image:'/images/amazing_logo1.png',
top:0,
right:60,
width:153,
height:40
});
top_view.add(logo);
var back_button = Titanium.UI.createButton({
width:80,
left:10,
height:40,
backgroundColor:'transparent',
backgroundImage:'/images/back.png'
});
top_view.add(back_button);
back_button.addEventListener('click',function(){
w.close({animated:true});
//post_win = null;
//back_button = null;
});
w.add(top_view);
//var win_title = 'web browser';
//if(t!=null){
// win_title = t;
//}
var barcol = '#222';
//if(c!=null){
// barcol = c;
//}
var flexSpace = Titanium.UI.createButton({
systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
});
var webwindow = Ti.UI.createWebView({top:40});
webwindow.url = url;
//w.backButtonTitle = '< back';
w.barColor = barcol;
//w.title = win_title;
w.add(webwindow);
/*
var loadIndBg = Ti.UI.createView({
width:80,
height:80,
backgroundColor:'#000000',
borderRadius:40,
opacity:0.5
});
webwindow.add(loadIndBg);
var loadInd = Ti.UI.createActivityIndicator({
height:50,
width:50,
style:Ti.UI.iPhone.ActivityIndicatorStyle.BIG
});
webwindow.add(loadInd);
*/
var back_button = Ti.UI.createButton({
image: '/images/btn_back.png',enabled:false
});
back_button.addEventListener('click', function(){
webwindow.goBack();
});
var forward_button = Ti.UI.createButton({
image: '/images/btn_fwd.png',enabled:false
});
forward_button.addEventListener('click', function(){
webwindow.goForward();
});
var refresh_button = Ti.UI.createButton({
systemButton:Ti.UI.iPhone.SystemButton.REFRESH
});
refresh_button.addEventListener('click', function(){
webwindow.reload();
});
w.toolbar = [back_button,flexSpace,refresh_button,flexSpace,forward_button];
webwindow.addEventListener('beforeload',function(e){
//Ti.API.info('BEFORELOAD e.url : '+e.url);
//loadIndBg.show();
//loadInd.show();
});
webwindow.addEventListener('load',function(e){
//loadIndBg.hide();
//loadInd.hide();
if(webwindow.canGoForward()){
forward_button.enabled = true;
} else {
forward_button.enabled = false;
}
if(webwindow.canGoBack()){
back_button.enabled = true;
} else {
back_button.enabled = false;
}
current_url = e.url;
Ti.API.info('LOAD e.url : '+e.url);
if(evals!=null){
webwindow.evalJS(evals);
}
//Ti.API.info('HTML: ');
//Ti.API.info(e.source.html);
});
/*
webwindow.addEventListener('swipe', function(e){
if(e.direction=='right'){
w.close({animated:true});
w = null;
webwindow = null;
}
});
*/
var send_link = Titanium.UI.createButton({
top:10,
right:10,
image:'images/email.png',
style:Titanium.UI.iPhone.SystemButtonStyle.PLAIN
});
if(emailer){
top_view.add(send_link);
}
// this makes sure the window opens
// currentWin is the currentwindow
if(currentWin!=undefined){
//Ti.API.info('currentWin:'+currentWin);
currentWin.tab.open(w);
}
send_link.addEventListener('click', function(e){
var fw = webwindow.toImage();
var oldFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'tune.jpg');
if(oldFile.exists()){
oldFile.deleteFile();
oldFile = null;
}
var newFile = Titanium.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'tune.jpg');
newFile.write(fw);
var at_img = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'tune.jpg');
var emailDialog = Titanium.UI.createEmailDialog({html:true,barColor:'#222'});
emailDialog.subject = "Check out this tune! : "+now_playing_tune.owner.display_name+" : "+now_playing_tune.title;
emailDialog.messageBody = "<b>I found this track you'll love on Amazing Radio</b><br />"+now_playing_tune.title+" : "+now_playing_tune.owner.display_name+"<br /><b>http://"+now_playing_tune.owner.permalink+".amazingtunes.com</b><br /><br />cheers!";
emailDialog.addAttachment(at_img);
emailDialog.open();
});
}
function trim (str, charlist) {
var whitespace, l = 0, i = 0;
str += '';
if (!charlist) {
whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
} else {
charlist += '';
whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
}
l = str.length;
for (i = 0; i < l; i++) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(i);
break;
}
}
l = str.length;
for (i = l - 1; i >= 0; i--) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(0, i + 1);
break;
}
}
return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}
function openWindow(win, url){
var heavy = true;
/*
if(os!='android'){
var back_button = Titanium.UI.createButton({
width:80,
height:40,
backgroundColor:'red',
backgroundImage:'/images/back.png'
});
//heavy = false;
}
*/
var post_win = Ti.UI.createWindow({
top:0,
left:0,
right:0,
bottom:0,
navBarHidden:heavy, // for android
//titleControl:titleView,
//backgroundGradient:row_gradient,
backgroundColor:'#333',
//barImage:'/images/bar_bg.png',
//backButtonTitle:'< back',
//barColor:'#222',
url:url
});
//if(os!='android'){
// post_win.leftNavButton = back_button;
//}
/*
if(os!='android'){
back_button.addEventListener('click',function(){
post_win.close({animated:true});
post_win = null;
back_button = null;
});
}
*/
//win.tab.open(post_win,{animated:true});
//alert('ok');
if(os=='android'){
post_win.open({animated:true});
} else {
win.tab.open(post_win,{animated:true});
}
}
exports.openWindow = openWindow;
exports.openCustomBrowser = openCustomBrowser;
exports.strip_tags = strip_tags;
exports.trim = trim;
exports.dateformat = dateformat;
exports.strtotime = strtotime;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment