//-----------------------------------------------
//rsh initialization
//-----------------------------------------------
window.dhtmlHistory.create({ toJSON: function(o) { return JSON.stringify(o); }, fromJSON: function(s) { return JSON.parse(s); } });

var historyListener = function(historyLocation, historyData) {
	//alert('listener ' + historyLocation +', ' + historyData);

	//fix history data on web root
	if(historyLocation == '')
		historyLocation = 'page/';

	jQuery.handleLinkClick(historyLocation, false);
};

window.onload = function() {
	dhtmlHistory.initialize();
	dhtmlHistory.addListener(historyListener);

	//bookmark handling - it should work somehow in rsh, but not sure how, so lets hack it a bit
	//check for # in url
	var url = '' + window.location;
	var hash = url.indexOf('#');

	if(hash > 0)
	{
		var href = url.substr(url.indexOf('#') + 1);

		if(href)
			jQuery.handleLinkClick(href);
	}
};

//-----------------------------------------------
//helper functions
//-----------------------------------------------
function parseLinks(what)
{
	var selector = '';

	//build selector string
	for(var i = 0; i < what.length; i++)
		what[i] = '#' + what[i] + ' a[target!=_blank]';
	selector = what.join(', ');

	//remove old click handlers
	$(selector).unbind("click");

	//add click handler
	$(selector)
		.click(function(event)
		{
			jQuery.handleLinkClick($(this).attr('href'));
			event.preventDefault();
		})
}

function initSpecialPages()
{
	if($('#homedescriptions').length)
		initHomeBoxes();

	if($('#gallerydescriptions').length)
		initGallery();
}

function initHomeBoxes()
{
	//default - show info description
	$('#homedescriptions li').hide();
	$('#d_0').show();

	//on mouseover over box - show description
	$('#boxes li a')
		.mouseover(function(event)
		{
			var id = $(this).parent().attr('id');
			id = id.substr(id.indexOf('_')+1);

			//decide which description to show
			switch(id)
			{
				case '1':
				case '3':
				case '6':
				case '8':
				case '9':
					id = '1';
					break;

				case '7':
					id = '2';
					break;

				case '10':
					id = '3';
					break;

				case '12':
					id = '4';
					break;

				case '13':
					id = '5';
					break;

				case '15':
					id = '6';
					break;

				default:
					id = '0';
			}

			//show it
			$('#homedescriptions').fadeOut(
				'fast',
				function()
  			{
  				$('#homedescriptions li').hide();
  				$('#d_'+id).show();
  				$('#homedescriptions').fadeIn('fast');
  			});
		})
}

function initGallery()
{
	//default - show first image
	$('#gallerydescriptions li').hide();
	$('#g_01').show();

	//on mouseover over preview image - show description/big image
	$('#previews li img')
		.mouseover(function(event)
		{
			var src = $(this).attr('src');
			src = src.substr(src.indexOf('gallery/')+8, 2);

			//show it
			$('#gallerydescriptions').fadeOut(
				'fast',
				function()
  			{
  				$('#gallerydescriptions li').hide();
  				$('#g_'+src).show();
  				$('#gallerydescriptions').fadeIn('fast');
  				var preview = $('#preview').children();
  				preview.attr('src', '/media/userfiles/gallery/' + src + '.jpg');
  				preview.attr('alt', $('#g_'+src+' h2').text());
  				preview.attr('title', $('#g_'+src+' h2').text());
  			});
		})
}

function initSuperfish(menu)
{
	$(menu).supersubs(
		{
    	minWidth:			12,			// minimum width of sub-menus in em units
      maxWidth:			27,			// maximum width of sub-menus in em units
      extraWidth:		1				// extra width can ensure lines don't sometimes turn over to slight rounding differences and font-family
		})
		.superfish(
			{
				delay:				300,															// one second delay on mouseout
				animation:		{height:'show',opacity:'show'},		// fade-in and slide-down animation
				speed:				'fast',														// faster animation speed
		});
}

function reloadMenu(menuId)
{
	//reload menu
	$('#menu_' + menuId).load(
		siteName() + 'menu/menu/' + menuId,
		'',
		function ()
		{
			parseLinks(Array('menu_' + menuId));
			//$('#menu_' + menuId + ' ul.acmenu').initMenu();
			initSuperfish('#menu_' + menuId + ' ul.sf-menu');
		}
	);
}

function handleEditorPageMenu()
{
	//editor menu available?
	if(!$('#page-edit').length)
		return;

	//edit mode?
	if($('#editorData').length)
	{
		$('#menu_3 > ul.editormenu > li > a').each(function(index)
		{
    	switch(index)
    	{
    		case 0:
					$(this).addClass('off');
    			break;

    		case 1:
    		case 2:
					$(this).removeClass('off');
    			break;
    	}
  	});
	}
	else
	{
		$('#menu_3 > ul.editormenu > li > a').each(function(index)
		{
    	switch(index)
    	{
    		case 1:
    		case 2:
					$(this).addClass('off');
    			break;
    	}
  	});
	}
}

function handleEditorNewsletterMenu()
{
	//editor menu available?
	if(!$('#newsletter-edit').length)
		return;

	//edit mode?
	if($('#editorData').length)
	{
		$('#menu_5 > ul.editormenu > li > a').each(function(index)
		{
    	switch(index)
    	{
    		case 0:
    		case 3:
					$(this).addClass('off');
    			break;

    		case 1:
    		case 2:
					$(this).removeClass('off');
    			break;
    	}
  	});
	}
	else
	{
		$('#menu_5 > ul.editormenu > li > a').each(function(index)
		{
    	switch(index)
    	{
    		case 1:
    		case 2:
					$(this).addClass('off');
    			break;
    	}
  	});
	}
}

function reloadTitle(type)
{
	//reload title
	$.get(
		siteName() + type + '/title/',
		null,
		function (data, status)
		{
			document.title = data;
		},
		'text'
	);
}

function siteName()
{
	//get site name
	var location = '' + window.location;
	var site = location.substr(7);
	site = site.substr(0, site.indexOf('/'));
	site = 'http://' + site + '/';

	return site;
}

function closeEditor()
{
	//close editor if not closed by save/discard
	if($('#editorData').length)
	{
		delete FCKeditorAPI.__Instances['editorData'];
		$('#editorData').remove();
	}
}

//-----------------------------------------------
//page functions
//-----------------------------------------------
function loadPageContent(href, callback, skipHistory)
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'page/content/' + href,
				'',
				function()
				{
					//add to history
					if(!skipHistory)
						if(href != '' && href != 'pageNew')
							dhtmlHistory.add('page/' + href, null);

					//reload menus
					reloadMenu(2);

					handleEditorPageMenu();

					//reload title
					reloadTitle('page');

					parseLinks(Array('main_content'));

					$('#main_content').fadeIn('slow');

					//for newly created pages
					if(href == 'pageNew')
						dhtmlHistory.add('page/' + $('#pagelink').val(), null);

					//call additional callback
					if(callback)
						callback();
				}
			);
		}
	);
}

function deletePage()
{
	var confirmResult = confirm('Do you really want to delete this page?');
	if(!confirmResult)
		return;

  $.post(
  	siteName() + 'page/delete',
	  {
  		'id': $('#pageid').val(),
  	},
		function (data, status)
		{
			$('#main_content').fadeOut(
				'slow',
				function()
				{
					$('#main_content').empty();
					$('#main_content').append(data);

					reloadMenu(2);

					$("#main_content").fadeIn('slow');
				}
			);
		},
		'text'
  );
}



//-----------------------------------------------
//page editor functions
//-----------------------------------------------
function openPageEditor()
{
	//ignore when editor already started
	if($('#editorData').length)
		return false;

	if(!window.FCKeditor)
	{
		$('head').append('<script src="/media/js/fckeditor/fckeditor.js" type="text/javascript"></script>');
	}

	$("#main_content").fadeOut(
		'slow',
		function()
		{
			$('#page-form').show();
			$('#page-edit').after('<textarea id="editorData" name="editorData"></textarea>');
			$('#editorData').val($('#page').html());
			$('#page').remove();

			window.oFCKeditor = new FCKeditor('editorData')
			window.oFCKeditor.BasePath = siteName() + '/media/js/fckeditor/';
			window.oFCKeditor.Height = 400;
			window.oFCKeditor.ReplaceTextarea();

			$("#main_content").fadeIn('slow');
		}
	);

	/*
	//add ckeditor if not added already - jquery append script element, runs its content and delete script element, so it is not visible in firebug!
	if(!window.CKEDITOR)
	{
		window.CKEDITOR_BASEPATH = siteName() + '/media/js/ckeditor/';
		$('head').append('<script src="media/js/ckeditor/ckeditor.js" type="text/javascript"></script>');
	}

	//remove previous ckeditor instance and replace textarea with new ckeditor
	var instance = window.CKEDITOR.instances['editorData'];
	if(instance)
		window.CKEDITOR.remove(instance);

	window.CKEDITOR.replace('editorData');
	*/
}

function FCKeditor_OnComplete(editorInstance)
{
	handleEditorPageMenu();
}

function closePageEditor(save)
{
	//ignore when no editor
	if(!$('#editorData').length)
		return false;

	var editor = FCKeditorAPI.GetInstance('editorData');

	//save mmodified page and close editor
	if(save)
	{
		if($('#default:checked').val() && !$('#published:checked').val())
		{
			alert('It is not possible to set unpublished page as default.');
			return false;
		}


		//var editorData = window.CKEDITOR.instances['editorData'].getData();
	  $.post(
	  	siteName() + 'page/save',
	  	{
	  		'id': $('#pageid').val(),
	  		'content': editor.GetData(),
	  		'shortTitle': $('#shortTitle').val(),
	  		'longTitle': $('#longTitle').val(),
	  		'menupoint': $('#menupoint input:radio:checked').val(),
	  		'published': $('#published').attr('checked'),
	  		'default': $('#default').attr('checked')
	  	},
			function (data, status)
			{
				if(data.substr(0, 12) == 'saveSuccess/')
				{
					href = data.substr(12);

					dhtmlHistory.add('page/' + href, null);
					loadPageContent(href, null, true);
				}
				else
				{
					alert('There was an error - page was not saved.');

					var href = '' + window.location;
					href = href.substr(href.lastIndexOf('/')+1);

					loadPageContent(href, null, true);
				}
			},
			'text'
		);

		/*
		$("#main_content").fadeOut(
			'slow',
			function()
			{
				$('#page-form').hide();
				$('#page-edit').after('<div id="page"></div>');
				$('#page').html(editor.GetHTML());

				$('#editorData' + '___Config').remove();
				$('#editorData' + '___Frame').remove();
				delete FCKeditorAPI.__Instances['editorData'];
				$('#editorData').remove();

				parseLinks(Array('main_content'));

				$("#main_content").fadeIn('slow');
			}
		);
		*/
	}
	//dont save, reload original content
	else
	{
		var href = '' + window.location;
		href = href.substr(href.lastIndexOf('/')+1);

		loadPageContent(href, null, true);
	}
}


//-----------------------------------------------
//contact form functions
//-----------------------------------------------
function loadContactForm()
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'user/contact/',
				'',
				function()
				{
					//reload menus
					reloadMenu(2);

					//reload title
					//reloadTitle('user');

					parseLinks(Array('main_content'));

					//handle submit of contact form
					handleContactSubmit();

					dhtmlHistory.add('js/contactForm', null);

					$("#main_content").fadeIn('slow', function(){$('#name').focus();});
				}
			);
		}
	);
}

function handleContactSubmit()
{
	//handle submit of form
	$('#contactForm').submit(
		function()
		{
		  $.post(
		  	siteName() + 'user/contact',
		  	{
			  	'contactForm': 'contactForm',
		  		'name': $('#name').val(),
		  		'email': $('#email').val(),
		  		'message': $('#message').val(),
		  		'captcha': $('#captcha').val(),
		  	},
				function (data, status)
				{
					$('#main_content').fadeOut(
						'slow',
						function()
  					{
							$('#main_content').empty();
							$('#main_content').append(data);

							reloadMenu(2);

							handleContactSubmit();

  						$("#main_content").fadeIn('slow');
  					}
					);
				},
				'text'
		  );

			return false;
		}
	);
}

//-----------------------------------------------
//order form functions
//-----------------------------------------------
function loadOrderForm()
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'user/order/',
				'',
				function()
				{
					//reload menus
					reloadMenu(2);

					//reload title
					//reloadTitle('user');

					parseLinks(Array('main_content'));

					//handle submit of order form
					handleOrderSubmit();

					dhtmlHistory.add('js/orderForm', null);

					$("#main_content").fadeIn('slow', function(){$('#name').focus();});
				}
			);
		}
	);
}

function handleOrderSubmit()
{
	//handle submit of form
	$('#orderForm').submit(
		function()
		{
		  $.post(
		  	siteName() + 'user/order',
		  	{
			  	'orderForm': 'orderForm',
		  		'name': $('#name').val(),
		  		'email': $('#email').val(),
		  		'item': $('#item option:selected').val(),
		  		'message': $('#message').val(),
		  		'captcha': $('#captcha').val(),
		  	},
				function (data, status)
				{
					$('#main_content').fadeOut(
						'slow',
						function()
  					{
							$('#main_content').empty();
							$('#main_content').append(data);

							reloadMenu(2);

							handleOrderSubmit();

  						$("#main_content").fadeIn('slow');
  					}
					);
				},
				'text'
		  );

			return false;
		}
	);
}

//-----------------------------------------------
//user functions
//-----------------------------------------------
function loadUserLogin()
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'user/login/',
				'',
				function()
				{
					//reload menus
					reloadMenu(2);

					//reload title
					//reloadTitle('user');

					parseLinks(Array('main_content'));

					//handle submit of login form
					handleLoginSubmit();

					$("#main_content").fadeIn('slow', function(){$('#userName').focus();});
				}
			);
		}
	);
}


function handleLoginSubmit()
{
	//handle submit of login form
	$('#loginForm').submit(
		function()
		{
		  $.post(
		  	siteName() + 'user/login',
		  	{
			  	'loginForm': 'loginForm',
		  		'userName': $('#userName').val(),
		  		'password': $('#password').val(),
		  	},
				function (data, status)
				{
					$('#main_content').fadeOut(
						'slow',
						function()
  					{
							$('#main_content').empty();
							$('#main_content').append(data);

							reloadMenu(2);

							handleLoginSubmit();

  						$("#main_content").fadeIn('slow');
  					}
					);
				},
				'text'
		  );

			return false;
		}
	);
}

function doUserLogout()
{
  $.post(
  	siteName() + 'user/logout',
  	null,
		function (data, status)
		{
			jQuery.handleLinkClick('/page/', false);
		},
		'text'
  );
}


//-----------------------------------------------
//menu editor functions
//-----------------------------------------------
function loadMenuOrder()
{
	//check for jstree
	if(!$.fn.jstree)
	{
		//$('head').append('<script src="media/js/jstree-1.0/jquery.jstree.js" type="text/javascript"></script>');
		$('head').append('<script src="media/js/jsTree-0.9.9a2/jquery.tree.js" type="text/javascript"></script>');
	}

	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'menu/editOrder/',
				'',
				function()
				{
					//add to history
					dhtmlHistory.add('#js/menuOrderEdit', null);

					//reload menus
					reloadMenu(2);

					//reload title
					reloadTitle('page');

					parseLinks(Array('main_content'));

	$('#menu_edit').tree(
		{
			ui :
			{
				theme_path : '/media/js/jstree-0.9/themes/default/style.css'
			}
		}
	);

					$('#main_content').fadeIn('slow');
				}
			);
		}
	);
}

function saveMenuOrder()
{
	//alert($('#menuedit_menu_1 > ul:eq(0)').serializelist('&menu1') + $('#menuedit_menu_2 > ul:eq(0)').serializelist('&menu2'));
	//return false;

	$.post(
		siteName() + 'menu/saveOrder/',
		$('#menuedit_menu_1 > ul:eq(0)').serializelist('&menu1') + $('#menuedit_menu_2 > ul:eq(0)').serializelist('&menu2'),
		function (data, status)
		{
			if(data == 'saveSuccess')
			{
	  		jQuery.handleLinkClick('/page/', false);
			}
			else
			{
				alert('menuOrderSave error');
			}
		},
		'text'
	);

	return false;
}

function cancelMenuOrder()
{
	jQuery.handleLinkClick('/page/', false);

	return false;
}

//-----------------------------------------------
//guestbook content functions
//-----------------------------------------------
function loadGuestbookContent(href)
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'guestbook/content/' + href,
				'',
				function()
				{
					dhtmlHistory.add('guestbook/' + href, null);

					//reload menus
					reloadMenu(2);

					//reload title
					reloadTitle('guestbook');

					parseLinks(Array('main_content'));

					$('#main_content').fadeIn('slow');
				}
			);
		}
	);
}

function loadGuestbookNewEntryForm()
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'guestbook/newEntry',
				'',
				function()
				{
					//reload menus
					reloadMenu(2);

					//reload title
					//reloadTitle('guestbook');

					parseLinks(Array('main_content'));

					//handle submit of geustbook newEntry form
					handleNewEntrySubmit();

					dhtmlHistory.add('js/guestbookNewEntryForm', null);

					$("#main_content").fadeIn('slow', function(){$('#name').focus();});
				}
			);
		}
	);
}

function handleNewEntrySubmit()
{
	$('#newEntryForm').submit(
		function()
		{
		  $.post(
		  	siteName() + 'guestbook/newEntry',
			  {
			  	'newEntryForm': 'newEntryForm',
		  		'name': $('#name').val(),
		  		'email': $('#email').val(),
		  		'message': $('#message').val(),
		  		'captcha': $('#captcha').val(),
		  	},
				function (data, status)
				{
					$('#main_content').fadeOut(
						'slow',
						function()
  					{
							$('#main_content').empty();
							$('#main_content').append(data);

							handleNewEntrySubmit();

  						$("#main_content").fadeIn('slow');
  					}
					);
				},
				'text'
		  );

			return false;
		}
	);
}

function guestbookPublishEntry(id)
{
  $.post(
  	siteName() + 'guestbook/publishEntry',
	  {
  		'id': id,
  	},
		function (data, status)
		{
			loadGuestbookContent('');
		},
		'text'
  );
}

function guestbookDeleteEntry(id)
{
	var confirmResult = confirm('Do you really want to delete this entry?');
	if(!confirmResult)
		return;

  $.post(
  	siteName() + 'guestbook/deleteEntry',
	  {
  		'id': id,
  	},
		function (data, status)
		{
			loadGuestbookContent('');
		},
		'text'
  );
}

function guestbookEditEntry(id)
{
  $.post(
  	siteName() + 'guestbook/editEntry',
	  {
  		'id': id,
  	},
		function (data, status)
		{
			$('#main_content').fadeOut(
				'slow',
				function()
				{
					$('#main_content').empty();
					$('#main_content').append(data);

					handleEditEntrySubmit();

					dhtmlHistory.add('js/guestbookEditEntry/'+id, null);

					$("#main_content").fadeIn('slow');
				}
			);
		},
		'text'
  );
}

function handleEditEntrySubmit()
{
	$('#editEntryForm').submit(
		function()
		{
		  $.post(
		  	siteName() + 'guestbook/editEntry',
			  {
			  	'editEntryForm': 'editEntryForm',
		  		'id': $('#id').val(),
		  		'name': $('#name').val(),
		  		'email': $('#email').val(),
		  		'message': $('#message').val(),
		  		'captcha': $('#captcha').val(),
		  	},
				function (data, status)
				{
					$('#main_content').fadeOut(
						'slow',
						function()
  					{
							$('#main_content').empty();
							$('#main_content').append(data);

							handleEditEntrySubmit();

  						$("#main_content").fadeIn('slow');
  					}
					);
				},
				'text'
		  );

			return false;
		}
	);
}

//-----------------------------------------------
//newsletter content functions
//-----------------------------------------------
function loadNewsletterContent(href)
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'newsletter/content/' + href,
				'',
				function()
				{
					//add to history
					if(href.substr(0, 19) != 'createFromTemplate_')
						dhtmlHistory.add('newsletter/' + href, null);

					//reload menus
					reloadMenu(2);

					handleEditorNewsletterMenu();

					//reload title
					reloadTitle('newsletter');

					parseLinks(Array('main_content'));

					$('#main_content').fadeIn('slow');

					//for newly created newsletters
					if(href.substr(0, 19) == 'createFromTemplate_')
					{
						dhtmlHistory.add('newsletter/' + $('#newsletterid').val(), null);

						//edit page
						openNewsletterEditor();
					}
				}
			);
		}
	);
}

function loadNewsletterTemplates()
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'newsletter/chooseTemplate/',
				'',
				function()
				{
					dhtmlHistory.add('#js/newsletterTemplates', null);

					parseLinks(Array('main_content'));

					$("#main_content").fadeIn('slow');
				}
			);
		}
	);
}

function loadNewsletterArchive(pageNumber)
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'newsletter/archive/' + pageNumber,
				'',
				function()
				{
					dhtmlHistory.add('#js/newsletterArchive/' + pageNumber, null);


					//reload menus
					reloadMenu(2);

					//reload title
					reloadTitle('newsletter');

					parseLinks(Array('main_content'));

					$("#main_content").fadeIn('slow');
				}
			);
		}
	);
}

function loadNewsletterSubscription()
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'newsletter/subscribe/',
				'',
				function()
				{
					dhtmlHistory.add('#js/newsletterSubscribe', null);

					//reload menus
					reloadMenu(2);

					//reload title
					//reloadTitle('newsletter');

					parseLinks(Array('main_content'));

					//handle submit of newsletter subscribe form
					handleSubscriptionSubmit();

					$("#main_content").fadeIn('slow', function(){$('#email').focus();});
				}
			);
		}
	);
}

function handleSubscriptionSubmit()
{
	$('#subscribeForm').submit(
		function()
		{
		  $.post(
		  	siteName() + 'newsletter/subscribe',
			  {
			  	'subscribeForm': 'subscribeForm',
		  		'email': $('#email').val(),
		  		'captcha': $('#captcha').val(),
		  	},
				function (data, status)
				{
					$('#main_content').fadeOut(
						'slow',
						function()
  					{
							$('#main_content').empty();
							$('#main_content').append(data);

							handleSubscriptionSubmit();

  						$("#main_content").fadeIn('slow');
  					}
					);
				},
				'text'
		  );

			return false;
		}
	);
}

function newsletterChooseTargetGroup()
{
	dhtmlHistory.add('js/newsletterChooseTargetGroup/', null);

  $.post(
  	siteName() + 'email/groupList',
	  {
	  	'newsletterId': $('#newsletterId').val(),
  	},
		function (data, status)
		{
			$('#main_content').fadeOut(
				'slow',
				function()
				{
					$('#main_content').empty();
					$('#main_content').append(data);

					parseLinks(Array('main_content'));

					$("#main_content").fadeIn('slow');
				}
			);
		},
		'text'
  );

	return false;
}

function newsletterSend(groupId)
{
	var confirmResult = confirm('Do you really want to mail newsletter?');
	if(!confirmResult)
		return;

  $.post(
  	siteName() + 'newsletter/send/'+groupId,
	  {
	  	'newsletterId': $('#newsletterId').val(),
  	},
		function (data, status)
		{
			$('#main_content').fadeOut(
				'slow',
				function()
				{
					$('#main_content').empty();
					$('#main_content').append(data);

					$("#main_content").fadeIn('slow');
				}
			);
		},
		'text'
  );

	return false;
}

//-----------------------------------------------
//newsletter editor functions
//-----------------------------------------------
function openNewsletterEditor()
{
	//ignore when editor already started
	if($('#editorData').length)
		return false;

	if(!window.FCKeditor)
	{
		$('head').append('<script src="/media/js/fckeditor/fckeditor.js" type="text/javascript"></script>');
	}

	$("#main_content").fadeOut(
		'slow',
		function()
		{
			$('#newsletter-form').show();
			$('#newsletter-edit').after('<textarea id="editorData" name="editorData"></textarea>');
			$('#editorData').val($('#newsletter').html());
			$('#newsletter').remove();

			window.oFCKeditor = new FCKeditor('editorData')
			window.oFCKeditor.BasePath = siteName() + '/media/js/fckeditor/';
			window.oFCKeditor.Height = 400;
			window.oFCKeditor.ReplaceTextarea();

			handleEditorNewsletterMenu();

			$("#main_content").fadeIn('slow');
		}
	);
}

function closeNewsletterEditor(save)
{
	//ignore when no editor
	if(!$('#editorData').length)
		return false;

	var editor = FCKeditorAPI.GetInstance('editorData');

	if(save)
	{
		//var editorData = window.CKEDITOR.instances['editorData'].getData();
	  $.post(
	  	siteName() + 'newsletter/save',
	  	{
	  		'content': editor.GetHTML(),
	  		'shortTitle': $('#shortTitle').val(),
	  		'longTitle': $('#longTitle').val(),
	  		'published': $('#published:checked').val()
	  	},
			function (data, status)
			{
				if(data.substr(0, 12) == 'saveSuccess/')
				{
				}
				else
				{
					alert('There was an error - page was not saved.');
				}

				var href = '' + window.location;
				href = href.substr(href.lastIndexOf('/')+1);

				loadNewsletterContent(href);
			},
			'text'
		);
	}
	//dont save, reload original content
	else
	{
		var href = '' + window.location;
		href = href.substr(href.lastIndexOf('/')+1);

		loadNewsletterContent(href);
	}

	/*
	$("#main_content").fadeOut(
		'slow',
		function()
		{
			$('#newsletter-form').hide();
			$('#newsletter-edit').after('<div id="newsletter"></div>');
			$('#newsletter').html(editor.GetHTML());

			$('#editorData' + '___Config').remove();
			$('#editorData' + '___Frame').remove();
			delete FCKeditorAPI.__Instances['editorData'];
			$('#editorData').remove();

			$("#main_content").fadeIn('slow');
		}
	);
	*/
}

//-----------------------------------------------
//email group functions
//-----------------------------------------------
function emailGroupEdit(id)
{
  $.post(
  	siteName() + 'email/groupEdit',
	  {
  		'id': id,
  	},
		function (data, status)
		{
			$('#main_content').fadeOut(
				'slow',
				function()
				{
					$('#main_content').empty();
					$('#main_content').append(data);

					handleEmailGroupEditSubmit();

					dhtmlHistory.add('js/emailGroupEdit/'+id, null);

					if(id == 'new')
						$("#main_content").fadeIn('slow', function(){$('#name').focus();});
					else
						$("#main_content").fadeIn('slow');
				}
			);
		},
		'text'
  );
}

function emailGroupDelete(id)
{
	var confirmResult = confirm('Do you really want to delete this group?');
	if(!confirmResult)
		return;

  $.post(
  	siteName() + 'email/groupDelete',
	  {
  		'id': id,
  	},
		function (data, status)
		{
			$('#main_content').fadeOut(
				'slow',
				function()
				{
					$('#main_content').empty();
					$('#main_content').append(data);

					parseLinks(Array('main_content'));

					$("#main_content").fadeIn('slow');
				}
			);
		},
		'text'
  );
}

function handleEmailGroupEditSubmit()
{
	$('#editEmailGroupForm').submit(
		function()
		{
		  $.post(
		  	siteName() + 'email/groupEdit',
			  {
			  	'editEmailGroupForm': 'editEmailGroupForm',
		  		'id': $('#id').val(),
		  		'name': $('#name').val(),
		  		'desc': $('#desc').val(),
		  	},
				function (data, status)
				{
					$('#main_content').fadeOut(
						'slow',
						function()
  					{
							$('#main_content').empty();
							$('#main_content').append(data);

							handleEmailGroupEditSubmit();
							parseLinks(Array('main_content'));

  						$("#main_content").fadeIn('slow');
  					}
					);
				},
				'text'
		  );

			return false;
		}
	);
}

function emailGroupAddEmails(id)
{
  $.post(
  	siteName() + 'email/groupAddEmails',
	  {
  		'id': id,
  	},
		function (data, status)
		{
			$('#main_content').fadeOut(
				'slow',
				function()
				{
					$('#main_content').empty();
					$('#main_content').append(data);

					handleEmailGroupAddEmailsSubmit();

					dhtmlHistory.add('js/emailGroupAddEmails/'+id, null);

					$("#main_content").fadeIn('slow');
				}
			);
		},
		'text'
  );
}

function handleEmailGroupAddEmailsSubmit()
{
	$('#emailGroupAddEmailsForm').submit(
		function()
		{
			//parse checkboxes
			var boxes = '';
			$.each($("#emailGroupAddEmailsForm input[name='boxes[]']"), function()
			{
				if(this.checked)
			  	boxes += this.value+'='+'1,';
			  else
			  	boxes += this.value+'='+'0,';
			});


		  $.post(
		  	siteName() + 'email/groupAddEmails',
			  {
			  	'emailGroupAddEmailsForm': 'emailGroupAddEmailsForm',
		  		'id': $('#id').val(),
		  		'boxes': boxes,
		  	},
				function (data, status)
				{
					$('#main_content').fadeOut(
						'slow',
						function()
  					{
							$('#main_content').empty();
							$('#main_content').append(data);

							handleEmailGroupAddEmailsSubmit();
							parseLinks(Array('main_content'));

  						$("#main_content").fadeIn('slow');
  					}
					);
				},
				'text'
		  );

			return false;
		}
	);
}

//-----------------------------------------------
//email address functions
//-----------------------------------------------
function emailList(id)
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'email/emailList/'+id,
				'',
				function()
				{
					dhtmlHistory.add('#js/emailList/'+id, null);

					//reload menus
					reloadMenu(2);

					//reload title
					//reloadTitle('newsletter');

					parseLinks(Array('main_content'));

					$("#main_content").fadeIn('slow');
				}
			);
		}
	);
}

function emailEdit(id)
{
  $.post(
  	siteName() + 'email/emailEdit',
	  {
  		'id': id,
  	},
		function (data, status)
		{
			$('#main_content').fadeOut(
				'slow',
				function()
				{
					$('#main_content').empty();
					$('#main_content').append(data);

					handleEmailEditSubmit();

					dhtmlHistory.add('js/emailEdit/'+id, null);

					if(id == 'new')
						$("#main_content").fadeIn('slow', function(){$('#email').focus();});
					else
						$("#main_content").fadeIn('slow');
				}
			);
		},
		'text'
  );
}

function emailDelete(id)
{
	var confirmResult = confirm('Do you really want to delete this email address?');
	if(!confirmResult)
		return;

  $.post(
  	siteName() + 'email/emailDelete',
	  {
  		'id': id,
  	},
		function (data, status)
		{
			$('#main_content').fadeOut(
				'slow',
				function()
				{
					$('#main_content').empty();
					$('#main_content').append(data);

					parseLinks(Array('main_content'));

					$("#main_content").fadeIn('slow');
				}
			);
		},
		'text'
  );
}

function handleEmailEditSubmit()
{
	$('#editEmailForm').submit(
		function()
		{
			//parse checkboxes
			var boxes = '';
			$.each($("#editEmailForm input[name='boxes[]']"), function()
			{
				if(this.checked)
			  	boxes += this.value+'='+'1,';
			  else
			  	boxes += this.value+'='+'0,';
			});

		  $.post(
		  	siteName() + 'email/emailEdit',
			  {
			  	'editEmailForm': 'editEmailForm',
		  		'id': $('#id').val(),
		  		'email': $('#email').val(),
		  		'boxes': boxes,
		  	},
				function (data, status)
				{
					$('#main_content').fadeOut(
						'slow',
						function()
  					{
							$('#main_content').empty();
							$('#main_content').append(data);

							handleEmailEditSubmit();
							parseLinks(Array('main_content'));

  						$("#main_content").fadeIn('slow');
  					}
					);
				},
				'text'
		  );

			return false;
		}
	);
}

function emailImport()
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'email/emailImport/',
				'',
				function()
				{
					dhtmlHistory.add('#js/emailImport/', null);

					//reload menus
					reloadMenu(2);

					//reload title
					//reloadTitle('newsletter');

					initEmailImport();
					handleEmailImportSubmit();

					$("#main_content").fadeIn('slow');
				}
			);
		}
	);
}


function emailValidationResult(result)
{
	$('#main_content').fadeOut(
		'slow',
		function()
  	{
  		closeEditor();

	  	$('#main_content').load(
				siteName() + 'email/validationResult/' + result,
				'',
				function()
				{
					//reload menus
					reloadMenu(2);

					//reload title
					//reloadTitle('newsletter');

					parseLinks(Array('main_content'));

					$("#main_content").fadeIn('slow');
				}
			);
		}
	);
}

function initEmailImport()
{
	$('#file').uploadify({
		'uploader'  		: '/media/js/uploadify/uploadify.swf',
		'cancelImg' 		: '/media/js/uploadify/cancel.png',
		'script'    		: siteName() + 'email/emailImport/',
		'fileDataName'	:	'file',
		'onComplete'		: uploadifyImportComplete,
		'wmode'					:	'transparent',
		'hideButton'		: true,
		'width'					: 100,
		'height'				: 25,
	});
}

function handleEmailImportSubmit()
{
	$('#importEmailForm').submit(
		function()
		{
			//parse checkboxes
			var boxes = '';
			$.each($("#importEmailForm input[name='boxes[]']"), function()
			{
				if(this.checked)
			  	boxes += this.value+'='+'1,';
			  else
			  	boxes += this.value+'='+'0,';
			});

			//set checkboxes data
			$('#file').uploadifySettings('scriptData', {'importEmailForm' : 'importEmailForm', 'boxes' : boxes});

			//submit
			$('#file').uploadifyUpload();

			return false;
		}
	);
}

function  uploadifyImportComplete(event, queueID, fileObj, response, data)
{
	$('#main_content').fadeOut(
		'slow',
		function()
		{
			$('#main_content').empty();
			$('#main_content').append(response);

			parseLinks(Array('main_content'));

			$("#main_content").fadeIn('slow');
		}
	);

	return true;
}

//-----------------------------------------------
//jquery initialization
//-----------------------------------------------
$(document).ready(function()
{
	jQuery.extend({
	  handleLinkClick: function(href, store)
	  {
	  	var storeHistory = store == false ? false : true;

			//console.log('click ' + href + ' ' + storeHistory);

			//href may contain http://... (IE7)
	  	if(href.substr(0, 7) == 'http://')
	  	{
	  		href = href.substr(7);
	  		href = href.substr(href.indexOf('/'));
	  	}

	  	//href may contain / as first char
	  	if(href.substr(0, 1) == '/')
	  	{
	  		href = href.substr(1);
	  	}

			//href contains page/ (used for non-ajax request)
			//it is page link
	  	if(href.substr(0, 5) == 'page/')
	  	{
	  		href = href.substr(5);

	  		//fadeout/reload/fadein page content
	  		/*
	  		switch(href)
	  		{
	  			case '':
	  			case 'home':
	  				loadPageContent(href, function(){initHomeBoxes();});
	  				break;

					case 'galerie':
	  				loadPageContent(href, function(){initGallery();});
	  				break;

	  			default:
	  				loadPageContent(href);
	  		}
	  		*/
	  		loadPageContent(href, function(){initSpecialPages();});

	  	}
	  	else if(href.substr(0, 11) == 'newsletter/')
	  	{
				href = href.substr(11);

				//fadeout/reload/fadein page content
 				loadNewsletterContent(href);
	  	}
	  	else if(href.substr(0, 10) == 'guestbook/')
	  	{
				href = href.substr(10);

				//fadeout/reload/fadein page content
 				loadGuestbookContent(href);
	  	}
	  	else if(href.substr(0, 3) == 'js/')
	  	{
	  		href = href.substr(3);

	  		//find parameters - i.e. page number for archive
	  		var action = href;
	  		var params = '';
	  		var pos
	  		if((pos = href.indexOf('/')) != -1)
	  		{
	  			action = href.substr(0, pos);
	  			params = href.substr(pos+1);
	  		}

	  		switch(action)
	  		{
	  			case 'pageEdit':
	  				openPageEditor();
	  				break;

	  			case 'pageSave':
	  				closePageEditor(true);
	  				break;

	  			case 'pageDiscard':
	  				closePageEditor(false);
	  				break;

	  			case 'pageDelete':
	  				deletePage();
	  				break;

	  			case 'pageNew':
	  				loadPageContent('pageNew', function(){openPageEditor();});
	  				break;

	  			/*-----------------------------------------------------------------*/
	  			case 'contactForm':
	  				loadContactForm();
	  				break;

	  			/*-----------------------------------------------------------------*/
	  			case 'orderForm':
	  				loadOrderForm();
	  				break;

					/*-----------------------------------------------------------------*/
	  			case 'menuOrderEdit':
	  				loadMenuOrder();
	  				break;

	  			case 'menuOrderSave':
	  				saveMenuOrder();
	  				break;

	  			case 'menuOrderCancel':
	  				cancelMenuOrder();
	  				break;

	  			/*-----------------------------------------------------------------*/
	  			case 'newsletterTemplates':
	  				loadNewsletterTemplates();
	  				break;

	  			case 'newsletterEdit':
	  				openNewsletterEditor();
	  				break;

	  			case 'newsletterSave':
	  				closeNewsletterEditor(true);
	  				break;

	  			case 'newsletterDiscard':
	  				closeNewsletterEditor(false);
	  				break;

	  			case 'newsletterChooseTargetGroup':
	  				newsletterChooseTargetGroup();
	  				break;

	  			case 'newsletterSend':
	  				newsletterSend(params);
	  				break;

	  			case 'newsletterSubscribe':
	  				loadNewsletterSubscription();
	  				break;

	  			case 'newsletterArchive':
	  				loadNewsletterArchive(params);
	  				break;

	  			/*-----------------------------------------------------------------*/
	  			case 'guestbookNewEntryForm':
	  				loadGuestbookNewEntryForm();
	  				break;

	  			case 'guestbookPublishEntry':
	  				guestbookPublishEntry(params);
	  				break;

	  			case 'guestbookEditEntry':
	  				guestbookEditEntry(params);
	  				break;

	  			case 'guestbookDeleteEntry':
	  				guestbookDeleteEntry(params);
	  				break;

					/*-----------------------------------------------------------------*/
	  			case 'userLogin':
	  			case 'userlogin':
	  				loadUserLogin();
	  				break;

	  			case 'userLogout':
						doUserLogout();
	  				break;

					/*-----------------------------------------------------------------*/
					case 'emailGroupEdit':
						emailGroupEdit(params);
	  				break;

					case 'emailGroupDelete':
						emailGroupDelete(params);
	  				break;

					case 'emailGroupAddEmails':
						emailGroupAddEmails(params);
	  				break;

					case 'emailList':
						emailList(params);
	  				break;

					case 'emailEdit':
						emailEdit(params);
	  				break;

					case 'emailDelete':
						emailDelete(params);
	  				break;

					case 'emailImport':
						emailImport();
	  				break;

	  			case 'emailValidationSuccess':
	  				emailValidationResult(1);
	  				break;

	  			case 'emailValidationError':
	  				emailValidationResult(0);
	  				break;
	  		}
	  	}
	  }

	}); //jquery.extend

	//parse links and add click handler
	parseLinks(Array('menu_1', 'menu_2', 'menu_3', 'main_content'));

	initHomeBoxes();

	//init menus
	//$('ul.acmenu').initMenu();
	initSuperfish('ul.sf-menu');

	//serialize ul list to hierarchical array
	$.fn.serializelist = function(prefix)
	{
		var serialized = '';

		//traverse all LIs
		var countLI = 0;
		$(this).children().each(function()
		{
			serialized += prefix + '['+countLI+'][id]=' + $(this).attr('id');

			//recursion for all children ULs
			$(this).children().each(function()
			{
				if(this.tagName == 'UL')
					serialized += $(this).serializelist(prefix + '['+countLI+'][submenu]');
			});

			//next child
			countLI++;
		});

		return(serialized);
	};


}); //document.ready
