//23 Mètode per emprar la consola sense que peti..
function firebug(text, type)
{
	if(window.console && window.console.firebug)
	{
		if ( typeof type == "undefined" ) type = 'log';
		eval("console."+type+"(text)");
	}
}

//23 Mètode "in_array" de JavaScript
Array.prototype.in_array = function(val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == val) {
			return true;
		}
	}
	return false;
}

//23 Mètode lcfirst
if ( typeof String.prototype.lcfirst !== "function" ) {
	String.prototype.lcfirst = function () {
		return this.substr(0,1).toLowerCase() + this.substr(1,this.length);
	};
}

//23 Mètode ucfirst
if ( typeof String.prototype.ucfirst !== "function" ) {
	String.prototype.ucfirst = function () {
		return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
	};
}

//23 Mètode trim
if(typeof String.prototype.trim !== "function") {
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/, ""); 
	}
}

//23 Mètode truncate
if(typeof String.prototype.truncate !== "function") {
	String.prototype.truncate = function(length, end) {
		if ( typeof length == "undefined" ) length = 100;
		if ( typeof end == "undefined" ) end = "...";
		return this.substr(0, length) + (this.length >= length ? " " + end : ""); 
	}
}

function sprintf ( ) {
	var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
	var a = arguments, i = 0, format = a[i++];

	// pad()
	var pad = function (str, len, chr, leftJustify) {
		if (!chr) {chr = ' ';}
		var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
		return leftJustify ? str + padding : padding + str;
	};

	// justify()
	var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
		var diff = minWidth - value.length;
		if (diff > 0) {
			if (leftJustify || !zeroPad) {
				value = pad(value, minWidth, customPadChar, leftJustify);
			} else {
				value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
			}
		}
		return value;
	};

	// formatBaseX()
	var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
		// Note: casts negative numbers to positive ones
		var number = value >>> 0;
		prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
		value = prefix + pad(number.toString(base), precision || 0, '0', false);
		return justify(value, prefix, leftJustify, minWidth, zeroPad);
	};

	// formatString()
	var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
		if (precision != null) {
			value = value.slice(0, precision);
		}
		return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
	};

	// doFormat()
	var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
		var number;
		var prefix;
		var method;
		var textTransform;
		var value;

		if (substring == '%%') {return '%';}

		// parse flags
		var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
		var flagsl = flags.length;
		for (var j = 0; flags && j < flagsl; j++) {
			switch (flags.charAt(j)) {
				case ' ': positivePrefix = ' '; break;
				case '+': positivePrefix = '+'; break;
				case '-': leftJustify = true; break;
				case "'": customPadChar = flags.charAt(j+1); break;
				case '0': zeroPad = true; break;
				case '#': prefixBaseX = true; break;
			}
		}

		// parameters may be null, undefined, empty-string or real valued
		// we want to ignore null, undefined and empty-string values
		if (!minWidth) {
			minWidth = 0;
		} else if (minWidth == '*') {
			minWidth = +a[i++];
		} else if (minWidth.charAt(0) == '*') {
			minWidth = +a[minWidth.slice(1, -1)];
		} else {
			minWidth = +minWidth;
		}

		// Note: undocumented perl feature:
		if (minWidth < 0) {
			minWidth = -minWidth;
			leftJustify = true;
		}

		if (!isFinite(minWidth)) {
			throw new Error('sprintf: (minimum-)width must be finite');
		}

		if (!precision) {
			precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
		} else if (precision == '*') {
			precision = +a[i++];
		} else if (precision.charAt(0) == '*') {
			precision = +a[precision.slice(1, -1)];
		} else {
			precision = +precision;
		}

		// grab value using valueIndex if required?
		value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

		switch (type) {
			case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
			case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
			case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
			case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
			case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
			case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
			case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
			case 'i':
			case 'd':
				number = parseInt(+value, 10);
				prefix = number < 0 ? '-' : positivePrefix;
				value = prefix + pad(String(Math.abs(number)), precision, '0', false);
				return justify(value, prefix, leftJustify, minWidth, zeroPad);
			case 'e':
			case 'E':
			case 'f':
			case 'F':
			case 'g':
			case 'G':
				number = +value;
				prefix = number < 0 ? '-' : positivePrefix;
				method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
				textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
				value = prefix + Math.abs(number)[method](precision);
				return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
			default: return substring;
		}
	};

	return format.replace(regex, doFormat);
}

var patterns = {
	email: /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/
}


/**
 * Mètode per a convertir els enllaços de les converses de Twitter
 * (23)
 */
if ( typeof String.prototype.twitterize !== "function" ) {
	String.prototype.twitterize = function() {
		var links = /(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp):\/\/)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(\/[a-zA-Z0-9\&amp;%_\.\/-~-]*)?/ig;
		var arrob = /@([a-z\-_0-9]+)/ig;
		var coixi = /#([a-z\-_0-9]+)/ig;
		return this.replace(links, function(){
			return '<a href="'+arguments[0]+'">'+arguments[0]+'</a>';
		}).replace(arrob, function(){
			return '@<a href="http://www.twitter.com/' + arguments[1] + '">'+arguments[1]+'</a>';
		}).replace(coixi, function(){
			return '#<a href="http://www.twitter.com/#search?q=%23' + arguments[1] + '">'+arguments[1]+'</a>';
		});
	}
}

function equals(x, y) {
	for(p in y) {
		if (typeof(x[p])=='undefined') {
			return false;
		}
	}

	for (p in y) {
		if (y[p]) {
			switch(typeof(y[p])) {
                case 'object':
                        if (!equals(x[p], y[p])) { return false }; break;
                case 'function':
                        if (typeof(x[p])=='undefined' || (p != 'equals' && y[p].toString() != x[p].toString())) { return false; }; break;
                default:
                        if (y[p] != x[p]) { return false; }
			}
		} else {
			if (x[p]) {
				return false;
			}
		}
	}

	for(p in x) {
		if(typeof(y[p])=='undefined') {return false;}
	}
	return true;
}

jQuery.fn.warning = function(text) {
	var close = jQuery("<a>").attr({href: "#close", title: "Tanca"})
				.append(jQuery("<img>").attr({src: webroot + "img/buttons/comment_alert_close.gif", alt: "X"})).click(function(e){
					$(this).parent().fadeOut(function() {$(this).remove();});
					e.preventDefault();
				});
	var capa = jQuery(document.createElement("div")).text(text)
				.append(close).css({
					position: "absolute",
					top: jQuery(this).position().top,
					left: jQuery(this).position().left,
					display: "none"
				}).addClass("comment-alert").appendTo(document.body).fadeIn("fast");
	
	setTimeout(function(){
		close.trigger("click");
	}, 5000);
}

/* Tamany d'un objecte! */
Object.size = function(obj) {
	var size = 0, key;
	for (key in obj) {
		if (obj.hasOwnProperty(key)) size++;
	}
	return size;
};

//23 Mètode per crear una capa d'alerta (tipus lightbox) amb un contingut donat
function createAlertBox(contents, title) {
	var $body = $(document.body);
	var sublayer = $('<div>', {id:"magic-layer"}).css('height', $body.height() + 'px').click(function(e) {
		if ( e.target.id == 'magic-layer' ) {
			sublayer.fadeOut(function() {
				$(this).remove();
			});
		}
	});
	var box = {
		heading: $('<div>').addClass('heading'),
		close: $('<a>', {href: '#close'}).text('TANCA').addClass('close').click(function(e){ 
					$("#magic-layer").fadeOut(function(){ $(this).remove() });
					e.preventDefault();
				}),
		title: $('<h1>').text('Alerta!'),
		wrapper: $('<div>').addClass('box'),
		content: $('<div>').addClass('content').html(contents)
	}
	
	var content = box.wrapper.append(box.heading.append(box.title).append(box.close)).append(box.content);
	$body.append(sublayer.append(content));
	
	// Set box top position
	var position = {
		window: $(window).scrollTop(),
		height: $(window).height(),
		getTop: function() {
			return position.window + (0.15 * position.height);
		}
	}
	console.log(position.getTop());
	content.css('margin-top', position.getTop() + 'px');
}
