//=======================
// Calameo
// Refactored JS
// Date: 2009-11-27
//========================

// Cookies
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire + '; path=/');
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

// Book title update
function updateBookName(url, newname)
{
	// Ajax request parameters
	var opt = new Hash();
	
	opt.parameters = new Hash();
	
	opt.parameters.set('do', 'update_title');
	opt.parameters.set('NewTitle', newname);

	// Success
	opt.onSuccess = function(t) {
		switch ( t.responseJSON.status )
		{
			case 'ok':
				Element.update('BookName', newname);
				Element.hide('BookNameEdit');
				Element.show('BookNameView')
				break;
			default:
			case 'error':
				opt.onFailure(t);
				break;
		}
	};
	
	// Failure
	opt.onFailure = function(t) {
		new Effect.Highlight('BookNameEdit', {startcolor: '#F4887E', endcolor: '#FFFFFF'});
	};
	
	new Ajax.Request(url, opt);
	return false;
}

// Send to a friend
function sendToAFriend(url)
{
	// GUI
	Form.Element.disable('ShareFormButton');
	
	Element.hide('SendShareForm');
	Element.show('SendShareLoading');
	Element.hide('SendShareSuccess');
	Element.hide('SendShareError');
	
	// Ajax request options
	var opt = new Hash();
	
	// Form data
	opt.parameters = $H( $('SendShareForm').serialize(true) );

	// Ajax mode
	opt.parameters.set('mode','ajax');
	
	// Success
	opt.onSuccess = function(t) {
		Element.hide('SendShareLoading');
		switch ( t.responseJSON.status )
		{
			case 'ok':
				if ( $('DisplaySelectedContacts') ) $('DisplaySelectedContacts').childElements().each(function(e){e.remove()});
				['SelectedContacts','Emails','Message','Lists'].each(function(e){Form.Element.setValue(e, '')});
				Element.update('Contacts');
				Element.show('SendShareSuccess');
				break;
			default:
			case 'error':
				if ( t.responseJSON.error ) Element.firstDescendant('SendShareError').update( t.responseJSON.error );
				Element.show('SendShareError');
				break;
		}
		if ( t.responseJSON.retry == true )
		{
			Element.show('SendShareForm');
			Form.Element.enable('ShareFormButton');
		}
		else Element.hide('SendShareForm');		
	};
	
	// Failure
	opt.onFailure = function(t) {
		Form.Element.enable('ShareFormButton');
		Element.hide('SendShareLoading');
		Element.hide('SendShareSuccess');
		Element.show('SendShareError');
		Element.show('SendShareForm');
	};
	
	// Request
	new Ajax.Request(url, opt);
	return false;
}

// Report abuse
function reportAbuse(url)
{
	// GUI
	Form.Element.disable('ReportAbuseButton');
	
	Element.hide('ReportAbuseForm');
	Element.show('ReportAbuseLoading');
	Element.hide('ReportAbuseSuccess');
	Element.hide('ReportAbuseError');
	
	// Ajax request options
	var opt = new Hash();
	
	// Form data
	opt.parameters = $H( $('ReportAbuseForm').serialize(true) );

	// Ajax mode
	opt.parameters.set('mode','ajax');
	
	// Success
	opt.onSuccess = function(t) {
		Element.hide('ReportAbuseLoading');
		switch ( t.responseJSON.status )
		{
			case 'ok':
				Element.show('ReportAbuseSuccess');
				break;
			default:
			case 'error':
				if ( t.responseJSON.error ) Element.firstDescendant('ReportAbuseError').update( t.responseJSON.error );
				Element.show('ReportAbuseError');
				break;
		}
		if ( t.responseJSON.retry == true )
		{
			Element.show('ReportAbuseForm');
			Form.Element.enable('ReportAbuseButton');
		}
		else Element.hide('ReportAbuseForm');		
	};
	
	// Failure
	opt.onFailure = function(t) {
		Form.Element.enable('ReportAbuseButton');
		Element.hide('ReportAbuseLoading');
		Element.hide('ReportAbuseSuccess');
		Element.show('ReportAbuseError');
		Element.show('ReportAbuseForm');
	};
	
	// Request
	new Ajax.Request(url, opt);
	return false;
}

// Favorites
function addToFavorites(url)
{
	// GUI
	Element.addClassName('AddToFavorites', 'loading');
	
	// Ajax request options
	var opt = new Hash();
	
	// Success
	opt.onSuccess = function(t) {
		Element.removeClassName('AddToFavorites', 'loading');
	
		switch ( t.responseJSON.status )
		{
			case 'ok':
				Element.hide('AddToFavorites');
				Element.show('RemoveFromFavorites');
				break;
			default:
			case 'error':
				opt.onFailure(t);
				break;
		}
	};
	
	// Failure
	opt.onFailure = function(t) {
		Element.removeClassName('AddToFavorites', 'loading');
	
		Element.show('AddToFavorites');
		Element.hide('RemoveFromFavorites');
	};
	
	// Request
	new Ajax.Request(url, opt);
	return false;
}
function removeFromFavorites(url)
{
	// GUI
	Element.addClassName('RemoveFromFavorites', 'loading');
	
	// Ajax request options
	var opt = new Hash();
	
	// Success
	opt.onSuccess = function(t) {
		Element.removeClassName('RemoveFromFavorites', 'loading');
	
		switch ( t.responseJSON.status )
		{
			case 'ok':
				Element.hide('RemoveFromFavorites');
				Element.show('AddToFavorites');
				break;
			default:
			case 'error':
				opt.onFailure(t);
				break;
		}
	};
	
	// Failure
	opt.onFailure = function(t) {
		Element.removeClassName('RemoveFromFavorites', 'loading');
	
		Element.hide('AddToFavorites');
		Element.show('RemoveFromFavorites');
	};
	
	// Request
	new Ajax.Request(url, opt);
	return false;
}
function deleteFavorite(url, message, id)
{
	var test = ( message != undefined && message != '' ) ? confirm(message) : true;
	
	if ( test == true )
	{
		// Ajax request options
		var opt = new Hash();
		
		opt.parameters = new Hash( {mode: 'ajax'} );
		
		// Success
		opt.onSuccess = function(t) {
			switch ( t.responseJSON.status )
			{
				case 'ok':
					alert(DeleteFavoriteSuccess);
					Element.hide('Favorite'+id);
					break;
				default:
				case 'error':
					opt.onFailure(t);
					break;
			}
		};
		
		// Failure
		opt.onFailure = function(t){
			alert(DeleteFavoriteError);
		};
	
		new Ajax.Request(url, opt);
	}
	return false;
}

// Comments
function displayCommentMsg(msg, className)
{
	Element.down('CommentsMsg', 'div').update(msg);
	Element.removeClassName('CommentsMsg', 'msg-error');
	Element.removeClassName('CommentsMsg', 'msg-valid');
	Element.addClassName('CommentsMsg', className);
	Element.show('CommentsMsg');
}
function postComment(url)
{
	// GUI
	Form.Element.disable('PostCommentButton');
	
	Element.hide('PostCommentForm');
	Element.show('PostCommentLoading');

	// Ajax request options
	var opt = new Hash();
	
	// Form data
	opt.parameters = $H( $('PostComment').serialize(true) );

	// Ajax mode
	opt.parameters.set('mode','ajax');
	
	// Success
	opt.onSuccess = function(t) {
		Element.hide('PostCommentLoading');
		if ( t.responseJSON.retry == true )
		{
			Element.show('PostCommentForm');
			Form.Element.enable('PostCommentButton');
		}
		else Element.hide('PostCommentForm');		
		switch ( t.responseJSON.status )
		{
			case 'ok':
				Form.Element.setValue('CommentText', '');
				Form.Element.enable('PostCommentButton');
		
				Element.show('CommentPanel');
				Element.show('PostCommentForm');
				
				displayCommentMsg(PostCommentSuccess, 'msg-valid');
				
				if ( typeof(updateCommentsList) == 'function' ) updateCommentsList();
				break;
			default:
			case 'error':
				opt.onFailure(t);
				break;
		}
	};
	
	// Failure
	opt.onFailure = function(t) {
		Form.Element.setValue('CommentText', '');
		Element.hide('PostCommentLoading');
		if ( t.responseJSON.retry == true )
		{
			Element.show('PostCommentForm');
			Form.Element.enable('PostCommentButton');
		}
		else Element.hide('PostCommentForm');		
	
		//alert(PostCommentError);
		displayCommentMsg(PostCommentError, 'msg-error');
	};
	
	// Request
	new Ajax.Request(url, opt);
	return false;
}
function postEarlyComment(url)
{
	// GUI
	Form.Element.disable('PostEarlyCommentButton');
	
	Element.hide('PostEarlyCommentForm');
	Element.show('PostEarlyCommentLoading');

	// Ajax request options
	var opt = new Hash();
	
	// Form data
	opt.parameters = $H( $('PostEarlyComment').serialize(true) );

	// Ajax mode
	opt.parameters.set('mode','ajax');
	
	// Success
	opt.onSuccess = function(t) {
		Element.hide('PostEarlyCommentLoading');
		if ( t.responseJSON.retry == true )
		{
			Element.show('PostEarlyCommentForm');
			Form.Element.enable('PostEarlyCommentButton');
		}
		else Element.hide('PostEarlyCommentForm');		
		switch ( t.responseJSON.status )
		{
			case 'ok':
				Form.Element.setValue('EarlyCommentText', '');
				Form.Element.enable('PostEarlyCommentButton');
		
				Element.hide('EarlyCommentPanel');
				Element.show('EarlyPostComment');
				Element.show('CommentPanel');
				Element.show('PostNewComment');
				
				displayCommentMsg(PostCommentSuccess, 'msg-valid');
				
				if ( typeof(updateCommentsList) == 'function' ) updateCommentsList();
				break;
			default:
			case 'error':
				opt.onFailure(t);
				break;
		}
	};
	
	// Failure
	opt.onFailure = function(t) {
		Form.Element.setValue('EarlyCommentText', '');
		Element.hide('PostEarlyCommentLoading');
		if ( t.responseJSON.retry == true )
		{
			Element.show('PostEarlyCommentForm');
			Form.Element.enable('PostEarlyCommentButton');
		}
		else Element.hide('PostEarlyCommentForm');		
	
		displayCommentMsg(PostCommentError, 'msg-error');
	};
	
	// Request
	new Ajax.Request(url, opt);
	return false;
}
function publishComment(url, id)
{
	// Ajax Request options
	var opt = new Hash();
	
	opt.parameters = new Hash( {mode:'ajax'} );
	
	// Success
	opt.onSuccess = function(t) {
		switch ( t.responseJSON.status )
		{
			case 'ok':
				Element.down('Comment'+id, '.comment').removeClassName('comment-offline');
				//displayCommentMsg(PublishCommentSuccess, 'msg-valid');
				break;
			default:
			case 'error':
				opt.onFailure(t);
				break;
		}
	};
	
	// Failure
	opt.onFailure = function(t) {
		displayCommentMsg(PublishCommentError, 'msg-error');
	};
	
	new Ajax.Request(url, opt);
	return false;
}
function unpublishComment(url, id)
{
	// Ajax Request options
	var opt = new Hash();

	opt.parameters = new Hash( {mode:'ajax'} );

	// Success
	opt.onSuccess = function(t) {
		switch ( t.responseJSON.status )
		{
			case 'ok':
				Element.down('Comment'+id, '.comment').addClassName('comment-offline');
				//displayCommentMsg(UnpublishCommentSuccess, 'msg-valid');
				break;
			default:
			case 'error':
				opt.onFailure(t);
				break;
		}
	};
	
	// Failure
	opt.onFailure = function(t) {
		displayCommentMsg(UnpublishCommentError, 'msg-error');
	};
	
	new Ajax.Request(url, opt);
	return false;
}

function blockCommentPoster(url, id, msg)
{
	// Confirmation
	var test = ( msg != '' && msg != undefined ) ? confirm(msg) : true;
	
	if ( test == true )
	{
		// Ajax Request options
		var opt = new Hash();
		
		opt.parameters = new Hash( {mode:'ajax'} );
	
		// Success
		opt.onSuccess = function(t) {
			switch ( t.responseJSON.status )
			{
				case 'ok':
					Element.down('Comment'+id, '.comment').addClassName('comment-blocked');
					displayCommentMsg(BlockPosterCommentSuccess, 'msg-valid');
					break;
				default:
				case 'error':
					opt.onFailure(t);
					break;
			}
		};
		
		// Failure
		opt.onFailure = function(t) {
			displayCommentMsg(BlockPosterCommentError, 'msg-error');
		};
		
		new Ajax.Request(url, opt);
	}
	
	return false;
}

function deleteComment(url, id, msg)
{
	// Confirmation
	var test = ( msg != '' && msg != undefined ) ? confirm(msg) : true;
	
	if ( test == true )
	{
		// Ajax Request options
		var opt = new Hash();
		
		opt.parameters = new Hash( {mode:'ajax'} );
	
		// Success
		opt.onSuccess = function(t) {
			switch ( t.responseJSON.status )
			{
				case 'ok':
					displayCommentMsg(DeleteCommentSuccess, 'msg-valid');
					new Effect.Fade('Comment'+id);									
					break;
				default:
				case 'error':
					opt.onFailure(t);
					break;
			}
		};
		
		// Failure
		opt.onFailure = function(t) {
			displayCommentMsg(DeleteCommentError, 'msg-error');
		};
		
		new Ajax.Request(url, opt);
	}
	
	return false;
}

// Report spam
function reportSpamComment(url, id, msg)
{
	// Confirmation
	var test = ( msg != undefined && msg != '' ) ? confirm(msg) : true;
	
	if ( test == true )
	{
		// Ajax Request options
		var opt = new Hash();
		
		opt.parameters = new Hash( {mode:'ajax'} );
		
		// Success
		opt.onSuccess = function(t) {
			switch ( t.responseJSON.status )
			{
				case 'ok':
					displayCommentMsg(DeleteCommentSuccess, 'msg-valid');
					new Effect.Fade('Comment'+id);									
					break;
				default:
				case 'error':
					opt.onFailure(t);
					break;
			}
		};
		
		// Failure
		opt.onFailure = function(t) {
			displayCommentMsg(DeleteCommentError, 'msg-error');
		};
		
		new Ajax.Request(url, opt);
	}
	
	return false;
}
function reportSpamMessage(url, redirect, msg)
{
	// Confirmation
	var test = ( msg != undefined && msg != '' ) ? confirm(msg) : true;
	
	if ( test == true )
	{
		// Ajax Request options
		var opt = new Hash();
		
		opt.parameters = new Hash( {mode:'ajax'} );
		
		// Success
		opt.onSuccess = function(t) {
			switch ( t.responseJSON.status )
			{
				case 'ok':
					window.location = redirect;
					break;
				default:
				case 'error':
					opt.onFailure(t);
					break;
			}
		};
		
		// Failure
		opt.onFailure = function(t) {
			alert(DeleteMessageError);
		};
		
		new Ajax.Request(url, opt);
	}
	
	return false;
}

// Contacts
function addToContacts(url)
{
	// GUI
	Element.hide('AddToContactsForm');
	Element.show('AddToContactsLoading');
	
	// Ajax request options
	var opt = new Hash();
	
	opt.parameters = $H( $('AddToContactsForm').serialize(true) );

	// Success
	opt.onSuccess = function(t) {
		switch ( t.responseJSON.status )
		{
			case 'ok':
				Element.hide('AddToContacts');
				Element.show('RemoveFromContacts');
		
				Form.Element.setValue('NewList', '');
				
				Element.show('AddToContactsSuccess');
				Element.show('AddToContactsClose');
				Element.hide('AddToContactsLoading');
			
				Selector.findChildElements('ListContainer', 'INPUT').each(function(e){if(e.type=='checkbox') e.checked=false;});
				break;
			default:
			case 'error':
				opt.onFailure(t);			
				break;
		}
			
	};
	
	// Failure
	opt.onFailure = function(t) {
		Element.show('AddToContacts');
		Element.hide('RemoveFromContacts');
		
		Element.show('AddToContactsError');
		Element.show('AddToContactsForm');
		Element.hide('AddToContactsLoading');
	};

	new Ajax.Request(url, opt);
	return false;
}
function removeFromContacts(url, msg)
{
	// Confirmation
	var test = ( msg != undefined && msg != '' ) ? confirm(msg) : true;
	
	if ( test == true )
	{
		// GUI
		Element.addClassName('RemoveFromContacts', 'loading');
		
		// Ajax request options
		var opt = new Hash();
		
		// Success
		opt.onSuccess = function(t) {
			switch ( t.responseJSON.status )
			{
				case 'ok':
					Element.removeClassName('RemoveFromContacts', 'loading');
					
					Element.show('AddToContacts');
					Element.hide('RemoveFromContacts');
				
					alert(RemoveFromContactsSuccess);
					break;
				default:
				case 'error':
					opt.onFailure(t);			
					break;
			}
				
		};
		
		// Failure
		opt.onFailure = function(t) {
			Element.removeClassName('RemoveFromContacts', 'loading');
		
			Element.hide('AddToContacts');
			Element.show('RemoveFromContacts');
		
			alert(RemoveFromContactsError);
		};
	
		new Ajax.Request(url, opt);
	}
	
	return false;
}

// Groups
function updateGroupPool(url)
{
	// GUI
	Form.Element.enable('GroupPoolButton');
	
	Element.hide('GroupPoolList');
	Element.show('GroupPoolLoading');
	
	// Ajax request parameters
	var opt = new Hash();
	
	// Success
	opt.onSuccess = function(t) {
		Element.show('GroupPoolList');
		Element.hide('GroupPoolLoading');
	};
	
	// Failure
	opt.onFailure = function(t) {
		Element.show('GroupPoolList');
		Element.hide('GroupPoolLoading');
	};
	
	new Ajax.Updater('LoadedLBContent', url, opt);
	return false;
}
function addToGroupPool(url, refresh_url)
{
	// GUI
	Form.Element.disable('GroupPoolButton');
	
	Element.hide('GroupPoolList');
	Element.show('GroupPoolLoading');
	
	// Ajax request parameters
	var opt = new Hash();
	
	opt.parameters = $H( $('GroupPoolForm').serialize(true) );
	
	opt.parameters.set('mode', 'ajax');
	
	// Success
	opt.onSuccess = function(t) {
		switch ( t.responseJSON.status )
		{
			case 'ok':
				updateGroupPool(refresh_url);
				break;
			default:
			case 'error':
				opt.onFailure(t);
				break;
		}
	};
	
	// Failure
	opt.onFailure = function(t) {
		alert(GroupPoolError);
		updateGroupPool(refresh_url);
	};

	// Request
	new Ajax.Request(url, opt);
	return false;
}
function removeFromGroupPool(url, refresh_url)
{
	// GUI
	Element.hide('GroupPoolList');
	Element.show('GroupPoolLoading');

	// Ajax request paramters
	var opt = new Hash();
	
	opt.parameters = new Hash();
	opt.parameters.set('mode', 'ajax');
	
	// Success
	opt.onSuccess = function(t) {
		switch ( t.responseJSON.status )
		{
			case 'ok':
				updateGroupPool(refresh_url);
				break;
			default:
			case 'error':
				opt.onFailure(t);
				break;
		}
	};
	
	// Failure
	opt.onFailure = function(t) {
		Element.show('GroupPoolList');
		Element.hide('GroupPoolLoading');
	
		alert(GroupDepoolError);
	};

	// Request
	new Ajax.Request(url, opt);
	return false;
}

// Ratings
var StarRating = Class.create({
	initialize: function(element, rate, ajax_url, options){
		this.Max = 5;
		this.locked = false;
		//
		this.Element = $(element);
		this.Rate = rate;
		this.AjaxUrl = ajax_url;
		options = ( options != undefined ) ? options : {};
		this.Messages = ( options.Messages != undefined ) ? options.Messages : [];
		this.StatText = ( options.StatText != undefined ) ? options.StatText : '';
		this.LoadingText = ( options.LoadingText != undefined ) ? options.LoadingText : '';
		this.ThankText  = ( options.ThankText != undefined ) ? options.ThankText : '';
		this.Callback = ( options.Callback != undefined ) ? options.Callback : false;
		//
		this.Element.update();
		//
		this.Stars = Builder.node('DIV', {className:'stars'});
		//
		for(var i = 0 ; i < this.Max ; i++ )
		{
			star = Builder.node('DIV', {className:'star'});
			//
			star.Rate = i+1;
			star.Rater = this;
			star.onclick = this.onClick;
			star.onmouseover = this.onMouseOver;
			star.onmouseout = this.onMouseOut;
			//
			this.Stars.appendChild(star);
		}
		this.Element.appendChild(this.Stars);
		this.Indicator = Builder.node('DIV', {className:'indicator'}, this.StatText);
		this.Element.appendChild(this.Indicator);
		this.Loading = Builder.node('DIV', {className:'loading', style:'display: none;'}, this.LoadingText);
		this.Element.appendChild(this.Loading);
		//
		this.setStars(this.Rate);
	},
	setStars: function(rate, hover)
	{
		for(var i = 1; i <= this.Stars.childNodes.length; i++)
		{
			var star = $(this.Stars.childNodes[i-1]);
			//
			star.removeClassName('full');	
			star.removeClassName('over');	
			star.removeClassName('blank');	
			//
			if ( i <= rate )
			{
				if ( hover )
				{
					star.addClassName('over');	
				}
				else
				{
					star.addClassName('full');	
				}
			}
			else if ( i-0.5 <= rate )
			{
				if ( hover )
				{
					star.addClassName('over');	
				}
				else
				{
					star.addClassName('half');
				}
			}
			else
			{
				star.addClassName('blank');	
			}
		}
	},
	setIndicator: function(msg)
	{
		Element.update(this.Indicator, msg);
	},
	onMouseOver: function()
	{
		if ( this.Rater.locked ) return;
		
		this.Rater.setStars(this.Rate, true);
		this.Rater.setIndicator(this.Rater.Messages[this.Rate-1]);
	},
	onMouseOut: function()
	{
		if ( this.Rater.locked ) return;
		
		this.Rater.setStars(this.Rater.Rate);
		this.Rater.setIndicator(this.Rater.StatText);
	},
	onClick: function()
	{
		if ( this.Rater.locked ) return;

		this.Rater.rate(this.Rate);
	},
	rate: function(rate)
	{
		if ( this.Callback ) return this.Callback();
		
		var obj = this;
		
		this.locked = true;
		
		this.NewRate = rate;
		
		Element.show(this.Loading);
		Element.hide(this.Indicator);
		
		var opt = new Hash();
		
		opt.parameters = new Hash();
		
		opt.parameters.set('mode', 'ajax');
		opt.parameters.set('Rating', this.NewRate);
		
		// Success
		opt.onSuccess = function(t) {
			switch ( t.responseJSON.status )
			{
				case 'ok':
					obj.Rate = obj.NewRate;
					obj.setStars(obj.Rate);
				
					Element.hide(obj.Loading);
					Element.show(obj.Indicator);
					
					obj.setIndicator(obj.ThankText);
					new Effect.Highlight(obj.Element, {startcolor:'#e0FFc9', endcolor:'#F8F9FA'});
					
					obj.locked = false;
					break;
				default:
				case 'error':
					opt.onFailure(t);
					break;
			}
		};
		
		// Failure
		opt.onFailure = function(t) {
			obj.locked = false;
			
			obj.setStars(obj.Rate);
	
			Element.hide(obj.Loading);
			Element.show(obj.Indicator);
			
			alert('Error!');	
		};
		
		// Making Ajax call
		new Ajax.Request(this.AjaxUrl, opt);
	}
});

// Tabs
function selectTab(tab, panel)
{
	Element.up(tab, '.tabs').select('li').each(function(e){Element.removeClassName(e,'active');});
	Element.up(tab, 'li').addClassName('active');
	Element.up(panel, '.tab-panels').select('div.tab-panel').each(function(e){e.hide()});
	Element.show(panel);
	return false;
}

// Lightboxes
function showLightBox(id, width, noescape, notransition, top)
{
	if ( width == undefined ) width = 400;	
	if ( noescape == undefined ) noescape = false;	
	
	hideAllLightBoxes(true);
	
	if ( noescape == false )
	{
		$('lbOverlay').hide().observe('click', (function() { hideLightBox(id); }));
		$(id).hide();
	}
	// Visibility: hidden et non pas display none pour l'upload SWFUpload
	$$('select', 'object', 'embed', 'iframe').each(function(e){ if( !Element.descendantOf(e, id) ) e.style.visibility = 'hidden' });
	// stretch overlay to fill page and fade in
	var arrayPageSize = getPageSize();
	$('lbOverlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
	if ( notransition )
	{
		new Effect.Appear('lbOverlay', { duration: 0, from: 0.7, to: 0.7 });
	}
	else
	{
		new Effect.Appear('lbOverlay', { duration: 0.25, from: 0.0, to: 0.7 });
	}
	// calculate top and left offset for the lightbox 
	var arrayPageScroll = document.viewport.getScrollOffsets();
	var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 7);
	var lightboxLeft = arrayPageScroll[0] + ((document.viewport.getWidth()-width-28)/2);
	$(id).setStyle({ width: width + 'px', top: lightboxTop + 'px', left: lightboxLeft + 'px' });
	if ( notransition )
	{
		$(id).show();
	}
	else
	{
		new Effect.Appear(id, { duration: 0.25, from: 0.0, to: 1 });
	}
	return false;
}
function hideLightBox(id, ignore_overlay)
{
	Element.hide(id);
	if ( ignore_overlay == undefined ) Element.hide('lbOverlay');
	$$('select', 'object', 'embed', 'iframe').each(function(e){ if( !Element.descendantOf(e, id) ) e.style.visibility = 'visible' });
}
function hideAllLightBoxes(ignore_overlay)
{
	$$('.lightbox').each(function(e){ hideLightBox(e, ignore_overlay)});
}

// Help lightbox
function showHelpLightBox(url)
{
	updateHelpLightBox(url);
	return showLightBox('HelpLightBox', 610);
}
function updateHelpLightBox(url)
{
	$('HelpLBContent').update(Builder.node('div', {className:'icon loading', style:'height:28px;'}, Builder.node('span')));
	new Ajax.Updater('HelpLBContent', url);
}

// Loaded lightbox
function showLoadedLightBox(url, width, hash)
{
	updateLoadedLightBox(url, hash);
	return showLightBox('LoadedLightBox', width);
}
function updateLoadedLightBox(url, hash)
{
	$('LoadedLBContent').update(Builder.node('div', {className:'icon loading', style:'height:28px;'}, Builder.node('span')));
	new Ajax.Updater('LoadedLBContent', url, { parameters: hash, evalScripts: true});
}
function openFeatureLightBox(id)
{
	Element.update('LoadedLBContent', $(id).innerHTML);
	Element.down('LoadedLBContent', '.details').show();
	return showLightBox('LoadedLightBox');
}
function getPageSize()
{
	 var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}

// Arrow switch (book overview)
function toggleArrowSwitch(id, toggle, on, off)
{
	if ( Element.hasClassName(toggle, on) )
	{
		Element.hide(id);
		Element.removeClassName(toggle, on);
		Element.addClassName(toggle, off);
	}
	else
	{
		Element.show(id);
		Element.removeClassName(toggle, off);
		Element.addClassName(toggle, on);
	}
}

// Progress bar
function ProgressBar(container, bar)
{
	this.Container = $(container);
	this.Bar = $(bar);
	this.setProgress = function(percent)
	{
		this.Bar.morph('width:'+percent+'%');
	}
	this.resetProgress = function()
	{
		this.Bar.setStyle({width: '0px'});	
	}
}

// Misc
function askBeforeRedirect(msg, url){
	if ( confirm(msg) ) window.location = url;
}
function limitTextFieldLength(text, length, update){
	if ( $F(text).length > length ) Form.Element.setValue(text, $F(text).substr(0,length));
	if ( update ) Element.update(update, (length - $F(text).length));
}
function requestAndReplaceCommentsHTML(url, id, loading_id)
{
	Element.hide(id);
	Element.show(loading_id);
	
	var updateCommentsUrl = url;

	new Ajax.Updater(id, url, {onSuccess: function(){Element.hide(loading_id); Element.show(id)}, onFailure: function(){Element.hide(loading_id); Element.show(id)}});
}
function updateInviteEmails(from, to)
{
	$(to).update($F(from));
}

// Panels
function openLoginPanel()
{
	return showLightBox('LoginPanel', 760);	
}
function toggleExpirationPanel(value, comparison)
{
	if ( value == comparison )
	{
		Element.hide('ExpirationPanel');
	}
	else
	{
		Element.show('ExpirationPanel');
	}
}

// Analytics
var datas = [];
function getChartData(id)
{
	return datas[id];
}

// Tabs
function switchTab(tabs, panels, tab, panel)
{
	Element.childElements(tabs).each(function(e){
		if ( e.id == tab )
		{
			Element.addClassName(e, 'ActiveTab');
			Element.removeClassName(e, 'Tab');
		}
		else
		{
			Element.addClassName(e, 'Tab');
			Element.removeClassName(e, 'ActiveTab');
		}
	});
	Element.childElements(panels).each(function(e){ ( e.id == panel ) ? Element.show(e) : Element.hide(e); });
	return false;
}

// Skin checking (didabled)
function checkSkinSyntax(url, skinUrl, container)
{
	params = new Hash();
	params.set('SkinUrl', skinUrl);
	$(container).update(Builder.node('div', {className:'icon loading', style:'height:28px;'}, Builder.node('span')));
	
	new Ajax.Request(url, {
					 		parameters: params,
					 		onSuccess: function(t)
							{
								var xotree = new XML.ObjTree();
								var response = xotree.parseXML( t.responseText );
								
								if ( response.Status['-type'] == 'success' )
								{
									$(container).update( response.Status.Message );
								}
								else
								{
									$(container).update( response.Status.Message );
								}								
							},
							onFailure: function(t)
							{
								$(container).update( 'Error' );
							}
					 }
					);
}

// Support (getsatisfaction.com)
function getSupportResults(form)
{
	showLightBox('support-lightbox');
	gsfn_search(form);
	return false;
}
function displaySupportResults(results)
{
	Element.update('gsfn_search_results');
	if ( results && results.length > 0 )
	{
		$A(results).each( function(e) { Element.insert('gsfn_search_results', Builder.node('li', {className: e.style}, Builder.node('a', {href: e.url}, e.subject))) });	
		Element.insert('gsfn_search_results', '<li class="gsfn_no_results"><p class="bold-text">Not quite right?</p>');	
	}
	else
	{
		Element.insert('gsfn_search_results', '<li class="gsfn_no_results"><p>No results.</p>');	
	}
	Element.insert('gsfn_search_results', '<a href="javascript:void(0);" class="big-button green-button" onclick="gsfn_submit();"><span>Create a Topic</span></a></li>');
}

// CMini version 2.0
// ---------------------------------------------
var CMiniLanguage = {
	FRENCH: 'fr',
	ENGLISH: 'en',
	SPANISH: 'es',	
	JAPANESE: 'ja',	
	GERMAN: 'de',	
	CHINESE: 'zh',	
	RUSSIAN: 'ru',	
	PORTUGUESE: 'pt',	
	ITALIAN: 'it',	
	KOREAN: 'ko'
}
var CMiniClickTo = {
	OVERVIEW: 'public',
	READ: 'view',
	URL: 'url'
}
var CMiniClickTarget = {
	SELF: '_self',
	NEW: '_blank'
}

var CMini = function()
{
	
	this.ViewerUrl = 'http://v.calameo.com/2.0/cmini.swf';
	
	this.BookCode = undefined;
	this.BookName = 'Read it online!';
	
	this.Width		= 240;
	this.Height		= 147;
	
	this.Language	= CMiniLanguage.ENGLISH;
	
	this.ClickTo	= CMiniClickTo.OVERVIEW;
	this.ClickToUrl	= '';
	this.ClickTarget = CMiniClickTarget.NEW;
	
	this.AutoFlip	= 0;
	
	this.Navigation	= true;
	
	this.Page		= 1;
	
	this.AuthID		= '';
	
	this.getHTML = function ()
	{
		var query = 'bkcode=' + this.getBookCode();
		query += '&amp;langid=' + this.getLanguage();
		query += '&amp;clickTo=' + this.getClickTo();
		if ( this.getClickToUrl() != '' ) query += '&amp;clickToUrl=' + this.getClickToUrl();
		query += '&amp;clickTarget=' + this.getClickTarget();
		query += '&amp;autoFlip=' + this.getAutoFlip();
		query += '&amp;showArrows=' + this.getNavigation();
		query += '&amp;page=' + this.getStartPage();

		var html = '<div style="text-align: center;">';
	
		if ( this.BookName != undefined )
		{
			if ( this.AuthID != '' )
			{
				html += '<div style="font-weight: bold;"><a href="http://www.calameo.com/books/' + this.getBookCode() + '?authid=' + this.getAuthID() + '">' + this.getBookName() + '</a></div>';
			}
			else
			{
				html += '<div style="font-weight: bold;"><a href="http://www.calameo.com/books/' + this.getBookCode() + '">' + this.getBookName() + '</a></div>';
			}
		}
		
		html += '<div style="padding-top: 8px;">';
		
		html += '<object id="' + this.getBookCode() + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + this.getWidth() + '" height="' + this.getHeight() + '">';
		html += '<param name="movie" value="' + this.ViewerUrl + '?' + query + '">';
		html += '<param name="scale" value="noscale" />';
		html += '<param name="loop" value="false" />';
		html += '<param name="salign" value="t" />';
		html += '<param name="allowScriptAccess" value="always" />';
		html += '<param name="wmode" value="transparent" />';
		html += '<embed src="' + this.ViewerUrl + '" type="application/x-shockwave-flash" scale="noscale" allowScriptAccess="always" loop="false" salign="t" wmode="transparent" style="width:' + this.getWidth() + 'px; height:' + this.getHeight() + 'px" flashvars="' + query + '"></embed>';
		html += '</object>';

		/* XHTML compatibility
		html += '<!--[if !IE]> -->';
		html += '<object type="application/x-shockwave-flash" data="' + this.ViewerUrl + '?' + query + '" wmode="transparent" allowScriptAccess="always" width="' + this.getWidth() + '" height="' + this.getHeight() + '">';
		html += '<!-- <![endif]-->';
		html += '<!--[if IE]>';
		html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' + this.getWidth() + '" height="' + this.getHeight() + '">';
		html += '<param name="movie" value="' + this.ViewerUrl + '?' + query + '" />';
		html += '<param name="wmode" value="transparent" />';
		html += '<param name="allowScriptAccess" value="always" />';
		html += '<!-->';
		html += '</object>';
		html += '<!-- <![endif]-->';
		*/
		
		html += '</div>';

		switch ( this.getLanguage() )
		{
			case CMiniLanguage.ENGLISH:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publish at Calam&eacute;o</a> or <a href="http://www.calameo.com/browse/">browse</a> others.</div>';
				break;
			case CMiniLanguage.FRENCH:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publiez sur Calam&eacute;o</a> ou <a href="http://www.calameo.com/browse/">explorez</a> la biblioth&egrave;que.</div>';
				break;
			case CMiniLanguage.SPANISH:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publish at Calam&eacute;o</a> or <a href="http://www.calameo.com/browse/">browse</a> others.</div>';
				break;
			case CMiniLanguage.JAPANESE:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publish at Calam&eacute;o</a> or <a href="http://www.calameo.com/browse/">browse</a> others.</div>';
				break;
			case CMiniLanguage.GERMAN:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publish at Calam&eacute;o</a> or <a href="http://www.calameo.com/browse/">browse</a> others.</div>';
				break;
			case CMiniLanguage.CHINESE:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publish at Calam&eacute;o</a> or <a href="http://www.calameo.com/browse/">browse</a> others.</div>';
				break;
			case CMiniLanguage.RUSSIAN:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publish at Calam&eacute;o</a> or <a href="http://www.calameo.com/browse/">browse</a> others.</div>';
				break;
			case CMiniLanguage.PORTUGUESE:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publish at Calam&eacute;o</a> or <a href="http://www.calameo.com/browse/">browse</a> others.</div>';
				break;
			case CMiniLanguage.ITALIAN:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publish at Calam&eacute;o</a> or <a href="http://www.calameo.com/browse/">browse</a> others.</div>';
				break;
			case CMiniLanguage.KOREAN:
				html += '<div style="font-size: 11px;"><a href="http://www.calameo.com/upload/">Publish at Calam&eacute;o</a> or <a href="http://www.calameo.com/browse/">browse</a> others.</div>';
				break;
		}

		html += '</div>';

		return html;
	};
	
	this.getJavascript = function ()
	{
		var html = '';
		
		html += '<script type="text/javascript" src="http://s1.calameoassets.com/calameo-v4/js/cmini.js"></script>\n';
		html += '<script type=\"text/javascript\">\n';
		html += 'var cmini = new CMini();\n';
		html += 'cmini.setLanguage("' + this.getLanguage() + '");\n';
		html += 'cmini.setSize(' + this.getWidth() + ', ' + this.getHeight() + ');\n';
		html += 'cmini.setClick("' + this.getClickTo() + '", "' + this.getClickTarget() + '");\n';
		html += 'cmini.setAutoFlip(' + this.getAutoFlip() + ');\n';
		html += 'cmini.showNavigation(' + this.getNavigation() + ');\n';
		html += 'cmini.setStartPage(' + this.getStartPage() + ');\n';
		html += 'cmini.display(this.getBookCode());\n';
		html += '</script>';

		return html;
	};
	
	this.getWordPress = function ( bkcode )
	{
		this.setBookCode( bkcode );
		
		var html = '';
		
		html += '[calameo';
		html += ' code=' + this.getBookCode();
		if ( this.getStartPage() > 1 )
		{
			html += ' page=' + this.getStartPage();
		}
		html += ' lang=' + this.getLanguage();
		html += ' width=' + this.getWidth();
		html += ' height=' + this.getHeight();
		html += ' clickto=' + this.getClickTo();
		html += ' clicktarget=' + this.getClickTarget();
		html += ' clicktourl=' + this.getClickToUrl();
		html += ' autoflip=' + this.getAutoFlip();
		html += ' showarrows=' + this.getNavigation();
		html += ' mode=mini]';

		return html;
	};
	
	this.get = function ( bkcode )
	{
		this.setBookCode( bkcode );
		return this.getHTML();
	};
	
	this.display = function ( bkcode )
	{
		document.write( this.get( bkcode ) );	
	};
	
	this.setBookCode = function ( bkcode )
	{
		this.BookCode = bkcode;
	};
	
	this.getBookCode = function ()
	{
		return this.BookCode;
	};
	
	this.setLanguage = function( langid )
	{
		this.Language = langid;	
	};
	
	this.getLanguage = function ()
	{
		if ( this.Language != CMiniLanguage.ENGLISH && this.Language != CMiniLanguage.FRENCH && this.Language != CMiniLanguage.SPANISH )
		{
			return CMiniLanguage.ENGLISH;			
		}

		return this.Language;
	};
	
	this.setSize = function ( width, height )
	{
		this.Width = width;
		this.Height = height;
	};
	
	this.getWidth = function ()
	{
		return this.Width;
	};
	
	this.getHeight = function ()
	{
		return this.Height;
	};
	
	this.setClick = function(to, target, url)
	{
		this.ClickTo = to;
		this.ClickTarget = target;
		
		if ( url == undefined ) url = '';
		
		this.ClickToUrl = url;
	};
	
	this.getClickTo = function ()
	{
		return this.ClickTo;
	};
	
	this.getClickToUrl = function ()
	{
		return this.ClickToUrl;
	};
	
	this.getClickTarget = function ()
	{
		return this.ClickTarget;
	};
	
	this.setBookName = function ( bookname )
	{
		this.BookName = bookname;	
	};
	
	this.getBookName = function ()
	{
		return this.BookName;
	};
	
	this.setAutoFlip = function ( seconds )
	{
		this.AutoFlip = seconds;	
	};
	
	this.getAutoFlip = function ()
	{
		return this.AutoFlip;
	};
	
	this.showNavigation = function ( navigation )
	{
		this.Navigation = navigation;	
	};
	
	this.getNavigation = function ()
	{
		return ( this.Navigation == true ) ? '1' : '0';
	};
	
	this.setStartPage = function ( page )
	{
		this.Page = page;	
	};
	
	this.getStartPage = function ()
	{
		return this.Page;
	};
	
	this.setAuthID = function ( authid )
	{
		this.AuthID = authid;	
	};
	
	this.getAuthID = function ()
	{
		return this.AuthID;
	};
}

// ----------------

// GetSatisfaction Widget (footer)
var GsfnClass = {
  create: function() {
    return function() { this.initialize.apply(this, arguments); }
  }
}

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(String, {
  interpret: function(value) { return value == null ? '' : String(value); }
});

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new GsfnTemplate(replacement);
  return function(match) { return template.evaluate(match) };
}

var GsfnTemplate = GsfnClass.create();
GsfnTemplate.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
GsfnTemplate.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || GsfnTemplate.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(object[match[3]]);
    });
  }
}

var GsfnScriptAttach = GsfnClass.create();
Object.extend(GsfnScriptAttach, {
  at: function(url) {
    var element = document.createElement('script');
    element.type = 'text/javascript';
    element.src = url;
    element.setAttribute('class', 'gsfn');
    document.getElementsByTagName('head')[0].appendChild(element);
  }
});

// Satisfaction code
gsfn_topic_list = { 
  open_tag:     '<ul class="gsfn_topic_list">', 
  item:         '<li class="gsfn_#{style}"><a href="#{url}" class="gsfn_link">#{subject}</a><span class="time">#{date}</span><div class="gsfn_summary">#{summary}</div></li>',
  result:       '<li class="gsfn_#{style}"><a href="#{url}" class="gsfn_link">#{subject}</a></li>',
  no_results:   '<li class="gsfn_no_results">There are no topics in the community yet.</li>',
  suggested:    '<li class="gsfn_suggestion">Are any of these topics helpful?</li>',
  topic_submit: '<li class="gsfn_submit">Not quite right? <input type="submit" onclick="gsfn_submit();" value="Create a Topic" /> <span class="gsfn_or">or</span> <a href="#" onclick="gsfn_cancel(); return false;">Cancel</a></li>',
  no_results_submit: '<li class="gsfn_no_results"><input type="submit" onclick="gsfn_submit();" value="Create a Topic" /> <span class="gsfn_or">or</span> <a href="#" onclick="gsfn_cancel(); return false;">Cancel</a></li>',
  close_tag:    '</ul>'
}

function gsfn_populate(id, template) { document.getElementById(id).innerHTML = template; }
function gsfn_append(id, template) { document.getElementById(id).innerHTML += template; }
function gsfn_cancel(id) { 
  document.getElementById('gsfn_search_query').value = "";
  document.getElementById('gsfn_search_results').innerHTML = "";
}

var gsfn_searched = false;
function gsfn_search(form) {
  document.getElementById('gsfn_search_results').innerHTML = "Searching the community...";
  var url = "http://getsatisfaction.com/calameo/searches"
  var params = []
  for (var i = form.elements.length - 1; i >= 0; i--) {
    if (form.elements[i].name) {
      if(form.elements[i].name == 'query') {
        params.push('utm_term=' + form.elements[i].value);
      }
      params.push(form.elements[i].name + '=' + form.elements[i].value);
    }
  };
  url += '?' + encodeURI(params.join('&'))
  GsfnScriptAttach.at(url);
  gsfn_searched = true;
}

function gsfn_submit() {
  form = document.getElementById('gsfn_search_form');
  if (gsfn_searched) {
    for (var i = form.elements.length - 1; i >= 0; i--){
      el = form.elements[i];
      if (el.name == 'query') {
        el.name = 'topic[subject]';
      } else if (el.name == 'tag') {
        el.name = 'topic[tag]';
      } else {
        el.disabled = 'disabled';
      }
    }
    form.submit();
    return true;
  } else {
    gsfn_search(form);
    return false;
  }
}

function gsfnResultsCallback(json) {
  var gsfn_topics = json;
  var topics_html = [];

  topics_html.push(gsfn_topic_list.open_tag);
  if (gsfn_topics.length == 0) {
    topics_html.push(gsfn_topic_list.no_results);
    topics_html.push(gsfn_topic_list.no_results_submit);
  } else {
    topics_html.push(gsfn_topic_list.suggested);
    for (var t=0; t < gsfn_topics.length; t++) {
      topics_html.push(new GsfnTemplate(gsfn_topic_list.result).evaluate(gsfn_topics[t]));
    }
    topics_html.push(gsfn_topic_list.topic_submit);
  }
  topics_html.push(gsfn_topic_list.close_tag);
  
  gsfn_populate('gsfn_search_results', topics_html.join('\n'));
}

function gsfnTopicsCallback(json) {
  var gsfn_topics = json;
  var topics_html = [];

  topics_html.push(gsfn_topic_list.open_tag);
  if (gsfn_topics.length == 0) {
    topics_html.push(gsfn_topic_list.no_results);
  } else {
    for (var t=0; t < gsfn_topics.length; t++) {
      topics_html.push(new GsfnTemplate(gsfn_topic_list.item).evaluate(gsfn_topics[t]));
    }
  }
  topics_html.push(gsfn_topic_list.close_tag);

  gsfn_populate('gsfn_content', topics_html.join('\n'));
}

// ----------------

//  Prototip 2.1.0.1 - 19-05-2009
//  Copyright (c) 2008-2009 Nick Stakenburg (http://www.nickstakenburg.com)
//
//  Licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License
//  http://creativecommons.org/licenses/by-nc-nd/3.0/

//  More information on this project:
//  http://www.nickstakenburg.com/projects/prototip2/

var Prototip = {
  Version: '2.1.0.1'
};

var Tips = {
  options: {
    images: 'http://s.calameo.com/calameo-v4/images/prototip/',
    zIndex: 9900
  }
};

Prototip.Styles = {
  // The default style every other style will inherit from.
  // Used when no style is set through the options on a tooltip.
  'default': {
    border: 0,
    className: 'standard',
    closeButton: false,
    hideAfter: false,
    hideOn: 'mouseleave',
    hook: false,
	showOn: 'mousemove'
  },
  'book': {
    border: 4,
    borderColor: '#847f71',
	radius: 4,
	className: 'default',
    closeButton: false,
	showOn: 'mousemove',
	delay: 0.25,
    hideOn: 'mouseleave',
    hideAfter: false,
	hook: { mouse: true, tip: 'leftTop' },
	offset: { x: 20, y: -50 },
	viewport: true
  }
};

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('N.Y(U,{4n:"1.6.0.3",2M:{26:!!10.4o("26").3r},3s:q(){9.3t("27");p(/^(4p?:\\/\\/|\\/)/.4q(s.o.V)){s.V=s.o.V}11{r a=/1G(?:-[\\w\\d.]+)?\\.4r(.*)/;s.V=(($$("4s[28]").3u(q(b){M b.28.29(a)})||{}).28||"").2N(a,"")+s.o.V}p(!9.2M.26){p(10.4t>=8&&!10.3v.2j){10.3v.2O("2j","4u:4v-4w-4x:4y","#2k#3w")}11{10.1c("3x:2P",q(){10.4z().4A("2j\\\\:*","4B: 2Q(#2k#3w);")})}}s.2l();I.1c(2R,"2S",9.2S)},3t:q(a){p((4C 2R[a]=="4D")||(9.2T(2R[a].4E)<9.2T(9["3y"+a]))){3z("U 4F "+a+" >= "+9["3y"+a]);}},2T:q(a){r b=a.2N(/3A.*|\\./g,"");b=4G(b+"0".4H(4-b.2U));M a.4I("3A")>-1?b-1:b},4J:$w("3B 4K"),1S:q(a){p(27.2V.3C){M a}a=a.2m(q(f,d){r b=N.2n(9)?9:9.C,c=d.4L;4M(c&&c!=b){4N{c=c.4O}4P(g){c=b}}p(c==b){M}f(d)});M a},2W:q(a){M(a>0)?(-1*a):(a).4Q()},2S:q(){s.3D()}});N.Y(s,{1A:[],13:[],2l:q(){9.2o=9.1o},1m:(q(a){M{1i:(a?"1T":"1i"),15:(a?"1H":"15"),1T:(a?"1T":"1i"),1H:(a?"1H":"15")}})(27.2V.3C),3E:{1i:"1i",15:"15",1T:"1i",1H:"15"},2a:{D:"2X",2X:"D",v:"1p",1p:"v",1U:"1U",1d:"1f",1f:"1d"},3F:{H:"1d",G:"1f"},2Y:q(a){M!!1V[1]?9.2a[a]:a},1j:(q(b){r a=J 4R("4S ([\\\\d.]+)").4T(b);M a?(3G(a[1])<7):X})(4U.4V),2Z:(27.2V.4W&&!10.4X),2O:q(a){9.1A.2p(a)},1B:q(a){r b=9.1A.3u(q(c){M c.C==$(a)});p(b){b.3H();p(b.17){b.F.1B();p(s.1j){b.1q.1B()}}9.1A=9.1A.3I(b)}a.1G=2b},3D:q(){9.1A.30(q(a){9.1B(a.C)}.1g(9))},2q:q(c){p(c==9.3J){M}p(9.13.2U===0){9.2o=9.o.1o;31(r b=0,a=9.1A.2U;b<a;b++){9.1A[b].F.u({1o:9.o.1o})}}c.F.u({1o:9.2o++});p(c.R){c.R.u({1o:9.2o})}9.3J=c},3K:q(a){9.32(a);9.13.2p(a)},32:q(a){9.13=9.13.3I(a)},3L:q(){s.13.1I("T")},W:q(b,f){b=$(b),f=$(f);r k=N.Y({1e:{x:0,y:0},O:X},1V[2]||{});r d=k.1u||f.2r();d.D+=k.1e.x;d.v+=k.1e.y;r c=k.1u?[0,0]:f.3M(),a=10.1C.2s(),g=k.1u?"1W":"18";d.D+=(-1*(c[0]-a[0]));d.v+=(-1*(c[1]-a[1]));p(k.1u){r e=[0,0];e.H=0;e.G=0}r i={C:b.1X()},j={C:N.2c(d)};i[g]=k.1u?e:f.1X();j[g]=N.2c(d);31(r h 3N j){3O(k[h]){S"4Y":S"4Z":j[h].D+=i[h].H;19;S"51":j[h].D+=(i[h].H/2);19;S"52":j[h].D+=i[h].H;j[h].v+=(i[h].G/2);19;S"53":S"54":j[h].v+=i[h].G;19;S"55":S"56":j[h].D+=i[h].H;j[h].v+=i[h].G;19;S"57":j[h].D+=(i[h].H/2);j[h].v+=i[h].G;19;S"58":j[h].v+=(i[h].G/2);19}}d.D+=-1*(j.C.D-j[g].D);d.v+=-1*(j.C.v-j[g].v);p(k.O){b.u({D:d.D+"B",v:d.v+"B"})}M d}});s.2l();r 59=5a.3P({2l:q(c,e){9.C=$(c);p(!9.C){3z("U: I 5b 5c, 5d 3P a 17.");M}s.1B(9.C);r a=(N.2t(e)||N.2n(e)),b=a?1V[2]||[]:e;9.1r=a?e:2b;p(b.1Y){b=N.Y(N.2c(U.33[b.1Y]),b)}9.o=N.Y(N.Y({1k:X,1h:0,34:"#5e",1n:0,K:s.o.K,1a:s.o.5f,1v:!(b.1b&&b.1b=="1Z")?0.14:X,1D:X,1w:"1H",3Q:X,W:b.W,1e:b.W?{x:0,y:0}:{x:16,y:16},1J:(b.W&&!b.W.1u)?1l:X,1b:"2u",E:X,1Y:"2k",18:9.C,12:X,1C:(b.W&&!b.W.1u)?X:1l,H:X},U.33["2k"]),b);9.18=$(9.o.18);9.1n=9.o.1n;9.1h=(9.1n>9.o.1h)?9.1n:9.o.1h;p(9.o.V){9.V=9.o.V.35("://")?9.o.V:s.V+9.o.V}11{9.V=s.V+"5g/"+(9.o.1Y||"")+"/"}p(!9.V.5h("/")){9.V+="/"}p(N.2t(9.o.E)){9.o.E={O:9.o.E}}p(9.o.E.O){9.o.E=N.Y(N.2c(U.33[9.o.1Y].E)||{},9.o.E);9.o.E.O=[9.o.E.O.29(/[a-z]+/)[0].2e(),9.o.E.O.29(/[A-Z][a-z]+/)[0].2e()];9.o.E.1E=["D","2X"].3R(9.o.E.O[0])?"1d":"1f";9.1s={1d:X,1f:X}}p(9.o.1k){9.o.1k.o=N.Y({36:27.5i},9.o.1k.o||{})}9.1m=$w("5j 3B").3R(9.C.5k.2e())?s.3E:s.1m;p(9.o.W.1u){r d=9.o.W.1t.29(/[a-z]+/)[0].2e();9.1W=s.2a[d]+s.2a[9.o.W.1t.29(/[A-Z][a-z]+/)[0].2e()].2v()}9.3S=(s.2Z&&9.1n);9.3T();s.2O(9);9.3U();U.Y(9)},3T:q(){9.F=J I("Q",{K:"1G"}).u({1o:s.o.1o});p(9.3S){9.F.T=q(){9.u("D:-3V;v:-3V;1K:2w;");M 9};9.F.P=q(){9.u("1K:13");M 9};9.F.13=q(){M(9.37("1K")=="13"&&3G(9.37("v").2N("B",""))>-5l)}}9.F.T();p(s.1j){9.1q=J I("5m",{K:"1q",28:"5n:X;",5o:0}).u({2x:"2f",1o:s.o.1o-1,5p:0})}p(9.o.1k){9.20=9.20.2m(9.38)}9.1t=J I("Q",{K:"1r"});9.12=J I("Q",{K:"12"}).T();p(9.o.1a||(9.o.1w.C&&9.o.1w.C=="1a")){9.1a=J I("Q",{K:"2g"}).21(9.V+"2g.2y")}},2z:q(){p(10.2P){9.39();9.3W=1l;M 1l}11{p(!9.3W){10.1c("3x:2P",9.39);M X}}},39:q(){$(10.3a).L(9.F);p(s.1j){$(10.3a).L(9.1q)}p(9.o.1k){$(10.3a).L(9.R=J I("Q",{K:"5q"}).21(9.V+"R.5r").T())}r g="F";p(9.o.E.O){9.E=J I("Q",{K:"5s"}).u({G:9.o.E[9.o.E.1E=="1f"?"G":"H"]+"B"});r b=9.o.E.1E=="1d";9[g].L(9.3b=J I("Q",{K:"5t 2A"}).L(9.3X=J I("Q",{K:"5u 2A"})));9.E.L(9.1L=J I("Q",{K:"5v"}).u({G:9.o.E[b?"H":"G"]+"B",H:9.o.E[b?"G":"H"]+"B"}));p(s.1j&&!9.o.E.O[1].3Y().35("5w")){9.1L.u({2x:"5x"})}g="3X"}p(9.1h){r d=9.1h,f;9[g].L(9.22=J I("5y",{K:"22"}).L(9.23=J I("3c",{K:"23 3d"}).u("G: "+d+"B").L(J I("Q",{K:"2B 5z"}).L(J I("Q",{K:"24"}))).L(f=J I("Q",{K:"5A"}).u({G:d+"B"}).L(J I("Q",{K:"3Z"}).u({1x:"0 "+d+"B",G:d+"B"}))).L(J I("Q",{K:"2B 5B"}).L(J I("Q",{K:"24"})))).L(9.3e=J I("3c",{K:"3e 3d"}).L(9.3f=J I("Q",{K:"3f"}).u("2C: 0 "+d+"B"))).L(9.40=J I("3c",{K:"40 3d"}).u("G: "+d+"B").L(J I("Q",{K:"2B 5C"}).L(J I("Q",{K:"24"}))).L(f.5D(1l)).L(J I("Q",{K:"2B 5E"}).L(J I("Q",{K:"24"})))));g="3f";r c=9.22.3g(".24");$w("5F 5G 5H 5I").30(q(j,h){p(9.1n>0){U.41(c[h],j,{1M:9.o.34,1h:d,1n:9.o.1n})}11{c[h].2D("42")}c[h].u({H:d+"B",G:d+"B"}).2D("24"+j.2v())}.1g(9));9.22.3g(".3Z",".3e",".42").1I("u",{1M:9.o.34})}9[g].L(9.17=J I("Q",{K:"17 "+9.o.K}).L(9.25=J I("Q",{K:"25"}).L(9.12)));p(9.o.H){r e=9.o.H;p(N.5J(e)){e+="B"}9.17.u("H:"+e)}p(9.E){r a={};a[9.o.E.1E=="1d"?"v":"1p"]=9.E;9.F.L(a);9.2h()}9.17.L(9.1t);p(!9.o.1k){9.3h({12:9.o.12,1r:9.1r})}},3h:q(e){r a=9.F.37("1K");9.F.u("G:1N;H:1N;1K:2w").P();p(9.1h){9.23.u("G:0");9.23.u("G:0")}p(e.12){9.12.P().43(e.12);9.25.P()}11{p(!9.1a){9.12.T();9.25.T()}}p(N.2n(e.1r)){e.1r.P()}p(N.2t(e.1r)||N.2n(e.1r)){9.1t.43(e.1r)}9.17.u({H:9.17.44()+"B"});9.F.u("1K:13").P();9.17.P();r c=9.17.1X(),b={H:c.H+"B"},d=[9.F];p(s.1j){d.2p(9.1q)}p(9.1a){9.12.P().L({v:9.1a});9.25.P()}p(e.12||9.1a){9.25.u("H: 3i%")}b.G=2b;9.F.u({1K:a});9.1t.2D("2A");p(e.12||9.1a){9.12.2D("2A")}p(9.1h){9.23.u("G:"+9.1h+"B");9.23.u("G:"+9.1h+"B");b="H: "+(c.H+2*9.1h)+"B";d.2p(9.22)}d.1I("u",b);p(9.E){9.2h();p(9.o.E.1E=="1d"){9.F.u({H:9.F.44()+9.o.E.G+"B"})}}9.F.T()},3U:q(){9.3j=9.20.1y(9);9.45=9.T.1y(9);p(9.o.1J&&9.o.1b=="2u"){9.o.1b="1i"}p(9.o.1b==9.o.1w){9.1O=9.46.1y(9);9.C.1c(9.o.1b,9.1O)}p(9.1a){9.1a.1c("1i",q(e){e.21(9.V+"5K.2y")}.1g(9,9.1a)).1c("15",q(e){e.21(9.V+"2g.2y")}.1g(9,9.1a))}r c={C:9.1O?[]:[9.C],18:9.1O?[]:[9.18],1t:9.1O?[]:[9.F],1a:[],2f:[]},a=9.o.1w.C;9.3k=a||(!9.o.1w?"2f":"C");9.1P=c[9.3k];p(!9.1P&&a&&N.2t(a)){9.1P=9.1t.3g(a)}r d={1T:"1i",1H:"15"};$w("P T").30(q(h){r g=h.2v(),f=(9.o[h+"47"].3l||9.o[h+"47"]);9[h+"48"]=f;p(["1T","1H","1i","15"].35(f)){9[h+"48"]=(9.1m[f]||f);9["3l"+g]=U.1S(9["3l"+g])}}.1g(9));p(!9.1O){9.C.1c(9.o.1b,9.3j)}p(9.1P){9.1P.1I("1c",9.5L,9.45)}p(!9.o.1J&&9.o.1b=="1Z"){9.2E=9.O.1y(9);9.C.1c("2u",9.2E)}9.49=9.T.2m(q(g,f){r e=f.5M(".2g");p(e){e.5N();f.5O();g(f)}}).1y(9);p(9.1a||(9.o.1w&&(9.o.1w.C==".2g"))){9.F.1c("1Z",9.49)}p(9.o.1b!="1Z"&&(9.3k!="C")){9.2F=U.1S(q(){9.1F("P")}).1y(9);9.C.1c(9.1m.15,9.2F)}r b=[9.C,9.F];9.3m=U.1S(q(){s.2q(9);9.2G()}).1y(9);9.3n=U.1S(9.1D).1y(9);b.1I("1c",9.1m.1i,9.3m).1I("1c",9.1m.15,9.3n);p(9.o.1k&&9.o.1b!="1Z"){9.2H=U.1S(9.4a).1y(9);9.C.1c(9.1m.15,9.2H)}},3H:q(){p(9.o.1b==9.o.1w){9.C.1z(9.o.1b,9.1O)}11{9.C.1z(9.o.1b,9.3j);p(9.1P){9.1P.1I("1z")}}p(9.2E){9.C.1z("2u",9.2E)}p(9.2F){9.C.1z("15",9.2F)}9.F.1z();9.C.1z(9.1m.1i,9.3m).1z(9.1m.15,9.3n);p(9.2H){9.C.1z(9.1m.15,9.2H)}},38:q(c,b){p(!9.17){p(!9.2z()){M}}9.O(b);p(9.2I){M}11{p(9.4b){c(b);M}}9.2I=1l;r e=b.5P(),d={2i:{1Q:e.x,1R:e.y}};r a=N.2c(9.o.1k.o);a.36=a.36.2m(q(g,f){9.3h({12:9.o.12,1r:f.5Q});9.O(d);(q(){g(f);r h=(9.R&&9.R.13());p(9.R){9.1F("R");9.R.1B();9.R=2b}p(h){9.P()}9.4b=1l;9.2I=2b}.1g(9)).1v(0.6)}.1g(9));9.5R=I.P.1v(9.o.1v,9.R);9.F.T();9.2I=1l;9.R.P();9.5S=(q(){J 5T.5U(9.o.1k.2Q,a)}.1g(9)).1v(9.o.1v);M X},4a:q(){9.1F("R")},20:q(a){p(!9.17){p(!9.2z()){M}}9.O(a);p(9.F.13()){M}9.1F("P");9.5V=9.P.1g(9).1v(9.o.1v)},1F:q(a){p(9[a+"4c"]){5W(9[a+"4c"])}},P:q(){p(9.F.13()){M}p(s.1j){9.1q.P()}p(9.o.3Q){s.3L()}s.3K(9);9.17.P();9.F.P();p(9.E){9.E.P()}9.C.4d("1G:5X")},1D:q(a){p(9.o.1k){p(9.R&&9.o.1b!="1Z"){9.R.T()}}p(!9.o.1D){M}9.2G();9.5Y=9.T.1g(9).1v(9.o.1D)},2G:q(){p(9.o.1D){9.1F("1D")}},T:q(){9.1F("P");9.1F("R");p(!9.F.13()){M}9.4e()},4e:q(){p(s.1j){9.1q.T()}p(9.R){9.R.T()}9.F.T();(9.22||9.17).P();s.32(9);9.C.4d("1G:2w")},46:q(a){p(9.F&&9.F.13()){9.T(a)}11{9.20(a)}},2h:q(){r c=9.o.E,b=1V[0]||9.1s,d=s.2Y(c.O[0],b[c.1E]),f=s.2Y(c.O[1],b[s.2a[c.1E]]),a=9.1n||0;9.1L.21(9.V+d+f+".2y");p(c.1E=="1d"){r e=(d=="D")?c.G:0;9.3b.u("D: "+e+"B;");9.1L.u({"2J":d});9.E.u({D:0,v:(f=="1p"?"3i%":f=="1U"?"50%":0),5Z:(f=="1p"?-1*c.H:f=="1U"?-0.5*c.H:0)+(f=="1p"?-1*a:f=="v"?a:0)+"B"})}11{9.3b.u(d=="v"?"1x: 0; 2C: "+c.G+"B 0 0 0;":"2C: 0; 1x: 0 0 "+c.G+"B 0;");9.E.u(d=="v"?"v: 0; 1p: 1N;":"v: 1N; 1p: 0;");9.1L.u({1x:0,"2J":f!="1U"?f:"2f"});p(f=="1U"){9.1L.u("1x: 0 1N;")}11{9.1L.u("1x-"+f+": "+a+"B;")}p(s.2Z){p(d=="1p"){9.E.u({O:"4f",60:"61",v:"1N",1p:"1N","2J":"D",H:"3i%",1x:(-1*c.G)+"B 0 0 0"});9.E.1Y.2x="4g"}11{9.E.u({O:"4h","2J":"2f",1x:0})}}}9.1s=b},O:q(b){p(!9.17){p(!9.2z()){M}}s.2q(9);p(s.1j){r a=9.F.1X();p(!9.2K||9.2K.G!=a.G||9.2K.H!=a.H){9.1q.u({H:a.H+"B",G:a.G+"B"})}9.2K=a}p(9.o.W){r j,h;p(9.1W){r k=10.1C.2s(),c=b.2i||{};r g,i=2;3O(9.1W.3Y()){S"62":S"63":g={x:0-i,y:0-i};19;S"64":g={x:0,y:0-i};19;S"65":S"66":g={x:i,y:0-i};19;S"67":g={x:i,y:0};19;S"68":S"69":g={x:i,y:i};19;S"6a":g={x:0,y:i};19;S"6b":S"6c":g={x:0-i,y:i};19;S"6d":g={x:0-i,y:0};19}g.x+=9.o.1e.x;g.y+=9.o.1e.y;j=N.Y({1e:g},{C:9.o.W.1t,1W:9.1W,1u:{v:c.1R||2L.1R(b)-k.v,D:c.1Q||2L.1Q(b)-k.D}});h=s.W(9.F,9.18,j);p(9.o.1C){r n=9.3o(h),m=n.1s;h=n.O;h.D+=m.1f?2*U.2W(g.x-9.o.1e.x):0;h.v+=m.1f?2*U.2W(g.y-9.o.1e.y):0;p(9.E&&(9.1s.1d!=m.1d||9.1s.1f!=m.1f)){9.2h(m)}}h={D:h.D+"B",v:h.v+"B"};9.F.u(h)}11{j=N.Y({1e:9.o.1e},{C:9.o.W.1t,18:9.o.W.18});h=s.W(9.F,9.18,N.Y({O:1l},j));h={D:h.D+"B",v:h.v+"B"}}p(9.R){r e=s.W(9.R,9.18,N.Y({O:1l},j))}p(s.1j){9.1q.u(h)}}11{r f=9.18.2r(),c=b.2i||{},h={D:((9.o.1J)?f[0]:c.1Q||2L.1Q(b))+9.o.1e.x,v:((9.o.1J)?f[1]:c.1R||2L.1R(b))+9.o.1e.y};p(!9.o.1J&&9.C!==9.18){r d=9.C.2r();h.D+=-1*(d[0]-f[0]);h.v+=-1*(d[1]-f[1])}p(!9.o.1J&&9.o.1C){r n=9.3o(h),m=n.1s;h=n.O;p(9.E&&(9.1s.1d!=m.1d||9.1s.1f!=m.1f)){9.2h(m)}}h={D:h.D+"B",v:h.v+"B"};9.F.u(h);p(9.R){9.R.u(h)}p(s.1j){9.1q.u(h)}}},3o:q(c){r e={1d:X,1f:X},d=9.F.1X(),b=10.1C.2s(),a=10.1C.1X(),g={D:"H",v:"G"};31(r f 3N g){p((c[f]+d[g[f]]-b[f])>a[g[f]]){c[f]=c[f]-(d[g[f]]+(2*9.o.1e[f=="D"?"x":"y"]));p(9.E){e[s.3F[g[f]]]=1l}}}M{O:c,1s:e}}});N.Y(U,{41:q(d,g){r j=1V[2]||9.o,f=j.1n,c=j.1h,e={v:(g.4i(0)=="t"),D:(g.4i(1)=="l")};p(9.2M.26){r b=J I("26",{K:"6e"+g.2v(),H:c+"B",G:c+"B"});d.L(b);r i=b.3r("2d");i.6f=j.1M;i.6g((e.D?f:c-f),(e.v?f:c-f),f,0,6h.6i*2,1l);i.6j();i.4j((e.D?f:0),0,c-f,c);i.4j(0,(e.v?f:0),c,c-f)}11{r h;d.L(h=J I("Q").u({H:c+"B",G:c+"B",1x:0,2C:0,2x:"4g",O:"4f",6k:"2w"}));r a=J I("2j:6l",{6m:j.1M,6n:"6o",6p:j.1M,6q:(f/c*0.5).6r(2)}).u({H:2*c-1+"B",G:2*c-1+"B",O:"4h",D:(e.D?0:(-1*c))+"B",v:(e.v?0:(-1*c))+"B"});h.L(a);a.4k=a.4k}}});I.6s({21:q(c,b){c=$(c);r a=N.Y({4l:"v D",3p:"6t-3p",3q:"6u",1M:""},1V[2]||{});c.u(s.1j?{6v:"6w:6x.6y.6z(28=\'"+b+"\'\', 3q=\'"+a.3q+"\')"}:{6A:a.1M+" 2Q("+b+") "+a.4l+" "+a.3p});M c}});U.4m={P:q(){s.2q(9);9.2G();r d={};p(9.o.W){d.2i={1Q:0,1R:0}}11{r a=9.18.2r(),c=9.18.3M(),b=10.1C.2s();a.D+=(-1*(c[0]-b[0]));a.v+=(-1*(c[1]-b[1]));d.2i={1Q:a.D,1R:a.v}}p(9.o.1k){9.38(d)}11{9.20(d)}9.1D()}};U.Y=q(a){a.C.1G={};N.Y(a.C.1G,{P:U.4m.P.1g(a),T:a.T.1g(a),1B:s.1B.1g(s,a.C)})};U.3s();',62,409,'|||||||||this|||||||||||||||options|if|function|var|Tips||setStyle|top||||||px|element|left|stem|wrapper|height|width|Element|new|className|insert|return|Object|position|show|div|loader|case|hide|Prototip|images|hook|false|extend||document|else|title|visible||mouseout||tooltip|target|break|closeButton|showOn|observe|horizontal|offset|vertical|bind|border|mouseover|fixIE|ajax|true|useEvent|radius|zIndex|bottom|iframeShim|content|stemInverse|tip|mouse|delay|hideOn|margin|bindAsEventListener|stopObserving|tips|remove|viewport|hideAfter|orientation|clearTimer|prototip|mouseleave|invoke|fixed|visibility|stemImage|backgroundColor|auto|eventToggle|hideTargets|pointerX|pointerY|capture|mouseenter|middle|arguments|mouseHook|getDimensions|style|click|showDelayed|setPngBackground|borderFrame|borderTop|prototip_Corner|toolbar|canvas|Prototype|src|match|_inverse|null|clone||toLowerCase|none|close|positionStem|fakePointer|ns_vml|default|initialize|wrap|isElement|zIndexTop|push|raise|cumulativeOffset|getScrollOffsets|isString|mousemove|capitalize|hidden|display|png|build|clearfix|prototip_CornerWrapper|padding|addClassName|eventPosition|eventCheckDelay|cancelHideAfter|ajaxHideEvent|ajaxContentLoading|float|iframeShimDimensions|Event|support|replace|add|loaded|url|window|unload|convertVersionString|length|Browser|toggleInt|right|inverseStem|WebKit419|each|for|removeVisible|Styles|borderColor|include|onComplete|getStyle|ajaxShow|_build|body|stemWrapper|li|borderRow|borderMiddle|borderCenter|select|_update|100|eventShow|hideElement|event|activityEnter|activityLeave|getPositionWithinViewport|repeat|sizingMethod|getContext|start|require|find|namespaces|VML|dom|REQUIRED_|throw|_|input|IE|removeAll|specialEvent|_stemTranslation|parseFloat|deactivate|without|_highest|addVisibile|hideAll|cumulativeScrollOffset|in|switch|create|hideOthers|member|fixSafari2|setup|activate|9500px|_isBuilding|stemBox|toUpperCase|prototip_Between|borderBottom|createCorner|prototip_Fill|update|getWidth|eventHide|toggle|On|Action|buttonEvent|ajaxHide|ajaxContentLoaded|Timer|fire|afterHide|relative|block|absolute|charAt|fillRect|outerHTML|align|Methods|REQUIRED_Prototype|createElement|https|test|js|script|documentMode|urn|schemas|microsoft|com|vml|createStyleSheet|addRule|behavior|typeof|undefined|Version|requires|parseInt|times|indexOf|_captureTroubleElements|textarea|relatedTarget|while|try|parentNode|catch|abs|RegExp|MSIE|exec|navigator|userAgent|WebKit|evaluate|topRight|rightTop||topMiddle|rightMiddle|bottomLeft|leftBottom|bottomRight|rightBottom|bottomMiddle|leftMiddle|Tip|Class|not|available|cannot|000000|closeButtons|styles|endsWith|emptyFunction|area|tagName|9500|iframe|javascript|frameBorder|opacity|prototipLoader|gif|prototip_Stem|prototip_StemWrapper|prototip_StemBox|prototip_StemImage|MIDDLE|inline|ul|prototip_CornerWrapperTopLeft|prototip_BetweenCorners|prototip_CornerWrapperTopRight|prototip_CornerWrapperBottomLeft|cloneNode|prototip_CornerWrapperBottomRight|tl|tr|bl|br|isNumber|close_hover|hideAction|findElement|blur|stop|pointer|responseText|loaderTimer|ajaxTimer|Ajax|Request|showTimer|clearTimeout|shown|hideAfterTimer|marginTop|clear|both|LEFTTOP|TOPLEFT|TOPMIDDLE|TOPRIGHT|RIGHTTOP|RIGHTMIDDLE|RIGHTBOTTOM|BOTTOMRIGHT|BOTTOMMIDDLE|BOTTOMLEFT|LEFTBOTTOM|LEFTMIDDLE|cornerCanvas|fillStyle|arc|Math|PI|fill|overflow|roundrect|fillcolor|strokeWeight|1px|strokeColor|arcSize|toFixed|addMethods|no|scale|filter|progid|DXImageTransform|Microsoft|AlphaImageLoader|background'.split('|'),0,{}));

// ----------------

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

// ----------------

// LiveValidation 1.3 (prototype.js version)
// Copyright (c) 2007-2008 Alec Hill (www.livevalidation.com)
// LiveValidation is licensed under the terms of the MIT License
var LiveValidation=Class.create();Object.extend(LiveValidation,{VERSION:"1.3 prototype",TEXTAREA:1,TEXT:2,PASSWORD:3,CHECKBOX:4,SELECT:5,FILE:6,massValidate:function(C){var D=true;for(var B=0,A=C.length;B<A;++B){var E=C[B].validate();if(D){D=E;}}return D;}});LiveValidation.prototype={validClass:"LV_valid",invalidClass:"LV_invalid",messageClass:"LV_validation_message",validFieldClass:"LV_valid_field",invalidFieldClass:"LV_invalid_field",initialize:function(B,A){if(!B){throw new Error("LiveValidation::initialize - No element reference or element id has been provided!");}this.element=$(B);if(!this.element){throw new Error("LiveValidation::initialize - No element with reference or id of '"+B+"' exists!");}this.elementType=this.getElementType();this.validations=[];this.form=this.element.form;this.options=Object.extend({validMessage:"Thankyou!",onValid:function(){this.insertMessage(this.createMessageSpan());this.addFieldClass();},onInvalid:function(){this.insertMessage(this.createMessageSpan());this.addFieldClass();},insertAfterWhatNode:this.element,onlyOnBlur:false,wait:0,onlyOnSubmit:false},A||{});var C=this.options.insertAfterWhatNode||this.element;this.options.insertAfterWhatNode=$(C);Object.extend(this,this.options);if(this.form){this.formObj=LiveValidationForm.getInstance(this.form);this.formObj.addField(this);}this.boundFocus=this.doOnFocus.bindAsEventListener(this);Event.observe(this.element,"focus",this.boundFocus);if(!this.onlyOnSubmit){switch(this.elementType){case LiveValidation.CHECKBOX:this.boundClick=this.validate.bindAsEventListener(this);Event.observe(this.element,"click",this.boundClick);case LiveValidation.SELECT:case LiveValidation.FILE:this.boundChange=this.validate.bindAsEventListener(this);Event.observe(this.element,"change",this.boundChange);break;default:if(!this.onlyOnBlur){this.boundKeyup=this.deferValidation.bindAsEventListener(this);Event.observe(this.element,"keyup",this.boundKeyup);}this.boundBlur=this.validate.bindAsEventListener(this);Event.observe(this.element,"blur",this.boundBlur);}}},destroy:function(){if(this.formObj){this.formObj.removeField(this);this.formObj.destroy();}Event.stopObserving(this.element,"focus",this.boundFocus);if(!this.onlyOnSubmit){switch(this.elementType){case LiveValidation.CHECKBOX:Event.stopObserving(this.element,"click",this.boundClick);case LiveValidation.SELECT:case LiveValidation.FILE:Event.stopObserving(this.element,"change",this.boundChange);break;default:if(!this.onlyOnBlur){Event.stopObserving(this.element,"keyup",this.boundKeyup);}Event.stopObserving(this.element,"blur",this.boundBlur);}}this.validations=[];this.removeMessageAndFieldClass();},add:function(A,B){this.validations.push({type:A,params:B||{}});return this;},remove:function(A,B){this.validations=this.validations.reject(function(C){return(C.type==A&&C.params==B);});return this;},deferValidation:function(A){if(this.wait>=300){this.removeMessageAndFieldClass();}if(this.timeout){clearTimeout(this.timeout);}this.timeout=setTimeout(this.validate.bind(this),this.wait);},doOnBlur:function(){this.focused=false;this.validate();},doOnFocus:function(){this.focused=true;this.removeMessageAndFieldClass();},getElementType:function(){switch(true){case (this.element.nodeName.toUpperCase()=="TEXTAREA"):return LiveValidation.TEXTAREA;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="TEXT"):return LiveValidation.TEXT;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="PASSWORD"):return LiveValidation.PASSWORD;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="CHECKBOX"):return LiveValidation.CHECKBOX;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="FILE"):return LiveValidation.FILE;case (this.element.nodeName.toUpperCase()=="SELECT"):return LiveValidation.SELECT;case (this.element.nodeName.toUpperCase()=="INPUT"):throw new Error("LiveValidation::getElementType - Cannot use LiveValidation on an "+this.element.type+" input!");default:throw new Error("LiveValidation::getElementType - Element must be an input, select, or textarea!");}},doValidations:function(){this.validationFailed=false;for(var C=0,A=this.validations.length;C<A;++C){var B=this.validations[C];switch(B.type){case Validate.Presence:case Validate.Confirmation:case Validate.Acceptance:this.displayMessageWhenEmpty=true;this.validationFailed=!this.validateElement(B.type,B.params);break;default:this.validationFailed=!this.validateElement(B.type,B.params);break;}if(this.validationFailed){return false;}}this.message=this.validMessage;return true;},validateElement:function(A,C){var D=(this.elementType==LiveValidation.SELECT)?this.element.options[this.element.selectedIndex].value:this.element.value;if(A==Validate.Acceptance){if(this.elementType!=LiveValidation.CHECKBOX){throw new Error("LiveValidation::validateElement - Element to validate acceptance must be a checkbox!");}D=this.element.checked;}var E=true;try{A(D,C);}catch(B){if(B instanceof Validate.Error){if(D!==""||(D===""&&this.displayMessageWhenEmpty)){this.validationFailed=true;this.message=B.message;E=false;}}else{throw B;}}finally{return E;}},validate:function(){if(!this.element.disabled){var A=this.doValidations();if(A){this.onValid();return true;}else{this.onInvalid();return false;}}else{return true;}},enable:function(){this.element.disabled=false;return this;},disable:function(){this.element.disabled=true;this.removeMessageAndFieldClass();return this;},createMessageSpan:function(){var A=document.createElement("span");var B=document.createTextNode(this.message);A.appendChild(B);return A;},insertMessage:function(B){this.removeMessage();var A=this.validationFailed?this.invalidClass:this.validClass;if((this.displayMessageWhenEmpty&&(this.elementType==LiveValidation.CHECKBOX||this.element.value==""))||this.element.value!=""){$(B).addClassName(this.messageClass+(" "+A));if(nxtSibling=this.insertAfterWhatNode.nextSibling){this.insertAfterWhatNode.parentNode.insertBefore(B,nxtSibling);}else{this.insertAfterWhatNode.parentNode.appendChild(B);}}},addFieldClass:function(){this.removeFieldClass();if(!this.validationFailed){if(this.displayMessageWhenEmpty||this.element.value!=""){if(!this.element.hasClassName(this.validFieldClass)){this.element.addClassName(this.validFieldClass);}}}else{if(!this.element.hasClassName(this.invalidFieldClass)){this.element.addClassName(this.invalidFieldClass);}}},removeMessage:function(){if(nxtEl=this.insertAfterWhatNode.next("."+this.messageClass)){nxtEl.remove();}},removeFieldClass:function(){this.element.removeClassName(this.invalidFieldClass);this.element.removeClassName(this.validFieldClass);},removeMessageAndFieldClass:function(){this.removeMessage();this.removeFieldClass();}};var LiveValidationForm=Class.create();Object.extend(LiveValidationForm,{instances:{},getInstance:function(A){var B=Math.random()*Math.random();if(!A.id){A.id="formId_"+B.toString().replace(/\./,"")+new Date().valueOf();}if(!LiveValidationForm.instances[A.id]){LiveValidationForm.instances[A.id]=new LiveValidationForm(A);}return LiveValidationForm.instances[A.id];}});LiveValidationForm.prototype={initialize:function(A){this.element=$(A);this.fields=[];this.oldOnSubmit=this.element.onsubmit||function(){};this.element.onsubmit=function(C){var B=(LiveValidation.massValidate(this.fields))?this.oldOnSubmit.call(this.element,C)!==false:false;if(!B){Event.stop(C);}}.bindAsEventListener(this);},addField:function(A){this.fields.push(A);},removeField:function(A){this.fields=this.fields.without(A);},destroy:function(A){if(this.fields.length!=0&&!A){return false;}this.element.onsubmit=this.oldOnSubmit;LiveValidationForm.instances[this.element.id]=null;return true;}};var Validate={Presence:function(A,B){var C=Object.extend({failureMessage:"Can't be empty!"},B||{});if(A===""||A===null||A===undefined){Validate.fail(C.failureMessage);}return true;},Numericality:function(B,C){var A=B;var B=Number(B);var C=C||{};var D={notANumberMessage:C.notANumberMessage||"Must be a number!",notAnIntegerMessage:C.notAnIntegerMessage||"Must be an integer!",wrongNumberMessage:C.wrongNumberMessage||"Must be "+C.is+"!",tooLowMessage:C.tooLowMessage||"Must not be less than "+C.minimum+"!",tooHighMessage:C.tooHighMessage||"Must not be more than "+C.maximum+"!",is:((C.is)||(C.is==0))?C.is:null,minimum:((C.minimum)||(C.minimum==0))?C.minimum:null,maximum:((C.maximum)||(C.maximum==0))?C.maximum:null,onlyInteger:C.onlyInteger||false};if(!isFinite(B)){Validate.fail(D.notANumberMessage);}if(D.onlyInteger&&((/\.0+$|\.$/.test(String(A)))||(B!=parseInt(B)))){Validate.fail(D.notAnIntegerMessage);}switch(true){case (D.is!==null):if(B!=Number(D.is)){Validate.fail(D.wrongNumberMessage);}break;case (D.minimum!==null&&D.maximum!==null):Validate.Numericality(B,{tooLowMessage:D.tooLowMessage,minimum:D.minimum});Validate.Numericality(B,{tooHighMessage:D.tooHighMessage,maximum:D.maximum});break;case (D.minimum!==null):if(B<Number(D.minimum)){Validate.fail(D.tooLowMessage);}break;case (D.maximum!==null):if(B>Number(D.maximum)){Validate.fail(D.tooHighMessage);}break;}return true;},Format:function(A,B){var A=String(A);var C=Object.extend({failureMessage:"Not valid!",pattern:/./,negate:false},B||{});if(!C.negate&&!C.pattern.test(A)){Validate.fail(C.failureMessage);}if(C.negate&&C.pattern.test(A)){Validate.fail(C.failureMessage);}return true;},Email:function(A,B){var C=Object.extend({failureMessage:"Must be a valid email address!"},B||{});Validate.Format(A,{failureMessage:C.failureMessage,pattern:/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i});return true;},Length:function(A,B){var A=String(A);var B=B||{};var C={wrongLengthMessage:B.wrongLengthMessage||"Must be "+B.is+" characters long!",tooShortMessage:B.tooShortMessage||"Must not be less than "+B.minimum+" characters long!",tooLongMessage:B.tooLongMessage||"Must not be more than "+B.maximum+" characters long!",is:((B.is)||(B.is==0))?B.is:null,minimum:((B.minimum)||(B.minimum==0))?B.minimum:null,maximum:((B.maximum)||(B.maximum==0))?B.maximum:null};switch(true){case (C.is!==null):if(A.length!=Number(C.is)){Validate.fail(C.wrongLengthMessage);}break;case (C.minimum!==null&&C.maximum!==null):Validate.Length(A,{tooShortMessage:C.tooShortMessage,minimum:C.minimum});Validate.Length(A,{tooLongMessage:C.tooLongMessage,maximum:C.maximum});break;case (C.minimum!==null):if(A.length<Number(C.minimum)){Validate.fail(C.tooShortMessage);}break;case (C.maximum!==null):if(A.length>Number(C.maximum)){Validate.fail(C.tooLongMessage);}break;default:throw new Error("Validate::Length - Length(s) to validate against must be provided!");}return true;},Inclusion:function(C,D){var E=Object.extend({failureMessage:"Must be included in the list!",within:[],allowNull:false,partialMatch:false,caseSensitive:true,negate:false},D||{});if(E.allowNull&&C==null){return true;}if(!E.allowNull&&C==null){Validate.fail(E.failureMessage);}if(!E.caseSensitive){var A=[];E.within.each(function(F){if(typeof F=="string"){F=F.toLowerCase();}A.push(F);});E.within=A;if(typeof C=="string"){C=C.toLowerCase();}}var B=(E.within.indexOf(C)==-1)?false:true;if(E.partialMatch){B=false;E.within.each(function(F){if(C.indexOf(F)!=-1){B=true;}});}if((!E.negate&&!B)||(E.negate&&B)){Validate.fail(E.failureMessage);}return true;},Exclusion:function(A,B){var C=Object.extend({failureMessage:"Must not be included in the list!",within:[],allowNull:false,partialMatch:false,caseSensitive:true},B||{});C.negate=true;Validate.Inclusion(A,C);return true;},Confirmation:function(A,B){if(!B.match){throw new Error("Validate::Confirmation - Error validating confirmation: Id of element to match must be provided!");}var C=Object.extend({failureMessage:"Does not match!",match:null},B||{});C.match=$(B.match);if(!C.match){throw new Error("Validate::Confirmation - There is no reference with name of, or element with id of '"+C.match+"'!");}if(A!=C.match.value){Validate.fail(C.failureMessage);}return true;},Acceptance:function(A,B){var C=Object.extend({failureMessage:"Must be accepted!"},B||{});if(!A){Validate.fail(C.failureMessage);}return true;},Custom:function(A,B){var C=Object.extend({against:function(){return true;},args:{},failureMessage:"Not valid!"},B||{});if(!C.against(A,C.args)){Validate.fail(C.failureMessage);}return true;},now:function(A,D,C){if(!A){throw new Error("Validate::now - Validation function must be provided!");}var E=true;try{A(D,C||{});}catch(B){if(B instanceof Validate.Error){E=false;}else{throw B;}}finally{return E;}},Error:function(A){this.message=A;this.name="ValidationError";},fail:function(A){throw new Validate.Error(A);}};

// ----------------

// Oldies
function browseContactList(list)
{
	if ( list != '' )
	{
		new Ajax.Request(list, {onSuccess:browseContactListSuccess, onFailure:browseContactListError });
	}
	else
	{
		$('Contacts').innerHTML = '';	
	}
}
function browseContactListSuccess(t)
{
	var xmlDoc = t.responseXML.documentElement;
	
	var contacts = xmlDoc.childNodes;

	$('Contacts').innerHTML = '';

	for ( var i = 0 ; i < contacts.length ; i++ )
	{
		var nodes = contacts.item(i).childNodes;
		var name = '';
		var id = 0;
		var thumbUrl = '';
		
		for ( var a = 0 ; a < nodes.length ; a++ )
		{
			switch ( nodes.item(a).nodeName )
			{
				case 'id':
					id = nodes.item(a).firstChild.nodeValue;
					break;
				
				case 'name':
					name = nodes.item(a).firstChild.nodeValue;
					break;

				case 'thumbUrl':
					thumbUrl = nodes.item(a).firstChild.nodeValue;
					break;
			}
		}
		
		if ( name != '' )
		{
			var d = document.createElement('DIV');
		
			var lnk = document.createElement('A');
			
			if ( checkAlreadySelectedContact(id) >= 0 )
			{
				Element.addClassName(lnk, 'SelectedContact');
			}

			lnk.id = id;
			lnk.name = name;
			lnk.thumbUrl = thumbUrl;
			
			lnk.innerHTML = '<img src="'+thumbUrl+'" alt="" />'+name;
			lnk.href = 'javascript:void(0);';
			
			lnk.onclick = selectContact;
			
			d.appendChild(lnk);
		
			$('Contacts').appendChild(d);
		}
	}
}
function browseContactListError(t)
{
}
function checkAlreadySelectedContact(id)
{
	var opts = $('DisplaySelectedContacts').options;
	
	for ( var i = 0 ; i < opts.length ; i++ )
	{
		if ( opts[i].value == id )
		{
			return i;
		}
	}
	
	return -1;
}
function selectContact()
{
	var test = checkAlreadySelectedContact(this.id);

	if ( test < 0 )
	{
		Element.addClassName(this, 'SelectedContact');
		
		var opt = document.createElement('OPTION');
		
		opt.text = this.name;
		opt.value = this.id;
		
		$('DisplaySelectedContacts').options.add(opt);
	}
	else
	{
		Element.removeClassName(this, 'SelectedContact');
		
		var obj = $('DisplaySelectedContacts');
		
		obj.remove(test);
	}
	
	var opts = $('DisplaySelectedContacts').options;
	
	var txt = '';
	
	for ( var i = 0 ; i < opts.length ; i++ )
	{
		txt += opts[i].value;
		if ( i < opts.length - 1 ) txt += ',';
	}
	
	$('SelectedContacts').value = txt;
}

/* CONTACTS */
function toggleContactSelection(obj, checkbox)
{
	var cb = $(checkbox);
	
	if ( cb )
	{
		if ( cb.checked == true )
		{
			cb.checked = false;
			Element.removeClassName(obj, 'SelectedContact');
			Element.addClassName(obj, 'Contact');
		}
		else
		{
			cb.checked = true;
			//new Effect.Highlight(obj, {duration: 0.5});
			Element.removeClassName(obj, 'Contact');
			Element.addClassName(obj, 'SelectedContact');
		}
	}
}
function triggerContactAction(form, id, action, confirmation)
{
	var test = true;
	
	if ( confirmation != undefined && confirmation != '' )
	{
		test = confirm(confirmation);
	}
	
	if ( test == true )
	{
		$(id).value = action;
		$(form).submit();
	}
}

/* CONTACTS */
function toggleMessageSelection(obj, checked)
{
	if ( checked == true )
	{
		Element.removeClassName(obj, 'Message');
		Element.addClassName(obj, 'SelectedMessage');
	}
	else
	{
		Element.removeClassName(obj, 'SelectedMessage');
		Element.addClassName(obj, 'Message');
	}
}
function triggerMessageAction(form, id, action, confirmation)
{
	var test = true;
	
	if ( confirmation != undefined && confirmation != '' )
	{
		test = confirm(confirmation);
	}
	
	if ( test == true )
	{
		$(id).value = action;
		$(form).submit();
	}
}

/* SELECT IMAGE */
function openSelectBackgroundContainer(id)
{
	new Element.toggle(id);
}
function closeSelectBackgroundContainer(id)
{
	new Element.toggle(id);
}
function selectBackground(field, display, id)
{
	if ( id == 'NoBackground' )
	{
		Element.hide('CustomBackgroundField');
		$(field).value = '';
	}
	else if ( id == 'CustomBackground' )
	{
		$(field).value = '';
		Element.show('CustomBackgroundField');
	}
	else
	{
		Element.hide('CustomBackgroundField');
		
		var url = $(id).firstChild.id;
		$(field).value = url;
	}
	
	$(display).innerHTML = $(id).innerHTML;
	
	closeSelectBackgroundContainer($(id).parentNode.parentNode);
}
/* SELECT SKIN */
function selectSkin(container, id, field, url)
{
	var skins = $(container).getElementsByClassName('SkinItem');
	$A(skins).each(function(skin){
		skin.removeClassName('Selected');
	}
	);
										 
	$(id).addClassName('Selected');
	
	var csu = $('CustomSkinUrl');
	var cfu = $(field);
	var sb = $('Preset'+field);
	if ( url == "__custom__" )
	{
		if ( csu && !csu.visible() )
		{
			if ( csu ) csu.show();
			if ( cfu )
			{
				if ( sb )
				{
					cfu.value = sb.value;
				}
				else
				{
					cfu.value = '';
				}
			}
		}
	}
	else
	{
		if ( csu ) csu.hide();
		if ( cfu ) cfu.value = url;
	}
}

/* PUBLISH */
function openAccessListPanel()
{
	if ( !document.accessListPanel )
	{
		document.accessListPanel = true;
		
		Element.show('AccessListPanel');
	}
}
function closeAccessListPanel()
{
	if ( document.accessListPanel )
	{
		document.accessListPanel = false;

		Element.hide('AccessListPanel');
	}
}
function toggleMoreOptionsPanel()
{
	Element.toggle('MoreOptionsPanel');
}
function toggleSharingOptionsPanel()
{
	Element.toggle('SharingOptionsPanel');
}
function toggleCustomizeViewerPanel()
{
	Element.toggle('CustomizeViewerPanel');
}
function toggleConvertionOptionsPanel()
{
	Element.toggle('ConvertionOptionsPanel');
}
/* PROFILES */
function openProfileSubscriptionsPanel()
{
	if ( !document.profileSubscriptionsPanel )
	{
		document.profileSubscriptionsPanel = true;
		
		Element.show('ProfileSubscriptionsPanel');
	}
}
function closeProfileSubscriptionsPanel()
{
	if ( document.profileSubscriptionsPanel )
	{
		document.profileSubscriptionsPanel = false;

		Element.hide('ProfileSubscriptionsPanel');
	}
}
/* BOOK */
function openEarlyCommentPanel()
{
	Element.show('PostEarlyCommentForm');
	Element.hide('PostEarlyCommentLoading');

	Form.Element.enable('PostEarlyCommentButton');

	if ( $('PostNewComment') ) Element.hide('PostNewComment');
	
	Element.show('EarlyCommentPanel');
}
function closeEarlyCommentPanel()
{
	if ( $('PostNewComment') ) Element.show('PostNewComment');
	
	Element.hide('EarlyCommentPanel');
}

/* Filesize */
function FileSize(value)
{
	this.Value = value;
		
	this.format = function()
	{
		if ( this.Value < 1024 )
		{
			return this.Value + " o";
		}
		else if ( this.Value < 1024 * 1024 )
		{
			return Math.round(this.Value/1024*100)/100 + " Ko";
		}
		else if ( this.Value < 1024 * 1024 * 1024 )
		{
			return Math.round(this.Value/1024/1024*100)/100 + " Mo";
		}
		else if ( this.Value > 1024 * 1024 * 1024 * 1024 )
		{
			return Math.round(this.Value/1024/1024/1024*100)*100 + " Go";
		}
		else
		{
			return Math.round(this.Value/1024/1024/1024/1024*100)/100 + " To";
		}
	}	
}

// Valide un formulaire dans une popup
function popIt(url, top, left, width, height)
{
	var winName = 'popup'+Math.round(10000*Math.random());
	var newWin = window.open(url, winName, 'top='+top+',left='+left+',resizable=yes,location=no,width='+width+',height='+height+',menubar=no,status=no,scrollbars=yes,menubar=no');
}

function popItCentered(url, width, height)
{
	var left = Math.round(( screen.width - width ) / 2);
	var top = Math.round((screen.height - height ) / 2);
	
	popIt(url, top, left, width, height);
}

function openBook(url)
{
	var width = screen.width;
	var height = screen.height;
	var left =0;
	var top = 0;
	
	var winName = 'book'+Math.round(10000*Math.random());
	window.open(url, winName, 'top='+top+',left='+left+',width='+width+',height='+height+',resizable=yes,location=no,menubar=no,status=no,scrollbars=no,menubar=no');
	
	return false;
}

//

// Affichage/Masquage multiple
function showAll(){
	var args = showAll.arguments;
	for ( i = 0 ; i < args.length ; i++ ) Element.show(args[i]);
}

function hideAll(){
	var args = hideAll.arguments;
	for ( i = 0 ; i < args.length ; i++ ) Element.hide(args[i]);
}

function toggleAll(){
	var args = toggleAll.arguments;
	for ( i = 0 ; i < args.length ; i++ ) Element.toggle(args[i]);
}

/* TIME REMAINING CALCULATOR */
function getCurrentTime()
{
	var t = new Date();
	return Math.round( t.getTime() / 1000 );
}
function calcRemainingTime(start, loaded, total)
{
	var c = getCurrentTime();

	var remaining = Math.round( ( c - start ) * total / loaded - ( c - start ) );

	var hours = Math.floor( remaining / 60 / 60 );
	var minutes = Math.floor( ( remaining - hours * 60 * 60 ) / 60 );
	var seconds = Math.floor( remaining - hours * 60 * 60 - minutes * 60 );
	
	str = "";
	
	if ( hours > 0 )
	{
		str += " "+hours+" h";
	}
	if ( minutes > 0 )
	{
		str += " "+minutes+" min.";
	}
	if ( seconds > 0 )
	{
		str += " "+seconds+" sec.";
	}
	return str;
}

/* BROWSE VIEWS */
function toggleBrowseView(key, id, on, off)
{
	if ( off != undefined ) Element.removeClassName(id, off);
	Element.addClassName(id, on);
	
	Element.show(on+"On");
	Element.hide(on+"Off");
	Element.hide(off+"On");
	Element.show(off+"Off");
	
	Cookie.set("CalameoBrowse"+key+"View", on);
}
function selectBrowseView(key, id, def)
{
	var mode = Cookie.get("CalameoBrowse"+key+"View");

	if ( mode != undefined )
	{
		toggleBrowseView(key, id, mode);	
	}
	else
	{
		toggleBrowseView(key, id, def);	
	}
}

function checkPublicToPrivate(msg, ppm, optionbox, publik, privat)
{
	if ( ppm == publik && $(optionbox).checked == false )
	{
		return confirm(msg);
	}
}