/**
 * core.js
 * 
 * Core functions for DNA javascript.
 */

// Create DNA if it hasn't been already.
if (!dna) {
	var dna = {};
}

dna.namespace = function () {
    /// <summary>Creates the specified namespace ('some.namespace.goes.here').</summary>

    var a = arguments, o = null, i, j, d;
    for (i = 0; i < a.length; i = i + 1) {
        d = a[i].split(".");
        o = dna;
        for (j = 0; j < d.length; j = j + 1) {
            o[d[j]] = o[d[j]] || {};
            o = o[d[j]];
        }
    }
    return o;
};

var htmlEncode = function(value) {
	return $('<div/>').text(value).html();
};

var htmlDecode = function(value) {
	return $('<div/>').html(value).text();
};

// Check for console (ie7) and alert instead if fallback set to true.
var alertFallback = false;
if (typeof console === "undefined" || typeof console.log === "undefined") {
	console = {};
	if (alertFallback) {
		console.log = function(msg) {
			alert(msg);
		};
	} else {
		console.log = function() {
		};
	}
}

var Log = function () {
	/// <summary>
	///		Handle DNA Javascript logging. Right now we just log to the console if it exists, 
	///		but we could log errors to our servers as well.
	///	</summary>
	var _startTimes = {};
	var _showTiming = false;

	function _logToConsole(level, args) {
		// Log a debug message to the console.
		console.log(args);
	}
	
	function _logToServer(level, message, object) {
		// NOT IMPLEMENTED.
	}
	
	var _public = {
		
		debug: function () { 
			_logToConsole("DEBUG", arguments);
		},
	
		error: function () {
			_logToConsole("ERROR", arguments);
			_logToServer("ERROR", arguments);
		},
		
		d: function () {
			_logToConsole("DEBUG", arguments);
		},
		
		time: function (name) {
			if (console && console.time) {
				console.time(name);
			} else {
				_startTimes[name] = (new Date()).getTime();
			}
		},
		
		timeEnd: function (name) {
			if (_showTiming) {
				if (console && console.timeEnd) {
					console.timeEnd(name);
				} else {
					var time = (new Date()).getTime() - _startTimes[name];
					console.log(name + ": " + time);
				}
			}
		}
	};
	return _public;
}();

dna.namespace('util').Util = function() {
	var _public = {
		compare : function(a, b) {
			///<summary>Compares two numbers or strings (for use with sort)</summary>
			if (a < b) {
				return -1;
			} else if (a > b) {
				return 1;
			} else {
				return 0;
			}
		}
	};
	return _public;
}();

