Skip to content

Instantly share code, notes, and snippets.

@justinobney
Created May 9, 2012 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinobney/2641333 to your computer and use it in GitHub Desktop.
Save justinobney/2641333 to your computer and use it in GitHub Desktop.
PMSApp.js
/**
This file is placed at the top of every page
inheriting from BasePage.vb, thus all the following
functions are available from thos pages.
*/
/** @namespace */
var PMSApp = PMSApp || {};
(function (app) {
/** @public */
app.scripts = {
/** This is a collection of scripts that can be easily called from PMSApp.js */
jQuery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
tmpl: 'http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js'
//Example var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>" REQUIRES jQuery 1.4.3
};
app.Check_jQuery = function (callback) {
if (typeof jQuery == 'undefined') {
app.getScript("jQuery", function () {
if (typeof jQuery == 'undefined') {
alert("Javascript Error: Something went terribly wrong loading jQuery. Please report this bug.");
} else {
if (typeof jQuery_init != 'undefined') {
jQuery_init();
}
callback(); //It is loaded. The magic happens now.
}
});
} else { // jQuery was already loaded
callback();
if (typeof jQuery_init != 'undefined') {
jQuery_init();
}
}
};
/** Accepts a URL of a CSS file to load to the current page. Useful if a JS plugin needs a CSS file also. */
app.LinkCSS = function (href) {
//Link the stylesheet needed.
var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = href;
cssNode.media = 'screen';
headID.appendChild(cssNode);
};
/** This loads a script asynchronously and then calls a callback function if supplied. */
app.getScript = function (loadScript, success, breakCache) {
var scriptObj, script = document.createElement('script'),
head = document.getElementsByTagName('head')[0],
done = false;
// This would allow script loading to be called like: PMSApp.getScript("jQuery");
if (typeof this.scripts[loadScript] !== 'undefined') {
scriptObj = this.scripts[loadScript];
} else { //Otherwise use default behavior.
scriptObj = loadScript;
}
var scriptSource = scriptObj.js || scriptObj;
script.src = (typeof breakCache === 'undefined') ? scriptSource : (scriptSource + '?ver=' + this.version);
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
// callback function provided as param
if (typeof success === 'function') {
success();
}
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
if (scriptObj.css) {
app.LinkCSS(scriptObj.css);
}
};
// Shortcut for the for each loop.
// function has 3 paramaters available: fn(this,el,i)
// 1: this - the array looping over
// 2: el - the element during the iteration
// 3: i - the index of the 'el' in the array
app.each = function (arr, fn) {
for (var i = 0, arr_length = arr.length; i < arr_length; i++) {
fn.call(arr, arr[i], i);
}
};
app.Format = function (source, params) {
if (jQuery) {
if (arguments.length > 2 && params.constructor != Array) {
params = jQuery.makeArray(arguments).slice(1);
}
if (params.constructor != Array) {
params = [params];
}
jQuery.each(params, function (i, n) {
source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
});
return source;
} else {
alert("jQuery is not available to use PMSApp.Format");
}
};
/**
@private function: Used in quick_sort
*/
function partition(array, begin, end, pivot) {
var piv = array[pivot];
array.swap(pivot, end - 1);
var store = begin;
var ix;
for (ix = begin; ix < end - 1; ++ix) {
if (array[ix] <= piv) {
array.swap(store, ix);
++store;
}
}
array.swap(end - 1, store);
return store;
}
Array.prototype.swap = function (a, b) {
var tmp = this[a];
this[a] = this[b];
this[b] = tmp;
};
/**
@private function: Used in quick_sort
*/
function qsort(array, begin, end) {
if (end - 1 > begin) {
var pivot = begin + Math.floor(Math.random() * (end - begin));
pivot = partition(array, begin, end, pivot);
qsort(array, begin, pivot);
qsort(array, pivot + 1, end);
}
}
app.quick_sort = function (array) {
qsort(array, 0, array.length);
};
// Source: http://stackoverflow.com/questions/497790
// Get app.dates object
app.getScript('http://pms.mmrgrp.com/Javascript/PMSApp.datatypes.js');
app.Init = function () {};
app.pageInitFunctions = [];
app.registerInitFunction = function (fn) {
if (typeof fn !== "function") {
throw new TypeError("Only functions are valid parameters for registerInitFunction(fn)");
}
app.pageInitFunctions.push(fn);
};
app.ProcessPageInits = function () {
if (!app.pageInitFunctions.length) {
return;
}
for (var i = 0; i < app.pageInitFunctions.length; i++) {
var fn = app.pageInitFunctions.pop();
fn();
}
};
app.querystring = function () {
// by Chris O'Brien, prettycode.org
var collection = {};
// Gets the query string, starts with '?'
var querystring = window.location.search;
// Empty if no query string
if (!querystring) {
return {
toString: function () {
return "";
}
};
}
// Decode query string and remove '?'
querystring = decodeURI(querystring.substring(1));
// Load the key/values of the return collection
var pairs = querystring.split("&");
for (var i = 0; i < pairs.length; i++) {
// Empty pair (e.g. ?key=val&&key2=val2)
if (!pairs[i]) {
continue;
}
// Don't use split("=") in case value has "=" in it
var seperatorPosition = pairs[i].indexOf("=");
if (seperatorPosition == -1) {
collection[pairs[i]] = "";
} else {
collection[pairs[i].substring(0, seperatorPosition)] = pairs[i].substr(seperatorPosition + 1);
}
}
// toString() returns the key/value pairs concatenated
collection.toString = function () {
return "?" + querystring;
};
return collection;
};
app.cookie = {
create: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
},
read: function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
erase: function (name) {
createCookie(name, "", -1);
}
}
app.checkiPhone = function () {
var is_iPhone = false;
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
if (document.cookie.indexOf("iphone_redirect=false") == -1) {
is_iPhone = true;
}
}
return is_iPhone
};
// this method is a custom extension of jQuery object. The purpose is
// similar to the standard jQuery $.getJSON (notice capitalized G in mine)
// The reason for this is the standard method will not work with a URL in
// the form ASP_WebService.asmx/methodName. So I simply extended to $.ajax
// call to look like the native. Made above code A LOT more readable.
// *NOTE* : Must have url & callback arguments in param Object. SEE ABOVE USE
app.GetJSON = function (param) {
if (param.url && param.callback) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: param.url,
data: param.data || "{}",
dataType: "json",
dataFilter: function (data) {
if (data.hasOwnProperty('d')) {
return data.d;
} else {
return data;
}
},
success: function (data) {
var cleanData = (data.d) ? data.d : data;
param.callback(cleanData);
}
})
}
}; //$.GetJSON custom function
app.Init();
var slice = [].slice,
subscriptions = {};
app.publish = function (topic) {
var args = slice.call(arguments, 1),
topicSubscriptions, subscription, length, i = 0,
ret;
if (!subscriptions[topic]) {
return true;
}
topicSubscriptions = subscriptions[topic].slice();
for (length = topicSubscriptions.length; i < length; i++) {
subscription = topicSubscriptions[i];
ret = subscription.callback.apply(subscription.context, args);
if (ret === false) {
break;
}
}
return ret !== false;
},
app.subscribe = function (topic, context, callback, priority) {
if (arguments.length === 3 && typeof callback === "number") {
priority = callback;
callback = context;
context = null;
}
if (arguments.length === 2) {
callback = context;
context = null;
}
priority = priority || 10;
var topicIndex = 0,
topics = topic.split(/\s/),
topicLength = topics.length,
added;
for (; topicIndex < topicLength; topicIndex++) {
topic = topics[topicIndex];
added = false;
if (!subscriptions[topic]) {
subscriptions[topic] = [];
}
var i = subscriptions[topic].length - 1,
subscriptionInfo = {
callback: callback,
context: context,
priority: priority
};
for (; i >= 0; i--) {
if (subscriptions[topic][i].priority <= priority) {
subscriptions[topic].splice(i + 1, 0, subscriptionInfo);
added = true;
break;
}
}
if (!added) {
subscriptions[topic].unshift(subscriptionInfo);
}
}
return callback;
},
app.unsubscribe = function (topic, callback) {
if (!subscriptions[topic]) {
return;
}
var length = subscriptions[topic].length,
i = 0;
for (; i < length; i++) {
if (subscriptions[topic][i].callback === callback) {
subscriptions[topic].splice(i, 1);
break;
}
}
}
})(PMSApp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment