jQuery(document).ready(function($) {
	$('.usergr-list').chosen();
	$('.usergr-list').chosen().change(function() {
		if ($(this).val()) {
			if ($.inArray('all', $(this).val()) == -1) {
				$(this).find('option[value="all"]').attr('disabled', true);
			} else {
				$(this).find('option').attr('disabled', true);
				$(this).find('option[value="all"]').attr('disabled', false);
			}
		} else {
			$(this).find('option').attr('disabled', false);
		}
		$(this).trigger("liszt:updated");
	});
	
	$('#ungroup-links').find('.collapse').each(function() {
		$(this).on('shown.bs.collapse', function() {
			$(this).parents('li').find('a.btn-edit-link').hide();
		});
		
		$(this).on('hidden.bs.collapse', function() {
			$(this).parents('li').find('a.btn-edit-link').show();
		});
	});
	
	$('.collapse').on('shown.bs.collapse', function() {
		var $this = $(this);
		var id = $this.attr('id');
		var parentId = $this.parent().attr('id');
		$('.collapse').each(function() {
			if ($(this).hasClass('in')) {
				if ($(this).attr('id') && $(this).attr('id') != id) {
					$(this).css('overflow', 'hidden');
					$(this).collapse('hide');
				} else {
					if ($(this).parent().attr('id') && $(this).parent().attr('id') != parentId) {
						$(this).css('overflow', 'hidden');
						$(this).collapse('hide');
					}
				}
			}
		});
	}); 
	
	$('#ql-group').find('li.link-item .collapse').each(function() {
		$(this).on('shown.bs.collapse', function() {
			$($(this).parents('li')[0]).find('a.btn-edit-link').hide();
		});
		
		$(this).on('hidden.bs.collapse', function() {
			$($(this).parents('li')[0]).find('a.btn-edit-link').show();
		});
	});

	// Drag and sortable
	$('#ungroup-links, .gr-ql-sortable').sortable({
		connectWith: ".connectedUngroup, .connectedSortable",
		handle : '.handle',
		receive : function() {
			$(this).find('ul li .gr-access-settings').each(function() {
				if ($(this).css('display') == 'block') {
					$(this).css('display', 'none');
				}
			});
			
			$(this).find('li .ql-show-on').each(function() {
				if ($(this).css('display') == 'block') {
					$(this).css('display','none');
				}
			});
		}
	});
	
	
	$('#ql-group, .gr-ql-sortable').sortable({
		receive : function() {
			$(this).find('ul li .gr-access-settings').each(function() {
				if ($(this).css('display') == 'none') {
					$(this).css('display', 'block');
				}
			});
			
			$(this).find('li .ql-show-on').each(function() {
				if ($(this).css('display') == 'none') {
					$(this).css('display','block');
				}
			});
		}
	});
	
	$('#ql-group').sortable({
		connectWith: ".connectedGroup",
		handle : '.handle'
	});
	
	$('#addNewGroup, #addLinkForm, #editGroup, #addMenuForm').on('shown.bs.collapse', function() {
		$(this).find('input:text')[0].focus();
	});
	
	// Clear all input when collapse hide
	$('#addNewGroup, #addLinkForm').on('hidden.bs.collapse', function() {
		$(this).find('input:text').each(function() {
			$(this).attr('value', '');
		});
	});
	
	// Add New Group
	$('input[name="add-group-name"]').off().unbind().keyup(function(event) {
		if (event.keyCode == 13) {
			$('.btn-group-addnew').click();
		}
	});
	$('.btn-group-addnew').off().unbind().on('click', function() {
		var groupName = $('input[name="add-group-name"]').val();
		if (groupName != '') {
			$.ajax({
				type : 'POST',
				url : 'index.php?athajax=dashboard&action=addgroup',
				data : {'groupname' : groupName},
				success : function(response) {
					$('#ql-group').prepend(response);
					$('#addNewGroup').collapse('hide');
					$('input[name="add-group-name"]').attr('value','');
					$('.gr-ql-sortable').sortable({
						connectWith: ".connectedUngroup, .connectedSortable"
					});
				}
			});
		} else {
			alert('The Group Name is empty!');
		}
	});
	
	// Cancel add new group quick link.
	$('#addNewGroup ul li a.btn-cancel').off().unbind().on('click', function() {
		$(this).parents('ul.add-group-form li input[name="add-group-name"]').attr('value','');
		$(this).parents('#addNewGroup').collapse('hide');
	});
	
	// Edit Group
	$('input[name="edit-group-name"]').off().unbind().keyup(function(event) {
		if (event.keyCode == 13) {
			$(this).parent().next().find('.btn-apply-gr').trigger('click');
		}
	});
	$('.btn-edit-gr').off().unbind().on('click', function() {
		$(this).parent().next().collapse('show');
		$(this).parent().next().css('overflow','visible');
	});
	
	$('.btn-apply-gr').off().unbind().on('click', function() {
		var newGroupName = $($(this).parents()[1]).find('input').val();
		var acl = $($(this).parents()[1]).find('select');
		$(this).parents('div#editGroup').prev().find('h4').html(newGroupName[0].toUpperCase()+newGroupName.slice(1));
		var content = '';
		var grAcl = [];
		if (acl && acl.find(':selected').length) {
			acl.find(':selected').each(function() {
				content += '<input type="hidden" value="'+$(this).val()+'" />';
				content += $(this).text()+',';
				grAcl.push($(this).val());
			});
		} else {
			content += 'Disable';
		}
		$(this).parents('#editGroup').next().find('h6').html(content);
		$(this).parents('ul').find('li .btn-cancel-gr').attr('data-grname', newGroupName);
		$(this).parents('ul').find('li .btn-cancel-gr').attr('data-acl', JSON.stringify(grAcl));
		$(this).parents('#editGroup').css('overflow','hidden');
		$(this).parents('#editGroup').collapse('hide');
	});
	
	// Cancel edit group
	$('.btn-cancel-gr').off().unbind().on('click', function() {
		var oldName = $(this).attr('data-grname'),
				acl = $.parseJSON($(this).attr('data-acl'));
		$(this).parents('#editGroup').css('overflow','hidden');
		$(this).parents('#editGroup').collapse('hide');
		$($(this).parents()[1]).find('li input[name="edit-group-name"]').attr('value', oldName);
		$(this).parents('ul').find('select option').attr('selected', false);
		if (acl && acl.length) {
			for (var i = 0; i<acl.length; i++) {
				$(this).parents('ul').find('select option[value="'+acl[i]+'"]').attr('selected', true);
				if (acl[i] == 'all') {
					$(this).parents('ul').find('select option').attr('disabled', true);
					$(this).parents('ul').find('select option[value="'+acl[i]+'"]').attr('disabled', false);
				}
			}
		} else {
			$(this).parents('ul').find('select option').attr('selected', false);
		}
		$(this).parents('ul').find('li select.usergr-list').trigger('liszt:updated');
	});
	
	// Delete Group
	$('.btn-remove-gr').off().unbind().on('click', function() {
		var groupName = $(this).parents('li').find('h4').text() , linkitems = $(this).parents('li').find('ul.gr-ql-sortable').find('li.link-item');
		var groupId = $(this).parents('li').attr('id');
		var notice = confirm('Delete group: '+groupName+' ?');
		if (notice){
			$.ajax({
				type : 'POST',
				url : 'index.php?athajax=dashboard&action=deletegroup',
				data : {'groupId' : groupId},
				success : function(data) {
					if (data == 'success'){
						$('#ungroup-links').prepend(linkitems);
						$('li#'+groupId).remove();
					}
				}
			});
		}
	});
	
	// Add Custom Link
	$('.btn-addlink').off().unbind().on('click', function() {
		var inputs = $('#addLinkForm').find('input:text'),
				params = {};
		inputs.each(function() {
			var name = $(this).attr('name').replace(/link-/,'');
			if (name) {
				params[name] = $(this).val();
			}
		});
		if (params['title'] == '') {
			alert('The title is empty');
		} else {
			$.ajax({
				type : 'POST',
				url : 'index.php?athajax=dashboard&action=addlink',
				data : params,
				success : function(response) {
					$('#ungroup-links').prepend(response);
					$('#addLinkForm').collapse('hide');
					setTimeout(function() {
						$('#group-dis .group-body').animate({scrollTop:0});
					}, 300);
				}
			});
		}
	});
	
	// Edit quicklink
	$('.btn-edit-link').on('click', function() {
		$(this).hide();
	});
	
	//Save edit quicklink
	$('.btn-apply').on('click', function() {
		var btn = $(this);
		var inputs = $($(this).parents()[1]).find('li input:text');
		var params = {};
		params['timeStamp'] = $(this).data('timestamp');
		inputs.each(function() {
			if ($(this).attr('name')){
				var name = $(this).attr('name').replace(/link-/,'');
			}
			
			if (name) {
				params[name] = $(this).val();
			}
		});
		params['acl'] = $($(this).parents()[1]).find('select').val();
		
		$.ajax({
			type : 'POST',
			url : 'index.php?athajax=dashboard&action=editlink',
			data : params,
			success : function(response) {
				var datas = $.parseJSON(response);
				btn.parents('.collapse').collapse('hide');
				if (datas.image != '') {
					$('li#'+datas.timeStamp).find('.ql-icon').removeClass('hidden');
					$('li#'+datas.timeStamp).find('.ql-icon').html('<img src="../'+datas.image+'" style="width: 30px; height:30px;" />');
				} else {
					$('li#'+datas.timeStamp).find('.ql-icon').removeClass('hidden');
					$('li#'+datas.timeStamp).find('.ql-icon').html('<span class="'+datas.icon+'"></span>');
				}
				$('li#'+datas.timeStamp).find('.link-title').find('h5').html(datas.title[0].toUpperCase() + datas.title.slice(1));
				$('li#'+datas.timeStamp).find('.link-title').find('span').html(datas.url);
				var showon = '';
				if (datas.access_group.length > 0) {
					for (var i = 0; i < datas.access_group.length; i++) {
						showon += '<input type="hidden" value="'+datas.access_group[i].id+'" />'+ datas.access_group[i].name.substr(0,1).toUpperCase()+datas.access_group[i].name.substr(1)+', ';
					}
				} else {
					showon = 'Disable';
				}
				$('li#'+datas.timeStamp).find('.ql-show-on strong').html(showon);
				$('li#'+datas.timeStamp).find('a.btn-edit-link').attr('data-title', datas.title);
				$('li#'+datas.timeStamp).find('a.btn-edit-link').attr('data-url', datas.url);
				$('li#'+datas.timeStamp).find('a.btn-edit-link').attr('data-img', datas.icon);
				$('li#'+datas.timeStamp).find('a.btn-edit-link').attr('data-image', datas.image);
				$('li#'+datas.timeStamp).find('a.btn-edit-link').attr('data-acl',JSON.stringify(datas.acl));
			}
		});
	});
	
	// Cancel edit quicklink
	$('.link-item').find('ul li .btn-cancel').on('click', function() {
		$($(this).parents('div.collapse')).collapse('hide');
		var timestamp = $(this).data('timestamp');
				title = $(this).parents('li#'+timestamp).find('.btn-edit-link').attr('data-title'),
				url = $(this).parents('li#'+timestamp).find('.btn-edit-link').attr('data-url'),
				icon = $(this).parents('li#'+timestamp).find('.btn-edit-link').attr('data-img'),
				image = $(this).parents('li#'+timestamp).find('.btn-edit-link').attr('data-image'),
				acl = $.parseJSON($(this).parents('li#'+timestamp).find('.btn-edit-link').attr('data-acl'));

		$($(this).parents('ul')[0]).find('input[name="link-title"]').attr('value', title);
		$($(this).parents('ul')[0]).find('input[name="link-url"]').attr('value', url);
		$($(this).parents('ul')[0]).find('input[name="link-icon"]').attr('value', icon);
		$($(this).parents('ul')[0]).find('input[name="link-image"]').attr('value', image);
		$($(this).parents('ul')[0]).find('select option').attr('selected', false)
		if (acl && acl.length) {
			for (var i = 0;i < acl.length; i++) {
				$($(this).parents('ul')[0]).find('select option[value="'+acl[i]+'"]').attr('selected', true);
				if (acl[i] == 'all') {
					$($(this).parents('ul')[0]).find('select option').attr('disabled', true);
					$($(this).parents('ul')[0]).find('select option[value="'+acl[i]+'"]').attr('disabled', false);
				}
			}
		} else {
			$($(this).parents('ul')[0]).find('select option').attr('selected', false);
		}
		$($(this).parents('ul')[0]).find('select').trigger('liszt:updated');
	});
	
	// Cancel add customlink
	$("#addLinkForm").find('li .btn-cancel').off().unbind().on('click', function() {
		$(this).parents('ul#addLinkForm').find('li input').each(function() {
			$(this).attr('value', '');
		});
		$(this).parents('ul#addLinkForm').collapse('hide');
	});

	// Remove Customlinks
	$('.btn-delete-customlink').on('click', function() {
		var btn = $(this);
		var notice = confirm('Delete this link ?');
		if (notice){
			var linkId = btn.data('timestamp');
			$.ajax({
				type : 'POST',
				url : 'index.php?athajax=dashboard&action=deletequicklink',
				data : {'linkid' : linkId},
				success : function(response) {
					if (response) {
						$('li#'+response).remove();
					}
				}
			});
		}
	});
	
	// Insert Image to use like icon
	$('.btn-image').on('click', function(e) {
		e.preventDefault();
		var $this = $(this);
		var loadurl = 'index.php?option=com_media&view=images&tmpl=component&asset=com_templates&author=&fieldid={field-media-id}&folder=';
		$('#jform-image-icon').find('.modal-body').html('<iframe id="image-icon-insert" name="imageIcon" width="100%" height="100%" src="'+loadurl+'"></iframe>');
		
		$('#image-icon-insert').on('load', function() {
			var imageForm = window.imageIcon.document.getElementById('imageForm');
			
			// Insert Image Url and Close Modal
			$(imageForm).find('button.button-save-selected').on('click', function() {
				var imageURL = $(imageForm).find('input#f_url').val();
				if (imageURL != '') {
					$($this.parents()[0]).find('input#image_url').attr('value', imageURL);
				}
				$('#jform-image-icon').modal('hide');
			});
			
			// Cancel button to close Modal
			$('.btn-cancel-image').on('click', function() {
				$('#dashboard-manage').modal({
					show : true
				});
				$('#jform-image-icon').modal('hide');
			});
			$(imageForm).find('button.button-cancel').off().unbind().on('click', function() {
				$('#jform-image-icon').modal('hide');
			});
		});
	});
	
	$('#jform-image-icon').on('shown.bs.modal', function() {
		var modalHeight = $('#jform-image-icon').height(),
				modalHeadHeight = $('#jform-image-icon .modal-header').innerHeight(),
				modalFootHeight = $('#jform-image-icon .modal-footer').innerHeight();
		var modalBodyHeight = modalHeight - modalHeadHeight - modalFootHeight;

		$('#jform-image-icon .modal-body').css('height', modalBodyHeight + 'px' );
	});
	
	// Search quicklinks
	var count = 0;
	$('input#searchLink').on('keyup', function() {
		var keyword = $(this).val();
		if (keyword != '') {
			$('#ungroup-links li.link-item').each(function() {
				var objTitle = $(this).find('.link-title').find('h5'),
						objUrl = $(this).find('.link-title').find('span');
				var title = objTitle.text(),
						url = objUrl.text();
				if (title.search(keyword, 'i') !== -1 || url.search(keyword, 'i') !== -1) {
					$(this).show();
					count++;
				} else {
					$(this).hide();
				}
			});
		} else {
			$('#ungroup-links li.link-item').show();
		}
	});
	
	/*
	* Menu Items
	*/
	$('#menu-groups').on('change', function() {
		if ($(this).val() == 'root') {
			$('input[name="menu-url"]').attr('value','#');
			$('input[name="menu-url"]').attr('readonly',true);
		} else {
			$('input[name="menu-url"]').attr('readonly',false);
		}
	});
	
	$('.menu-group .group-title').children('a').on('click', function() {
		var mnItem_ct = $(this).parent().next();
		if (!mnItem_ct.hasClass('in')) {
			setTimeout(function() {
				mnItem_ct.prev().addClass('active');
				mnItem_ct.css('overflow', 'visible');
			},400);
		} else {
			mnItem_ct.prev().removeClass('active');
			mnItem_ct.css('overflow', 'hidden');
		}
	});

	$('.menu-group ul.links.collapse').on('hidden.bs.collapse', function() {
		$(this).prev().removeClass('active');
		$(this).css('overflow','hidden');
	});
	
	// Add New Menu Item
	$('#addMenuForm').find('ul li .btn-addmenu').off().unbind().on('click', function() {
		var params = {};
		params['parent'] = $('#menu-groups').val();
		$(this).parent().parent().find('li input').each(function() {
			var name = $(this).attr('name').replace(/^menu-/,'');
			params[name] = $(this).val();
		});
		
		if (params['title'] == '') {
			var note = 'The menu title should not be empty!';
			alert(note); return;
		} else {
			var li = $('.menu-group li.group-quicklinks');
			var count = 0;
			if (params['parent'] == 'root') {
				$.each(li, function(key, group) {
					var groupName = $(group).attr('id').replace(/-[0-9].*/,'');
					if (params['title'] == groupName) {
						var note = 'The menu title already exists';
						alert(note); return;
					} else {
						count++;
					}
				})
			}
			if (count == li.length || params['parent'] != 'root') {
				$.ajax({
					type : 'POST',
					url : 'index.php?athajax=dashboard&action=addmenuitem',
					data : {'params' : params},
					success : function(response) {
						if (params['parent'] != 'root') {
							var id = params['parent'].match(/[0-9].*/);
							if ($('li#'+params['parent']).find('ul#menu-'+id[0]).length > 0) {
								$('li#'+params['parent']).find('ul#menu-'+id[0]).append(response);
								$('li#'+params['parent']).find('ul#menu-'+id[0]).collapse('show');
								var scrollTo = $('li#'+params['parent']).find('ul#menu-'+id[0]);
								$('#dashboard-manage .modal-body').animate(scrollTo.offset().top);
							} else {
								var $parent = $('li.ja-menu-item[id="'+params['parent']+'"]');
								$(response).insertAfter($parent);
								$parent.parent('ul').collapse('show');
								$parent.parent('ul').animate($parent.offset().top);
							}
							var newID = $(response).attr('id').match(/[0-9].*/)[0],
									level = $(response).attr('level');
							var $option = '<option value="'+newID+'">';
							for (var i = 0; i < level; i++) {
								$option += '-';
							}
							$option += ' '+params['title'].substr(0,1).toUpperCase()+params['title'].substr(1)+'</option>';
							$($option).insertAfter($('select#menu-groups').find('option[value="'+params['parent']+'"]'));
						} else {
							$('ul.menu-group').append(response);
							$('#addMenuForm').collapse('hide');
							var id = $($(response)[0]).attr('id').match(/[0-9].*/)[0];
							var group = params['title'].replace(/\s+/g,'');
							var $option = '<option value="'+group+'-'+id+'">-'+params['title'].substr(0,1).toUpperCase()+params['title'].substr(1)+'</option>';
							$('select#menu-groups').append($option);
							$('#dashboard-manage .modal-body').animate({scrollTop:$('#dashboard-manage').height()});
						}
						$('#addMenuForm').find('ul li input').attr('value','');
						$('#addMenuForm').find('ul li input[name="menu-url"]').attr('value','#');
						$('select#menu-groups').find('option[value="root"]').attr('selected', true);
					}
				});
			}
		}
	});
	
	// Cancel add new Menu Item
	$('#addMenuForm').find('ul li .btn-cancel').off().unbind().on('click', function() {
		$(this).parents('#addMenuForm').collapse('hide');
		$(this).parents('#addMenuForm').find('ul li input').attr('value','');
		$(this).parents('#addMenuForm').find('ul li input[name="menu-url"]').attr('value','#');
		$('select#menu-groups').find('option[value="root"]').attr('selected', true)
		$('.menu-parents').css('display','none');
		$('.new-menu-group').css('display','block');
	});
	
	// Edit Menu Group
  $('.mn-group-edit').children('a').off().unbind().on('click', function() {
		var parentTop = $(this).parent().parent().offset().top - $('#dashboard-manage').offset().top - $('.modal-header').outerHeight(true);
		var editContent = $(this).parent().find('.edit-mn-group');
		if (editContent.innerHeight() > parentTop) {
			editContent.addClass('under');
		} else {
			editContent.removeClass('under');
		}
		if (!editContent.hasClass('in')) {
			editContent.addClass('in');
		}
		$('.mn-group-edit').children('a').hide();
		$('.mn-item-actions').children('button').hide();
  });
	// Save edit menu group
	$('.btn-mn-group-edit').off().unbind().on('click', function() {
		var btn = $(this);
		var id = $($(this).parents('.mn-group-edit')[0]).children('a').data('timestamp'),
				inputs = $(this).parent().parent('ul').find('li input:text');
		var data = {};
		data['id'] = id;
		inputs.each(function() {
			var name = $(this).attr('name');
			if (name) {
				data[name] = $(this).val();
			}
		});
		$.ajax({
			type: 'POST',
			url: 'index.php?athajax=dashboard&action=editmenugroup',
			data: {'data' : data},
			success: function(response) {
				var params = $.parseJSON(response);
				var icon = '';
				if (params['menu-image'] != '') {
					icon = '<span class="mn-icon"><img src="../'+params['menu-image']+'" style="max-width:30px; max-height:30px;" /></span>';
				} else if(params['menu-icon'] != '') {
					icon = '<span class="mn-icon"><i class="'+params['menu-icon']+'"></i></span>';
				}
				var editBtn = btn.parents('.mn-group-edit').children('a');
				btn.parents('.group-title').children('a').html(icon+' <span class="leaf"></span> '+params['menu-title'].substr(0,1).toUpperCase() + params['menu-title'].substr(1));
				editBtn.attr('data-title', params['menu-title']);
				editBtn.attr('data-icons', params['menu-icon']);
				editBtn.attr('data-image', params['menu-image']);
				$('.mn-group-edit').children('a').show();
				$('.mn-item-actions').children('button').show();
				btn.parent().parent().parent().collapse('hide');
			}
		});
	});
	
	// Cancel Edit Menu Group
	$('.mn-group-edit').find('ul li .btn-cancel').off().unbind().on('click', function() {
		var ulParent = $(this).parent().parent('ul');
		var oldTitle = $(this).parents('.mn-group-edit').children('a').data('title'),
				oldIcon = $(this).parents('.mn-group-edit').children('a').data('icons'),
				oldImage = $(this).parents('.mn-group-edit').children('a').data('image');
		
		$(this).parent().parent().parent().collapse('hide');
		ulParent.find('li input[name="menu-title"]').attr('value', oldTitle);
		ulParent.find('li input[name="menu-icon"]').attr('value', oldIcon);
		ulParent.find('li input[name="menu-image"]').attr('value', oldImage);
		$('.mn-group-edit').children('a').show();
		$('.mn-item-actions').children('button').show();
	});
	
	// Delete custom menu group
	$('.delete-mn-group').off().unbind().on('click', function() {
		var name = $($(this).parents('.group-title')[0]).children('a').text().trim();
		var notice = confirm('Delete menu: '+name+'?. All sub-menu items will be deleted also.');
		if (notice) {
			var group = $($(this).parents('.group-quicklinks')[0]);
			var id = group.attr('id');
			$('select#menu-groups').find('option[value="'+id+'"]').remove();
			group.remove();
		}
	});
	
	// Edit custom menu item
	$('.btn-edit-menu-item').off().unbind().on('click',function() {
		$('.mn-group-edit').children('a').hide();
		$('.mn-item-actions').children('button').hide();
		var innerTop = $(this).parent().parent().offset().top - $('#dashboard-manage').offset().top - $('.modal-header').outerHeight(true);
		var innerEdit = $(this).parent().children('.mn-edit-item');
		innerEdit.addClass('in');
		innerEdit.css('height','auto');
		if (innerEdit.innerHeight() > innerTop) {
			innerEdit.addClass('under');
		} else {
			innerEdit.removeClass('under');
		}
		innerEdit.css('overflow','visible');
	});
	//Save edit custom menu item
	$('.btn-mn-item-edit').off().unbind().on('click', function() {
		var btn = $(this);
		var data = {};
		data['id'] = $(btn.parents('.mn-item-actions')[0]).children('.btn-edit-menu-item').data('timestamp');
		data['parent'] = btn.parent().parent().find('select').val();
		data['level'] = btn.parents('li.ja-menu-item ').attr('level');
		data['parents'] = btn.parents('li.ja-menu-item ').attr('parent');
		var inputs = btn.parent().parent().find('li input:text');
		inputs.each(function() {
			var name = $(this).attr('name');
			if (name) {
				data[name] = $(this).val();
			}
		});
		//console.log(data); return;
		$.ajax({
			type: 'POST',
			url: 'index.php?athajax=dashboard&action=editmenuitem',
			data: {'data' : data},
			success: function(response) {
				var params = $.parseJSON(response);
				var icon = '';
				if (params['menu-image'] != '') {
					icon = '<span class="mn-icon"><img src="../'+params['menu-image']+'" style="max-width:30px; max-height:30px;" /></span>';
				} else if(params['menu-icon'] != '') {
					icon = '<span class="mn-icon"><i class="'+params['menu-icon']+'"></i></span>';
				}
				var titleBlock = btn.parents('.mn-item-inner').children('.mn-item-title');
				titleBlock.children('h4').html(' <span class="leaf"></span> '+icon+params['menu-title'].substr(0,1).toUpperCase()+params['menu-title'].substr(1));
				titleBlock.children('small').html('<span class="leaf"> </span>'+params['menu-url']);
				
				var editBTN = btn.parents('.mn-item-inner').children('.mn-item-actions').children('.btn-edit-menu-item');
				editBTN.attr('data-title',params['menu-title']);
				editBTN.attr('data-url',params['menu-url']);
				editBTN.attr('data-icons',params['menu-icon']);
				editBTN.attr('data-image',params['menu-image']);
				
				btn.parents('.mn-edit-item').removeClass('in');
				btn.parents('.mn-edit-item').css('height', '0px');
				
				$('.mn-group-edit').children('a').show();
				$('.mn-item-actions').children('button').show();
			}
		});
	});
	
	// Cancel edit custom menu item
	$('.mn-edit-item').find('ul li .btn-cancel').off().unbind().on('click', function() {
		var btnEdit = $(this).parents('.mn-item-inner').children('.mn-item-actions').children('.btn-edit-menu-item');
		
		var oldTitle = btnEdit.attr('data-title'),
				oldUrl	 = btnEdit.attr('data-url'),
				oldIcon  = btnEdit.attr('data-icons'),
				oldImage = btnEdit.attr('data-image');
				oldparent = btnEdit.attr('data-parent');
		
		var ul = $(this).parent().parent('ul');
		ul.find('li input[name="menu-title"]').attr('value', oldTitle);
		ul.find('li input[name="menu-url"]').attr('value', oldUrl);
		ul.find('li input[name="menu-icon"]').attr('value', oldIcon);
		ul.find('li input[name="menu-image"]').attr('value', oldImage);
		ul.find('li select').find('option[value="'+oldparent+'"]').attr('selected','true');
		
		$(this).parent().parent().parent().removeClass('in');
		$('.mn-group-edit').children('a').show();
		$('.mn-item-actions').children('button').show();
	});
	
	// delete custom menu item
	$('.delete-menu-item').off().unbind().on('click', function() {
		var name = $(this).data('title');
		var note = confirm('Delete '+name+' menu ?');
		if (note) {
			var item = $($(this).parents('.ja-menu-item')[0]);
			var itemId = item.attr('id');
			$('select#menu-groups').find('option[value="'+itemId+'"]').remove();
			item.remove();
		}
	});
	
	// Sortable menu group
	$('ul.menu-group').sortable({
		handle : '.handle'
	});
	
	
	
	$('.menu-item-list').sortable({
		handle : '.handle',
		items : 'li:not(.ul-state-disable)',
		start : function(event, ui) {
			var current = $(ui.item);
			
			// Get children nodes
			var childrenNodes = $(this).find('li[parent~="'+current.attr('id')+'"]');
			childrenNodes.hide(); //hide all children notes
			
			// Get same level nodes
			var sameLevelNodes = $(this).find('li[level="'+current.attr('level')+'"]');
			sameLevelNodes.each(function() {
				// Hide all children node of the same level nodes.
				var _childrenNodes = $(this).parent().find('li[parent~="'+$(this).attr('id')+'"]');
				_childrenNodes.addClass('child-nodes-tmp-hide');
				_childrenNodes.hide();
			});
			
			// Disable others nodes is not same level
			$(this).find('li.ja-menu-item').each(function() {
				if (!$(this).hasClass('ui-sortable-placeholder')) {
					if ($(this).attr('level') != current.attr('level') || $(this).attr('parent') != current.attr('parent')) {
						$(this).addClass('ul-state-disable');
						$(this).css('opacity','0.3');
					}
				}
			});
			$(this).sortable('refresh');
		},
		stop : function(event, ui) {
			var current = $(ui.item);
			// Show children node
			var childrenNodes = $(this).find('li[parent~="'+current.attr('id')+'"]');
			current.after(childrenNodes);
			childrenNodes.show(); // Show children notes
			
			// Show all children node of the same level nodes.
			var prevItem = current.prev();
			var prevItemChildrenNodes = $(this).find('li[parent~="'+prevItem.attr('id')+'"]');
			prevItem.after(prevItemChildrenNodes);
			$('li.child-nodes-tmp-hide').show().removeClass('child-nodes-tmp-hide');
			
			// Endable other nodes are not same level.
			$(this).find('li.ja-menu-item').each(function() {
				if ($(this).hasClass('ul-state-disable')) {
					$(this).removeClass('ul-state-disable');
					$(this).css('opacity','1');
				}
			});
			$(this).sortable('refresh');
		}
	});
});