
function getPath(obj, key) {
    return key.split(".").reduce(function(o, x) {
        return (typeof o == "undefined" || o === null) ? o : o[x];
    }, obj);
}

function isSet(obj, key) {
    return key.split(".").every(function(x) {
        if(typeof obj != "object" || obj === null || ! x in obj)
            return false;
        obj = obj[x];
        return true;
    });
}

function getResponseErrors(variable, path, defaultMessage)
{
    var messages = "No Error Info provided.\n";

	if ( typeof(defaultMessage) != 'undefined' ) {
		messages = defaultMessage;
	}

    if ( isSet(variable, path) ) {
        messages = getPath(variable, path).join("\n");
        if ( messages != '' ) {
            messages += "\n";
        }
    }

    return messages;
}

function flash(message, state, timeout) {
    var $alert = $('<div class="alert"></div>');
    var $close = $('<button data-dismiss=".alert" class="close">&times;</button>');
    var $text  = $('<p class="alert-message"></p>');
    var remove = function() {
        $alert.fadeOut(function() {
            $(this).remove();
        });
    }

    $alert.addClass('alert-' + (state || 'info'));
    $alert.addClass('alert-floating');
    $close.on('click', remove);
    $text.html(message);
    $alert.append($close);
    $alert.append($text);
    $('body').append($alert);

    if (0 !== timeout) {
        setTimeout(remove, timeout || 3000);
    }
}

// Found this at: http://www.hashbangcode.com/blog/format-numbers-commas-javascript
function addCommas(nStr){
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
