
/**
 *  Requires:   prototype.js
 *  Manual:     http://www.prototypejs.org/api
 */


/* -------- GENERAL -------- */

function debug( str )
{
	if( typeof( console ) != 'undefined' ) console.log( str )
	else alert( str );
}

function hide( element )
{
	if( $( element ) )
	{
		$( element ).hide();
	}
}

function show( element, display )
{
	if( $( element ) )
	{
		$( element ).show();
	}
}

function printMailTo( email, label, subject )
{
	label    = ( typeof( label ) == 'string' ) ? label : email;

	var str  = '<a href="mailto:' + email.escapeHTML();
	str      += ( typeof( subject ) == 'string' ) ? '?subject=' + subject.escapeHTML(): '';
	str      += '">' + label.escapeHTML() + '</a>';
	document.write( str );
}

function getUrlParam( key )
{
	var value   = null;
	if( m = document.location.toString().match( RegExp( '([?]|&)' + key + '=([^&]*)(&|$)' ) ) )
	{
		value = m[2];
	}
	return value;
}


/* -------- DYNAMIC FEATURES -------- */

function embedLabel( id )
{
	var element  = $( id );
	if( element )
	{
		Event.observe( element, 'focus', function () { labelFocus( this ); } );
		Event.observe( element, 'blur', function () { labelBlur( this ); } );
	}
	labelBlur( element );
}

function labelFocus( element )
{
	if( element.hasClassName( 'label' ) )
	{
		element.value  = '';
		element.removeClassName( 'label' );
	}
}
function labelBlur( element )
{
	if( element.value == '' || element.value == element.getAttribute( 'labelValue' ) )
	{
		element.value  = element.getAttribute( 'labelValue' );
		element.addClassName( 'label' );
	}
}

function enableButton( buttonId, fieldId, type )
{
	type	= type.toLowerCase();
	if(
		! ( button = $( buttonId ) )
		|| ! ( field = $( fieldId ) )
		|| ( type != 'email' )
	)
	{
		return;
	}
	Event.observe( field, 'keyup', function () { enableButtonChange( buttonId, this.value, type ); } );
	Event.observe( field, 'change', function () { enableButtonChange( buttonId, this.value, type ); } );
	Event.observe( field, 'blur', function () { enableButtonChange( buttonId, this.value, type ); } );

	enableButtonChange( buttonId, field.value, type );
}

function enableButtonChange( buttonId, fieldValue, type )
{
	switch( type.toLowerCase() )
	{
		case 'email':
			$( buttonId ).disabled	=  fieldValue.match(
				/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
			)
			? false : true;
			break;
	}
}


/* -------- MAILING LIST -------- */

function submitMailingList( email )
{
   $( 'mailingListForm' ).update( '<p>Please wait...</p>' );

   new Ajax.Request( 'action.ajax.php', {
		method:		'post',
		parameters:	{ action: 'mailingList', email: email },
		onSuccess:	function( transport )
		{
			$( 'mailingListForm' ).update( transport.responseText );
		}
    } );
}


/* -------- EVENTS -------- */

function switchMap(element, mapHtml)
{
	var showLink	= element;
	Element.extend(element);
	if( element	= element.up('.event') )
	{
		if( element = element.select( '.map' )[0] )
		{
			var src	= ''
			if( !element.hasClassName( 'populated' ) && typeof( mapHtml ) == 'string' )
			{
				mapHtml		= mapHtml.replace(/( width=\"[0-9]+\")/g, '' );
				mapHtml		= mapHtml.replace(/( height=\"[0-9]+\")/g, '' );
				mapHtml		= mapHtml.replace(/( style=\"[^\"]+\")/g, '');

				element.update( mapHtml );
				element.addClassName( 'populated' );
			}
			element.toggle();
			showLink.update( ( ( showLink.innerHTML == 'hide map' ) ? 'show map' : 'hide map' ) )
		}
	}
}


/* -------- AUDIO PLAYER -------- */

var playerPopup;

function openFlowPlayer( type, path )   // FlowPlayer
{
	var params;
	if( typeof( type ) == 'string' && type.length > 0 && typeof( path ) == 'string' && path.length > 0 )
	{
		path  = path.replace( / /g, '%20' );
		switch( type )
		{
			case 'mp3':
				params = '?src=mp3/' + path;
				break;
			case 'flv':
				params = '?src=videos/' + path;
				break;
		}
	}

	//debug( params );
	var w = 468;
	var h = 350;
	var l = parseInt( ( screen.availWidth / 2 ) - ( w / 2 ) );
	var t = parseInt( ( screen.availHeight / 2 ) - ( h / 2 ) );
	playerPopup = window.open( 'flowplayer.html' + params, 'player', 'toolbar=0,location=0,menubar=0,directories=0,scrollbars=0,status=0,resizable=0,Width='+w+',Height='+h+',left='+l+',top='+t+',screenX='+l+',screenY='+t+'' );
	if( playerPopup && ! playerPopup.closed )
	{
		playerPopup.focus();
	}
}

function playlistObject()
{
	this.list   = new Array();

	this.add = function ( index, location )   // title, creator, image, group
	{
		this.list[ index ]   = new Object();
		this.list[ index ].location   = location;
	}
}

function playMp3( index )
{
	if( ! playerPopup || ( typeof( playerPopup.playMp3 ) != 'function' && typeof( playerPopup.playMp3 ) != 'object' ))
	{
		openPlayer( index );
	} else {
		playerPopup.playMp3( index );
		playerPopup.focus();
	}
}

function openPlayer( index )  // E-Phonic
{
	var params  = ( typeof( index ) == 'number' && index >= 0 ) ? '?index=' + index : '';
	var w = 269;
	var h = 226;
	var l = parseInt( ( screen.availWidth / 2 ) - ( w / 2 ) );
	var t = parseInt( ( screen.availHeight / 2 ) - ( h / 2 ) );
	playerPopup = window.open( 'ephonic.html' + params, 'player', 'toolbar=0,location=0,menubar=0,directories=0,scrollbars=0,status=0,resizable=0,Width='+w+',Height='+h+',left='+l+',top='+t+',screenX='+l+',screenY='+t+'' );
	playerPopup.focus();
}

function download( type, path )
{
	if( typeof( type ) == 'string' && type.length > 0 && typeof( path ) == 'string' && path.length > 0 )
	{
		path  = path.replace( / /g, '%20' );
		switch( type )
		{
			case 'mp3':
				window.location = 'mp3/' + path;
				break;
		}
	}
}

function Playlist()
{
	this.tracks = new Array();

	this.add = function ( creator, title, location )
	{
		var track      = Object();
		track.creator  = creator;
		track.title    = title;
		track.location = 'mp3/' + location;
		this.tracks[ this.tracks.length ]   = track;
	}

	// E-Phonic tracklist xml string
	this.trackListXml = function ()
	{
		var str  = '<trackList>';

		for( var i = 0; i < this.tracks.length; i++ )
		{
			str   += '<track>';
			str   += '<location>' + this.tracks[i].location + '</location>';
			str   += '<creator>' + this.tracks[i].creator + '</creator>';
			str   += '<title>' + this.tracks[i].title + '</title>';
			str   += '</track>' +"\n";
		}
		str  += '</trackList>';
		return str;
	}
}




function toggleAutoplay( element )
{
	Element.extend(element);

	var exdate	= new Date();
	exdate.setDate( exdate.getDate() + 30 );

	if( element.hasClassName( 'off' ) )		// Turn autoplay on
	{
		element.update( 'turn off autoplay' );
		element.removeClassName( 'off' );
		element.addClassName( 'on' );
		document.cookie	= 'autoplay=1' + ';expires=' + exdate.toGMTString();
		//debug( 'Turn autoplay on' + "\n"+ document.cookie );
	} else {											// Turn autoplay on
		element.update( 'turn on autoplay' );
		element.removeClassName( 'on' );
		element.addClassName( 'off' );
		document.cookie	= 'autoplay=0' + ';expires=' + exdate.toGMTString();
		//debug( 'Turn autoplay off' + "\n"+ document.cookie );
	}
}


/* -------- PHOTO GALLERY + VIDEO GALLERY  -------- */

var activeThumbnail;

function makeActiveThumbnail( element )
{
	clearActiveThumbnail();
	if( $( element ) )
	{
		activeThumbnail   = element;
		$( activeThumbnail ).removeClassName( 'seen' );
		$( activeThumbnail ).addClassName( 'active' );
	}
}
function clearActiveThumbnail()
{
	if( $( activeThumbnail ) )
	{
		$( activeThumbnail ).removeClassName( 'active' );
		$( activeThumbnail ).addClassName( 'seen' );
		activeThumbnail   = null;
	}
}


/* -------- PHOTO GALLERY -------- */

var photoOverlay;
var bodyOverlay;
var photoOverlayImages;
var photoCurrentImgId;
var photoCurrentThumbnail;
var photoImgIdPrefix = 'img_';

function initPhotos()
{
	if(
			( photoOverlay       = $( 'photoOverlay' ) )
		&& ( photoOverlayImages = $( 'photoOverlayImages' ) )
	)
	{
		if( $( 'backContainer' ) )
		{
			Event.observe( 'backContainer', 'click',			function( event ) { prevPhoto(); Event.stop( event ); });
			Event.observe( 'backContainer', 'contextmenu',	function( event ) { prevPhoto(); Event.stop( event ); });
			Event.observe( 'backContainer', 'mouseover',		function( event ) { showBackButton(); Event.stop( event ); });
			Event.observe( 'backContainer', 'mouseout', 		function( event ) { hideBackButton(); Event.stop( event ); });
		}

		if( $( 'nextContainer' ) )
		{
			Event.observe( 'nextContainer', 'click',			function( event ) { nextPhoto(); Event.stop( event ); });
			Event.observe( 'nextContainer', 'contextmenu',	function( event ) { nextPhoto(); Event.stop( event ); });
			Event.observe( 'nextContainer', 'mouseover',		function( event ) { showNextButton(); Event.stop( event ); });
			Event.observe( 'nextContainer', 'mouseout', 		function( event ) { hideNextButton(); Event.stop( event ); });
		}

		if( $( 'closeButton' ) )
		{
			Event.observe( 'closeButton', 'click',				function( event ) { hidePhoto(); Event.stop( event ); });
		}
												// should be mosueup, but can't be stopped by click event on other elements
		Event.observe( document.body, 'click',					function( event ) { hidePhoto(); });
		Event.observe( window, 'resize',							function( event ) { hidePhoto(); Event.stop( event ); });

		hideBackButton();
		hideNextButton();

		//debug( photoOverlay.innerHTML );

		var thumbnails  = document.getElementsByClassName( 'thumbnail' );
		for( var i = 0; i < thumbnails.length; i++ )
		{
			//debug( 'thumbnails: ' + thumbnails[i].getAttribute( 'image' ));
			if( thumbnails[i].getAttribute( 'image' ) )
			{
				Event.observe( thumbnails[i], 'click', function ( event ) { loadPhoto( this ); Event.stop( event ); } );
			}
		}

		if( typeof( bodyOverlay ) == 'undefined' )
		{
			bodyOverlay                = document.createElement( 'div' );
			bodyOverlay.id             = 'bodyOverlay';
			bodyOverlay.style.display  = 'none';
			document.body.appendChild( bodyOverlay );
		}
	}
}

function loadPhoto( element )
{
	var src  = element.getAttribute( 'image' );
	var imgId  = photoImgIdPrefix + src;

	if( ! photoOverlayImages || $( imgId ) && photoCurrentImgId == imgId )
	{
		//debug( 'loadPhoto 1 - photo is already current photo so do nothing' );
		displayPhoto();
	} else if( $( imgId ) )
	{
		//debug( 'loadPhoto 2-  photo previously displayed so make it current photo' );
		hide( photoCurrentImgId );
		photoCurrentImgId  = imgId;
		show( photoCurrentImgId );
		displayPhoto();
	} else {
		//debug( 'loadPhoto 3: photo not previously displayed so create and make it current' );
		hide( photoCurrentImgId );

		photoCurrentImgId       = imgId;

		// Works in FF, onload doesn't work in IE
		img                  = document.createElement( 'img' );
		img.id               = imgId;
		img.src              = src;
		img.style.display    = '';
		//img.onload           = displayPhoto;
		Event.observe( img, 'load', displayPhoto );
		photoOverlayImages.appendChild( img );
		//debug( photoOverlayImages.parentNode.innerHTML +"\n" );

		// Old method works in FF & IE:
		//photoOverlayImages.innerHTML   += '<img src="' + src + '" id="' + imgId + '" style="display:" onload="displayPhoto()" />';
	}
	makeActiveThumbnail( element );
	photoCurrentThumbnail   = element;
}

var displayPhotoCount      = 0;
var displayPhotoCountMax   = 10;
var displayPhotoDelay      = 500;

function displayPhotoSize()
{
	if( ! $( photoCurrentImgId ) || displayPhotoCount >= displayPhotoCountMax )
	{
		return;
	}

	show( bodyOverlay );
	show( photoOverlay );
	show( photoCurrentImgId );

	//debug( "1 dim: " + $( photoCurrentImgId ).getWidth() +' x '+ $( photoCurrentImgId ).getHeight() +"\n"+ $( photoCurrentImgId ).src);

	var imgSize  = ( $( photoCurrentImgId ).getWidth() <= 0 || $( photoCurrentImgId ).getHeight() <= 0 )
							? null
							: $( photoCurrentImgId ).getDimensions();

	//hide( photoOverlay );

	if( ! imgSize )
	{
		setTimeout( 'displayPhoto()', displayPhotoDelay );
		displayPhotoCount++;
	} else {
		displayPhotoCount = 0;
	}

	return imgSize;
}

function displayPhoto()
{
	//debug( 'displayPhoto' );
	var imgSize;
	var viewport       = document.viewport.getDimensions();

	if( ! ( imgSize = displayPhotoSize() ) ) return;		// Use setTimeout to check image dimensions (seems to be required in IE):

	/*if( $('photoOverlay').getStyle('position') == 'fixed' )		// 'absolute' in IE6, otherwise 'fixed'
	{
		if( ! ( imgSize = displayPhotoSize() ) ) return;		// Use setTimeout to check image dimensions (seems to be required in IE):
	} else {
		//imgSize	= { width: 648, height: 432 };
	}*/

	//debug( "displayPhoto\nimg - w: " + imgSize.width + ', h:' + imgSize.height +"\nviewport - w: " + viewport.width + ', h:' + viewport.height );

	$( 'backContainer' ).style.width		= parseInt( imgSize.width / 2) + 'px';
	$( 'nextContainer' ).style.width		= parseInt( imgSize.width / 2) + 'px';
	$( 'backContainer' ).style.height	= imgSize.height + 'px';
	$( 'nextContainer' ).style.height	= imgSize.height + 'px';

	if( $('photoOverlay').getStyle('position') != 'absolute' )		// 'absolute' in IE6, otherwise 'fixed'
	{
		moveLeft       = parseInt( ( viewport.width / 2 ) - ( imgSize.width / 2 ) );
		moveTop        = parseInt( ( viewport.height / 2 ) - ( imgSize.height / 2 ) );
		photoOverlay.style.left  = moveLeft + 'px';
		photoOverlay.style.top   = moveTop + 'px';
	}

	/*debug( "displayPhoto\n"+
		$( 'backContainer' ).style.width +"\n"+
		$( 'nextContainer' ).style.width +"\n"+
		$( 'backContainer' ).style.height +"\n"+
		$( 'nextContainer' ).style.height +"\n"+
		photoOverlay.style.left +"\n"+
		photoOverlay.style.top
	);*/

	show( bodyOverlay );
	show( photoOverlay );
	show( photoCurrentImgId );
}

function prevPhoto()
{
	var allPhotos  = $$( '.thumbnail' );

	for( var i = 0; i < allPhotos.length && allPhotos[i] != photoCurrentThumbnail; i++ );

	if( allPhotos[i] != photoCurrentThumbnail || i == 0 ) return;                      // First photo

	loadPhoto( allPhotos[i-1] );
}

function nextPhoto()
{
	var allPhotos  = $$( '.thumbnail' );

	for( var i = 0; i < allPhotos.length && allPhotos[i] != photoCurrentThumbnail; i++ );

	if( allPhotos[i] != photoCurrentThumbnail || i >= allPhotos.length - 1 ) return;    // Last photo

	loadPhoto( allPhotos[i+1] );
}

function hidePhoto()
{
	//debug( 'hidePhoto()' );
	if( photoOverlay && photoOverlay.style.display != 'none' )
	{
		hide( photoOverlay );
		hide( bodyOverlay );
		clearActiveThumbnail();
	}
}

function showBackButton()
{
	$( 'backButtonBg' ).style.visibility	= 'visible';
	$( 'backButton' ).style.visibility		= 'visible';
}
function hideBackButton()
{
	$( 'backButtonBg' ).style.visibility	= 'hidden';
	$( 'backButton' ).style.visibility		= 'hidden';
}
function showNextButton()
{
	//debug( 'showNextButton()' );
	$( 'nextButtonBg' ).style.visibility	= 'visible';
	$( 'nextButton' ).style.visibility		= 'visible';
}
function hideNextButton()
{
	//debug( 'hideNextButton()' );
	$( 'nextButtonBg' ).style.visibility	= 'hidden';
	$( 'nextButton' ).style.visibility		= 'hidden';
}


Event.observe( window, 'load', initPhotos );


/* -------- VIDEO -------- */

function initVideos()
{
	var thumbnails    = document.getElementsByClassName( 'thumbnail' );

	for( var i = 0; i < thumbnails.length; i++ )
	{
		if( thumbnails[i].getAttribute( 'flvSrc' ) || thumbnails[i].getAttribute( 'divId' ) )
		{
			thumbnails[i].onclick   = function () { displayVideo( this ); };
		}
	}
}

var videoFlowPlayerId   = 'video_FlowPlayer';
var videoCurrentId      = videoFlowPlayerId;
var flvFolder     = '../videos/';

function displayVideo( element )
{
	if( src = element.getAttribute( 'flvSrc' ) )
	{
		if( videoCurrentId && videoCurrentId != videoFlowPlayerId && $( videoFlowPlayerId ) )
		{
			hide( videoCurrentId );
			show( videoFlowPlayerId );
		}
		// play src
		videoCurrentId = videoFlowPlayerId;
		//debug( flvFolder + src );
		$( 'FlowPlayer' ).playClip( { name: 'play clip', url: flvFolder + src } );
	}
	else if( divId = element.getAttribute( 'divId' ) )
	{
		if( videoCurrentId != divId && $( divId ) )
		{
			//$( 'FlowPlayer' ).DoStop(); ?????
			hide( videoCurrentId );
			show( divId );
		}
		// display you tube video
		videoCurrentId = divId;
	}
	//debug( '-------------------' );
	makeActiveThumbnail( element );
}

Event.observe( window, 'load', initVideos );


/* --------  -------- */

