/**
 * Used to log to the console.
 */
jQuery.fn.log = function (msg)
{
	try
	{
		if (console)
			console.log("%s: %o", msg, this);
	}
	catch(e) {}

	return this;
}

/**
 * Bootstrap - modified for static pages.
 */
function bootstrap(url) {

	var parts = url.substring(1).split("/");
	var page = "home";

	if (parts.length > 0 && parts[0] != '') {
		page = parts[0];
	}

	// Try to run the page specific function.
	try {
		routes[page]();
	}
	catch (e) {
		$(document).log("Bootstrap could not run for page ["+page+"] function.");
		$(document).log("error: " + e);
	}

}

/**
 * Patch in a case insensitive contains method to jQuery.
 */
jQuery.expr[':'].iContains = function(a,i,m){
	// @note: the second line should be better performance wise.
    // return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
   	return (a.textContent || a.innerText || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
};


/**
 * Patch in a method to allow removing items from an array.
 */
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};


/**
 * Trunacte function.
 * Tries to truncate after the end of a word - not mid way.
 * Appends '...' to the end if truncated.
 */
function truncate(val, len) {
	var trunc = val;

	if (trunc.length > len) {
		trunc = trunc.substring(0, len);
		trunc = trunc.replace(/\w+$/, '');
		trunc += "...";
	}

	return trunc;
}

/**
 * Add the ability to use regex in jQuery selectors.
 * http://james.padolsey.com/javascript/regex-selector-for-jquery/
 */
jQuery.expr[':'].regex = function(elem, index, match) {
	var matchParams = match[3].split(','),
		validLabels = /^(data|css):/,
		attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

jQuery.fn.exists = function(){return jQuery(this).length>0;}

/**
 * Hack in support for indexOf on arrays.
 */
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(elt /*, from*/) {
		var len = this.length;

		var from = Number(arguments[1]) || 0;
		from = (from < 0) ? Math.ceil(from) : Math.floor(from);
		if (from < 0) {
			from += len;
		}

		for (; from < len; from++) {
			if (from in this && this[from] === elt) {
				return from;
			}
		}
		return -1;
	};
}