// Global sliding speed
var slideSpeed = 250;

var mp3titles = new Array();
var mp3filenames = new Array();
var mp3index = 0;
var mp3paused = false;

// For use within normal web clients
var isiPad = navigator.userAgent.match(/iPad/i) != null;

$(document).ready(function() {
	/* Email Defuscator */
	$('.email').defuscate();

	/* Javascript verification */
	$('input[name="json"]').attr('value','yesitis!');

	/* Single Lightbox for a.lightbox */
	$('a.lightbox').each(function() {
		$(this).lightBox();
	});
	/* Lightbox Gallery for a.gallery*/
	$('a.gallery').lightBox();

	/*** Cufon font replacement ***/
	$(document).ready(function() {
		Cufon.replace('.helvetica, h1', {
			fontFamily: 'Helvetica LT',
			hover: true
		});
		Cufon.replace('.sans', {
			fontFamily: 'Neo Sans',
			hover: true
		});
	});
	
	var showDelay, hideDelay;
	var subMenuhideDelay;
	/*** Menu hover feature ***/
	$('li.mainMenuItem').hover(
		// User hovers over menuitem => Show the sub menu and hide all others
		function() {
			var id = parseInt($(this).attr('id').substr("mainMenuItem".length));

			clearTimeout(hideDelay);
			clearTimeout(subMenuhideDelay);

			// Hide all submenus, except the one we need to show
			$('ul.subMenuList:not(#subMenu' + id + ')')
				.hide()
				.data('over',false);

			$('li.mainMenuItem:not(#' + $(this).attr('id') +')').each(function() {
				imageHover($(this), false);
			});

			var mainMenuPos = $(this).position();
			var mainMenuWidth = $(this).outerWidth();

			// Show the one we want to show
			$('ul#subMenu' + id)
				.css('min-width', mainMenuWidth)
				.css('left', mainMenuPos.left + 'px');

			$('ul#subMenu' + id)
				.show()
				.data('over',true);

			imageHover(this, true);
		},
		// User leaves menuitem => Hide all sub menus again but show the active one
		function() {
			var self = this;

			hideDelay = setTimeout(function() {
				$('ul.subMenuList').hide();
				imageHover(self, false);
			}, 500);

			//imageHover(this, false);
		}
	);


	$('ul.subMenuList').hover(
		// User hovers over a submenu => Prevent the submenu from being hidden (by li.mainMenuItem's mouseout) and make sure its still visible
		function() {
			var menuId = $(this).attr('id').substr('subMenu'.length);
			var $mainMenu = $('#mainMenuItem' + menuId);

			clearTimeout(showDelay);
			clearTimeout(hideDelay);
			clearTimeout(subMenuhideDelay);

			$(this).show();
			imageHover($mainMenu, true);
		},

		// User leaves a submenu => Hide the submenu and show the active menu again
		function() {
			var id = $(this).attr('id');
			var menuId = $(this).attr('id').substr('subMenu'.length);
			var $mainMenu = $('#mainMenuItem' + menuId);

			// Hide all the menus
			$('ul.subMenuList:not(#' + id + ')').hide();

			// But the current one should fade out slowly and show active menu in the end
			subMenuhideDelay = setTimeout(function() {
				$('ul.subMenuList').hide();
				imageHover($mainMenu, false);
			}, 500);

		}
	);

	// If any submenuitem has a hover image => show the hover image if the user hovers of the submenuitem
	$('li.subMenuItem').hover(
		function() {
			// For iPads a hover is enough to trigger the link
			if(isiPad) location.href = $(this).find('a').attr('href');
		},
		function() {
		}
	);

	function imageHover(element, state) {
		// No effect if this is the currently visited page
		if($(element).hasClass('activeMenu')) return;
		
		$(element).toggleClass('active', state);

		if($(element).find('img.active').length > 0) {
			$(element).find('img.normal').toggle(! state);
			$(element).find('img.active').toggle(state);
		}
	}

	/*** Scrolling behavior ***/
	// Scrolls to the html-anchor one the user presses the link
	var relativeUpScroll = $('.arrowUpBox').height()/2;
	var relativeDownScroll = $('.arrowUpBox').outerHeight()
							+ $('.picture').outerHeight()
							+ parseInt($('.arrowDownBox').css('padding-top'))
							+ $('.arrowDownBox').height()/2;

	$('a.canScroll')
		.attr('onclick','return false')
		.click(function() {
			var settings = {
				axis: 'y',
				offset: {
					left: 0,
					top: 0
				}
			};

			var $target = $('a[name="' + $(this).attr('href').substr(1) + '"]');
			// scrollRelative ==> Keeps the arrows in the suite doku always above the cursor
			if ($(this).hasClass('scrollRelative')) {
				settings.offset.top = $(document).scrollTop() - $(this).offset().top;

				// If scrolling down => add distance between up arrow and down arrow (because $target is up arrow)
				if ($target.offset().top > $(this).offset().top)
					settings.offset.top += relativeDownScroll;
				else
					settings.offset.top += relativeUpScroll;
			}

			$.scrollTo($target, slideSpeed, settings);

			return 1;
		});

	/*** Icon hover behavior ***/
	// Images with the canHover class will have their image url changed to "[image]-active.png" if the user hovers on it
	$('.canHover').live({
		mouseover: function() {
			// Extracts the filename from the filepath
			// img[0] - complete filename
			// img[1] - filename without -active (if present) and without extension (e.g. .png)
			// img[2] - "-active" or undefined
			var img = $(this).find('img').attr('src').match(/([\w0-9]+)(-active)?\.png$/i);

			// Append '-active' to image
			if(img) {
				$(this).find('img').attr('src',
					$(this).find('img').attr('src').replace(img[0], img[1] + '-active.png')
				);
			}
		},
		mouseout: function() {
			var img = $(this).find('img').attr('src').match(/([\w0-9]+)(-active)?\.png$/i);

			// Remove '-active' suffix from image
			if(img) {
				$(this).find('img').attr('src',
					$(this).find('img').attr('src').replace(img[0], img[1] + '.png')
				);
			}
		}
	});

	function toggleParagraph($paraTitle, nextState) {
		$textPara = $paraTitle.parent().find('.textparagraph')

		if (nextState) {
			$textPara.addClass('expanded');
			$textPara.show(slideSpeed);
			$paraTitle.removeClass('canHover');
			$paraTitle.each(function() {
				$(this).find('img').attr('src',
					$(this).find('img').attr('src').replace(/Right(-active)?/, 'Down-active')
				);
			});
		// Otherwise return to default state and hide the content
		} else {
			$textPara.removeClass('expanded');
			$textPara.hide(slideSpeed);
			$paraTitle.addClass('canHover');
			$paraTitle.each(function() {
				$(this).find('img').attr('src',
					$(this).find('img').attr('src').replace('Down-active', 'Right')
				);
			});
		}
	}

	/*** Expand all button */
	$('.expandAll a').data('allExpand', false);
	$('.expandAll a').click(function() {
		var newState = ! $(this).data('allExpand');
		$(this).data('allExpand', newState);
		toggleParagraph($('.paragraphs:not(.leftCol) .paragraph h2'), newState);

		if (newState) {
			$(this).find('img').attr('src', $(this).find('img').attr('src').replace('ExpandAll', 'ContractAll'));
		} else {
			$(this).find('img').attr('src', $(this).find('img').attr('src').replace('ContractAll', 'ExpandAll'));
		}
		return false;
	});

	/*** Expandable paragraphs behavior, not for left column of 'referenzen' page ***/
	// This makes the single paragraphs expandable and contractable
	$('.paragraphs:not(.expanded)').each(function() {
		var $column = $(this);
		// Hide all textparagraphs and save it's 'expanded' state
		$column.find('.textparagraph:not(.expanded)')
			.hide()
			.data('expanded', false);

		// Already expanded elements? => Show expanded icon
		$column.find('.textparagraph.expanded').each(function() {
			$img = $(this).parent().find('h2 img');
			if($img.length > 0)
				$img.attr('src', $img.attr('src').replace(/Right(-active)?/, 'Down-active'));
			$(this).parent().find('h2').removeClass('canHover');
		});

		// For normal text pages (page.text) we only have expandable paragraphs
		// But for e.g. the 'referenzen' page there is a left column of paragraphs and a right column where behavior changes
		// Instead of expanding text below, it shows and expands a paragraph in the right column.
		// This behavior is not handled here, but in the code below.
		if (! $column.hasClass('leftCol')) {
			// On click, expand or hide the text below the paragraph
			$column.find('.paragraph h2.expandable a').click(function () {
				if($(this).attr('href').match(/^#anchor/))
					location.hash = $(this).attr('href').substr('#anchor'.length);
				
				var expanded = ! $(this).parent().parent().find('.textparagraph').hasClass('expanded');

				// Hide all others if one is shown
				if(expanded)
					toggleParagraph($(this).parent().parent().parent().find('.paragraph h2'), false)
				// Toggle this paragraph
				toggleParagraph($(this).parent(), expanded)

				return false;
			});
		}
	});

	/*
	 * leftparagraphs and rightparagraphs "menu" behavior
	 * For the left column of 'referenzen' page
	 */

	// Hide all paragraphs in the right column
	$('.paragraphs.rightCol a.anchor').hide();

	$('.paragraphs.rightCol .projects').data('expanded', false);

	// In page.projects.tpl we have defined the first element to
	// be opened, we also need to define it in the code here
	$('.paragraphs.rightCol .projects').first().data('expanded', true);

	// On click, show/hide the appropriate paragraph in the right column
	$('.paragraphs.leftCol:not(.expanded) .paragraph h2').click(function (event) {
		var anchor = $(this).find('a').attr('href').substr(1);
		var anchorBase = '';
		var $textPara = $('a[name="' + anchor + '"]').parent();
		
		// Special case: If we want to reference these paragraphs, the browsers shouldn't jump to them,
		// so they should be prefixed with 'anchor'
		if(! $textPara.length) {
			anchorBase = 'anchor';
			$textPara = $('a[name="' + anchorBase + anchor + '"]').parent();
			
			// For the hashtag, get the project id of the first expanded project. And if no project is expanded, get the first
			if($textPara.find('.textparagraph.expanded').length > 0)
				projectAnchor = $textPara.find('.textparagraph.expanded').parent().find('h2 a').attr('href').substr('#anchor'.length);
			else 
				projectAnchor = $textPara.find('.paragraph h2 a').attr('href').substr('#anchor'.length);
		}
		
		var nextState = ! $textPara.data('expanded');
		$textPara.data('expanded', nextState);

		// To expand: Hide all other paragraphs then show the selected one
		if(nextState) {
			// Set anchor in address bar
			if(anchorBase)
				location.hash = projectAnchor;

			// reshuffle the projects that they always slide downwards
			$textPara.parent().prepend($textPara);

			// Invoke hide on all other elements that are expanded
			$('.paragraphs.leftCol .paragraph h2').each(function() {
				var anch = $(this).find('a').attr('href').substr(1);
				
				if($('a[name="' + anchorBase + anch + '"]').parent().data('expanded') && anchor != anch) {
					$(this).trigger('click');
				}
			});

			$textPara.show(slideSpeed);
			$(this).removeClass('canHover');
			$(this).find('img').attr('src',
				$(this).find('img').attr('src').replace(/Right(-active)?/, 'Down-active')
			);

		// To hide: Just hide the current paragraph
		} else {
			$textPara.hide(slideSpeed);
			$(this).addClass('canHover');

			$(this).find('img').attr('src',
				$(this).find('img').attr('src').replace('Down-active', 'Right')
			);
		}
		
		return false;
	});

	// This line of code expands the first project of each company on the 'Referenzen' page
	toggleParagraph($('.projectsPage .rightCol .projects .paragraph:nth-child(2) h2.expandable'), true);
	// #123 => opens paragraph #anchor123, only on projects page
	if($('div.projectsPage').length > 0) {
		$paraLink = $('.rightCol a[href="#anchor' + window.location.hash.substr(1) + '"]');
		
		if($paraLink.length > 0 && window.location.hash.match(/^#\d+$/)) {
			company = $paraLink.parent().parent().parent().find('a').attr('name').substr('anchor'.length);
			
			$paragraph = $('.rightCol a[name="anchor' + company + '"]').parent();
			// Expand Company
			if(! $paragraph.data('expanded')) {
				$('.leftCol a[href="#' + company + '"]')
					.parent()
					.trigger('click');
			}
			// Expand project
			$textParagraph = $paraLink.parent().parent().find('.textparagraph:not(.expanded)');
			if($textParagraph.length > 0 && $textParagraph.data('expanded') != true) {
				$paraLink.trigger('click');
			}
			
		}
	}


	/*** Glossar Feature ***/
	// Hide all description boxes
	$('.glossarBox').hide();
	$('.glossarBox a:first-child').hide();
	$('.glossar ul:first li').data('visible',false);
	// On click, show the selected description box

	$('.glossar ul:first li').click(function() {
		var id = $(this).find('a').attr('href').substr(1);
		var visible = ! $(this).data('visible');

		if(visible) {
			$('.glossar ul:first li').data('visible', false);
			$('.glossar ul:first li').removeClass('visible');
			$(this).data('visible', visible);
			// Fade out all other
			$('.glossarBox :not(a[name="' + id + '"])').parent().fadeOut('fast');
			// Fade in selected box
			$('.glossarBox a[name="' + id + '"]').parent().fadeIn('fast');
			$(this).addClass('visible');
		} else {
			$('.glossarBox a[name="' + id + '"]').parent().fadeOut('fast');
			$(this).removeClass('visible');
		}

		return false;
	});
});


// Exports a n-th (idx) canvas to download
function Cufon2PNG(idx) {
	var i = 0;
	$('#menuBar canvas[width!="13"]').each(function() {
		if($(this).attr('width') <= 16) return;

		i++;
		// cheap id selection
		if(i-1 != idx) return;

		Canvas2Image.saveAsPNG($(this)[0]);
		///$('body').append('<img src="'+$(this)[0].toDataURL()+'">');
		//console.log($(this)[0].toDataURL());
	});
}

function Cufon2PNGinElem(elem, idx) {
	var i = 0;
	elem.find('canvas').each(function() {
		if($(this).attr('width') <= 16) return;

		i++;
		// cheap id selection
		if(i-1 != idx) return;

		Canvas2Image.saveAsPNG($(this)[0]);
	});
}

/*
 * Email Defuscator - jQuery plugin 1.0-beta2
 *
 * Copyright (c) 2007 Joakim Stai
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 *
 */

/**
 * Converts obfuscated email addresses into normal, working email addresses.
 *
 * @name defuscate
 * @param Boolean link If true, all defuscated email addresses will be turned into links, defaults to true (optional)
 * @param String find The regular expression used to search for obfuscated email addresses (optional)
 * @param String replace Replacement text for defuscating email addresses (optional)
 * @descr Converts obfuscated email addresses into normal, working email addresses
 */

jQuery.fn.defuscate = function( settings ) {
    settings = jQuery.extend({
        link: true,
        find: /\b([A-Z0-9._%-]+)\([^)]+\)((?:[A-Z0-9-]+\.)+[A-Z]{2,6})\b/gi,
        replace: '$1@$2'
    }, settings);
    return this.each(function() {
        if ( $(this).is('a[@href]') ) {
            $(this).attr('href', $(this).attr('href').replace(settings.find, settings.replace));
			$(this).html($(this).attr('href').substr(7));
            var is_link = true;
        }
        $(this).html($(this).html().replace(settings.find, (settings.link && !is_link ? '<a href="mailto:' + settings.replace + '">' + settings.replace + '</a>' : settings.replace)));
    });
};

