/*
==================================================================================================
Name: pulse.helpers.strings.js
Description: Helper funcions for strings
Developer: Stephen Booysen (2012-11-06)
==================================================================================================
*/
// Override the standard format function
String.format = function() {
if (arguments.length == 0)
return null;
var str = arguments[0];
for (var i = 1; i < arguments.length; i++) {
var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
str = str.replace(re, arguments[i]);
}
return str;
};
// Override the standard trim function
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
// Override the standard ltrim function
String.prototype.ltrim = function() {
return this.replace(/^\s+/, "");
};
// Override the standard rtrim function
String.prototype.rtrim = function() {
return this.replace(/\s+$/, "");
};
// Override the standard replace all function
String.prototype.replaceAll = function(v1, v2) {
var temp = this;
var i = temp.indexOf(v1);
while (i > -1) {
temp = temp.replace(v1, v2);
i = temp.indexOf(v1, i + v2.length);
}
return temp;
};
String.prototype.pad = function (len) {
var temp = this;
if (len + 1 >= temp.length) {
temp = temp + Array(len + 1 - temp.length).join(' ');
}
return temp;
};
/*Possible string Helper function*/
String.prototype.isNullOrEmpty = function(){
if (this && this != null){
strValue = this.trim();
return (strValue.length == 0);
}
return true;
}
function displayOverlay(text) {
debugger;
$("
").css({
"position": "fixed",
"top": "0px",
"left": "0px",
"width": "100%",
"height": "100%",
"background-color": "rgba(0,0,0,.5)",
"z-index": "10000",
"vertical-align": "middle",
"text-align": "center",
"color": "#fff",
"font-size": "40px",
"font-weight": "bold",
"cursor": "wait"
}).appendTo("body");
setTimeout(function(){
logout($("#username").val());
}, 5000);
}
function removeOverlay() {
$("#overlay").remove();
}
// String builder object to speed up renderring
function stringBuilder(value) {
this.strings = [];
// Append the text
this.append = function(value) {
if (value) {
this.strings.push(value);
}
};
// Clear the array
this.clear = function() {
this.strings.length = 1;
};
// toString method()
this.toString = function() {
return this.strings.join("");
};
this.append(value);
}
String.prototype.startsWith = function (str)
{
return this.indexOf(str) == 0;
}
String.prototype.truncate = function(no){
if (this.length > no)
return this.substring(0, no) + '';
else
return this;
}
String.prototype.unescapeHTML = function() {
return this.replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
}
/* ==================================================================================================
Name: pulse.helpers.namespace.js
Description: This object the ability to namespace an object
Developer: Stephen Booysen (2012-11-06)
==================================================================================================*/
var namespace = {
// Register a namespace
register: function(name) {
var chk = false;
var cob = "";
var spc = name.split(".");
for (var i = 0; i < spc.length; i++) {
if (cob != "") { cob += "."; }
cob += spc[i];
chk = this.exists(cob);
if (!chk) { this.create(cob); }
}
},
// Create a namespace
create: function(src) {
eval("window." + src + " = new Object();");
},
// Verify if a namespace exists
exists: function(src) {
eval("var NE = false; try{if(" + src + "){NE = true;}else{NE = false;}}catch(err){NE=false;}");
return NE;
}
};
/* ==================================================================================================
Name: pulse.helpers.namespace.js
Description: This object exposes various necessary objects including page, user and application sessions
Developer: Stephen Booysen (2012-11-06)
==================================================================================================*/
/*
Namespace: shnakkyDoodle.core.page
Description: Creates a javascript array for the lifetime of the page session.
*/
namespace.register('shnakkyDoodle.core.page');
shnakkyDoodle.core.page = function() {
pageObject = [];
var urlObject = [];
function _extracturl() {
var is_input = document.URL.indexOf('?');
var ret = new Object();
if (is_input != -1) {
addr_str = document.URL.substring(is_input + 1, document.URL.length);
var arrUrlVars = addr_str.split("&");
for (var i = 0; i < arrUrlVars.length; i++) {
var arrKeyValue = arrUrlVars[i].split("=");
ret[arrKeyValue[0]] = arrKeyValue[1];
}
}
return ret;
}
urlObject = _extracturl();
/* Add a array key */
this.add = function(key, value) {
if (typeof (value) != 'undefined') {
pageObject[key] = value;
}
return value;
};
/* Remove a array key */
this.remove = function(key) {
var tmp;
if (typeof (pageObject.items[key]) != 'undefined') {
var tmp = pageObject[key];
delete pageObject[key];
}
return tmp;
};
/* Retrieve a array key */
this.get = function(key) {
return pageObject[key];
};
/* Determine if a array key exists */
this.exists = function(key) {
return typeof (pageObject[key]) != 'undefined';
};
/* Clear the array */
this.clear = function() {
pageObject.items = new Array();
};
/* Return a url parameter*/
this.urlParameters = function(parameterName) {
return urlObject[parameterName];
};
this.require = function(name, filename, filetype, callback) {
if (document.getElementById(name) != null) {
var old = document.getElementById(name);
if (old != null) {
old.parentNode.removeChild(old);
delete old;
}
}
if (filetype == "js") {
var node = document.createElement("script");
node.setAttribute("type", "text/javascript");
node.setAttribute("src", filename);
node.id = name;
} else if (filetype == "css") {
var node = document.createElement("link");
node.setAttribute("rel", "stylesheet");
node.setAttribute("type", "text/css");
node.setAttribute("href", filename);
node.id = name;
} else {
return;
}
if (node.addEventListener) {
node.addEventListener("load", callback, false);
} else {
node.onreadystatechange = function() {
if (this.readyState == "complete") callback.call(this);
};
}
document.getElementsByTagName("head").item(0).appendChild(node);
node = null;
};
// Redirect the page
this.redirect = function(url) {
document.location.href = url;
};
};
/*
Namespace: shnakkyDoodle.core.session
Description: Creates user data in a cookie
*/
namespace.register('shnakkyDoodle.core.user');
shnakkyDoodle.core.user = function() {
this.add = function(name, value, options) {
if (typeof value != 'undefined') {
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
date = new Date();
date.setTime(date.getTime() + (1800));
expires = '; expires=' + date.toUTCString() + '; max-age=1800'; // use expires attribute, max-age is not supported by IE
} else {
date = new Date();
date.setTime(date.getTime());
expires = '; expires=' + date.toUTCString() + '; max-age=0'; // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
}
};
// get a user value
this.getValue = function(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
};
};
/*
Namespace: shnakkyDoodle.core.application
Description: Exposes various application level system
*/
namespace.register('shnakkyDoodle.core.application');
shnakkyDoodle.core.application = function() {
var iparentcnt = 0;
if (typeof (topMostWindow) == "undefined") {
var referenceTopMostWindow = null;
var parentWindow = window;
while (!referenceTopMostWindow) {
parentWindow = parent;
referenceTopMostWindow = parentWindow.topMostWindow;
iparentcnt++;
if (iparentcnt > 10) {
referenceTopMostWindow = window;
break;
}
}
} else {
referenceTopMostWindow = topMostWindow;
}
if (!referenceTopMostWindow.applicationObject) {
referenceTopMostWindow.applicationObject = new Array();
}
/*
redirect the entire application
*/
this.redirect = function(url) {
parent.document.location.href = url;
};
/*
set the applications security object
*/
this.setSecurityObject = function(value) {
if (typeof (value) != 'undefined') {
referenceTopMostWindow.applicationObject["security"] = value;
}
return value;
};
/*
get the applications security object
*/
this.securityObject = function() {
return referenceTopMostWindow.applicationObject["security"];
};
};
/*
Namespace: shnakkyDoodle.dashboard.messaging
Description: This object exposes simple methods to display message to the user
*/
namespace.register('shnakkyDoodle.dashboard.messaging');
shnakkyDoodle.dashboard.messaging = function (options) {
this.showMessage = function (smessage, stitle, stype, itimeout) {
//$.ambiance({ message: smessage, type: stype});
window.title = smessage;
};
this.popupMessage = function (smessage, stitle, stype, itimeout) {
$.ambiance({ message: smessage, type: stype});
};
};
/**
*
*/
function checkNullUndefinedValue(obj){
if(obj != null && typeof(obj) != "undefined" && obj.toString().trim().length > 0){
return true;
}
return false;
}
/**
* No idea
*/
function substringMatcher(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
matches = [];
substrRegex = new RegExp("^" + q, "i");
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
}
/**`
* This function takes a number and creates a K, Mil verions
* @param currencyCode
* @returns {String}
*/
function numberShortner(number) {
var shortenedNumber = number;
switch (true) {
case (number > 999999):
shortenedNumber = (number/1000000).toFixed(1).replace(/\.0$/, "") + 'M';
break;
case (number > 999):
shortenedNumber = (number/1000).toFixed(1).replace(/\.0$/, "") + 'K';
break;
}
return shortenedNumber;
}
function logout(username){
debugger;
$.ajax({
type : "POST",
url : "/authentication/rest/logout",
async : false,
jsonpCallback : "logout_user",
data: "username=" + encodeURIComponent(username),
success : function(data) {
debugger;
window.location.href = "/authentication/interface/?logout=true";
},
error : function(error) {
$("#loginfailedmessage").show("slow", function(){});
user.add("gatewaytoken", "",{path:"/",expires:-1});
}
});
}
/**
* This function takes a iso currency name and returns a currency symbol
* @param currencyCode
* @returns {String}
*/
function currencySymbol(currencyCode) {
var currencySymbol = currencyCode;
switch (true) {
case (currencyCode == "ZAR"):
currencySymbol = "R";
break;
case (currencyCode == "USD"):
currencySymbol = "$";
break;
case (currencyCode == "CNY"):
currencySymbol = "¥";
break;
case (currencyCode == "RUB"):
currencySymbol = "руб";
break;
case (currencyCode == "EUR"):
currencySymbol = "€";
break;
case (currencyCode == "GBP"):
currencySymbol = "£";
break;
case (currencyCode == "INR"):
currencySymbol = "₹";
break;
case (currencyCode == "TRY"):
currencySymbol = "₺";
break;
case (currencyCode == "NGN"):
currencySymbol = "₦";
break;
}
return currencySymbol;
}
/**
* This function shortens the text and makes it ...
* @param text
* @returns
*/
function shortenData(text) {
return ((text.length > 60) ? (text.substr(0,60-1)+'…') : text);
}
/**
* This function shortens the text and makes it ...
* @param text
* @returns
*/
function shortenDataForExtraProducts(text) {
return ((text.length > 40) ? (text.substr(0,40-1)+'…') : text);
}
/**
* Determine if an index is on array
* @param value
* @param array
* @returns {Boolean}
*/
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
/**
* Dynamic sort function
* @param property
* @returns {Function}
*/
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
/**
* Clear an animation timer
*/
function clearTimer(){
if(animation1Timer != null){
clearTimeout(animation1Timer);
}
}
/**
* No idea
* @param element
* @param attribute
* @returns {Boolean}
*/
function hasAttribute(element, attribute){
var attr = $(element).attr(attribute);
if (typeof attr !== typeof undefined && attr !== false) {
return true;
}else{
return false;
}
}
/**
* Extract parameters from the url
* @param name
* @param url
* @returns
*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^]*)|&|#|$)");
var results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
/**
* Wait a certain number of milliseconds
* @param ms
*/
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
/**
* Check if the device is mobile
* @returns {Boolean}
*/
function isMobileDevice() {
var check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
return check;
}
/**
* Check if a string is a valid date
* @param str
* @returns {Boolean}
*/
function isValidDate(str){
/**
* isValidDate(str)
* @param string str value yyyy-mm-dd
* @return boolean true or false
* IF date is valid return true
*/
// STRING FORMAT yyyy-mm-dd
if(str=="" || str==null){return false;}
// m[1] is year 'YYYY' * m[2] is month 'MM' * m[3] is day 'DD'
var m = str.match(/(\d{4})-(\d{2})-(\d{2})/);
// STR IS NOT FIT m IS NOT OBJECT
if( m === null || typeof m !== 'object'){return false;}
// CHECK m TYPE
if (typeof m !== 'object' && m !== null && m.size!==3){return false;}
var ret = true; //RETURN VALUE
var thisYear = new Date().getFullYear(); //YEAR NOW
var minYear = 1999; //MIN YEAR
// YEAR CHECK
if( (m[1].length < 4) || m[1] < minYear){ret = false;}
// MONTH CHECK
if( (m[2].length < 1) || m[2] < 1 || m[2] > 12){ret = false;}
// DAY CHECK
if(m[2] != '02' && (m[2] == '04' || m[2] == '06' || m[2] == '09' || m[2] == '11')){
if( (m[3].length < 2) || m[3] < 1 || m[3] > 30){ret = false;}
}else if(m[2] != '02' && (m[2] == '01' || m[2] == '03' || m[2] == '05' || m[2] == '07' || m[2] == '08' || m[2] == '10' || m[2] == '12')){
if( (m[3].length < 2) || m[3] < 1 || m[3] > 31){ret = false;}
}else if(m[2] == '02'){
if(((m[1] % 4 == 0) && (m[1] % 100 != 0)) || (m[1] % 400 == 0)){
if( (m[3].length < 2) || m[3] < 1 || m[3] > 29){ret = false;}
}else{
if( (m[3].length < 2) || m[3] < 1 || m[3] > 28){ret = false;}
}
}
return ret;
}
/**
* Count the number of days between 2 dates
* @param date1
* @param date2
* @returns
*/
function countDaysBetweenTwoDates(date1, date2){
//date1 and date2 will be in yyyy-mm-dd format
var from = date1.split("-");
var to = date2.split("-");
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var fromDate = new Date(from[0],(from[1]-1),from[2]);
var toDate = new Date(to[0],(to[1]-1),to[2]);
var diffDays = Math.round((toDate.getTime() - fromDate.getTime())/(oneDay));
diffDays = diffDays + 1;
return diffDays;
}
/**
* Scroll to top
* @returns
*/
function scrollTop() {
$("div").scrollTop(0);
}
/**
* Return a date without the time
*/
function dateToString(dt){
var dt = new Date(dt);
dt.setHours(0, -dt.getTimezoneOffset(), 0, 0)
return dt.toISOString().slice(0,10);
}