drifterz28
2/12/2013 - 2:11 PM

JavaScript Helper functions. Comments in code

JavaScript Helper functions. Comments in code

// console logging with out breaking IE
function debug(msg){
    if (window.console){
        console.log(msg);
    }
}

// insert dom, does not reflow
var box2 = document.getElementById("box2");
box2.insertAdjacentHTML('beforebegin', '<div><p>This gets inserted.</p></div>');
/*
beforebegin
The HTML would be placed immediately before the element, as a sibling.
afterbegin
The HTML would be placed inside the element, before its first child.
beforeend
The HTML would be placed inside the element, after its last child.
afterend
The HTML would be placed immediately after the element, as a sibling.
*/

// gets current position from top.
document.documentElement.scrollTop

// run in function to get function name
// will not run in strict and is taxing
log(arguments.callee.name);

// Loop thru an object like for in loop but a for each.
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (fn, scope) {
        'use strict';
        var i, len;
        for (i = 0, len = this.length; i < len; ++i) {
            if (i in this) {
                fn.call(scope, this[i], i, this);
            }
        }
    };
}

// isset function like with php
function isset(pram) {
    return (typeof pram != 'undefined');
}

// suffle an array
function Shuffle(o) {
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
}

// money(number) provides a price with $ sign, 1234.234 would come out at 1,234.23
function money(price) {
    var n = price, c = 2, d = ".", t = ",",s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return '$'+s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

// cross domain JSONP with simple callback.
var jsonp = {
    // From http://javascriptweblog.wordpress.com/2010/11/29/json-and-jsonp/
    // Thank you.
    fetch: function(url, callback) {
        var fn = 'JSONPCallback';
        window[fn] = this.evalJSONP(callback);
        url = url.replace('=JSONPCallback', '=' + fn);
        var scriptTag = document.createElement('SCRIPT');
        scriptTag.src = url;
        document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
    },

    evalJSONP: function(callback){
        return function(data) {
            var validJSON = false;
            if (typeof data === "string") {
                validJSON = JSON.parse(data);
            } else {
                // found that I dont need to change to string and convert back.
                validJSON = data;
                //validJSON = JSON.parse(JSON.stringify(data));
            }
            if (validJSON) {
                callback(validJSON);
            } else {
                throw("JSONP call returned invalid or empty JSON");
            }
        }
    }
}

/**
 * Used to check if CSS is loaded and prevent noticalbe
 * FOUC
 */
function isCssReady(callback) {
    var testElem = document.createElement('span'),
        entry = document.getElementsByTagName('script')[0],
        node,
        count = 0,
        value = '';

    testElem.id = 'gp-css-ready'; // make sure this element is present in the stylesheet
    testElem.style.color = '#fff'; // and that this property is overriden by a unique color with a !important
    entry.parentNode.insertBefore(testElem, entry);
    
    (function poll() {
        node = document.getElementById('gp-css-ready');

        if (window.getComputedStyle) {
            value = document.defaultView.getComputedStyle(testElem, null).getPropertyValue('color');
        } else if (node.currentStyle) { // IE-specific
            value = node.currentStyle.color;
        }
        if (value && value === 'rgb(254, 220, 186)' || value.toLowerCase() === '#fedcba') {
            if(typeof callback === 'function'){
                callback();
            }
            return cssReady;
        } else {
            setTimeout(poll, 10);
        }

    }());
}

// find days in month
function daysInMonth(month,year) {
    year = (typeof year === 'undefined')? new Date().getFullYear() : year;
    return new Date(year, month, 0).getDate();
}

// pad numbers to include zeros
function pad(v){return ('0'+v).split('').reverse().splice(0,2).reverse().join('')}
pad(6)  // 06
pad(13) // 13

// turn get request into objec.
var qp = function() {
  return document.location.search.replace(/(^\?)/,'').split("&").map(function(n){return n=n.split('='),this[n[0]]=n[1],this}.bind({}))[0]
};

var toggleState = function(elem, one, two) {
  elem = (typeof elem === 'string') ? document.querySelector(elem) : elem;
  elem.setAttribute('data-state', elem.getAttribute('data-state') === one ? two : one);
}

// YYYYMMDD
new Date().toISOString().split('T')[0].split('-').join('');