/* rxMenu - RASAMAX Menu Library
SIA RASAMAX - 2009

Requirements:
rxLib
jQuery - http://jquery.com
jQuery UI - http://jqueryui.com
jQuery.form - http://malsup.com/jquery/form/
Jeditable - http://www.appelsiini.net/projects/jeditable
livequery - http://plugins.jquery.com/project/livequery/
*/

//////////////////////////////////////////////////////////////
// rx-menu
//////////////////////////////////////////////////////////////

if (!rx) var rx = {};

rx = $.extend(rx, {

// Menu setup
menuInit : function () {
//var executionTime = new Date();
$('.rx-menu').each(function () {
var menuId = $(this).attr('menuId');
var isNormal = $(this).is('.normal');

// If appropriate directory is found on a page then make menu .withDirectory
rx.menuInitDirectory(menuId);

// Removes blank image to show [+] if .normal.expandByPlus & has subs
$('li:has(>ul) > a table .rx-plus').removeClass('rx-blank');

// Define .rx-plus [+] event for all cases of use (temporal and constant)
$('.rx-menu[menuId='+menuId+']').delegate('.rx-plus:not(.rx-blank)','click',function (event) {
	rx.menuToggleCategory($(this).parents('li:first'));
	// Stop trigger of parent <a>.click and .href
	event.stopPropagation();
	event.preventDefault();
	return false; // !!! stopPropagation didn't work
});


// Activate expand of normal menu (except 'none' categories)
if ($('.rx-menu[menuId='+menuId+']').is('.normal'))
	// if ExpandByPlus then <plus> expands categories else <a> expands
	if (!$('.rx-menu[menuId='+menuId+']').is('.expandByPlus'))
		$('.rx-menu[menuId='+menuId+']').delegate('a[href]','click',function () {
		var catId = $(this).parents('li:first').attr('id');
		var catIdNum = catId.substring(catId.lastIndexOf('g')+1,catId.lastIndexOf('_'));
		rx.menuToggleCategoryFromRoot('m'+menuId+'g'+catIdNum);
		});

// Activate a category selection click (except 'none' categories)
$('.rx-menu[menuId='+menuId+']').delegate('a[href]','click', function () {
	var parentLi = $(this).parents('li:first');
	var catId = $(parentLi).attr('id');
	var catIdNum = catId.substring(catId.lastIndexOf('g')+1,catId.lastIndexOf('_'));
	// Make category selected
	rx.menuMakeCategorySelected(parentLi);
	// Make Hash-based request
	if (this.search) rx.history(this.search);
	// If category is a remote URL link
	var outerHTML = this.outerHTML || null;
	// Fix for Firefox who doesn't support outerHTML
	if (!outerHTML) {
		outerHTML = $('<div></div').append($(this).clone()).html();
	}
	if (outerHTML.match(/\"http:/i)) rx.menuRemoteCategoryCallOld('m'+menuId+'g'+catIdNum);
	else return false;
});

// Activate icon change for current style
//if ($('.rx-menu[menuId='+menuId+']').attr('currentItemIcon')!='')
if ($(this).attr('currentItemIcon')!='')
	$(this).delegate('tr','click',function () {
		var menu = $('.rx-menu[menuId='+menuId+']');
		$('img.rx-icon',menu).not('img[categoryIcon]').attr({'src':menu.attr('itemIcon')});
		$('img.rx-icon[categoryIcon]',menu).each(function() {this.src=$(this).attr('categoryIcon');});//attr({'src':menu.attr('itemIcon')});
		$('img.rx-icon:first',this).attr('src',menu.attr('currentItemIcon'));
	});

// Activate icon change on mouse over
if ($(this).attr('hoverItemIcon')!='') {

	// Hover (mouseover/mouseout)
	$(this).delegate('tr','mouseover',function () {
		var img = $('img.rx-icon:first',this);
		var menu = $('.rx-menu[menuId='+menuId+']');
		img.attr({'src':menu.attr('hoverItemIcon')});
	}).delegate('tr','mouseout',function () {
		var img = $('img.rx-icon:first',this);
		var menu = $('.rx-menu[menuId='+menuId+']');
		$('.rx-menu[menuId='+menuId+'] img.rx-icon').not('.selected img.rx-icon:first,img[categoryIcon]').attr({'src':menu.attr('itemIcon')});
		img.attr({'src':$($(this).parent().parent()).is('.selected') ? menu.attr('currentItemIcon') : img.attr('categoryIcon') ? img.attr('categoryIcon') : menu.attr('itemIcon')});
	});
	}

// Expand categories with type "expanded" or "extended"
$('.rx-menu.normal li.expanded').each(function() {
	rx.menuExpandCategory(this);
});

});
//console.log('Execution time:'+ (new Date - executionTime));
},


menuExpandCategory : function (liObj) {
// IE7 hides UL after slideToggle(), used toggle() instead
if ($.browser.msie && $.browser.version.substr(0,3)=="7.0")
	$('ul:first',liObj).show();
else
	$('ul:first',liObj).slideDown('slow');
// Toggle [+] if exists
$('.rx-plus:first:not(.rx-blank)',liObj).addClass('rx-minus');
},



menuCollapseCategory : function (liObj) {
if (typeof(liObj)=='string') liObj = $('#category_'+liObj+'_li');
// IE7 hides UL after slideToggle(), used toggle() instead
if ($.browser.msie){
	if($.browser.version.substr(0,3)=="7.0"){
		$('ul:first',liObj).hide();
		setTimeout("rx.correctIeTableHeight();",1000);
	}
	else{
		$('ul:first',liObj).slideUp('slow',function(){
			// Correct table height in IE. Called in callback to execute once, need timeout to get correct height
			setTimeout("rx.correctIeTableHeight();",1000);
		});
	}
}
else{
	$('ul:first',liObj).slideUp('slow');
}
// Toggle [+] if exists
$(liObj).find('.rx-plus:first:not(.rx-blank)').removeClass('rx-minus');
},


menuToggleCategory : function (liObj) {	
// IE7 hides UL after slideToggle(), used toggle() instead
if ($.browser.msie && $.browser.version.substr(0,3)=="7.0")
	$('ul:first',liObj).toggle();
else
	$('ul:first',liObj).slideToggle('slow');
// Toggle [+] if exists
$(liObj).find('.rx-plus:first:not(.rx-blank)').toggleClass('rx-minus');
},



menuToggleCategoryFromRoot : function (categoryId) {
categoryId = rx.menuGetId(categoryId);
rx.menuExpandCategoryParentsFromRoot(categoryId);
rx.menuToggleCategory($('#category_'+categoryId+'_li'));
},


menuExpandCategoryFromRoot : function (categoryId) {
categoryId = rx.menuGetId(categoryId);
rx.menuExpandCategoryParentsFromRoot(categoryId);
if (!$('#category_'+categoryId+'_li').parents('.rx-menu:first').is('.hover')) rx.menuExpandCategory($('#category_'+categoryId+'_li'));
},


menuExpandCategoryParentsFromRoot : function (categoryId) {
categoryId = rx.menuGetId(categoryId);
if (!$('#category_'+categoryId+'_li').parents('.rx-menu:first').is('.hover')) {
	// Collapse all categories except .expanded
	$('.rx-menu li').not($('#category_'+categoryId+'_li').parents('.rx-menu li').add('.rx-menu li.expanded')).not($('#category_'+categoryId+'_li')).each(function () {
	rx.menuCollapseCategory(this);
	});
	// Expand this and its parents categories
	$('#category_'+categoryId+'_li').parents('.rx-menu li').each(function () {
		rx.menuExpandCategory(this);
	});
	}
rx.menuMakeCategorySelected($('#category_'+categoryId+'_li'));
},


menuRemoteCategoryCall : function (categoryId) {
$('#category_'+categoryId+'_li a:first').click();
},


menuRemoteCategoryCallOld : function (categoryId) {
var anchor = $('#category_'+categoryId+'_li a:first');
//anchor.click();
rx.menuExpandCategoryFromRoot(categoryId);
if (!anchor.attr('href')) return false;
if (anchor.attr('target')) {
	if (anchor.attr('target')=='_blank')
		window.open(anchor.attr('href'));
}
	else window.location.href=anchor.attr('href');
},


// Activate current category style
menuMakeCategorySelected : function (obj) {
$('.rx-menu table').removeClass('selected');
var catObj = typeof(obj)=='object'?obj:$('#category_'+obj+'_li');
$('table:first',catObj).addClass('selected');
// Make all parent categories selected
$('table:first',$(catObj).parents('li:last')).addClass('selected');
// Make navigation path
rx.showNavigation();
// Make directory current (if cache is enabled)
rx.directoryMakeCategorySelected();
},



// Emulate category click remotly
menuCategoryClick : function (liObj) {
if (typeof(liObj)=='object')
	$('a:first',liObj).click();
else
	$('#category_'+liObj+'_li a:first').click();
},



menuConfigOff : function (menuId) {
$('.rx-menu'+(typeof(menuId)!='undefined'?'[menuId='+menuId+']':'')).each(function() {
	var menuId = $(this).attr('menuId');
	//$('ul',this).sortable('destroy');
	$(".rx-menu li").draggable('destroy');
	$(".rx-menu a").droppable('destroy');
	$('.rx-menu-sort-handler',this).remove();
	$('div.editable',this).removeClass('editable').removeAttr('title').editable('destroy');
	$('input[type=hidden]',this).remove();
	// Remove temporal [+]
	$('.temporalExpandByPlus:not(:has(li[id^=category_]))',this).remove();
	$(this)
	// Strip out the <form>
	//.appendTo($(this).parent().parent())
	// Unbind only mouseover event created for config mode
	.undelegate('li','mouseover.config').undelegate('li','contextmenu.config')
	// Remove child events
	.undelegate('li > .ui-icon', 'click')
	.removeClass('config');
	//$('form',$(this).parent()).remove();
	// Fix for IE 7 (in config mode span-buttons are pushed up)
	if ($.browser.msie && $.browser.version.substr(0,3)=="7.0") $('li',this).css({border:''});
	rx.menuInitDirectory(menuId);
});
},

menuConfigOn : function (menuId) {
//var executionTime = new Date();
$('.rx-menu'+(typeof(menuId)!='undefined'?'[menuId='+menuId+']':'')).each(function() {
var menuId = $(this).attr('menuId');
$(this).removeClass('withDirectory');
// If trying to run ConfigOn again then do not allow it
if ($(this).parent().is('form')) return false;

// Add and show icons in LI on hover
$(this).delegate('li','mouseover.config', function() {
	var parent = $(this);
	// Buttons
	if (!$(' > .ui-icon',this).size()) {
		// Generate icons (append is better then prepend)
		parent.find('a:first').append('<span class="rx-menu-icons"><span class="ui-icon ui-corner-all ui-icon-grip-dotted-vertical ui-state-default" title="'+rx.translate('draggable')+'"></span><span class="ui-icon ui-corner-all ui-icon-wrench ui-state-default" title="'+rx.translate('category_settings')+'"></span><span class="ui-icon ui-corner-all ui-icon-close ui-state-default" title="'+rx.translate('tooltip_delete')+'"></span><span class="ui-icon ui-corner-all ui-icon-folder-collapsed ui-state-default" title="'+rx.translate('add_new_category')+'"></span></span>').end();
		// Show buttons after delay
		setTimeout(function(){$(' > a .rx-menu-icons',parent).fadeIn();},1000);
		// Hide buttons after dalay (no mouseout)
		setTimeout(function(){$(' > a .rx-menu-icons',parent).fadeOut(500,function() {$(' > a .rx-menu-icons',parent).remove();});},4000);
	}

	// Init editable on hover
	// Editable captions
	$('div[id^=m'+menuId+'g]:not(.editable)', this).editable((rx.menuPathToModule?rx.menuPathToModule:'')+"rxMenuController.php?action=saveCategoryName&menuId="+menuId, {
		indicator	: '<div class="rx-menu-jeditable-loading">Saving...</div>',
		tooltip		: rx.translate("editable_tooltip"),//"Click to Edit.\nEnter or click away to submit new name.\nEsc to cancel.",
		event		: "click",
		onblur		: 'submit',
		onedit		: function() {
			var parentA = $(this).parents('a:first');
			parentA.attr('href_disabled',parentA.attr('href'));
			parentA.removeAttr('href');
		},
		onsubmit	: function() {
			var parentA = $(this).parents('a:first');
			parentA.attr('href',parentA.attr('href_disabled'));
			parentA.removeAttr('href_disabled');
			// Draw refreshed navigation
			setTimeout(function(){rx.showNavigation();},1000);
		},
		onreset		: function() {
			var parentA = $(this).parents('a:first');
			parentA.attr('href',parentA.attr('href_disabled'));
			parentA.removeAttr('href_disabled');
		}
	}).addClass('editable');
})
.delegate('li','contextmenu.config', function(event) {
	if ($('>a>.rx-menu-icons',this).size())
		$('>a>.rx-menu-icons',this).remove();
	else
		$('>a',this).append('<span class="rx-menu-icons"><span class="ui-icon ui-corner-all ui-icon-grip-dotted-vertical ui-state-default" title="'+rx.translate('draggable')+'"></span><span class="ui-icon ui-corner-all ui-icon-wrench ui-state-default" title="'+rx.translate('category_settings')+'"></span><span class="ui-icon ui-corner-all ui-icon-close ui-state-default" title="'+rx.translate('tooltip_delete')+'"></span><span class="ui-icon ui-corner-all ui-icon-folder-collapsed ui-state-default" title="'+rx.translate('add_new_category')+'"></span></span>').find('.rx-menu-icons').show().end();
	event.preventDefault();
})


// Add subcategory create button event
.delegate('.ui-icon-folder-collapsed', 'click', function () {
	var catId = $(this).parents('li:first').attr('id');
	var catIdNum = catId.match(/category_m([0-9]*)g([0-9]*)_li/)[2];
	var menuId = catId.match(/category_m([0-9]*)g([0-9]*)_li/)[1];
	$.get((rx.menuPathToModule?rx.menuPathToModule:'')+'rxMenuController.php?action=createCategory',{'menuId':menuId,'groupid':catIdNum},
	function(data, textStatus) {
		var visible = $('#'+catId+' ul').is(':visible') ? 1 : 0;
		// .replaceWith cannot be used if there was no <ul> before adding new category (no subcategories)
		$('#'+catId+' ul').remove();
		$('#'+catId).append(data.response);
		rx.menuInit(menuId);
		rx.menuConfigOff(menuId);
		rx.menuConfigOn(menuId);
		if ($('.rx-menu[menuId='+menuId+']').is('.normal')) {
			if (visible) {
				$('#'+catId+' > ul').show();
				$('#'+catId+' > ul > li:not(.rx-menu-separator):last').hide().slideDown();
			}
			else rx.menuExpandCategory($('#'+catId));
		}
	},
	'json');
	// Stop click propagation and category call
	return false;
})
// Delete category button event
.delegate('.ui-icon-close', 'click', function () {
	var catId = $(this).parents('li:first').attr('id');
	var catIdNum = catId.match(/category_m([0-9]*)g([0-9]*)_li/)[2];
	var menuId = catId.match(/category_m([0-9]*)g([0-9]*)_li/)[1];
	rx.confirm('Delete category Nr.'+catIdNum+'-'+$('#'+catId+' div:first').text()+'?',
		// Yes
		function () {
			$.getJSON((rx.menuPathToModule?rx.menuPathToModule:'')+'rxMenuController.php?action=deleteCategory',{'menuId':menuId,'categoryid':catIdNum},
			function(data, textStatus) {
				$('#'+catId).slideUp(700,function(){$('#'+catId).remove();});
				},
			'json');
			}
		);
	// Stop click propagation and category call
	return false;
})
// Settings button event
.delegate('.ui-icon-wrench', 'click', function () {
	var catId = $(this).parents('li:first').attr('id');
	var catIdNum = catId.match(/category_m([0-9]*)g([0-9]*)_li/)[2];
	var menuId = catId.match(/category_m([0-9]*)g([0-9]*)_li/)[1];
	// Remove any other rx-window if trying to get another in IE
	$('#rx-window').remove();
	// Define buttons as it's the only way to make them translatable
	var buttons = {};
	buttons[rx.translate('cancel')] = function () {$('#rx-window').dialog('close');};
	buttons[rx.translate('save')] = function () {$('#rx-window form').submit();setTimeout(function() {rx.menuReload(menuId);},1500);};
	$('<div id="rx-window">').appendTo('body').html(rx.translate('loading')+'...')
	.dialog({
			position: ['center',50],
			bgiframe: true,
			modal : $.browser.msie ? false : true, // IE slows down a lot on modal
			width : 400,
			show : $.browser.msie ? 'fold' : 'scale', // fold is faster for IE
			hide : $.browser.msie ? 'fold' : 'scale', // fold is faster for IE
			title : rx.translate('category_settings'),
			buttons : buttons,
			beforeclose : function() {
				// Remove Uploadify, otherwise dialog cannot be closed :\
				$('#rx-window object').remove();
			},
			close : function () {$('#rx-window').remove();}
		})
	.load((rx.menuPathToModule?rx.menuPathToModule:'')+'rxCategorySettings.php?menuId='+menuId+'&categoryId='+catIdNum+(menuId ? '&menuId='+menuId : ''));
	// Stop click propagation and category call
	return false;
})

.delegate('div.editable','click',function(event) {
	// Block category selection on clicking for editing
	event.stopPropagation();
	event.preventDefault();
});

// Add temporal [+] if doesn't have already
if (!$(this).is('.expandByPlus') && $(this).is('.vertical.normal'))
	$('table',this).find('tr:first')
		.prepend('<td class="temporalExpandByPlus" width="10px"><div class="rx-plus"></div></td>')
			.each(function() {
				if (!$('ul',$(this).parents('li:first')).size())
					$('.rx-plus',this).addClass('rx-blank');
			})
		.end();

// Hidden form elements for position posting
$('li:not(.rx-menu-separator)',this).each(function () {
	var catId = this.id;
	var catIdNum = catId.match(/category_m([0-9]*)g([0-9]*)_li/)[2];
	// Hidden input data
	//$(this).prepend('<input name="category_'+catIdNum+'_pos" class="catPos" type="hidden"><input name="category_'+catIdNum+'_groupid" class="catGroupId" type="hidden"><input name="category_'+catIdNum+'_id" class="catId" value="'+catIdNum+'" type="hidden">');

	// Fix for IE 7 - in config mode span-buttons are pushed up
	if ($.browser.msie && $.browser.version.substr(0,3)=="7.0") $(this).css({border:'1px solid transparent'});
	
	// Add sortableHandler
	//$('table:first tr',this).prepend('<td class="rx-menu-sort-handler"></td>');
	
	// Add temporal subcategory for empty categories so it's possible to expand it and drag another category in
	if (!$(this).find('>ul').size()) $(this).append('<ul class="temporalExpandByPlus" style="margin-left:'+$('.rx-menu li>ul:first').css('margin-left')+'"><li class="rx-menu-separator"><a>&nbsp;</a></li></ul>');
});
// 60

// Show [+] for empty categories
if ($(this).is('.vertical.normal'))
	$('.rx-blank',this).removeClass('rx-blank');
// 61

}).addClass('config')


.find("li").draggable({
	helper: "clone",
	handle: 'a:first'
}).end()
.find("a").droppable({
	hoverClass: 'rx-menu-drop-target',
	accept: 'li',
	tolerance: 'pointer',
	drop: function(event, ui) {
		$($(this).parent()).after(ui.draggable);
		// Set new groupId-s for <li> (maybe move it to )
		$('.rx-menu ul').each(function () {
			for(var i=0; i<this.children.length; i++) {
				if (this.children[i].id) {
				//$('.catPos:first',this.children[i]).val(i);
				//$('.catGroupId:first',this.children[i]).val($(this.children[i]).parent().parent().is('li') ? $('.catId:first',$(this.children[i]).parent().parent()).val() : 0);
				$(this.children[i]).attr({'catId':this.children[i].id.match(/category_m[0-9]*g([0-9]*)_li/)[1], 'pos':i, 'groupId':$(this.children[i]).parent().parent().is('li') ? $(this.children[i]).parent().parent().attr('catId') : 0});
				}
			}
		});
	}
}).end()
// 105

// Form
//.wrap('<form method="post"></form>')
//.parents('form:first')
.prepend($('<select name="menuType"><option value="normal">Normal<option value="hover">Hover</select>').val($('.rx-menu[menuId='+menuId+']').is('.hover')?'hover':'normal'))
.prepend($('<select name="menuOrientation"><option value="vertical">Vertical<option value="horizontal">Horizontal</select>').val($('.rx-menu[menuId='+menuId+']').is('.horizontal')?'horizontal':'vertical'))
.prepend('<div style="float:left;clear:right;"></div>')

/*
// Sortalbe/arrange ON button
.prepend($('<button type="button" style="padding:0px;background:none;border:none;"><span class="ui-icon ui-corner-all ui-icon-shuffle ui-state-default" title="'+rx.translate('draggable')+'"></span></button>')
	.click(function() {
		var executionTime = new Date();
		var menu = $('.rx-menu'+(menuId?'[menuId='+menuId+']':''));

		// Hide sortable/arrange ON button
		$('.ui-icon-shuffle').hide();

		// Hidden form elements for position posting
		$('li:not(.rx-menu-separator)',menu).each(function () {
			var catId = this.id;
			var catIdNum = catId.match(/category_m([0-9]*)g([0-9]*)_li/)[2];
			// Hidden input data
			$(this).prepend('<input name="category_'+catIdNum+'_pos" class="catPos" type="hidden"><input name="category_'+catIdNum+'_groupid" class="catGroupId" type="hidden"><input name="category_'+catIdNum+'_id" class="catId" value="'+catIdNum+'" type="hidden">');
		
			// Fix for IE 7 - in config mode span-buttons are pushed up
			if ($.browser.msie && $.browser.version.substr(0,3)=="7.0") $(this).css({border:'1px solid transparent'});
			
			// Add sortableHandler
			//$('table:first tr',this).prepend('<td class="rx-menu-sort-handler"></td>');
			
			// Add temporal subcategory for empty categories so it's possible to expand it and drag another category in
			if (!$(this).find('>ul').size()) $(this).append('<ul class="temporalExpandByPlus" style="margin-left:'+$('.rx-menu li>ul:first').css('margin-left')+'"><li class="rx-menu-separator"><a>&nbsp;</a></li></ul>');
		});
		// 60

		// Show [+] for empty categories
		if (menu.is('.vertical.normal'))
			$('.rx-blank',menu).removeClass('rx-blank');
		// 61

		// Sortable menu items
		$('ul',menu).sortable({
			forceHelperSize: true,
			helper: 'clone',
			opacity: 0.6,
			//delay: 100,
			placeholder: 'rx-article-sort-placeholder',
			tolerance: 'pointer',
			cursor: 'move',
			revert: true,
			handle: 'a:first', // Required by IE to sort subs
			//handle: ' > li > .ui-icon-grip-dotted-vertical', // Required by IE
			//handle: '.rx-menu-sort-handler:first',
			// This handle doesn't work after optimization
			//handle: '.ui-icon-grip-dotted-vertical:first',
			connectWith: ($.browser.msie ? '' : '.rx-menu ul'), // canceled for IE - too slow
			containment: ($.browser.msie ? 'parent' : ''), // IE does not use connectWith, "this" disallows moving to upper level
			cancel: '.rx-menu-separator',
		 	stop: function(event, ui) {
				$('.rx-menu ul').each(function () {
					for(var i=0; i<this.children.length; i++) {
						if (this.children[i].id) {
						$('.catPos:first',this.children[i]).val(i);
						$('.catGroupId:first',this.children[i]).val($(this.children[i]).parent().parent().is('li') ? $('.catId:first',$(this.children[i]).parent().parent()).val() : 0);
						}
					}
				});
				}
			});
		// 1218, no connectWith - 150

	//console.log('Execution time - menuSortable:'+ (new Date - executionTime));
	})

)*/
// New category button
.prepend($('<button type="button" style="padding:0px;background:none;border:none;"><span class="ui-icon ui-corner-all ui-icon-folder-collapsed ui-state-default" title="'+rx.translate('add_new_category')+'"></span></button>')
	.click(function() {
		$.get((rx.menuPathToModule?rx.menuPathToModule:'')+'rxMenuController.php?action=createCategory',{'menuId':menuId,'groupid':0},
			function(data, textStatus) {
				rx.menuConfigOff(menuId);
				var rxMenuParent = $('.rx-menu[menuId='+menuId+']').parent();
				$('.rx-menu[menuId='+menuId+']').remove();
				rxMenuParent.append(data.response);
				rx.menuInit(menuId);
				rx.menuConfigOn(menuId);
			}
		,'json');
		})
)
// Submit category positions & menu type button
//.prepend($('<button type="submit" style="padding:0px;background:none;border:none;"><span class="ui-icon ui-corner-all ui-icon-disk ui-state-default" title="'+rx.translate('save')+'"></span></button>'))
.prepend($('<button type="button" style="padding:0px;background:none;border:none;"><span class="ui-icon ui-corner-all ui-icon-disk ui-state-default" title="'+rx.translate('save')+'"></span></button>')
	.click(function() {
		//console.log('MenuId: '+$(this).parents('.rx-menu').attr('menuId'));
		var postObj = {};
		$('.rx-menu[menuId='+menuId+'] li[id]').each(function(index) {
			postObj[index] = {'catId':$(this).attr('catId'),'pos':$(this).attr('pos'),'groupId':$(this).attr('groupId')};
		});
		//console.log(postObj); // Juris Vaiders - Error happens here, the funny thing is that it's not in SVN. Max change? 
		$.post((rx.menuPathToModule?rx.menuPathToModule:'')+'rxMenuController.php?action=saveMenuPos&menuId='+menuId,postObj,function(r) {if (r.error) rx.alert(r.error); $.jGrowl(r.responseText);}, "json");
	})
)

/*
.ajaxForm({
	dataType : 'json',
	beforeSubmit : function (data, ui, options) {
		// if ($(ui).attr('formState')==$(ui).formSerialize()) {
		// 			rx.alert('<div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;"><p><span class="ui-icon ui-corner-all ui-icon-info" style="float: left; margin-right: .3em;"></span>'+rx.translate('no_date_to_update')+'</p></div>');
		// 			//$.jGrowl('<div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;"><p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span><strong>Hey!</strong> No data to update.</p></div>');
		// 			return false;
		// 		}
		// 		else
		$(ui).attr({'formState' : $(ui).formSerialize()});
	},
	success : function(response, status) {
		if (response.reload) rx.menuReload(menuId);
		//alert(response.responseText);
		//rx.alert((response.error ? '<div class="ui-state-error ui-corner-all" style="padding: 0 .7em;"><p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span><strong>Alert:</strong> '+response.error+'</p></div>' : response.responseText)+(response.reload?' Menu is reloaded.':''));
		$.jGrowl((response.error ? '<div class="ui-state-error ui-corner-all" style="padding: 0 .7em;"><p><span class="ui-icon ui-corner-all ui-icon-alert" style="float: left; margin-right: .3em;"></span><strong>Alert:</strong> '+response.error+'</p></div>' : response.responseText ? response.responseText : '')+(response.reload?' Menu is reloaded.':''));
	}
	})
//*/
;
	/*.each(function () {
		$(this).attr({'formState' : $(this).formSerialize(), 'action' : (rx.menuPathToModule?rx.menuPathToModule:'')+'rxMenuController.php?action=saveMenuPos&menuId='+$('.rx-menu',this).attr('menuId')});
		})*/
	;
//console.log('Execution time - menuConfigOn:'+ (new Date - executionTime));
},

menuConfigToggle : function (menuId) {
$('.rx-menu'+(typeof(menuId)!='undefined'?'[menuId='+menuId+']':'')).each(function () {
	if ($(this).is('.config'))
		rx.menuConfigOff($(this).attr('menuId'));
	else
		rx.menuConfigOn($(this).attr('menuId'));
});
},

menuCheckboxesOn : function (globalMenuId) {
$('.rx-menu'+(typeof(globalMenuId)!='undefined'?'[menuId='+globalMenuId+']':'')).removeClass('withDirectory').each(function (){
	var menuId = $(this).attr('menuId');
	// Do not run this setup again
	if ($('.rx-menu[menuId='+menuId+']').is('.menuCheckboxes')) return;
	if ($(this).is('.config'))
		rx.menuConfigOff(menuId);
	// Add checkboxes
	$('li',this).prepend('<input type="checkbox" style="position:absolute;right:0px;top:0px;">');
	// Define click and checked
	$('input:checkbox',this).click(function () {
		var catId = $(this).parents('li:first').attr('id');
		var catIdNum = catId.substring(catId.lastIndexOf('g')+1,catId.lastIndexOf('_'));
		$('#article_cat_m'+menuId+'g'+catIdNum).attr('checked',this.checked?1:0);
		}).each(function() {
			var catId = $(this).parents('li:first').attr('id');
			var catIdNum = catId.substring(catId.lastIndexOf('g')+1,catId.lastIndexOf('_'));
			$(this).attr('checked',$('#article_cat_m'+menuId+'g'+catIdNum).attr('checked'));
		});
	// Add temporal [+] if doesn't have already
	if (!$(this).is('.expandByPlus') && $(this).is('.vertical.normal'))
		$('table',this)
			.find('tr:first')
			.prepend('<td class="temporalExpandByPlus" width="10px"><div class="rx-plus"></div></td>')
				.each(function() {
					if (!$('ul',$(this).parents('li:first')).size())
						$('.rx-plus',this).addClass('rx-blank');
				})
			.end();

// If no category checked then check current
if (!$('.rx-menu input:checked').size()) {
	// Needs double checked=1, because .click() sets checked=1 after execution
	$('.rx-menu li:has(table.selected):last').find('input:first').attr('checked',1).click().attr('checked',1);
}

// Set category caption click to check checkbox instead of category call
$('.rx-menu[menuId=0]').delegate('div','click.checkCheckbox', function () {
	$(this).parents('li:first').find('>input[type=checkbox]').click();
	return false;
});

// Flag that this menu has checkboxes on
}).addClass('menuCheckboxes');
},

menuCheckboxesOff : function (menuId) {
$('.rx-menu'+(menuId?'[menuId='+menuId+']':'')+' input[type=checkbox]').remove();
$('.rx-menu'+(menuId?'[menuId='+menuId+']':'')+' .temporalExpandByPlus').remove();
$('.rx-menu'+(menuId?'[menuId='+menuId+']':'')).removeClass('menuCheckboxes');
$('.rx-menu[menuId=0]').undelegate('div','click.checkCheckbox');
rx.menuInitDirectory(menuId);
},

toggleMenuCheckboxes : function (menuId) {
$('.rx-menu'+(typeof(menuId)!='undefined'?'[menuId='+menuId+']':'')).each(function () {
	menuId = $(this).attr('menuId');
	if (!$(this).is('.menuCheckboxes'))
		rx.menuCheckboxesOn(menuId);
	else
		rx.menuCheckboxesOff(menuId);
});
},

menuChangeLayout : function (menuId) {
$('.rx-menu'+(typeof(menuId)!='undefined'?'[menuId='+menuId+']':'')).each(function () {
	menuId = $(this).attr('menuId');
	$(this).removeClass('horizontal').removeClass('vertical').removeClass('normal').removeClass('hover');
	alert('Orient:'+$(this).parents('form:first').find('select:first').val()+';Type'+$(this).parents('form:first').find('select:last').val());
	$(this).addClass($(this).parents('form:first').find('select:first').val());
	$(this).addClass($(this).parents('form:first').find('select:last').val());
});
},

menuGetContent : function (menuId, groupId) {
$('.rx-menu'+(typeof(menuId)!='undefined'?'[menuId='+menuId+']':'')).each(function () {
	menuId = $(this).attr('menuId');
	$.get((rx.menuPathToModule?rx.menuPathToModule:'')+'rxMenuController.php',{action:'getContent','menuId':menuId,'groupId':(groupId?groupId:0)},function(data, textStatus){
		alert(data);
		}
	);
});
},

// Can be used to load unlocked categories
menuReload : function (menuId, groupId) {
$('.rx-menu'+(typeof(menuId)!='undefined'?'[menuId='+menuId+']':'')).each(function () {
	menuId = $(this).attr('menuId');
	$.get((rx.menuPathToModule?rx.menuPathToModule:'')+'rxMenuController.php',{action:'getContent','menuId':menuId,'groupId':(groupId?groupId:0)},function(data, textStatus){
		var currentCategoryId = $('.rx-menu[menuId='+menuId+'] table.selected').parents('li:first').attr('id');
		var configMode = $('.rx-menu[menuId='+menuId+']').is('.config');
		if (configMode) rx.menuConfigOff(menuId);
		if (groupId)
			$('#category_m'+menuId+'g'+groupId+'_li > ul').replaceWith(data);
		else
			$('.rx-menu[menuId='+menuId+']').replaceWith(data);
		rx.menuInit();
		// Without setTimeout menuConfigOn mode intersects with menuInit (ajaxComplete)
		if (configMode) setTimeout(function() { rx.menuConfigOn(menuId);},1000);
		rx.menuExpandCategoryParentsFromRoot($('#'+currentCategoryId));
		}
	);
});
},


// Allows to accept 'm0g1' format, $('#category_m0g1_li') or document.getElementById('category_m0g1_li') object
menuGetId : function (category) {
if (typeof(category)=='object') {
	var id = $(category).attr('id');
	if(typeof(id)=='undefined'){
		category = '';
	}
	else{
		category = id.substring(id.indexOf('_')+1,id.lastIndexOf('_'));
	}
}
// If it's a string do nothing
return category;
},


menuConvertToOldRequest : function () {
$(".rx-menu a[href*=cid=]:not(a[href*=ttp:])").each(function() {
	this.target = 'main_refresh_frame';
	this.href = 'main.php' + this.search;	
});
},

menuInitDirectory : function (menuId) {
if (!menuId) menuId = '0';
// If appropriate directory is found on a page then make menu .withDirectory
if ($('#directoryForMenu'+menuId).size() && !$('.rx-menu[menuId='+menuId+']').is('.config, .menuCheckboxes')) {
	// Make zero-level categories hidden and disable [+] setting (if this setting is set, otherwise it breaks directory functionality)
	$('.rx-menu[menuId='+menuId+']').addClass('withDirectory').removeClass('expandByPlus');
	// Expand current category on start (actually not needed after first_web_view)
	rx.menuExpandCategory($('.rx-menu[menuId='+menuId+'] li:has(table.selected):last'));
}
},

menuCategoryPicker : function(menuIdTargetId,categoryIdTargetId) {
$('.rx-menu div').click(function(event) {
	$('.rx-menu div').unbind('click');
	event.stopPropagation();
	event.preventDefault();
	$('#'+menuIdTargetId).val(this.id.substring(this.id.indexOf('m')+1,this.id.indexOf('g')));
	$('#'+categoryIdTargetId).val(this.id.substring(this.id.indexOf('g')+1));
	$('#menuCategoryPickerMessage').fadeOut().slideUp(1000);
});
$('#menuCategoryPickerMessage').fadeIn();
},

// Build navigation object
showNavigation : function() {
// Find a menu with currecntly selected category
var rxMenu = $('.rx-menu:has(table.selected)');
// Take first menu if no category is selected
if (!rxMenu.size()) rxMenu = $('.rx-menu:first');//$('.rx-menu[menuId=0]');
var menuId = rxMenu.attr('menuId');
// Take current category - added :last - otherwise selector gets all selected items, but we need only last
var currentCategory = $('a:has(table.selected):last',rxMenu);
if (!currentCategory.size()) currentCategory = $('a:first',rxMenu);
$('.rx-navigation-path').each(function() {
	var thisNav = this;
	$(thisNav).empty();
	var showOnlyCurrent = $(thisNav).attr('showOnlyCurrent');
	var align = $(thisNav).attr('align') || 'left';
	if (showOnlyCurrent){
		// Show only current category
		$(thisNav).empty().prepend(currentCategory.clone()).find('a').removeAttr('href').end();
	}
	else
		// Collecting parents to build path
		currentCategory.parents('li').each(function() {
			var a = $('a:first',this).clone().find('div').append($(thisNav).children().size()?'&nbsp;>&nbsp;':'').end();
			//var a = $('a:first',this).clone().find('table').css({width:'auto'}).end().find('div').append($(thisNav).children().size()?'&nbsp;>&nbsp;':'').end();
			if (align=='right') $(thisNav).append(a);
			else $(thisNav).prepend(a);
		});
	// Clean up rx-menu styles
	$('a',this).css({'float':align,textAlign:align}).find('table').removeClass().css({width:'auto'}).end().find('.rx-icon').parent().hide().end().end().find('.rx-plus').parent().hide();
});
// This will add correct style to navigation (breadcrumbs)
$('.rx-navigation-path').children().addClass('navigation').find('td').css({'padding-left':'0','padding-right':'0'});
// Padding is not needed in navigation, otherwise it produces unequal spaces between navigation items 
/*if ($.browser.msie){
	$('.rx-navigation-path a td').css({'padding-left':'0','padding-right':'0'});	
}*/
},

directoryMakeCategorySelected : function() {
var id = $('.rx-menu li:has(table.selected):first').attr('id');
if (id) {
	id = id.substring(id.indexOf('_')+1,id.lastIndexOf('_'));
	$('.rx-directory .selected').removeClass('selected');
	$('#directory_'+id).addClass('selected');
}
}

}
);



// LiveQuery






rx.menuPathToModule = rx.getScriptPath('rxMenu.js');
//rx.menuPathToModule = 'modules/rxMenu';

// Startup and fixes
$(function () {
rx.menuInit();
});