/* LANGUAGE SWITCH */
function toggleLanguageSwitch()
{
	Effect.toggle('LanguageSelector', 'slide', {queue:'front', duration: 0.5});	
}
function closeLanguageSwitch(force)
{
	Effect.SlideUp('LanguageSelector', {queue:'front', duration: 0.5});
}

/* HELP LIGHT BOX */
function showHelpLightBox(url)
{
	updateHelpLightBox(url);
	return showLightBox('HelpLightBox', 610);
}
function updateHelpLightBox(url)
{
	$('HelpLBContent').update(Builder.node('div', {className:'AjaxProcessing', style:'height:28px;'}));
	new Ajax.Updater('HelpLBContent', url);
}

/* LOADED LIGHT BOX */
function showLoadedLightBox(url, width, hash)
{
	updateLoadedLightBox(url, hash);
	return showLightBox('LoadedLightBox', width);
}
function updateLoadedLightBox(url, hash)
{
	$('LoadedLBContent').update(Builder.node('div', {className:'AjaxProcessing', style:'height:28px;'}));
	new Ajax.Updater('LoadedLBContent', url, { parameters: hash, evalScripts: true});
}

/* TABS */
function switchTab(tabs, panels, tab, panel)
{
	var tl = $(tabs);
	
	if ( tl )
	{
		var list = Element.childElements(tabs);
		
		for ( var i = 0 ; i < list.length ; i++ )
		{
			if ( list[i].id == tab )
			{
				Element.addClassName(list[i], 'ActiveTab');
				Element.removeClassName(list[i], 'Tab');
			}
			else
			{
				Element.addClassName(list[i], 'Tab');
				Element.removeClassName(list[i], 'ActiveTab');
			}
		}
		
		var pl = $(panels);
		
		if ( pl )
		{
			var list = document.getElementsByClassName('TabPanel');
		
			for ( var i = 0 ; i < list.length ; i++ )
			{
				if ( list[i].id == panel )
				{
					Element.show(list[i]);
				}
				else
				{
					Element.hide(list[i]);
				}
			}
		}
	}
	return false;
}

/*SEARCH */
function goSearch(form, url, id, mode)
{
	$(form).action = url;
	$(id).value = mode;
	$(form).submit();
}

/* TOC */
function tocIncrementLevel(id)
{
	var d = $('Item'+id);
	var level = $('TocLevel'+id);
	
	if ( d && level && level.value < 6 )
	{
		var oldLevel = level.value;
		var newLevel = Math.round(oldLevel)+1;
		level.value = newLevel;
		
		Element.removeClassName('ItemLevel'+id, 'Level'+oldLevel);
		Element.addClassName('ItemLevel'+id, 'Level'+newLevel);
		
		if ( newLevel >= 6 )
		{
			level.value = 6;
			Element.hide('LevelUp'+id);
		}
		else
		{
			Element.show('LevelUp'+id);
		}
		
		Element.show('LevelDown'+id);
	}	
}
function tocDecrementLevel(id)
{
	var d = $('Item'+id);
	var level = $('TocLevel'+id);
	
	if ( d && level && level.value > 1 )
	{
		var oldLevel = level.value;
		var newLevel = Math.round(oldLevel)-1;
		level.value = newLevel;
		
		Element.removeClassName('ItemLevel'+id, 'Level'+oldLevel);
		Element.addClassName('ItemLevel'+id, 'Level'+newLevel);
		
		if ( newLevel <= 1 )
		{
			level.value = 1;
			Element.hide('LevelDown'+id);
		}
		else
		{
			Element.show('LevelDown'+id);
		}
		
		Element.show('LevelUp'+id);
	}	
}
function tocInsert()
{
	var li = document.createElement('LI');
	
	var ul = $('Toc').childNodes;
	
	var index = ++numItems;
	
	li.id = 'Item'+index;
	
	var html = '<table border="0" width="645" cellspacing="4" cellpadding="0">';
	html += '<tr>';
	html += '<td width="15">';
	html += '<a class="NoBg" style="display: none;" id="LevelDown'+index+'" href="javascript:void(0);" onclick="tocDecrementLevel('+index+');"><img src="'+imageUrl+'icons/previous.gif" alt="" /></a>';
	html += '</td>';
	html += '<td width="15">';
	html += '<a class="NoBg" id="LevelUp'+index+'" href="javascript:void(0);" onclick="tocIncrementLevel('+index+');"><img src="'+imageUrl+'icons/next.gif" alt="" /></a>';
	html += '</td>';
	html += '<td>';
	html += '<div id="ItemLevel'+index+'" class="Level1">';
	html += '<input type="text" name="Toc['+index+'][Title]" id="TocTitle'+index+'" value="" style="width: 420px;" />';
	html += '</div>';
	html += '</td>';
	html += '<td width="30" align="right">';
	html += '<input class="Medium" type="text" name="Toc['+index+'][PageNumber]" id="TocPageNumber'+index+'" value="" style="font-weight: bold; width: 30px; text-align: right;" />';
	html += '</td>';
	html += '<td width="15" align="right">';
	html += '<a href="javascript:void(0);" onclick="tocDelete('+index+');"><img src="'+imageUrl+'icons/delete.png" alt="" /></a>';
	html += '<input type="hidden" name="Toc['+index+'][Level]" id="TocLevel'+index+'" value="1" />';
	html += '</td>';
	html += '</tr>';
	html += '</table>';
	
	li.innerHTML = html;
								
	$('Toc').appendChild(li);
	
	Sortable.create("Toc");
}
function tocDelete(id)
{
	var d = $('Item'+id);
	
	if ( d )
	{
		Element.remove(d);
	}
}

/* PANEL */
function initSlidePanel(id, box, left, right, infos, maximum)
{
	$(id).maximum = maximum;
	$(id).box = box;
	$(id).left = left;
	$(id).right = right;
	$(id).infos = infos;
	
	if ( document.slidePanelPage == undefined )
	{
		document.slidePanelPage = new Array();
	}
	
	document.slidePanelPage[id] = 0;

	$(infos).innerHTML = ( document.slidePanelPage[id] + 1 ) + ' / '+maximum;
			
	Element.hide(left);
	
	if ( maximum <= 1 )
	{
		Element.hide(right);	
	}
}
function slidePanel(id, offset)
{
	var box = $(id).box;
	var left = $(id).left;
	var right = $(id).right;
	var maximum = $(id).maximum;
	var infos = $(id).infos;
	
	if ( offset > 0 )
	{
		if ( document.slidePanelPage[id] > 0 )
		{
			document.slidePanelPage[id]--;
			
			new Effect.Move(box, {duration: 0.5, x: offset, mode:"relative", queue: "end"});
			
			$(infos).innerHTML = ( document.slidePanelPage[id] + 1 ) + ' / '+maximum;
			
		}
	}
	else
	{
		if ( document.slidePanelPage[id] < maximum -1 )
		{
			document.slidePanelPage[id]++;
			
			new Effect.Move(box, {duration: 0.5, x: offset, mode:"relative", queue: "end"});
			
			$(infos).innerHTML = ( document.slidePanelPage[id] + 1 ) + ' / '+maximum;
			
		}
	}
	
	if ( document.slidePanelPage[id] == 0 )
	{
		Element.hide(left);
	}
	else
	{
		Element.show(left);
	}
	if ( document.slidePanelPage[id] >= maximum -1 )
	{
		Element.hide(right);
	}
	else
	{
		Element.show(right);
	}
}

/* SEND/SHARE */
function sendShare(url)
{
	var post = $('SendShareForm').serialize() + '&mode=ajax';

	$('ShareFormButton').disabled = true;
	
	Element.hide('SendShareForm');
	Element.show('SendShareLoading');
	Element.hide('SendShareSuccess');
	Element.hide('SendShareError');

	new Ajax.Request(url, {postBody:post, onSuccess:sendShareSuccess, onFailure:sendShareError });
}

function sendShareSuccess(t)
{
	if ( t.responseText == 'ok' )
	{
		$('ShareFormButton').disabled = false;
		
		var obj = $('DisplaySelectedContacts');

		for ( var i = 0 ; i < obj.options.length ; i++ )
		{
			obj.remove(i);
		}
		
		$('SelectedContacts').value = '';
		$('Emails').value = '';
		$('Message').value = '';
		
		$('Contacts').innerHTML = '';
		
		$('Lists').value = '';
	
		Element.hide('SendShareForm');
		Element.hide('SendShareLoading');
		Element.show('SendShareSuccess');
		Element.hide('SendShareError');
	
		//alert(SendShareSuccess);
	}
	else
	{
		sendShareError(t);
	}
}
function sendShareError(t)
{
	$('ShareFormButton').disabled = false;
	
	Element.hide('SendShareForm');
	Element.hide('SendShareLoading');
	Element.hide('SendShareSuccess');
	Element.show('SendShareError');

	//alert(SendShareError);
}
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();
	}
}


/* SEARCH */
function toggleAdvancedSearchPanel()
{
	if ( document.useAdvancedSearch == true )
	{
		document.useAdvancedSearch = false;
		
		$('UseAdvancedSearch').value = '';
		
		new Effect.SlideUp('AdvancedPanel', {duration: 0.5});
	}
	else
	{
		document.useAdvancedSearch = true;

		$('UseAdvancedSearch').value = '1';
		
		new Effect.SlideDown('AdvancedPanel', {duration: 0.5});
	}
}
/* INVITE */
function updateInviteEmails(from, to)
{
	$(to).innerHTML = $(from).value;
}
/* 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);
	
	if ( url == "__custom__" )
	{
		if ( csu && !csu.visible() )
		{
			if ( csu ) csu.show();
			if ( cfu ) cfu.value = '';
		}
	}
	else
	{
		if ( csu ) csu.hide();
		if ( cfu ) cfu.value = url;
	}
}

/* PUBLISH */
function openAccessListPanel()
{
	if ( !document.accessListPanel )
	{
		document.accessListPanel = true;
		
		new Element.show('AccessListPanel');
	}
}
function closeAccessListPanel()
{
	if ( document.accessListPanel )
	{
		document.accessListPanel = false;

		new Element.hide('AccessListPanel');
	}
}
function toggleMoreOptionsPanel()
{
	new Element.toggle('MoreOptionsPanel');
}
function toggleSharingOptionsPanel()
{
	new Element.toggle('SharingOptionsPanel');
}
function toggleCustomizeViewerPanel()
{
	new Element.toggle('CustomizeViewerPanel');
}
function toggleConvertionOptionsPanel()
{
	new Element.toggle('ConvertionOptionsPanel');
}
/* PROFILES */
function openProfileSubscriptionsPanel()
{
	if ( !document.profileSubscriptionsPanel )
	{
		document.profileSubscriptionsPanel = true;
		
		new Element.show('ProfileSubscriptionsPanel');
	}
}
function closeProfileSubscriptionsPanel()
{
	if ( document.profileSubscriptionsPanel )
	{
		document.profileSubscriptionsPanel = false;

		new Element.hide('ProfileSubscriptionsPanel');
	}
}
/* BOOK */
function openEarlyCommentPanel()
{
	//if ( $('SharePanel') ) Element.hide('SharePanel');
	//if ( $('AbusePanel') ) Element.hide('AbusePanel');
	
	Element.show('PostEarlyCommentForm');
	Element.hide('PostEarlyCommentLoading');

	$('PostEarlyCommentButton').disabled = false;

	if ( $('PostNewComment') ) Element.hide('PostNewComment');
	
	Element.show('EarlyCommentPanel');
}
function closeEarlyCommentPanel()
{
	if ( $('PostNewComment') ) Element.show('PostNewComment');
	
	Element.hide('EarlyCommentPanel');
}

/* COMMENTS */

function postComment(url)
{
	var post = 'mode=ajax&' + $('PostComment').serialize();
	
	$('PostCommentButton').disabled = true;
	
	Element.hide('PostCommentForm');
	Element.show('PostCommentLoading');

	new Ajax.Request(url, {postBody:post, onSuccess:postCommentSuccess, onFailure:postCommentError });
}
function postCommentSuccess(t)
{
	if( t.responseText != 'ok' )
	{
		postCommentError(t);
	}
	else{
		
		$('CommentText').value = '';
		
		$('PostCommentButton').disabled = false;

		//Element.hide('EarlyCommentPanel');
		//Element.show('EarlyPostComment');
		Element.show('CommentPanel');
		//Element.show('PostNewComment');
		Element.show('PostCommentForm');
		Element.hide('PostCommentLoading');
		
		alert(PostCommentSuccess);
		
		if ( typeof(updateCommentsList) == 'function' )
		{
			updateCommentsList();
		}
	}
}
function postCommentError(t)
{
	$('CommentText').value = '';
	
	$('PostCommentButton').disabled = false;

	Element.show('PostCommentForm');
	Element.hide('PostCommentLoading');

	alert(PostCommentError);
}

function postEarlyComment(url)
{
	var post = 'mode=ajax&' + $('PostEarlyComment').serialize();
	
	$('PostEarlyCommentButton').disabled = true;
	
	Element.hide('PostEarlyCommentForm');
	Element.show('PostEarlyCommentLoading');

	new Ajax.Request(url, {postBody:post, onSuccess:postEarlyCommentSuccess, onFailure:postEarlyCommentError });
}
function postEarlyCommentSuccess(t)
{
	if( t.responseText!='ok' )
	{
		postEarlyCommentError(t);
	}
	else
	{
		$('EarlyCommentText').value = '';
		
		$('PostEarlyCommentButton').disabled = false;

		Element.hide('EarlyCommentPanel');
		Element.show('EarlyPostComment');
		Element.show('CommentPanel');
		Element.show('PostNewComment');
		
		Element.show('PostEarlyCommentForm');
		Element.hide('PostEarlyCommentLoading');
	
		alert(PostCommentSuccess);
		
		if ( typeof(updateCommentsList) == 'function' )
		{
			updateCommentsList();
		}
	}
}
function postEarlyCommentError(t)
{
	$('EarlyCommentText').value = '';
	
	$('PostEarlyCommentButton').disabled = false;

	Element.show('PostEarlyCommentForm');
	Element.hide('PostEarlyCommentLoading');

	alert(PostCommentError);
}

function publishComment(url)
{
	var post = 'mode=ajax';
	
	Element.hide('CommentsList');
	Element.show('CommentsLoading');

	new Ajax.Request(url, {postBody: post, onSuccess:publishCommentSuccess, onFailure:publishCommentError});
}
function publishCommentSuccess(t)
{
	if( t.responseText=='error' )
	{
		publishCommentError(t);
	}
	else{
		
		if ( typeof(updateCommentsList) == 'function' )
		{
			updateCommentsList();
		}
		
		alert(PublishCommentSuccess);
	}
}
function publishCommentError(t)
{
	Element.show('CommentsList');
	Element.hide('CommentsLoading');

	alert(PublishCommentError);
}

function unpublishComment(url, success_msg)
{
	var post = 'mode=ajax';
	
	Element.hide('CommentsList');
	Element.show('CommentsLoading');

	new Ajax.Request(url, {postBody: post, onSuccess:unpublishCommentSuccess, onFailure:unpublishCommentError});
}
function unpublishCommentSuccess(t)
{
	if( t.responseText=='error' )
	{
		unpublishCommentError(t);
	}
	else{
		
		if ( typeof(updateCommentsList) == 'function' )
		{
			updateCommentsList();
		}
		
		alert(UnpublishCommentSuccess);
	}
}
function unpublishCommentError(t)
{
	Element.show('CommentsList');
	Element.hide('CommentsLoading');

	alert(UnpublishCommentError);
}

function blockPosterComment(url, message)
{
	var test = true;
	
	if ( message != '' && message != undefined )
	{
		test = confirm(message);	
	}
	
	if ( test == true )
	{
		var post = 'mode=ajax';
		
		Element.hide('CommentsList');
		Element.show('CommentsLoading');
	
		new Ajax.Request(url, {postBody: post, onSuccess:blockPosterCommentSuccess, onFailure:blockPosterCommentError});
	}
}
function blockPosterCommentSuccess(t)
{
	if( t.responseText=='error' )
	{
		blockPosterCommentError(t);
	}
	else{
		
		if ( typeof(updateCommentsList) == 'function' )
		{
			updateCommentsList();
		}
		
		alert(BlockPosterCommentSuccess);
	}
}
function blockPosterCommentError(t)
{
	Element.show('CommentsList');
	Element.hide('CommentsLoading');

	alert(BlockPosterCommentError);
}

function reportSpamComment(url, id, message)
{
	var test = true;
	
	if ( message != '' && message != undefined )
	{
		test = confirm(message);	
	}
	
	if ( test == true )
	{
		var post = 'mode=ajax';
		
		new Ajax.Request(url,
						 	{
								postBody: post,
								onSuccess:function(t)
								{
									if ( t.responseText == 'ok' )
									{
										alert(DeleteCommentSuccess);
										new Effect.Fade('Comment'+id);									
									}
									else
									{
										alert(DeleteCommentError);
									}
								},
								onFailure:function(t)
								{
									alert(DeleteCommentError);
								}
							}
						);
	}
}

function deleteComment(url, message)
{
	var test = true;
	
	if ( message != '' && message != undefined )
	{
		test = confirm(message);	
	}
	
	if ( test == true )
	{
		var post = 'mode=ajax';
	
		Element.hide('CommentsList');
		Element.show('CommentsLoading');
	
		new Ajax.Request(url, {postBody: post, onSuccess:deleteCommentSuccess, onFailure:deleteCommentError});
	}
}
function deleteCommentSuccess(t)
{
	if( t.responseText=='error' )
	{
		deleteCommentError(t);
	}
	else{
		
		if ( typeof(updateCommentsList) == 'function' )
		{
			updateCommentsList();
		}
		
		alert(DeleteCommentSuccess);
	}
}
function deleteCommentError(t)
{
	Element.show('CommentsList');
	Element.hide('CommentsLoading');

	alert(DeleteCommentError);
}

/* MESSAGE */
function reportSpamMessage(url, redirect, message)
{
	var test = true;
	
	if ( message != '' && message != undefined )
	{
		test = confirm(message);	
	}
	
	if ( test == true )
	{
		var post = 'mode=ajax';
		
		new Ajax.Request(url,
						 	{
								postBody: post,
								onSuccess:function(t)
								{
									if ( t.responseText == 'ok' )
									{
										window.location = redirect;
									}
									else
									{
										alert(DeleteMessageError);
									}
								},
								onFailure:function(t)
								{
									alert(DeleteMessageError);
								}
							}
						);
	}
}

/* GROUP POOL */
function updateGroupPool(url)
{
	Element.hide('GroupPoolList');
	Element.show('GroupPoolLoading');
	
	new Ajax.Updater('LoadedLBContent', url, {onSuccess:showGroupPoolSuccess});
}
function showGroupPoolSuccess(t)
{
	Element.show('GroupPoolList');
	Element.hide('GroupPoolLoading');
}
function addToGroupPool(url, refresh_url)
{
	var post = 'mode=ajax&' + $('GroupPoolForm').serialize();

	$('GroupPoolButton').disabled = true;

	Element.hide('GroupPoolList');
	Element.show('GroupPoolLoading');

	new Ajax.Request(url,
					 		{
								postBody:post,
								onSuccess:function(t){
											if( t.responseText!='ok' )
											{
												$('GroupPoolButton').disabled = false;
											
												Element.show('GroupPoolList');
												Element.hide('GroupPoolLoading');
											
												alert(GroupPoolError);
											}
											else{
												$('GroupPoolButton').disabled = false;
												
												updateGroupPool(refresh_url);
											}
								},
								onFailure:function(t){
											$('GroupPoolButton').disabled = false;
										
											Element.show('GroupPoolList');
											Element.hide('GroupPoolLoading');
										
											alert(GroupPoolError);
								}
							}
						);
}
function removeFromGroupPool(url, refresh_url)
{
	var post = 'mode=ajax';

	Element.hide('GroupPoolList');
	Element.show('GroupPoolLoading');

	new Ajax.Request(url,
					 		{
								postBody:post,
								onSuccess:function(t){
									if( t.responseText!='ok' )
									{
										groupPoolError(t);
									}
									else
									{
										updateGroupPool(refresh_url);
									}
								},
								onFailure:function(t){
									Element.show('GroupPoolList');
									Element.hide('GroupPoolLoading');
								
									alert(GroupDepoolError);
								}
							}
						);
}

/* ABUSE */
function reportAbuse(url)
{
	var post = 'mode=ajax&' + $('AbuseForm').serialize();

	$('ReportAbuseButton').disabled = true;

	Element.hide('ReportAbuseForm');
	Element.show('ReportAbuseLoading');

	new Ajax.Request(url, {postBody:post, onSuccess:reportAbuseSuccess, onFailure:reportAbuseError });
}
function reportAbuseSuccess(t)
{
	if( t.responseText!='ok' )
	{
		reportAbuseError(t);
	}
	else{
		$('ReportAbuseButton').disabled = false;
		
		Element.hide('ReportAbuseForm');
		Element.hide('ReportAbuseLoading');
		Element.hide('ReportAbuseError');
		Element.show('ReportAbuseSuccess');
		
		//hideLightBox('AbusePanel');
		
		//alert(ReportAbuseSuccess);
	}
}
function reportAbuseError(t)
{
	$('ReportAbuseButton').disabled = false;

	Element.hide('ReportAbuseForm');
	Element.hide('ReportAbuseLoading');
	Element.show('ReportAbuseError');
	Element.hide('ReportAbuseSuccess');

	//alert(ReportAbuseError);
}

/* FAVORITES */
function addToFavorites(url)
{
	Element.addClassName('AddToFavorites', 'AjaxProcessing');
	
	new Ajax.Request(url, {onSuccess:addToFavSuccess, onFailure:addToFavError});
}

function removeFromFavorites(url)
{
	Element.addClassName('RemoveFromFavorites', 'AjaxProcessing');
	
	new Ajax.Request(url, {onSuccess:remFromFavSuccess, onFailure:remFromFavError});
}
function addToFavSuccess(t)
{
	var reg = new RegExp("^([0-9]+)\:ok$","i");

	if ( !t.responseText.match(reg) )
	{
		addToFavError(t);
	}else {
		Element.removeClassName('AddToFavorites', 'AjaxProcessing');
		
		Element.hide('AddToFavorites');
		Element.show('RemoveFromFavorites');
	}
}
function addToFavError(t)
{
	Element.removeClassName('AddToFavorites', 'AjaxProcessing');

	Element.show('AddToFavorites');
	Element.hide('RemoveFromFavorites');
	alert('Error ' + t.status + ' -- ' + t.statusText);
}
function remFromFavSuccess(t)
{
	var reg = new RegExp("^([0-9]+)\:ok$","i");
	
	if ( !t.responseText.match(reg) )
	{
		remToFavError(t);
	}else {
		Element.removeClassName('RemoveFromFavorites', 'AjaxProcessing');

		Element.show('AddToFavorites');
		Element.hide('RemoveFromFavorites');
	}
}
function remFromFavError(t)
{
	Element.removeClassName('RemoveFromFavorites', 'AjaxProcessing');

	Element.hide('AddToFavorites');
	Element.show('RemoveFromFavorites');
	alert('Error ' + t.status + ' -- ' + t.statusText);
}
function deleteFavorite(url, message)
{
	var test = true;
	
	if ( message != '' && message != undefined )
	{
		test = confirm(message);	
	}
	
	if ( test == true )
	{
		var post = 'mode=ajax';
	
		new Ajax.Request(url, {postBody: post, onSuccess:deleteFavoriteSuccess, onFailure:deleteFavoriteError});
	}
}
function deleteFavoriteSuccess(t)
{
	var reg = new RegExp("^([0-9]+)\:ok$","i");

	if ( !t.responseText.match(reg) )
	{
		deleteFavoriteError(t);
	}
	else{
		var id = parseInt(t.responseText);

		alert(DeleteFavoriteSuccess);
		
		new Element.hide('Favorite'+id);
	}
}
function deleteFavoriteError(t)
{
	alert(DeleteFavoriteError);
}

/* CONTACTS */
function addToContacts(url)
{
	post = $('AddToContactsForm').serialize();

	Element.hide('AddToContactsForm');
	Element.show('AddToContactsLoading');
	
	new Ajax.Request(url, {postBody:post, onSuccess:addToContactSuccess, onFailure:addToContactError});
}

function removeFromContacts(url, message)
{
	var test = true;
	
	if ( message != '' && message != undefined )
	{
		test = confirm(message);	
	}
	
	if ( test == true )
	{
		Element.addClassName('RemoveFromContacts', 'AjaxProcessing');
		
		new Ajax.Request(url, {onSuccess:remFromContactSuccess, onFailure:remFromContactError});
	}
}
function addToContactSuccess(t)
{
	if ( t.responseText == 'ok' )
	{
		$('NewList').value = "";

		var lists = $('ListContainer').getElementsByTagName('INPUT');
		
		if ( lists )
		{
			for ( var i = 0 ; i < lists.length ; i++ )
			{
				if ( lists[i].type == 'checkbox' )
				{
					lists[i].checked = false;
				}
			}
		}
		
		hideLightBox('AddToContactsPanel');
		
		Element.show('AddToContactsForm');
		Element.hide('AddToContactsLoading');
	
		Element.hide('AddToContacts');
		Element.show('RemoveFromContacts');

		alert(AddToContactsSuccess);
	}
	else
	{
		addToContactError(t);
	}
}
function addToContactError(t)
{
	Element.show('AddToContacts');
	Element.hide('RemoveFromContacts');
	
	Element.show('AddToContactsForm');
	Element.hide('AddToContactsLoading');

	alert(AddToContactsError);

	toggleAddToContactsPanel();
}
function remFromContactSuccess(t)
{
	Element.removeClassName('RemoveFromContacts', 'AjaxProcessing');
	
	Element.show('AddToContacts');
	Element.hide('RemoveFromContacts');

	alert(RemoveFromContactsSuccess);
}
function remFromContactError(t)
{
	Element.removeClassName('RemoveFromContacts', 'AjaxProcessing');

	Element.hide('AddToContacts');
	Element.show('RemoveFromContacts');

	alert(RemoveFromContactsError);
}

/* MISC */
function toggleExpirationPanel(value, comparison)
{
	if ( value == comparison )
	{
		Element.hide('ExpirationPanel');
	}
	else
	{
		Element.show('ExpirationPanel');
	}
}

/* PROGRESS BAR */
function ProgressBar(container, bar, percent){
	this.Container = $(container);
	this.Bar = $(bar);
	if ( !percent ) percent = 0;
	this.setProgress = function(percent, effect)
	{
		this.Bar.morph('width:'+percent+'%');
	}
	this.resetProgress = function()
	{
		this.Bar.setStyle({width: '0px'});	
	}
}

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; // Math.round(screen.width/ 2);
	var top = 0; //Math.round(screen.height/ 2);
	
	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;
}

//
function askBeforeRedirect(msg, url){
	var answer = confirm(msg);
	if ( answer ) window.location = url;
}

// Détection d'objets
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+args[i+1]+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+args[i+1]+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+args[i+1]+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+args[i+1]+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

// 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]);
}

function limitTextFieldLength(text,length, update){
	if ( text.value.length > length ) text.value = text.value.substr(0,length);
	if ( update ) $(update).innerHTML = length - text.value.length;	
}

/* 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;
}

/* AJAX */
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)}});
}

/* 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);	
	}
}

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');
  }
};

/* 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(); //.observe('click', (function(event) { if (event.element().id == id) hideLightBox(id); }));
	}
	// Visibility: hidden et non pas display none pour l'upload SWFUpload
	$$('select', 'object', 'embed', 'iframe').each(function(node){ if( !Element.descendantOf(node, id) ) node.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)/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)
{
	$(id).hide();
	if ( ignore_overlay == undefined ) $('lbOverlay').hide();
	$$('select', 'object', 'embed', 'iframe').each(function(node){ if( !Element.descendantOf(node, id) ) node.style.visibility = 'visible' });
}
function hideAllLightBoxes(ignore_overlay)
{
	var boxes = document.getElementsByClassName('LightBox');
	for(var i = 0;i<boxes.length;i++) hideLightBox(boxes[i], ignore_overlay);
}
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];
}

/* STAR RATING */
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();
		
		this.locked = true;
		
		this.NewRate = rate;
		
		var post = 'mode=ajax&Rating=' + this.NewRate;
		
		Element.show(this.Loading);
		Element.hide(this.Indicator);
		//Element.hide(this.Stars);
		
		// Making Ajax call
		this.Responder = Ajax.Responders.register(this);
		new Ajax.Request(this.AjaxUrl, {postBody:post});
	},
	onComplete: function(request, response)
	{
		Ajax.Responders.unregister(this.Responder);
		
		if ( response.responseText == 'ok' )
		{
			this.Rate = this.NewRate;
			this.setStars(this.Rate);
		
			Element.hide(this.Loading);
			Element.show(this.Indicator);
			//Element.show(this.Stars);
			
			this.setIndicator(this.ThankText);
			new Effect.Highlight(this.Element, {startcolor:'#e0FFc9', endcolor:'#F8F9FA'});
			
			this.locked = false;
			
			//alert('Success: '+response.responseText);	
		}
		else
		{
			this.onFailure(request, response);	
		}
	},
	onFailure: function(request, response)
	{
		Ajax.Responders.unregister(this.Responder);
		
		this.locked = false;
		
		this.setStars(this.Rate);

		Element.hide(this.Loading);
		Element.show(this.Indicator);
		//Element.show(this.Stars);
		
		alert('Error!');	
	}
});
function openLoginPanel()
{
	return showLightBox('LoginPanel', 760);	
}
function openSharePanel()
{
	if ( $('SendShareForm') ) Element.show('SendShareForm');
	if ( $('SendShareLoading') ) Element.hide('SendShareLoading');
	if ( $('SendShareSuccess') ) Element.hide('SendShareSuccess');
	if ( $('SendShareError') ) Element.hide('SendShareError');
	showLightBox('SharePanel', 500);
	if ( $('Lists') ) Element.show('Lists');
	if ( $('DisplaySelectedContacts') ) Element.show('DisplaySelectedContacts');
}

/* ArrowSwitch */
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);
	}
}

function checkPublicToPrivate(msg, ppm, optionbox, public, private)
{
	if ( ppm == public && $(optionbox).checked == false )
	{
		return confirm(msg);
	}
}

function updateBookName(url, newname)
{
	var post = new Hash();
	
	post.set('do', 'update_title');
	post.set('NewTitle', newname);

	new Ajax.Request(url, {parameters:post, onSuccess:function(t){
												if( t.responseText=='ok' )
												{
													$('BookName').innerHTML = newname;
													$('BookNameView').show();
													$('BookNameEdit').hide();
												}
												else
												{
													new Effect.Highlight('BookNameEdit', {startcolor: '#F4887E', endcolor: '#FFFFFF'});
												}
										  },
										  onFailure:function(t){
												new Effect.Highlight('BookNameEdit', {startcolor: '#F4887E', endcolor: '#FFFFFF'});
										  }});
}

function checkSkinSyntax(url, skinUrl, container)
{
	params = new Hash();
	params.set('SkinUrl', skinUrl);
	$(container).update(Builder.node('div', {className:'AjaxProcessing', style:'height:28px;'}));
	
	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' );
							}
					 }
					);
}

var Switcher = Class.create({
	
	initialize: function(container, switcher_class)
	{
		this.Container = container;
		this.SwitcherClass = switcher_class;
	},
	
	addSwitch: function(switcher, panel, status)
	{
		var sw = $(switcher);
		sw.__Panel = $(panel);
		sw.__Switcher = this;
		
		Event.observe(sw, 'click', this.togglePanelEvent);
		
		if ( status == 'on' )
		{
			sw.removeClassName('SwitcherOff');
			sw.addClassName('SwitcherOn');
			
			sw.__Panel.show();
		}
		else
		{
			//sw.addClassName('Grey');
			sw.removeClassName('SwitcherOn');
			sw.addClassName('SwitcherOff');
			
			sw.__Panel.hide();
		}
	},
	
	openPanel: function(switcher)
	{
		var sw = $(switcher);
		
		//sw.removeClassName('Grey');
		sw.removeClassName('SwitcherOff');
		sw.addClassName('SwitcherOn');
		
		sw.__Panel.show();
	},
	
	closePanel: function(switcher)
	{
		var sw = $(switcher);
	
		//sw.addClassName('Grey');
		sw.removeClassName('SwitcherOn');
		sw.addClassName('SwitcherOff');
		
		sw.__Panel.hide();
	},
	
	togglePanelEvent: function(evnt)
	{
		var sw = evnt.element();

		sw.__Switcher.closeAll();

		if ( sw.hasClassName('SwitcherOff') )
		{
			sw.__Switcher.openPanel(sw);
		}
		else
		{
			sw.__Switcher.closePanel(sw);
		}
	},
	
	closeAll: function()
	{
		$$('#'+this.Container+' .'+this.SwitcherClass).each( function(element){ element.__Switcher.closePanel( element ); });
	}
});

var datas = [];
function getChartData(id)
{
	return datas[id];
}