$(document).ready(function() {
	// Link modal
	$('#editLinkModal').on('show.bs.modal', function (event) {
		// menu type definitions, only using Applications at present
		var MENU_TYPE_COMPANYLINKS 	= '0';
		var MENU_TYPE_APPLICATIONS	= '1';

		var menu_type = $("#form-menu-type").val();
		$('#menu-csrf-token').val(Document.csrf_token);
		// hide the default perms checkbox, will be shown if adding new link.
		$('#editLinkModalViewAll').hide();
		// Only show the CSS class field if this is the applications menu
		$('#fg-menu-css-class').hide();
		if (menu_type == MENU_TYPE_APPLICATIONS)
		{
			$('#fg-menu-css-class').show();
		}

		$('#edit-link-modal-errors').css('display', 'none');
		$('#fg-menu-title').removeClass('has-error');
		$('#fg-menu-link').removeClass('has-error');
		$('#menu-link').val('');
		$('#menu-css-class').val('');
		var button = $(event.relatedTarget);
		var item_id = button.data('itemid');

		if (item_id == 'add-link') // User is adding a new link
		{
			$('#editLinkModalLabel').text(lmsg('menu_builder.add_new_link'));

			// set some sensible initial values.
			$('#menu-item-id').val(item_id);
			$('#menu-title').val('');
			$('#menu-link').val('');
			$('#menu-css-class').val('glyphicons-link');
			$('#menu-new-window').prop('checked', true);
			$('#menu-is-visible').prop('checked', true);
			// make sure default perms checkbox is visible.
			$('#editLinkModalViewAll').show();
		}
		else // Update an existing link, grab settings
		{
			$('#editLinkModalLabel').text(lmsg('menu_builder.update_link'));
			$.get('/menu/admin/infobar/' + item_id + '/getitem', function(data){
				var obj = jQuery.parseJSON(data);
				$('#menu-item-id').val(obj.id);
				$('#menu-title').val(obj.title);
				$('#menu-link').val(obj.url);
				if ('icon' in obj && obj.icon.type === 'glyphicon') {
                    $('#menu-css-class').val(obj.icon.class);
                } else {
                    $('#menu-css-class').val(null);
                }
				if (obj.new_window)
				{
					$('#menu-new-window').prop('checked', true);
				} else {
					$('#menu-new-window').prop('checked', false);
				}
				if (obj.disabled)
				{
                    $('#menu-is-visible').prop('checked', false);
				} else {
                    $('#menu-is-visible').prop('checked', true);
				}
			});
		}
	});

	$('#modal-link-save-button').on('click', function(e){
		var link = $('#menu-link');
		FixLink(link.get()[0]);
		var data = {};
		data.csrf_token = document.csrf_token;
		data.id = $('#menu-item-id').val();
		data.title = $('#menu-title').val();
		data.link = link.val();
		data.css_class = $('#menu-css-class').val();
		data.menu_type = $('#form-menu-type').val();
		data.new_window = $('#menu-new-window').prop('checked') ? 1 : 0;
		data.is_visible = $('#menu-is-visible').prop('checked') ? 1 : 0;
		data.view_by_all = $('#menu-view-by-all').prop('checked') ? 1 : 0;

		if (validateEntries(data))
		{
			$.post('/menu/admin/infobar/setitem', data, function(data){
				if(data.status == 'OK')
				{
					// close the modal and show success message.
					$('#editLinkModal').modal('toggle');
					if (data.new_link === 1 || data.redirect_to_perms === 0)
					{
						if (data.redirect_to_perms === 1)
						{
							window.location.replace('/menu/admin/infobar/' + data.id + '/perms');
						}
						else
						{
							reloadPageWithMessage(data.message);
						}

					}
					else
					{
						reloadPageWithMessage(data.message);
					}
				}
				else
				{
					// close the modal and show failure message.
					$('#editLinkModal').modal('toggle');
					cla.showMessage(data.message, 'Unable to create link.', true);
				}
			});
		}
	});

	$('#btn-add-divider').on('click', function(e){
		var data = {};
		data.csrf_token = document.csrf_token;
		data.id = 'add-divider';
		data.menu_type = $('#form-menu-type').val();

		$.post('/menu/admin/infobar/setitem', data, function(data){
			if(data.status == 'OK')
			{
				reloadPageWithMessage(data.message);
			}
			else
			{
				cla.showMessage(data.message, '', true);
			}
		});
		return false;
	});
	// highlight the current page in the sidebar
	highlightAdminMenu();
});

// Highlight currently active sidebar link in menu admin section
function highlightAdminMenu()
{
	var target = $("input[name='activeMenu']").val();
	$('[data-highlight="' + target + '"]').addClass('active');
}

function deleteItem(item_id)
{
	var data = {item_id:item_id, csrf_token:document.csrf_token};
	$.post('/menu/admin/infobar/deleteitem', data, function(data){
		if (data.status == 'OK')
		{
			reloadPageWithMessage(data.message);
		}
		else
		{
			cla.showMessage(data.message, '', true);
		}
	});


}

function toggleVisibility(item_id)
{
	var data = {item_id:item_id, csrf_token:document.csrf_token};
	$.post('/menu/admin/infobar/togglevisibility', data, function(data){
		if (data.status == 'OK')
		{
			var icon = $('#app_visibility_icon_' + data.id);
			if (data.visibility === true)
			{
				icon.removeClass('text-danger');
				icon.addClass('text-success');
				icon.attr('name', 'eye-outline');
			}
			else
			{
				icon.removeClass('text-success');
				icon.addClass('text-danger');
				icon.attr('name', 'eye-off-outline');
			}
			cla.showMessage(data.message, lmsg('menu_builder.vis_changed_detail'), false);
		}
		else
		{
			cla.showMessage(data.message, lmsg('menu_builder.vis_change_failed_detail'), true);
		}
	});
	return false;
}

function validateEntries(data)
{
	var MAX_LINK_LENGTH = 1024;

	$('#fg-menu-title').removeClass('has-error');
	$('#fg-menu-link').removeClass('has-error');
	var errors = Array();
	if(data.title.length == 0)
	{
		errors.push(lmsg('search.admin.empty_title'));
		$('#fg-menu-title').addClass('has-error');
	}
	if (data.link.length == 0)
	{
		errors.push(lmsg('search.admin.invalid_url'));
		$('#fg-menu-link').addClass('has-error');
	}

	if (data.link.length > MAX_LINK_LENGTH)
	{
		errors.push(lmsg('menu_builder.errors.link_too_long', MAX_LINK_LENGTH));
		$('#fg-menu-link').addClass('has-error');
	}
	if(errors.length > 0)
	{
		// nicely format the error text
		var errTxt = '';

		for (var i = 0; i < errors.length; i++)
		{
			errTxt += errors[i] + '. ';
		}


		$('#edit-link-modal-errors').text(errTxt);
		$('#edit-link-modal-errors').css('display', 'block');
		console.log(errors);
		return false;
	}
	return true;
}

function reloadPageWithMessage(message) {
    window.location.replace(
        [
            window.location.protocol,
            '//',
            window.location.host,
            window.location.pathname
        ].join('')
        + '?message=' + encodeURI(message) + '#page-footer'
    );
}
