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 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);
}
Date.prototype.toRelativeTime = function(now_threshold) {
	var delta = new Date() - this;

	now_threshold = parseInt(now_threshold, 10);

	if (isNaN(now_threshold)) {
		now_threshold = 0;
	}

	if (delta <= now_threshold) {
		return lang.now;
	}

	var units = null;
	var conversions = {
		millisecond: 1, // ms    -> ms
		second: 1000,   // ms    -> sec
		minute: 60,     // sec   -> min
		hour:   60,     // min   -> hour
		day:    24,     // hour  -> day
		month:  30,     // day   -> month (roughly)
		year:   12      // month -> year
	};

	for (var key in conversions) {
		if (delta < conversions[key]) {
			break;
		} else {
			units = key; // keeps track of the selected key over the iteration
			delta = delta / conversions[key];
		}
	}

	// pluralize a unit when the difference is greater than 1.
	delta = Math.floor(delta);
	if (delta !== 1)  units = eval("lang.time.plural." + units);
	else units = eval("lang.time.singular." + units);
	return sprintf(lang.time.rel_format, delta, units, lang.time.ago);
};
/*
 * Wraps up a common pattern used with this plugin whereby you take a String
 * representation of a Date, and want back a date object.
 */
Date.fromString = function(str) {
	return new Date(Date.parse(str));
};

function camelize(string) {
    var a = string.split('_'), i;
    s = [];
    for (i=0; i<a.length; i++){
        s.push(a[i].charAt(0).toUpperCase() + a[i].substring(1));
    }
    s = s.join('');
    return s;
}

function onError(data, section) {
    jQuery.each(data.data, function(model, errors) {
        for (fieldName in this) {
            var element = jQuery((typeof section != 'undefined' ? section + " " : "") + "#" + camelize(model + '_' + fieldName));
            var _insert = jQuery(document.createElement('span'));
			_insert.insertAfter(element).hide().addClass('error').text(this[fieldName]).slideDown();
        }
    });
};

function portfolioHover() {
	$(".portfolio-list").hover( function(e){
		$(this).find(".portfolio-thumbnail").stop(true, true).animate({ opacity: 'show' }, 'slow');
	}, function(e) {
		$(this).find(".portfolio-thumbnail").stop(true, true).animate({ opacity: 'hide' }, 'slow');
	});
}

$(document).ready(function($) { 

	$(".desc").hide();
	
	// Toggle slideshow
	$("#close-tab > a").click(function(e) {
		if ( !$(this).hasClass("hidded") ) {
			$(this).addClass("hidded");
			$(this).text(lang.show);
			$.cookie('slider', false);
		} else {
			$(this).removeClass("hidded");
			$(this).text(lang.hide);
			$.cookie('slider', true);
		}
		$("#slideshow-holder").animate({height: "toggle"}, 400);
		e.preventDefault();
	});
	
	var hash = window.location.hash;
	if ( hash != "#all" && hash != "" && $("h2.open-close#" + hash.replace("#","")).length) {
		$("h2.open-close#" + hash.replace("#","")).addClass("current").next(".desc").slideDown(400);
		$.scrollTo(hash, 300);
	}

	// Fancybox
	$(".covers a:has(img), .stylable a:has(img)").fancybox({
		"transitionIn"	: "elastic", 
		"transitionOut"	: "elastic",
		"overlayShow": false
	});

	// Testimonials
	$("#testimonials").faded({
		autoheight: 300,
		autoplay: 6e3,
		speed: 1e3,
		autopagination: false
	});
	
	$("h2.open-close").click(function(e){
		var $this = $(this);
		if ($(this).is(".current")) {
			$(this).removeClass("current");
			$(this).next(".desc").slideUp(400);
		} else {
			$(".desc").slideUp(400);
			$("h2.open-close").removeClass("current");
			$(this).addClass("current");
			$(this).next(".desc").slideDown(400, function() {
				$.scrollTo($this.children("a").attr("href"), 500);
				window.location.hash = $this.children("a").attr("href");
			});
		}
		e.preventDefault();
	});
	var email = "contact";
	var domain = "musicavermella";
	$("#contact-email").html("").append($("<a>", {href: "mailto:" + email + "@" + domain + ".com"}).text(email + " at " + domain + " dot com"));

	// Menu easing
	$("h2 a").hover(function() {
		$(this).find("span").stop().animate({ 
			marginLeft: "10" 
		}, 200);
	} , function() { 
		$(this).find("span").stop().animate({
			marginLeft: "0" 
		}, 200);
	});
	
	// Sliding tabs
	//Default Action
	$(".tab_content").hide(); //Hide all content
	$(".tabs li:first").addClass("active").show(); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content
	//On Click Event
	$(".tabs li").click(function() {
		$(".tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		return false;
	});

	// Releases thumbnail views
	var thumbs = $(".portfolio-list .portfolio-thumbnail");
	thumbs.hide();
	portfolioHover();
	
	$('#portfolio-filter li a:first').addClass('current');
	$('#portfolio-filter li a').click(function(e) {
		$('#portfolio-filter li a').removeClass('current');
		$(this).addClass('current');
		$.get( sys.webroot + sys.params.url.url + "/" +"releases/" +  $(this).attr('href').replace("#","") , function(data) {
			$('.portfolio-tiles-gallery').quicksand( $(data).find('li'), {
				adjustHeight: 'dynamic',
				attribute: function(v) {
					return $(v).find('img').attr('src');
				}
			}, function() {
				portfolioHover();
			});
		});
		e.preventDefault();
	});
	
	// Sliding tabs news
	//Default Action
	$(".news_content").hide(); //Hide all content
	$(".news li:first").addClass("active").show(); //Activate first tab
	$(".news_content:first").show(); //Show first tab content
	//On Click Event
	$(".news li").click(function(e) {
		$(".news li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".news_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		e.preventDefault();
	});
	
	// Contact form ajax and validation
	$("#ContactAddForm").submit(function(e) {
		var $this = $(this);
		$this.find(".error").fadeOut(function() {jQuery(this).remove()});
		$this.next().show().animate({opacity: .7}, 500);
		$.ajax({
			"type"	: "POST",
			"url"	: $this.closest("form").attr("action"),
			"dataType":"json",
			"data"	: $this.serializeArray(),
			"success": function(data, st) {
				if ( st == "success" ) {
					if ( data.success ) {
						$this.find(".text input, textarea").val("");
						$this.find(".submit-btn").prepend($("<span>").addClass("success").text(data.success.message));
					} else if ( data.errors ) {
						onError(data.errors);
					} else {
						alert("unknown error");
					}
				} else {
					alert(st);
				}
				$this.next().animate({opacity: .0}, 500, function() {
					$(this).hide();
				});
			}
		});
		e.preventDefault();
	});
});

// Nivo slider
$(window).load(function() {
	$('#slider').nivoSlider({
		effect:'random',
		slices:25,
		animSpeed:1000,
		pauseTime:4000,
		directionNav:true, //Next and Prev
		directionNavHide:true, //Only show on hover
		controlNav:true
	});
});
