(function($) {

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

// open external links in new window
$(function() {
	var host = parseUri(window.location.href).host;
	$('#wrapper a').each(function() {
		var link_host = parseUri($(this).attr('href')).host;
		if (link_host && link_host != host) {
			$(this).attr('target', '_blank');
		}
	})
});

// music player
$(function() {
    var files = $('.file-type-music')
    var currentLink = null;
    if (files.length) {
		files.addClass('playable');
        $('<div id="jplayer"/>').appendTo('body').jPlayer({
            solution: 'flash, html',
            swfPath: '/media/js',
            ready: function() {
                var player = $(this);
                files.find('a').click(function() {
                    var link = $(this).parent();
                    var media = $(this).attr('href');
                    files.removeClass('playing');
                    if (this == currentLink) {
                        currentLink = null;
                        player.jPlayer('stop');
                    } else {
                        currentLink = this;
                        player.jPlayer('setMedia', { mp3: media });
                        player.jPlayer('play', 0);
                        link.addClass('playing');
                    }
                    return false;
                });
            },
            ended: function() {
                currentLink = null;
                files.removeClass('playing');
            },
            error: function(event) {
                console.log(event.jPlayer.error);
            }
        });
    }
});

// deobfuscate email addresses
$(function() {
	$('.email-address').each(function() {
		$(this).find('.hidden').remove();
		var text = $(this).text();
		var a = $('<a/>').attr('href', 'mailto:' + text).text(text);
		$(this).replaceWith(a);
	})
});

})(jQuery);

$(document).ready(function() {
	$("a.grouped_items").fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'	:	600, 
		'speedOut'	:	200, 
		'overlayShow'	:	true
	});
});
