/*
 * Scripts
 *
 */
jQuery(function($) {
 
	var Engine = {
		utils : {
			links : function(){
				$('a[rel*=external]').click(function(e){
					e.preventDefault();
					window.open($(this).attr('href'));						  
				});
			},
			mails : function(){
				$('a[href^=mailto:]').each(function(){
					var mail = $(this).attr('href').replace('mailto:','');
					var replaced = mail.replace('/at/','@');
					$(this).attr('href','mailto:'+replaced);
					if($(this).text() == mail) {
						$(this).text(replaced);
					}
				});
			}
		}
	};

	Engine.showcase = function(){
		var container = $('#showcase');
		if (container.length === 0) {
			return;
		}
		
		var items = container.find('div.item, div.item-a');
		
		if (items.length < 2) {
	//		return;
		}
		
		var current = items.index($(items).filter('.active'));

		var nav = $('<ul class="showcase-navig"><li class="prev"/><li class="next"/></ul>');

		var prev = $('<a href="#">Previous</a>').click(function(e){
			e.preventDefault();			
			cycle(-1);			
		});

		var next = $('<a href="#">Next</a>').click(function(e){
			e.preventDefault();			
			cycle(1);						
		});
		
		var counter = null;		
		
		var cycle = function(diff) {
			var newIndex = current + diff;
			
			items.eq(current).hide();
			
			if (newIndex < 0) {
				current = items.length - 1;
			}
			else if (newIndex === items.length) {
				current = 0;
			}
			else {
				current = newIndex;
			}
			
			//update counter if it exists
			if (counter !== null) {
				counter.html( parseInt(current+1, 10) + '/'+ items.length );			
			}
			
			//we don't want to fade as IE cannot handle PNG24 properly
			if (!$.browser.msie) {
				items.eq(current).fadeIn('slow');
			}
			else {
				items.eq(current + " image").show();
			}
			
		};
		
		nav.find('.prev').append(prev);
		nav.find('.next').append(next);
		
		if (container.hasClass('add-counter')) {
			counter = $('<li class="counter" />');
			counter.html( parseInt(current+1, 10) + '/'+ items.length );
			
			nav.append(counter);
		}
		
		items.hide().eq(0).show().before(nav);
	};

	Engine.showcase();
	Engine.utils.links();
	Engine.utils.mails();
	
});