/**
 * @version		$Id$
 * @author		JoomlaUX
 * @package		Joomla.Site
 * @subpackage	mod_jux_easy_megamenu
 * @copyright	Copyright (C) 2008 - 2018 JoomlaUX. All rights reserved.
 * @license		License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php
 */
var AdminMegamenu = window.AdminMegamenu || {};

!function ($) {
	var currentSelected = null,
	megamenu, nav_items, nav_subs, nav_cols, nav_all;

	$.fn.megamenuAdmin = function (options) {
		var defaultOptions = {
		};

		var options = $.extend(defaultOptions, options);
		megamenu = $(this).find('.jux-easy-megamenu');
		nav_items = megamenu.find('ul[class*="level"]>li>:first-child');
		nav_subs = megamenu.find('.jux-nav-child');
		nav_cols = megamenu.find('[class*="span"]');

		nav_all = nav_items.add(nav_subs).add(nav_cols);
		// hide sub
		nav_items.each (function () {
			var a = $(this),
				liitem = a.closest('li');
			if (liitem.data ('hidesub') == 1) {
				var sub = liitem.find('.jux-nav-child:first');
				// check if have menu-items in sub
				sub.css('display','none');
				a.removeClass ('dropdown-toggle').data('toggle', '');
				liitem.removeClass('jux-dropdown jux-dropdown-submenu jux-mega');
			}
		});



		// hide toolbox
		hide_toolbox(true);

        switch_menu_view();

        clear_image_preview();

        updatemenu();

		// bind events for all selectable elements
		bindEvents (nav_all);

		// unbind all events for toolbox actions & inputs
		$('.toolbox-action, .toolbox-toggle, .toolbox-input').unbind ("focus blur click change keydown");

		// stop popup event when click in toolbox area
		$('.jux-admin-mm-row').click (function(event) {
			event.stopPropagation();
			// return false;
		});
		// deselect when click outside menu
		$(document.body).click (function(event) {
			hide_toolbox (true);
			//event.stopPropagation();
		});

		// bind event for action

		$('.toolbox-action').click (function(event) {
			var action = $(this).data ('action');

			if (action) {
				actions.datas = $(this).data();
				actions[action] ();
			}
			event.stopPropagation();
			return false;
		});
		$('.toolbox-toggle').change (function(event) {
			var action = $(this).data ('action');
			if (action) {
				actions.datas = $(this).data();
				actions[action] ();
			}
			event.stopPropagation();
			return false;
		});
		// ignore events
		$('.toolbox-input').bind ('focus blur click', function(event) {
			event.stopPropagation();
			return false;
		});
		$('.toolbox-input').bind ('keydown', function(event) {
			if (event.keyCode == '13') {
				apply_toolbox (this);
				event.preventDefault();
			}
		});

		$('.toolbox-input').change (function(event) {
			apply_toolbox (this);
			event.stopPropagation();
			return false;
		});

		return this;
	};

	// Actions
	var actions = {};
	actions.data = {};
	actions.toggleDisplay = function(){
		if (!currentSelected) return ;
		var liitem = currentSelected.closest('li');
		if(liitem.hasClass('display-toggle')){
			liitem.removeClass('display-toggle');
			liitem.data('display',1);
		}else{
			liitem.addClass('display-toggle');
			liitem.data('display',(-1));
		}
		// update toolbox status
		update_toolbox ();
	}
	actions.toggleSub = function () {
		if (!currentSelected) return ;
		var liitem = currentSelected.closest('li'),
		sub = liitem.find ('.jux-nav-child:first');
		if (liitem.data('group')) return; // not allow do with group
		if (sub.length == 0 || sub.css('display') == 'none') {
			// add sub
			if (sub.length == 0) {
				sub = $('<div class="jux-nav-child jux-dropdown-menu "><div class="mega-dropdown-inner sortable-juxr"><div class="row-wrap"><div class="row-fluid row sortable-col"><div class="mega-col-module mega-col-block span12" data-width="12"><div class="mega-inner"></div></div></div></div></div></div>').appendTo(liitem);
				bindEvents (sub.find ('[class*="span"]'));
				liitem.addClass ('jux-mega');
				liitem.find('.jux-menu-item-wrapper').children('.jux-caret').remove();
				liitem.find('.jux-menu-item-wrapper').append('<i class="jux-caret fa fa-angle-down"></i>');

			} else {
				sub.css('display','');
				liitem.data('hidesub', 0);

			}
			liitem.data('group', 0);
			currentSelected.addClass ('dropdown-toggle').data('toggle', 'dropdown');
			liitem.addClass(liitem.data('level') == 1 ? 'jux-dropdown' : 'jux-dropdown-submenu');
			bindEvents(sub);
		} else {
			unbindEvents(sub);
			liitem.find('.jux-menu-item-wrapper').children('.jux-caret').remove();
			// check if have menu-items in sub
			if (liitem.find('ul.level'+liitem.data('level')).length > 0) {
				sub.css('display','none');
				liitem.data('hidesub', 1);
			} else {
				// just remove it
				sub.remove();
				liitem.find('.jux-menu-item-wrapper').children('.jux-caret').remove();
			}
			liitem.data('group', 0);
			currentSelected.removeClass ('dropdown-toggle').data('toggle', '');
			liitem.removeClass('jux-dropdown jux-dropdown-submenu jux-mega');
		}
		$( ".jux-ez-menu-item-options .sortable-col" ).sortable({
			items: "> .mega-col-block",
		}).disableSelection();

		$( ".jux-ez-menu-item-options .sortable-juxr" ).sortable({
			items: "> .row-wrap",
				placeholder: "ui-state-highlight",
			start: function(e,ui) {
				ui.placeholder.height(ui.item.height());
				ui.placeholder.width(ui.item.width());
			}
		}).disableSelection();
		// update toolbox status
		update_toolbox ();
	}

	actions.toggleIconSwitch = function () {
		if (!currentSelected) return ;
		var liitem = currentSelected.parent();
		var icon = currentSelected.find('.jux-icon:first'),
		img = currentSelected.find('.jux-img:first');
		if(icon.length == 0 && img.length == 0) {
			var imgClass = 'jux-img-l';
				if(liitem.data('level') == 1) {
					if($('select#jux_mm_top_menu_icon_position').val() === 'right') {
						imgClass = 'jux-img-r';
					}
					if($('select#jux_mm_top_menu_icon_position').val() === 'above') {
						imgClass = 'jux-img-above';
					}
				} else {
					if($('select#jux_mm_sm_icon_position').val() === 'right') {
						imgClass = 'jux-img-r';
					}
					if($('select#jux_mm_sm_icon_position').val() === 'above') {
						imgClass = 'jux-img-above';
					}
				}
				liitem.find('.jux-menu-item-wrapper:first').prepend('<i class="hide jux-icon '+imgClass+'" ></i>');
			liitem.data('sicon', 1);
		} else {
			if(icon.length == 1 && img.length == 0) {
				icon.remove();
				var imgClass = 'jux-img-l';
				if(liitem.data('level') == 1) {
					if($('select#jux_mm_top_menu_icon_position').val() === 'right') {
						imgClass = 'jux-img-r';
					}
					if($('select#jux_mm_top_menu_icon_position').val() === 'above') {
						imgClass = 'jux-img-above';
					}
				} else {
					if($('select#jux_mm_sm_icon_position').val() === 'right') {
						imgClass = 'jux-img-r';
					}
					if($('select#jux_mm_sm_icon_position').val() === 'above') {
						imgClass = 'jux-img-above';
					}
				}
				var imgUrl = liitem.data('imgurl') ? liitem.data('imgurl') : '';
				var hideClass = liitem.data('imgurl') ? '' : ' hide';
				liitem.find('.jux-menu-item-wrapper:first').prepend('<div class="jux-img '+imgClass+ hideClass+'"><img src="'+imgUrl+'" alt="" /></div>');
				liitem.data('sicon', 2);
			}
			if(icon.length == 0 && img.length == 1) {
				img.remove();
				var iconClass = 'jux-icon-l';
				if(liitem.data('level') == 1) {
					if($('select#jux_mm_top_menu_icon_position').val() === 'right') {
						iconClass = 'jux-icon-r';
					}
					if($('select#jux_mm_top_menu_icon_position').val() === 'above') {
						iconClass = 'jux-icon-above';
					}
				} else {
					if($('select#jux_mm_sm_icon_position').val() === 'right') {
						iconClass = 'jux-icon-r';
					}
					if($('select#jux_mm_sm_icon_position').val() === 'above') {
						iconClass = 'jux-icon-above';
					}
				}

				var xicon = liitem.data('xicon') ? liitem.data('xicon') : '';
				var hideClass = liitem.data('xicon') ? '' : ' hide';
				liitem.find('.jux-menu-item-wrapper:first').prepend('<i class="jux-icon '+iconClass+ ' '+ xicon + hideClass +'"></i>');
				liitem.data('sicon', 1);
			}
		}
		update_toolbox ();
	}

	actions.toggleGroup = function () {
		if (!currentSelected) return ;
		var liitem = currentSelected.parent(),
			sub = liitem.find ('.jux-nav-child:first');
		if (liitem.data('level') == 1) return; // ignore for top level
		if (liitem.data('group')) {
			liitem.data('group', 0);
			liitem.removeClass('mega-group').addClass('jux-dropdown-submenu');
			currentSelected.addClass ('dropdown-toggle').data('toggle', 'dropdown');
			sub.removeClass ('mega-group-ct').addClass ('jux-dropdown-menu');
			sub.css('width', sub.data('width'));
			rebindEvents(sub);
		} else {
			currentSelected.removeClass ('dropdown-toggle').data('toggle', '');
			liitem.data('group', 1);
			liitem.removeClass('jux-dropdown-submenu').addClass('mega-group');
			sub.removeClass ('jux-dropdown-menu').addClass ('mega-group-ct');
			sub.css('width', '');
			rebindEvents(sub);
		}
		// update toolbox status
		update_toolbox ();
	}

	actions.moveItemsLeft = function () {
		if (!currentSelected) return ;
		var $item = currentSelected.closest('li'),
		$liparent = $item.parent().closest('li'),
		level = $liparent.data('level'),
		$col = $item.closest ('[class*="span"]'),
		$items = $col.find ('ul:first > li'),
		itemidx = $items.index ($item),
		$moveitems = $items.slice (0, itemidx+1),
		itemleft = $items.length - $moveitems.length,
		$rows = $col.parent().parent().children ('[class*="row"]'),
		$cols = $rows.children('[class*="span"]').filter (function(){return !$(this).data('position')}),
		colidx = $cols.index ($col);
		if (!$liparent.length) return ; // need make this is mega first

		if (colidx == 0) {
			// add new col
			var oldSelected = currentSelected;
			currentSelected = $col;
			// add column to first
			actions.datas.addfirst = true;
			actions.addColumn ();
			$cols = $rows.children('[class*="span"]').filter (function(){return !$(this).data('position')});
			currentSelected = oldSelected;
			colidx++;
		}
		// move content to right col
		var $tocol = $($cols[colidx-1]);
		var $ul = $tocol.find('ul:first');
		if (!$ul.length) {
			$ul = $('<ul class="mega-nav sortable-sub-item level'+level+'">').appendTo ($tocol.children('.mega-inner'));
		}
		$moveitems.appendTo($ul);
		$( ".jux-ez-menu-item-options .sortable-sub-item" ).sortable({
			items: "> li",
			revert: true,
				placeholder: "ui-state-highlight",
			start: function(e,ui) {
				ui.placeholder.height(ui.item.height());
				ui.placeholder.width(ui.item.width());
			}
		}).disableSelection();
		if (itemleft == 0) {
			$col.find('ul:first').remove();
		}
		// update toolbox status
		update_toolbox ();
	}

	actions.moveItemsRight = function () {
		if (!currentSelected) return ;
		var $item = currentSelected.closest('li'),
		$liparent = $item.parent().closest('li'),
		level = $liparent.data('level'),
		$col = $item.closest ('[class*="span"]'),
		$items = $col.find ('ul:first > li'),
		itemidx = $items.index ($item),
		$moveitems = $items.slice (itemidx),
		itemleft = $items.length - $moveitems.length,
		$rows = $col.parent().parent().children ('[class*="row"]'),
		$cols = $rows.children('[class*="span"]').filter (function(){return !$(this).data('position')}),
		colidx = $cols.index ($col);
		if (!$liparent.length) return ; // need make this is mega first

		if (colidx == $cols.length - 1) {
			// add new col
			var oldSelected = currentSelected;
			currentSelected = $col;
			actions.datas.addfirst = false;
			actions.addColumn ();
			$cols = $rows.children('[class*="span"]').filter (function(){return !$(this).data('position')});
			currentSelected = oldSelected;
		}
		// move content to right col
		var $tocol = $($cols[colidx+1]);
		var $ul = $tocol.find('ul:first');
		if (!$ul.length) {
			$ul = $('<ul class="mega-nav sortable-sub-item level'+level+'">').appendTo ($tocol.children('.mega-inner'));
		}
		$moveitems.prependTo($ul);
		$( ".jux-ez-menu-item-options .sortable-sub-item" ).sortable({
			items: "> li",
			revert: true,
				placeholder: "ui-state-highlight",
			start: function(e,ui) {
				ui.placeholder.height(ui.item.height());
				ui.placeholder.width(ui.item.width());
			}
		}).disableSelection();
		if (itemleft == 0) {
			$col.find('ul:first').remove();
		}

		// update toolbox status
		show_toolbox (currentSelected);
	}

	actions.addRow = function () {
		if (!currentSelected) return ;
		var $row = $('<div class="row-wrap"><div class="row-fluid row sortable-col"><div class="mega-col-module mega-col-block span12"><div class="mega-inner"></div></div></div></div>').appendTo(currentSelected.find('[class*="row"]:first').parent()),
		$col = $row.children().children();

		// bind event
		bindEvents ($col);
		currentSelected = null;
		$( ".jux-ez-menu-item-options .sortable-col" ).sortable({
			items: "> .mega-col-block",
		}).disableSelection();
		$( ".jux-ez-menu-item-options .sortable-juxr" ).sortable({
			items: "> .row-wrap",
				placeholder: "ui-state-highlight",
			start: function(e,ui) {
				ui.placeholder.height(ui.item.height());
				ui.placeholder.width(ui.item.width());
			}
		}).disableSelection();
		// switch selected to new column
		show_toolbox ($col);
	}

	actions.alignment = function () {
		var liitem = currentSelected.closest ('li');
		liitem.removeClass ('mega-align-left mega-align-center mega-align-right mega-align-justify').addClass ('mega-align-'+actions.datas.align);
		
		var itemWrapper = liitem.children('a').find('.jux-menu-item-wrapper');
		var iconPosition = liitem.data('level') < 2 ? $('#jux_mm_top_menu_icon_position').val() : $('#jux_mm_sm_icon_position').val();
		var liItemLevel = liitem.data('level');
		if (actions.datas.align == 'justify') {
			if(liItemLevel >= 2) {
				liitem.children('a').find('.jux-caret').removeClass('fa-angle-left').addClass('fa-angle-right');
			}
			currentSelected.addClass('span12');
			currentSelected.css('width', '');
			liitem.css('position', 'static');
		} else {
			if(actions.datas.align == 'right') {
				if(iconPosition == 'above') {
					if(liItemLevel >= 2) {
						liitem.children('a').find('.jux-caret').removeClass('fa-angle-right').addClass('fa-angle-left');
					}
				} else {
					if(liItemLevel >= 2) {
						liitem.children('a').find('.jux-caret').removeClass('fa-angle-right').addClass('fa-angle-left');
					}
				}
			} else {
				if(liItemLevel >= 2) {
					liitem.children('a').find('.jux-caret').removeClass('fa-angle-left').addClass('fa-angle-right');
				}
			}
			currentSelected.removeClass('span12');
			if (currentSelected.data('width')) currentSelected.css('width', currentSelected.data('width'));
			liitem.css('position', 'inherit');
		}
		liitem.data('alignsub', actions.datas.align);
		update_toolbox ();
	}

	actions.addColumn = function () {
		if (!currentSelected) return ;
		var $cols = currentSelected.parent().children('[class*="span"]'),
			colcount = $cols.length + 1,
			colwidths = defaultColumnsWidth (colcount);

		// add new column
		var $col = $('<div class="mega-col-nav mega-col-block"><div class="mega-inner"></div></div>');
		if (actions.datas.addfirst)
			$col.prependTo (currentSelected.parent());
		else {
			$col.insertAfter (currentSelected);
		}
		$cols = $cols.add ($col);
		// bind event
		bindEvents ($col);
		// update widthf
		$cols.each (function (i) {
			$(this).removeClass ('span'+$(this).data('width')).addClass('span'+colwidths[i]).data('width', colwidths[i]);
		});
		// switch selected to new column
		show_toolbox ($col);
	}

	actions.removeColumn = function () {
		if (!currentSelected){
			return;
		}

		var $col = currentSelected,
			$row = $col.parent(),
			$rows = $row.parent().children ('[class*="row"]'),
			$allcols = $rows.children('[class*="span"]'),
			$allmenucols = $allcols.filter (function(){return !$(this).data('position')}),
			$haspos = $allcols.filter (function(){return $(this).data('position')}).length,
			$cols = $row.children('[class*="span"]'),
			colcount = $cols.length - 1,
			colwidths = defaultColumnsWidth (colcount),
			type_menu = $col.data ('position') ? false : true;

		if ((type_menu && ((!$haspos && $allmenucols.length == 1) || ($haspos && $allmenucols.length == 0)))
			|| $allcols.length == 1) {
			// if this is the only one column left
			return;
		}

		// remove column
		// check and move content to other column
		if (type_menu) {
			var colidx = $allmenucols.index($col),
				tocol = colidx == 0 ? $allmenucols[1] : $allmenucols[colidx-1];

			$col.find ('ul:first > li').appendTo ($(tocol).find('ul:first'));
		}

		var colidx = $allcols.index($col),
			nextActiveCol = colidx == 0 ? $allcols[1] : $allcols[colidx-1];

		if (colcount < 1) {
			$row.remove();
		} else {
			$cols = $cols.not ($col);
			// update width
			$cols.each (function (i) {
				$(this).removeClass ('span'+$(this).data('width')).addClass('span'+colwidths[i]).data('width', colwidths[i]);
			});
			// remove col
			$col.remove();
		}

		show_toolbox ($(nextActiveCol));
	}

	actions.hideWhenCollapse = function () {
		if (!currentSelected) return ;
		var type = toolbox_type ();
		if (type == 'sub') {
			var liitem = currentSelected.closest('li');
			if (liitem.data('hidewcol')) {
				liitem.data('hidewcol', 0);
				liitem.removeClass ('sub-hidden-collapse');
			} else {
				liitem.data('hidewcol', 1);
				liitem.addClass ('sub-hidden-collapse');
			}
		} else if (type == 'col') {
			if (currentSelected.data('hidewcol')) {
				currentSelected.data('hidewcol', 0);
				currentSelected.removeClass ('hidden-collapse');
			} else {
				currentSelected.data('hidewcol', 1);
				currentSelected.addClass ('hidden-collapse');
			}
		}
		update_toolbox ();
	}

	// toggle screen
	actions.toggleScreen = function () {
		if ($('.toolbox-togglescreen').hasClass('jux-fullscreen-full')) {
			$('.subhead-collapse').removeClass ('subhead-fixed');
			$('#jux-admin-megamenu').closest('.controls,li').removeClass ('jux-admin-control-fixed');
			$('.toolbox-togglescreen').removeClass ('jux-fullscreen-full').find('i').removeClass().addClass(actions.datas.iconfull);
		} else {
			$('.subhead-collapse').addClass ('subhead-fixed');
			$('#jux-admin-megamenu').closest('.controls,li').addClass ('jux-admin-control-fixed');
			$('.toolbox-togglescreen').addClass ('jux-fullscreen-full').find('i').removeClass().addClass(actions.datas.iconsmall);
			$('.pane-sliders').css('position','static');
		}
	}

	actions.saveConfig = function (e) {
		var config = {}, order = {}, menuType = $('#jform_params_mod_menu').val(),
		items = megamenu.find('ul[class*="level"] > li');
		items.each (function(index){
			var $this = $(this),
			id = $this.data('id'),
			item = {};
			itemOrder = {};
			if ($this.hasClass ('jux-mega')) {
				var $sub = $this.find ('.jux-nav-child:first');
				item['sub'] = {};

				var childItems = $this.find('ul[class*="level"] > li');
				childItems.each(function(cIndex) {
					var cItem = $(this);
					itemOrder[cItem.data('id')] = cItem.data('id');
				});


				for (var d in $sub.data()) {
					if (d != 'id' && d != 'level' && $sub.data(d))
						item['sub'][d] = $sub.data(d);
				}
				// build row
				var $rows = $sub.find('[class*="row"]:first').parent().children('[class*="row"]').children(),
				rows = [],
				i = 0;

				$rows.each (function () {
					var row = [],arow = [],
					$cols = $(this).children('[class*="span"]'),
					j = 0;
					$cols.each (function(){
						var li = $(this).find('ul[class*="level"] > li:first'),
							ali = li.parent().children('li'),
							col = {};
						if (li.length ) {
							col['item'] = li.data('id');

						} else if ($(this).data('position')) {
							col['position'] = $(this).data('position');
						} else {
							col['item'] = -1;
						}

						if(li.data('display') == -1){
							col['display'] = -1;
						}else{
							col['display'] = 1;
						}

						for (var d in $(this).data()) {
							if (d != 'id' && d != 'level' && d != 'position' && $(this).data(d)){
								col[d] = $(this).data(d);
							}
						}
						delete col.sortableItem;
						row[j++] = col;
					});
					rows[i++] = row;
				});
				item['sub']['rows'] = rows;
			}
			for (var d in $this.data()) {
				if (d != 'id' && d != 'level' && $this.data(d)) {
					if (d == 'caption')
						item[d] = $this.data(d).replace(/</g, "[lt]").replace(/>/g, "[gt]");
					else
						item[d] = $this.data(d);
				}
			}

			if (Object.keys(item).length) {
				order[$this.data('id')] = itemOrder;
				config[id] = item;
			}
			delete config[id].sortableItem;
		});

		var option = get_megamenu_options();

		var jmmconfig = $('#jform_params_mega_config'),
			jmmorder = $('#jform_params_mega_order'),
			jmmoption = $('#jform_params_mega_options'),
			jmmstyle = $('#jform_params_mega_style'),
            curstyle = null,
			curconfig = null;

		try {
			curconfig = jmmconfig.val() ? $.parseJSON(jmmconfig.val()) : {};
		} catch(e){
			curconfig = {};
		}
		if($.isArray(curconfig) && curconfig.length == 0){
			curconfig = {};
		}

		try {
			curorder = jmmorder.val() ? $.parseJSON(jmmorder.val()) : {};
		} catch(e){
			curorder = {};
		}
		if($.isArray(curorder) && curorder.length == 0){
			curorder = {};
		}

        try {
            curstyle = jmmstyle.val() ? $.parseJSON(jmmstyle.val()) : {};
        } catch(e){
            curstyle = {};
        }
        if($.isArray(curstyle) && curstyle.length == 0){
            curstyle = {};
		}

        curconfig[menuType] = JSON.parse(JSON.stringify(config));
        curorder[menuType] = JSON.parse(JSON.stringify(order));
        curstyle[menuType] = JSON.parse(JSON.stringify(updatemenu(false)));
		var jsonConfig = JSON.stringify(curconfig);
		var jsonOrder = JSON.stringify(curorder);
		var jsonOption = JSON.stringify(option);
		var jsonStyle = JSON.stringify(curstyle);
		var menu_style =
		jmmconfig.val(jsonConfig);
		jmmorder.val(jsonOrder);
        jmmoption.val(jsonOption);
        jmmstyle.val(jsonStyle);
	}



	get_megamenu_options = function() {
		// 1: true, 0: false
		var option = {},optionObj = {};

        var menuType = $('#jform_params_mod_menu').val();

        /* General Options */
        var menu_orientation = $('#jux_ez_mm_orientation').val();
        optionObj.menu_orientation = menu_orientation;
        var sm_verticalDrop = $('#jux_ez_mm_vertical_dropdown').val();
        optionObj.sm_vertical_drop = sm_verticalDrop;
        var sm_horizontalDrop = $('#jux_ez_mm_horizontal_dropdown').val();
		optionObj.sm_horizontal_drop = sm_horizontalDrop;
		//rtl
		var rtl = $('input[name="jux_easy_mm_rtl"]').is(':checked') ? 1 : 0 ;
        optionObj.rtl = rtl;
        //animation
		var sm_animation = $('#jux_ez_mm_animation').val();
        optionObj.sm_animation = sm_animation;
        var sm_animation_duration = $('input[name="jux_ez_mm_animation_duration"]').val();
        optionObj.sm_animation_duration = sm_animation_duration;
        var sm_animation_delay = $('input[name="jux_ez_mm_animation_delay"]').val();
        optionObj.sm_animation_delay = sm_animation_delay;
        //Sticky Menu
        var sticky_menu = $('input[name="jux_ez_mm_use_sticky"]').is(':checked') ? 1 : 0;
        optionObj.sticky_menu = sticky_menu;
        var sticky_wrap = $('#jux_ez_mm_sticky_wrap').val();
        optionObj.sticky_wrap = sticky_wrap;
        var sticky_margin_top = $('input[name="jux_ez_mm_sticky_margin_top"]').val();
        optionObj.sticky_margin_top = sticky_margin_top;
        //other
		var disable_carets = $('input[name="jux_ez_mm_disable_caret"]').is(':checked') ? 1 : 0 ;
        optionObj.disable_carets = disable_carets;
        /* End General Options */

		/* Menu Bar */
        //Border
        var menubar_border_style = $('#jux_mm_menu_bar_border_style').val();
        optionObj.menubar_border_style = menubar_border_style;
        //Width
        var menubar_border_width = $('input[name="jux_mm_menu_bar_border_width"]').val();
        optionObj.menubar_border_width = menubar_border_width;
        var menubar_border_color = $('input[name="jux_mm_menu_bar_border_color"]').val();
        optionObj.menubar_border_color = menubar_border_color;
        var menubar_border_top = $('input[name="jux_mm_menu_bar_border_position_top"]').is(':checked') ? 1 : 0;
        optionObj.menubar_border_top = menubar_border_top;
        var menubar_border_right = $('input[name="jux_mm_menu_bar_border_position_right"]').is(':checked') ? 1 : 0;
        optionObj.menubar_border_right = menubar_border_right;
        var menubar_border_bottom = $('input[name="jux_mm_menu_bar_border_position_bottom"]').is(':checked') ? 1 : 0;
        optionObj.menubar_border_bottom = menubar_border_bottom;
        var menubar_border_left = $('input[name="jux_mm_menu_bar_border_position_left"]').is(':checked') ? 1 : 0;
        optionObj.menubar_border_left = menubar_border_left;
        //Border Radius
		//left
        var menubar_border_radius_tleft = $('input[name="jux_mm_menu_bar_radius_top_left"]').val();
        optionObj.menubar_border_radius_tleft = menubar_border_radius_tleft;
        //top
        var menubar_border_radius_tright = $('input[name="jux_mm_menu_bar_radius_top_right"]').val();
        optionObj.menubar_border_radius_tright = menubar_border_radius_tright;
        //left
        var menubar_border_radius_bright = $('input[name="jux_mm_menu_bar_radius_bottom_right"]').val();
        optionObj.menubar_border_radius_bright = menubar_border_radius_bright;
        //left
        var menubar_border_radius_bleft = $('input[name="jux_mm_menu_bar_radius_bottom_left"]').val();
        optionObj.menubar_border_radius_bleft = menubar_border_radius_bleft;
        //background
		var menubar_bg_type = $('#jux_mm_menu_bar_bg_type').val();
        optionObj.menubar_bg_type = menubar_bg_type;
        var menubar_solid_bg = $('#jux_mm_menu_bar_solid_bg_color').val();
        optionObj.menubar_solid_bg = menubar_solid_bg;
        var menubar_bg_start_color = $('input#jux_mm_menu_bar_bg_start_color').val();
        optionObj.menubar_bg_start_color = menubar_bg_start_color;
        var menubar_bg_end_color = $('input#jux_mm_menu_bar_bg_end_color').val();
        optionObj.menubar_bg_end_color = menubar_bg_end_color;
        //shadow
		var menubar_bs_h_length = $('input[name="jux_mm_menu_bar_h_shadow"]').val();
        optionObj.menubar_bs_h_length = menubar_bs_h_length;
        var menubar_bs_v_length = $('input[name="jux_mm_menu_bar_v_shadow"]').val();
        optionObj.menubar_bs_v_length = menubar_bs_v_length;
        var menubar_bs_blur = $('input[name="jux_mm_menu_bar_shadow_blur"]').val();
        optionObj.menubar_bs_blur = menubar_bs_blur;
        var menubar_bs_size = $('input[name="jux_mm_menu_bar_shadow_size"]').val();
        optionObj.menubar_bs_size = menubar_bs_size;
        var menubar_bs_color = $('#jux_mm_menu_bar_shadow_color').val();
        optionObj.menubar_bs_color = menubar_bs_color;
        var menubar_bs_inset = $('#jux_mm_menu_bar_shadow_inset').is(':checked') ? 1 : 0;
        optionObj.menubar_bs_inset = menubar_bs_inset;
        //alignment
		var menubar_align = $('#jux_mm_menu_bar_alignment').val();
		optionObj.menubar_align = menubar_align;
		//padding
        var menubar_padding_left = $('input[name="jux_mm_menu_bar_padding_left"]').val();
        optionObj.menubar_padding_left = menubar_padding_left;
        var menubar_padding_right = $('input[name="jux_mm_menu_bar_padding_right"]').val();
        optionObj.menubar_padding_right = menubar_padding_right;
        var menubar_padding_top = $('input[name="jux_mm_menu_bar_padding_top"]').val();
        optionObj.menubar_padding_top = menubar_padding_top;
        var menubar_padding_bottom = $('input[name="jux_mm_menu_bar_padding_bottom"]').val();
        optionObj.menubar_padding_bottom = menubar_padding_bottom;
        //margin
        var menubar_margin_left = $('input[name="jux_mm_menu_bar_margin_left"]').val();
        optionObj.menubar_margin_left = menubar_margin_left;
        var menubar_margin_right = $('input[name="jux_mm_menu_bar_margin_right"]').val();
        optionObj.menubar_margin_right = menubar_margin_right;
		/* End Menu Bar */
		var topmenu_border_style = $('#jux_mm_top_menu_border_style').val();
        optionObj.topmenu_border_style = topmenu_border_style;
        var topmenu_border_width = $('input[name="jux_mm_top_menu_border_width"]').val();
        optionObj.topmenu_border_width = topmenu_border_width;
        var topmenu_border_color = $('#jux_mm_top_menu_border_color').val();
        optionObj.topmenu_border_color = topmenu_border_color;
        var topmenu_border_top = $('input[name="jux_mm_top_menu_border_position_top"]').is(':checked') ? 1 : 0;
        optionObj.topmenu_border_top = topmenu_border_top;
        var topmenu_border_right = $('input[name="jux_mm_top_menu_border_position_right"]').is(':checked') ? 1 : 0;
        optionObj.topmenu_border_right = topmenu_border_right;
        var topmenu_border_bottom = $('input[name="jux_mm_top_menu_border_position_bottom"]').is(':checked') ? 1 : 0;
        optionObj.topmenu_border_bottom = topmenu_border_bottom;
        var topmenu_border_left = $('input[name="jux_mm_top_menu_border_position_left"]').is(':checked') ? 1 : 0;
        optionObj.topmenu_border_left = topmenu_border_left;
        //Border Radius
        //left
        var topmenu_border_radius_tleft = $('input[name="jux_mm_top_menu_radius_top_left"]').val();
        optionObj.topmenu_border_radius_tleft = topmenu_border_radius_tleft;
        //top
        var topmenu_border_radius_tright = $('input[name="jux_mm_top_menu_radius_top_right"]').val();
        optionObj.topmenu_border_radius_tright = topmenu_border_radius_tright;
        //left
        var topmenu_border_radius_bright = $('input[name="jux_mm_top_menu_radius_bottom_right"]').val();
        optionObj.topmenu_border_radius_bright = topmenu_border_radius_bright;
        //left
        var topmenu_border_radius_bleft = $('input[name="jux_mm_top_menu_radius_bottom_left"]').val();
        optionObj.topmenu_border_radius_bleft = topmenu_border_radius_bleft;
        //background
        var topmenu_bg_type = $('#jux_mm_top_menu_bg_type').val();
        optionObj.topmenu_bg_type = topmenu_bg_type;
        var topmenu_solid_bg = $('#jux_mm_top_menu_solid_bg_color').val();
        optionObj.topmenu_solid_bg = topmenu_solid_bg;
        var topmenu_bg_start_color = $('input#jux_mm_top_menu_bg_start_color').val();
        optionObj.topmenu_bg_start_color = topmenu_bg_start_color;
        var topmenu_bg_end_color = $('input#jux_mm_top_menu_bg_end_color').val();
        optionObj.topmenu_bg_end_color = topmenu_bg_end_color;
        //Font
		var topmenu_font_family = $('#jux_mm_top_menu_font_family').val();
        optionObj.topmenu_font_family = topmenu_font_family;
        var topmenu_font_url = $('#jux_mm_top_menu_font_family option:selected').data('url');
        optionObj.topmenu_font_url = topmenu_font_url;
        var topmenu_font_style = $('#jux_mm_top_menu_font_style').val();
        optionObj.topmenu_font_style = topmenu_font_style;
        var topmenu_font_weight = $('#jux_mm_top_menu_font_weight').val();
        optionObj.topmenu_font_weight = topmenu_font_weight;
        var topmenu_font_size = $('input[name="jux_mm_top_menu_font_size"]').val();
        optionObj.topmenu_font_size = topmenu_font_size;
        var topmenu_font_color = $('#jux_mm_top_menu_font_color').val();
        optionObj.topmenu_font_color = topmenu_font_color;
        var topmenu_font_upper = $('#jux_mm_top_menu_uppercase').is(':checked') ? 1 : 0;
        optionObj.topmenu_font_upper = topmenu_font_upper;
        //Icon
		var topmenu_icon_size = $('input[name="jux_mm_top_menu_icon_size"]').val();
        optionObj.topmenu_icon_size = topmenu_icon_size;
		var topmenu_icon_color = $('#jux_mm_top_menu_icon_color').val();
        optionObj.topmenu_icon_color = topmenu_icon_color;
		var topmenu_icon_position = $('#jux_mm_top_menu_icon_position').val();
		optionObj.topmenu_icon_position = topmenu_icon_position;
		//Shadow
		var topmenu_bs_h_length = $('input[name="jux_mm_top_menu_h_shadow"]').val();
		optionObj.topmenu_bs_h_length = topmenu_bs_h_length;
		var topmenu_bs_v_length = $('input[name="jux_mm_top_menu_v_shadow"]').val();
		optionObj.topmenu_bs_v_length = topmenu_bs_v_length;
		var topmenu_bs_blur = $('input[name="jux_mm_top_menu_shadow_blur"]').val();
		optionObj.topmenu_bs_blur = topmenu_bs_blur;
		var topmenu_bs_size = $('input[name="jux_mm_top_menu_shadow_size"]').val();
		optionObj.topmenu_bs_size = topmenu_bs_size;
		var topmenu_bs_color = $('input[name="jux_mm_top_menu_shadow_color"]').val();
		optionObj.topmenu_bs_color = topmenu_bs_color;
		var topmenu_bs_inset = $('input#jux_mm_top_menu_shadow_inset').is(':checked') ? 1 : 0;
		optionObj.topmenu_bs_inset = topmenu_bs_inset;

        //padding
        var topmenu_padding_left = $('input[name="jux_mm_top_menu_padding_left"]').val();
        optionObj.topmenu_padding_left = topmenu_padding_left;
        var topmenu_padding_right = $('input[name="jux_mm_top_menu_padding_right"]').val();
        optionObj.topmenu_padding_right = topmenu_padding_right;
        var topmenu_padding_top = $('input[name="jux_mm_top_menu_padding_top"]').val();
        optionObj.topmenu_padding_top = topmenu_padding_top;
        var topmenu_padding_bottom = $('input[name="jux_mm_top_menu_padding_bottom"]').val();
        optionObj.topmenu_padding_bottom = topmenu_padding_bottom;
        //margin
        var topmenu_margin_left = $('input[name="jux_mm_top_menu_margin_left"]').val();
        optionObj.topmenu_margin_left = topmenu_margin_left;
        var topmenu_margin_right = $('input[name="jux_mm_top_menu_margin_right"]').val();
        optionObj.topmenu_margin_right = topmenu_margin_right;
        var topmenu_margin_top = $('input[name="jux_mm_top_menu_margin_top"]').val();
        optionObj.topmenu_margin_top = topmenu_margin_top;
        var topmenu_margin_bottom = $('input[name="jux_mm_top_menu_margin_bottom"]').val();
        optionObj.topmenu_margin_bottom = topmenu_margin_bottom;
        var topmenu_h_shadow = $('input[name="jux_mm_tm_h_shadow"]').val();
        optionObj.topmenu_h_shadow = topmenu_h_shadow;
        var topmenu_caption_size = $('input[name="jux_mm_top_menu_caption_size"]').val();
        optionObj.topmenu_caption_size = topmenu_caption_size;
        var topmenu_caption_color = $('input#jux_mm_top_menu_caption_color').val();
        optionObj.topmenu_caption_color = topmenu_caption_color;
		/* End Top Menu */

		/*Top Menu Hover */
		var topmenu_hvr_txt_color = $('#jux_mm_tm_hvr_txt_color').val();
        optionObj.topmenu_hvr_txt_color = topmenu_hvr_txt_color;
		//background
		var topmenu_hvr_bg_type = $('#jux_mm_tm_hvr_bg_type').val();
        optionObj.topmenu_hvr_bg_type = topmenu_hvr_bg_type;
        var topmenu_hvr_solid_color = $('#jux_mm_tm_hvr_solid_bg_color').val();
        optionObj.topmenu_hvr_solid_color = topmenu_hvr_solid_color;

        var topmenu_hvr_bg_start_color = $('#jux_mm_tm_hvr_bg_start_color').val();
        optionObj.topmenu_hvr_bg_start_color = topmenu_hvr_bg_start_color;
        var topmenu_hvr_bg_end_color = $('#jux_mm_tm_hvr_bg_end_color').val();
        optionObj.topmenu_hvr_bg_end_color = topmenu_hvr_bg_end_color;
        //border
		var topmenu_hvr_border_color = $('#jux_mm_tm_hvr_border_color').val();
        optionObj.topmenu_hvr_border_color = topmenu_hvr_border_color;
		//icon
		var topmenu_hvr_icon_color = $('#jux_mm_tm_hvr_icon_color').val();
        optionObj.topmenu_hvr_icon_color = topmenu_hvr_icon_color;
        var topmenu_hvr_caption_color = $('input#jux_mm_tm_hvr_caption_color').val();
        optionObj.topmenu_hvr_caption_color = topmenu_hvr_caption_color;
		/* ENd Top Menu Hover */

		/* SUB MENU */
		//border
		var submenu_border_style		= $('#jux_mm_sm_border_style').val();
		optionObj.submenu_border_style	= submenu_border_style;
        var submenu_border_width 		= $('input[name="jux_mm_sm_border_width"]').val();
        optionObj.submenu_border_width	= submenu_border_width;
        var submenu_border_color 		= $('#jux_mm_sm_border_color').val();
        optionObj.submenu_border_color	= submenu_border_color;
        var submenu_border_top			= $('#jux_mm_sm_border_position_top').is(':checked') ? 1 : 0;
        optionObj.submenu_border_top	= submenu_border_top;
        var submenu_border_right		= $('#jux_mm_sm_border_position_right').is(':checked') ? 1 : 0;
        optionObj.submenu_border_right	= submenu_border_right;
        var submenu_border_bottom		= $('#jux_mm_sm_border_position_bottom').is(':checked') ? 1 : 0;
        optionObj.submenu_border_bottom	= submenu_border_bottom;
        var submenu_border_left			= $('#jux_mm_sm_border_position_left').is(':checked') ? 1 : 0;
        optionObj.submenu_border_left	= submenu_border_left;
        //Item Border
        var submenu_item_border_style		= $('#jux_mm_sm_item_border_style').val();
        optionObj.submenu_item_border_style	= submenu_item_border_style;
        var submenu_item_border_width 		= $('input[name="jux_mm_sm_item_border_width"]').val();
        optionObj.submenu_item_border_width	= submenu_item_border_width;
        var submenu_item_border_color 		= $('#jux_mm_sm_item_border_color').val();
        optionObj.submenu_item_border_color	= submenu_item_border_color;
        var submenu_item_border_top			= $('#jux_mm_sm_item_border_position_top').is(':checked') ? 1 : 0;
        optionObj.submenu_item_border_top	= submenu_item_border_top;
        var submenu_item_border_right		= $('#jux_mm_sm_item_border_position_right').is(':checked') ? 1 : 0;
        optionObj.submenu_item_border_right	= submenu_item_border_right;
        var submenu_item_border_bottom		= $('#jux_mm_sm_item_border_position_bottom').is(':checked') ? 1 : 0;
        optionObj.submenu_item_border_bottom= submenu_item_border_bottom;
        var submenu_item_border_left		= $('#jux_mm_sm_item_border_position_left').is(':checked') ? 1 : 0;
        optionObj.submenu_item_border_left	= submenu_item_border_left;
        //Border radius
		var submenu_border_radius_tleft		= $('input[name="jux_mm_sm_radius_top_left"]').val();
        optionObj.submenu_border_radius_tleft	= submenu_border_radius_tleft;
        var submenu_border_radius_tright	= $('input[name="jux_mm_sm_radius_top_right"]').val();
        optionObj.submenu_border_radius_tright	= submenu_border_radius_tright;
        var submenu_border_radius_bright	= $('input[name="jux_mm_sm_radius_bottom_right"]').val();
        optionObj.submenu_border_radius_bright	= submenu_border_radius_bright;
        var submenu_border_radius_bleft		= $('input[name="jux_mm_sm_radius_bottom_left"]').val();
        optionObj.submenu_border_radius_bleft	= submenu_border_radius_bleft;
        //icon
        var submenu_icon_size = $('input[name="jux_mm_sm_icon_size"]').val();
        optionObj.submenu_icon_size	= submenu_icon_size;
        var submenu_icon_color = $('#jux_mm_sm_icon_color').val();
        optionObj.submenu_icon_color	= submenu_icon_color;
        var submenu_icon_position = $('#jux_mm_sm_icon_position').val();
        optionObj.submenu_icon_position	= submenu_icon_position;
        //Font
        var submenu_font_family = $('#jux_mm_sm_font_family').val();
        optionObj.submenu_font_family	= submenu_font_family;
        var submenu_font_url = $('#jux_mm_sm_font_family option:selected').data('url');
        optionObj.submenu_font_url = submenu_font_url;
        var submenu_font_style = $('#jux_mm_sm_font_style').val();
        optionObj.submenu_font_style	= submenu_font_style;
        var submenu_font_weight = $('#jux_mm_sm_font_weight').val();
        optionObj.submenu_font_weight	= submenu_font_weight;
        var submenu_font_size = $('input[name="jux_mm_sm_font_size"]').val();
        optionObj.submenu_font_size	= submenu_font_size;
        var submenu_font_color = $('#jux_mm_sm_font_color').val();
        optionObj.submenu_font_color	= submenu_font_color;
        var submenu_font_upper = $('#jux_mm_sm_uppercase').is(':checked') ? 1 : 0;
        optionObj.submenu_font_upper	= submenu_font_upper;
        //Shadow
        var submenu_bs_h_length = $('input[name="jux_mm_sm_h_shadow"]').val();
        optionObj.submenu_bs_h_length = submenu_bs_h_length;
        var submenu_bs_v_length = $('input[name="jux_mm_sm_v_shadow"]').val();
        optionObj.submenu_bs_v_length = submenu_bs_v_length;
        var submenu_bs_blur = $('input[name="jux_mm_sm_shadow_blur"]').val();
        optionObj.submenu_bs_blur = submenu_bs_blur;
        var submenu_bs_size = $('input[name="jux_mm_sm_shadow_size"]').val();
        optionObj.submenu_bs_size = submenu_bs_size;
        var submenu_bs_color = $('#jux_mm_sm_shadow_color').val();
        optionObj.submenu_bs_color = submenu_bs_color;
        var submenu_bs_inset = $('#jux_mm_sm_shadow_inset').is(':checked') ? 1 : 0;
        optionObj.submenu_bs_inset = submenu_bs_inset;
        //background
        var submenu_bg_type = $('#jux_mm_sm_bg_type').val();
        optionObj.submenu_bg_type = submenu_bg_type;
        var submenu_solid_color = $('#jux_mm_sm_solid_bg_color').val();
        optionObj.submenu_solid_color = submenu_solid_color;
        var submenu_padding_top = $('input[name="jux_mm_sm_padding_top"]').val();
        optionObj.submenu_padding_top = submenu_padding_top;
        var submenu_padding_right = $('input[name="jux_mm_sm_padding_right"]').val();
        optionObj.submenu_padding_right = submenu_padding_right;
        var submenu_padding_bottom = $('input[name="jux_mm_sm_padding_bottom"]').val();
        optionObj.submenu_padding_bottom = submenu_padding_bottom;
        var submenu_padding_left = $('input[name="jux_mm_sm_padding_left"]').val();
        optionObj.submenu_padding_left = submenu_padding_left;

        var submenu_item_padding_top = $('input[name="jux_mm_sm_item_padding_top"]').val();
        optionObj.submenu_item_padding_top = submenu_item_padding_top;
        var submenu_item_padding_right = $('input[name="jux_mm_sm_item_padding_right"]').val();
        optionObj.submenu_item_padding_right = submenu_item_padding_right;
        var submenu_item_padding_bottom = $('input[name="jux_mm_sm_item_padding_bottom"]').val();
        optionObj.submenu_item_padding_bottom = submenu_item_padding_bottom;
        var submenu_item_padding_left = $('input[name="jux_mm_sm_item_padding_left"]').val();
        optionObj.submenu_item_padding_left = submenu_item_padding_left;

        var submenu_caption_size = $('input[name="jux_mm_sm_caption_size"]').val();
        optionObj.submenu_caption_size = submenu_caption_size;
        var submenu_caption_color = $('input#jux_mm_sm_caption_color').val();
        optionObj.submenu_caption_color = submenu_caption_color;
		/* END SUB MENU */

		/* SUB MENU HOVER */
		// Text Color
		var submenu_hvr_txt_color = $('#jux_mm_sm_hvr_txt_color').val();
        optionObj.submenu_hvr_txt_color = submenu_hvr_txt_color;
		// Background
        var submenu_hvr_bg_type = $('#jux_mm_sm_hvr_bg_type').val();
        optionObj.submenu_hvr_bg_type = submenu_hvr_bg_type;
        var submenu_hvr_solid_color = $('#jux_mm_sm_hvr_solid_bg_color').val();
        optionObj.submenu_hvr_solid_color = submenu_hvr_solid_color;
        // Border
		var submenu_hvr_border_color = $('#jux_mm_sm_hvr_border_color').val();
        optionObj.submenu_hvr_border_color = submenu_hvr_border_color;
		// Icon
        var submenu_hvr_icon_color = $('#jux_mm_sm_hvr_icon_color').val();
        optionObj.submenu_hvr_icon_color = submenu_hvr_icon_color;

        var submenu_hvr_caption_color = $('input#jux_mm_sm_hvr_caption_color').val();
        optionObj.submenu_hvr_caption_color = submenu_hvr_caption_color;
		/* END SUB MENU HOVER */

		/* MOBILE MENU */
		var mobile_breakpoint = $('#jux_mm_mobile_menu_breakpoint').val();
        optionObj.mobile_breakpoint = mobile_breakpoint;
		var mobile_menu_title = $('#jux_mm_mobile_menu_title').val();
        optionObj.mobile_menu_title = mobile_menu_title;
		var mobile_menu_toggle_icon = $('#jux_mm_mobile_menu_toggle_icon').val();
        optionObj.mobile_menu_toggle_icon = mobile_menu_toggle_icon;
		var mobile_layout = $('#jux_mm_mobile_menu_layout').val();
        optionObj.mobile_layout = mobile_layout;
		/* END MOBILE MENU */

		/* ADVANCED */
		var custom_css = $('#jux_mm_adv_custom_css').val();
        optionObj.custom_css = custom_css;
		var css_prefix = $('#jux_mm_adv_css_prefix').val();
        optionObj.css_prefix = css_prefix;
		/* END ADVANCED */

        var jmmoption = $('#jform_params_mega_options'), curoption = null;
        try {
            curoption = jmmoption.val() ? $.parseJSON(jmmoption.val()) : {};
        } catch(e){
            curoption = {};
        }
        if($.isArray(curoption) && curoption.length == 0){
            curoption = {};
        }
        curoption[menuType] = optionObj;
        return curoption;
	}

	toolbox_type = function () {
		return currentSelected.hasClass ('jux-nav-child') ? 'sub' : (currentSelected[0].tagName == 'DIV' ? 'col':'item');
	}

	hide_toolbox = function (show_intro) {
		$('#jux-admin-mm-tb .admin-toolbox').hide();
		currentSelected = null;
		if (megamenu && megamenu.data('nav_all')) megamenu.data('nav_all').removeClass ('selected');
		megamenu.find ('li').removeClass ('open');
		if (show_intro) {
			$('#jux-admin-mm-intro').show();
		} else {
			$('#jux-admin-mm-intro').hide();
		}
	}

	show_toolbox = function (selected) {
		hide_toolbox (false);
		if (selected) currentSelected = selected;
		// remove class open for other
		megamenu.find ('ul[class*="level"] > li').each (function(){
			if (!$(this).has (currentSelected).length > 0) $(this).removeClass ('open');
			else $(this).addClass ('open');
		});

		// set selected
		megamenu.data('nav_all').removeClass ('selected');
		currentSelected.addClass ('selected');
		var type = toolbox_type ();
		$('#jux-admin-mm-tool' + type).show();
		update_toolbox (type);

		$('#jux-admin-mm-tb').show();
	}

	update_toolbox = function (type) {
		if (!type) type = toolbox_type ();
		// remove all disabled status
		$('#jux-admin-mm-tb .disabled').removeClass('disabled');
		$('#jux-admin-mm-tb .active').removeClass('active');

		switch (type) {
			case 'item':
				// value for toggle
				var liitem = currentSelected.closest('li'),
					liparent = liitem.parent().closest('li'),
					sub = liitem.find ('.jux-nav-child:first');

				$('.toolitem-title').attr('value', liitem.data ('title') || '');
				$('.toolitem-exclass').attr('value', liitem.data ('class') || '');
				$('.toolitem-xicon').attr('value', liitem.data ('xicon') || '');
				$('.toolitem-imgurl').attr('value', liitem.data ('imgurl') || '');
				$('.toolitem-caption').attr('value', liitem.data ('caption') || '');
				// toggle Display
				var toggle = $('.toolitem-display');
				toggle.find('label').removeClass('active btn-success btn-danger btn-primary');
				if(liitem.data('display') == 1){
					update_toggle (toggle,1);
				} else {
					// sub enabled
					update_toggle (toggle,0	);
				}

				// toggle Submenu
				var toggle = $('.toolitem-sub');
				toggle.find('label').removeClass('active btn-success btn-danger btn-primary');
				if (liitem.data('group')) {
					// disable the toggle
					$('.toolitem-sub').addClass ('disabled');
				} else if (sub.length == 0 || sub.css('display') == 'none') {
					// sub disabled
					update_toggle (toggle, 0);
				} else {
					// sub enabled
					update_toggle (toggle, 1);
				}

				// toggle Menu Item Icon
				var toggle = $('.toolitem-iconswitch');
				toggle.find('label').removeClass('active btn-success btn-primary');
				if(liitem.data('sicon') == 2) {
					// img url enabled
					$('#juxMenuItemIcon').hide();
					$('#juxMenuItemImage').show();
					update_toggle (toggle, 2);
				} else {
					// icon enabled
					$('#juxMenuItemIcon').show();
					$('#juxMenuItemImage').hide();
					update_toggle (toggle, 1);
				}

				// toggle Group
				var toggle = $('.toolitem-group');
				toggle.find('label').removeClass('active btn-success btn-danger btn-primary');
				if (liitem.data('level') == 1 || sub.length == 0 || liitem.data('hidesub') == 1) {
					// disable the toggle
					$('.toolitem-group').addClass ('disabled');
				} else if (liitem.data('group')) {
					// Group off
					update_toggle (toggle, 1);
				} else {
					// Group on
					update_toggle (toggle, 0);
				}

				// move left/right column action: disabled if this item is not in a mega submenu
				if (!liparent.length || !liparent.hasClass('jux-mega')) {
					$('.toolitem-moveleft, .toolitem-moveright').addClass ('disabled');
				}

				break;

			case 'sub':
				var liitem = currentSelected.closest('li');
				$('.toolsub-exclass').attr('value', currentSelected.data ('class') || '');

				if (liitem.data('group')) {
					$('.toolsub-width').attr('value', '').addClass ('disabled');
					// disable alignment
					$('.toolsub-alignment').addClass ('disabled');
				} else {
					$('.toolsub-width').attr('value', currentSelected.data ('width') || '');
					// if not top level, allow align-left & right only
					var navWrapper = liitem.parents('.jux-easy-megamenu');
					if (liitem.data('level') > 1) {
						$('.toolsub-align-center').addClass ('disabled');
						$('.toolsub-align-justify').addClass ('disabled');
					} else {
						if(navWrapper.hasClass('vertical')) {
							$('.toolsub-align-center').addClass ('disabled');
						}
					}

					// active align button
					if (liitem.data('alignsub')) {
						$('.toolsub-align-'+liitem.data('alignsub')).addClass ('active');
						if (liitem.data('alignsub') == 'justify' &&  !navWrapper.hasClass('vertical')) {
							$('.toolsub-width').addClass ('disabled');
						} else {
							$('.toolsub-width').removeClass('disabled');
						}
					}
				}

				// toggle hidewhencollapse
				var toggle = $('.toolsub-hidewhencollapse');
				toggle.find('label').removeClass('active btn-success btn-danger btn-primary');
				if (liitem.data('hidewcol')) {
					// toggle enable
					update_toggle (toggle, 1);
				} else {
					// toggle disable
					update_toggle (toggle, 0);
				}

				break;

			case 'col':
				$('.toolcol-exclass').attr('value', currentSelected.data ('class') || '');
				$('.toolcol-position').val (currentSelected.data ('position') || '').trigger("liszt:updated");
				$('.toolcol-width').val (currentSelected.data ('width') || '').trigger("liszt:updated");
				/* enable/disable module chosen */
				if (currentSelected.find ('.mega-nav').length > 0) {
					//$('.toolcol-position').parent().addClass('disabled');
				}
				// disable choose width if signle column
				if (currentSelected.parent().children().length == 0) {
					$('.toolcol-width').parent().addClass ('disabled');
				}

				// toggle hidewhencollapse
				var toggle = $('.toolcol-hidewhencollapse');
				toggle.find('label').removeClass('active btn-success btn-danger btn-primary');
				if (currentSelected.data('hidewcol')) {
					// toggle enable
					update_toggle (toggle, 1);
				} else {
					// toggle disable
					update_toggle (toggle, 0);
				}

				break;
		}
	}

	switch_menu_view = function() {
        $('#jux_ez_menu_item_options').click(function (e) {
            hide_toolbox(true);

            if ($('#jux-admin-megamenu').hasClass('jux-ez-menu-item-options')) {

            } else {
                $('#jux-admin-megamenu').addClass('jux-ez-menu-item-options');
                $('#jux-ez-menu-custom-css').remove();
                $('#jux-ez-menu-default-css').remove();
                $('#jux-ez-menu-custom-css').remove();
            }
            e.preventDefault();
            e.stopPropagation();

        });

        $('#jux_ez_menu_style_options').click(function (e) {
            hide_toolbox(true);

            if ($('#jux-admin-megamenu').hasClass('jux-ez-menu-item-options')) {

                updatemenu();

                $('#jux-admin-megamenu').removeClass('jux-ez-menu-item-options');
            }
            e.preventDefault();
            e.stopPropagation();
        });

        $('.jux-prev-switch').find('span').click(function () {
            $('.jux-prev-switch').find('.active').removeClass("active");
            $(this).addClass('active');
            var trigger = $(this).data('trigger');
			$('#' + trigger).trigger('click');
			updatemenu();
        });
	}

	clear_image_preview = function(prevTarget) {
		$('.button-clear-prev-img').on('click', function() {
			$('.field-media-preview').html('');
		});
	}

	radioToggleSwitch = function(clickTarget, toggleTarget, inputName) {
        var toggleEl = $(toggleTarget);
        var clickEl = $(clickTarget);
        var inputVal = clickEl.children('input[name="'+inputName+'"]');
        if(inputVal.is(':checked')) {
            toggleEl.show();
        } else {
            toggleEl.hide();
        }
        clickEl.on('click', function() {
            var inputVal = $(this).children('input[name="'+inputName+'"]');
            if(inputVal.is(':checked')) {
                toggleEl.show();
            } else {
                toggleEl.hide();
            }
        });
	}

	toggleDivOnChange_Select = function(selectTarget, toggleTarget1, toggleTarget2, compareVal) {
		var selectEl = $(selectTarget);
		var toggleEl1 = $(toggleTarget1);
        var toggleEl2 = $(toggleTarget2);
        var selectElVal = selectEl.val();
        toggleEl1.hide();
        toggleEl2.hide();
        if(selectElVal === compareVal) {
            toggleEl1.show();
            toggleEl2.hide();
        } else {
            toggleEl2.show();
            toggleEl1.hide();
        }
	}

	load_menu_template = function() {

	}

	sticky_menu = function(navbar, sticky) {
        if (window.pageYOffset >= sticky) {
            navbar.addClass("jux-mm-sticky")
        } else {
            navbar.removeClass("jux-mm-sticky");
        }
    }

	update_toggle = function (toggle, val) {
		$input = toggle.find('input[value="'+val+'"]');

		$input.attr('checked', 'checked');
		$input.trigger ('update');
	}

	apply_toolbox = function (input) {
		var name = $(input).data ('name'),
		value = input.value,
		type = toolbox_type ();
		switch (name) {
			case 'width':
				if (type == 'sub') {
					currentSelected.css('width', value+'px');
				}
				if (type == 'col') {
					currentSelected.removeClass('span'+currentSelected.data(name)).addClass ('span'+value);
				}
				currentSelected.data (name, value);
				break;

			case 'class':
				if (type == 'item') {
					var item = currentSelected.closest('li');
				} else {
					var item = currentSelected;
				}
				item.removeClass(item.data(name) || '').addClass (value);
				item.data (name, value);
                //item.attr('data-'+name, value);
				break;

			case 'xicon':
				if (type == 'item') {
					currentSelected.closest('li').data (name, value);
					currentSelected.find('i.jux-icon').remove();
					var item_level = currentSelected.parent().data('level');
					if(item_level <= 1) {
						var icon_pos = $('#jux_mm_top_menu_icon_position').val();
					} else {
                        var icon_pos = $('#jux_mm_sm_icon_position').val();
					}
					if (value) {
						if(icon_pos == 'right') {
                            $('<i class="jux-icon jux-icon-r ' + value + '"></i>').insertAfter(currentSelected.find('.jux-menu-item-title'));
                        } else if(icon_pos == 'left') {
                            currentSelected.find('.jux-menu-item-wrapper').prepend($('<i class="jux-icon jux-icon-l '+value+'"></i>'));
						} else {
                            currentSelected.find('.jux-menu-item-wrapper').prepend($('<i class="jux-icon jux-icon-above '+value+'"></i>'));
						}
                    }
				}
				break;
			case 'imgurl':
				if (type == 'item') {
					currentSelected.closest('li').data (name, value);
					currentSelected.find('.jux-img').remove();
					var item_level = currentSelected.parent().data('level');
					if(item_level <= 1) {
						var icon_pos = $('#jux_mm_top_menu_icon_position').val();
					} else {
                        var icon_pos = $('#jux_mm_sm_icon_position').val();
					}
					if (value) {
						if(icon_pos == 'right') {
                            $('<div class="jux-img jux-img-r"><img src="' + value + '" alt=""></div>').insertAfter(currentSelected.find('.jux-menu-item-title'));
                        } else if(icon_pos == 'left') {
                            currentSelected.find('.jux-menu-item-wrapper').prepend($('<div class="jux-img jux-img-l"><img src="' + value + '" alt=""></div>'));
						} else {
                            currentSelected.find('.jux-menu-item-wrapper').prepend($('<div class="jux-img jux-img-above"><img src="' + value + '" alt=""></div>'));
						}
                    }
				}
				break;
			case 'title':
					if (type == 'item') {
						var liItem = currentSelected.closest('li');
						liItem.data (name, value);
						if (value) {
							if(value == " ") {
								if(currentSelected.find('.mega-caption').length < 1) {
									if(!liItem.hasClass('jux-empty-title')) {
										liItem.addClass('jux-empty-title');
									}
								}
							} else {
								if(liItem.hasClass('jux-empty-title')) {
									liItem.removeClass('jux-empty-title');
								}
							}
							currentSelected.find('.jux-menu-item-title').children('.menu-original-title').hide();
							currentSelected.find('.jux-menu-item-title').children('span').first().text(value);
							currentSelected.find('.jux-menu-item-title').children('span').first().show();
						} else {
							if(liItem.hasClass('jux-empty-title')) {
								liItem.removeClass('jux-empty-title');
							}
							currentSelected.find('.jux-menu-item-title').children('.menu-original-title').show();
							currentSelected.find('.jux-menu-item-title').children('span').first().hide();
						}
					}
					break;

			case 'caption':
				if (type == 'item') {
					var liItem = currentSelected.closest('li');
					liItem.data (name, value);
					currentSelected.find('span.mega-caption').remove();
					if (value) {
						currentSelected.find('.jux-menu-item-title').append($('<span class="mega-caption">'+value+'</span>'));
						if(value == "") {
							if($('input[name="toolitem-title"]').val() === " ") {
								if(!liItem.hasClass('jux-empty-title')) {
									liItem.addClass('jux-empty-title');
								}
							} else {
								if(liItem.hasClass('jux-empty-title')) {
									liItem.removeClass('jux-empty-title');
								}
							}
						} else {
							if(liItem.hasClass('jux-empty-title')) {
								liItem.removeClass('jux-empty-title');
							}
						}
					} else {
						if($('input[name="toolitem-title"]').val() === " ") {
							if(!liItem.hasClass('jux-empty-title')) {
								liItem.addClass('jux-empty-title');
							}
						} else {
							if(liItem.hasClass('jux-empty-title')) {
								liItem.removeClass('jux-empty-title');
							}
						}
					}
				}
				break;

			case 'position':
				// replace content if this is not menu-items type
				if (currentSelected.find ('ul[class*="level"]').length == 0) {
					if (value) {
						$.ajax({
							url: MOD_ACTION,
							data:{'task':'module', 'mid': value,'base_url':BASE_URL,'t':$.now()},
							dataType: 'html',
						}).done(function ( data ) {
							currentSelected.find('.mega-inner').html(data).find('input,select,textarea').removeAttr('name').removeAttr('class').removeAttr('id').removeAttr('required');
                            currentSelected.children('.mega-inner').children('.moduletable').addClass('disabled');
                            currentSelected.children('.mega-inner').append('<span class="module-label">'+Joomla.JText._('MOD_JUX_MEGA_MENU_MODULE_LABEL', 'Module')+'</span>');
						});
					} else {
						currentSelected.find('.mega-inner').html('');
					}
					currentSelected.data (name, value);
				}

				break;
		}
	}

	defaultColumnsWidth = function (count) {
		if (count < 1) return null;
		var total = 12,
		min = Math.floor(total / count),
		widths = [];
		for(var i=0;i<count;i++) {
			widths[i] = min;
		}
		widths[count - 1] = total - min*(count-1);
		return widths;
	}

	bindEvents = function (els) {
		if (megamenu.data('nav_all'))
			megamenu.data('nav_all', megamenu.data('nav_all').add(els));
		else
			megamenu.data('nav_all', els);

		els.mouseover(function(event) {
			megamenu.data('nav_all').removeClass ('hover');
			$this = $(this);
			clearTimeout (megamenu.data('hovertimeout'));
			megamenu.data('hovertimeout', setTimeout(function(){
				$this.addClass('hover');
			}, 100));
			event.stopPropagation();
		});
		els.mouseout(function(event) {
			clearTimeout (megamenu.data('hovertimeout'));
			$(this).removeClass('hover');
		});

		els.click (function(event){
            $('.jux-prev-switch span.off').trigger('click');
			show_toolbox ($(this));
			event.stopPropagation();
			return false;
		});
	}

	unbindEvents = function (els) {
		megamenu.data('nav_all', megamenu.data('nav_all').not(els));
		els.unbind('mouseover').unbind('mouseout').unbind('click');
	}

	rebindEvents = function (els) {
		unbindEvents(els);
		bindEvents(els);
	}

	toggleinner = function(e){
		var itemsinner = $('.mega-inner');
		if(e){
			$.each(itemsinner,function(){
				var nav_child = $(this).closest('.jux-nav-child');
				if(nav_child.find('.mega-col-module').length == 0){
					if($(this).find('[data-type="category"]').length == 0){
						$(this).closest('.jux-nav-child').css('display','');;

					}
				}
				else {
					if($(this).find('[data-type="category"]').length == 0){
						$(this).closest('.mega-col-nav').css('display','');
					}
				}
				var liinner = $(this).closest('li');
				liinner.children('a').addClass ('dropdown-toggle');
				liinner.addClass(liinner.data('level') == 1 ? 'jux-dropdown' : 'jux-dropdown-submenu');
			});
		}else{
			$.each(itemsinner,function(){
				var nav_child = $(this).closest('.jux-nav-child');
				if(nav_child.find('.mega-col-module').length == 0){
					if($(this).find('[data-type="category"]').length == 0){
						$(this).closest('.jux-nav-child').css('display','none');;
						var liinner = $(this).closest('li');
						liinner.removeClass('jux-dropdown jux-dropdown-submenu jux-mega');
					}
				}
				else {
					/*if($(this).find('[data-type="category"]').length == 0){
						$(this).closest('.mega-col-nav').css('display','none');
					}*/
				}
			});
		}
	}

}(jQuery);

!function($){
	$.extend(AdminMegamenu, {
		prepare :function(){

            //$('select').chosen();
						// $('select').chosen({allow_single_deselect: true});
			var JUXmegamenu = $('#jux-admin-mm-container').megamenuAdmin().find(':input').removeAttr('name');

            var horizonralDropdown = '#jux-horizontal-dropdown', verticalDropdown = '#jux-vertical-dropdown', selectTarget = '#jux_ez_mm_orientation', compareVal = 'horizontal';
            toggleDivOnChange_Select(selectTarget, horizonralDropdown, verticalDropdown, compareVal);
			$(selectTarget).change(function() {
                toggleDivOnChange_Select(selectTarget, horizonralDropdown, verticalDropdown, compareVal);
			});

            var topmenuGradientColor = '#jux-top-menu-bg-start-color, #jux-top-menu-bg-end-color', topmenuSolidColor = '#jux-top-menu-solid-bg-color', bgTypeTarget = '#jux_mm_top_menu_bg_type', bgTypeCompareVal = 'solid';
            toggleDivOnChange_Select(bgTypeTarget, topmenuSolidColor, topmenuGradientColor, bgTypeCompareVal);
            $(bgTypeTarget).change(function() {
                toggleDivOnChange_Select(bgTypeTarget, topmenuSolidColor, topmenuGradientColor, bgTypeCompareVal);
            });

            var menubarGradientColor = '#jux-menu-bar-bg-start-color, #jux-menu-bar-bg-end-color', menubarSolidColor = '#jux-menu-bar-solid-bg-color', mbBgTypeTarget = '#jux_mm_menu_bar_bg_type', mbBgTypeCompareVal = 'solid';
            toggleDivOnChange_Select(mbBgTypeTarget, menubarSolidColor, menubarGradientColor, mbBgTypeCompareVal);
            $(mbBgTypeTarget).change(function() {
                toggleDivOnChange_Select(mbBgTypeTarget, menubarSolidColor, menubarGradientColor, mbBgTypeCompareVal);
            });

            $('.js-rslider').each(function() {
            	var $this = $(this);
                var inputVal = $('input[name="'+$this.attr('id')+'"]').val();

            	$this.slider({
                    range: $this.data('range'),
                    value: $this.data('value'),
                    min: $this.data('min'),
                    max: $this.data('max'),
                    step: $this.data('step'),
                    slide: function( event, ui ) {
                        $('#'+$this.data('label')+'-label').text(ui.value);
                        $('input[name="'+$this.data('inputname')+'"]').val(ui.value);
                        updatemenu();
                    },
					stop: function(event, ui) {
                        $('#'+$this.data('label')+'-label').text(ui.value);
                        $('input[name="'+$this.data('inputname')+'"]').val(ui.value);
                        updatemenu();
                    }
                })
			});

            /* BRANDING */
            radioToggleSwitch('#jux_ez_mm_use_logo .switch', '#jux-logo', 'jux_ez_mm_use_logo');

			/* STICKY MENU */
            var toggleEls = "#jux-sticky-margin-top, #jux-sticky-wrap";
            radioToggleSwitch('#jux-use-sticky .switch', toggleEls, 'jux_ez_mm_use_sticky');

            /*color picker */
            $('.jux-colorpicker').each(function() {
            	var inputColor = $(this);
                $(this).minicolors({
                    control: $(this).attr('data-control') || 'hue',
                    defaultValue: $(this).attr('data-defaultValue') || '',
                    format: $(this).attr('data-format') || 'hex',
                    keywords: $(this).attr('data-keywords') || '',
                    inline: $(this).attr('data-inline') === 'true',
                    letterCase: $(this).attr('data-letterCase') || 'lowercase',
                    opacity: $(this).attr('data-opacity'),
                    position: $(this).attr('data-position') || 'bottom',
                    swatches: $(this).attr('data-swatches') ? $(this).attr('data-swatches').split('|') : [],
                    change: function (hex, opacity) {
                        if (!hex) return;
                        if (opacity) {
                            var id = inputColor.attr('id');
                            $('#' + id + '_opacity').val(opacity).attr('value', opacity);
                        }
                        updatemenu();
                    },
                    theme: 'bootstrap'
                });
            });

            var megamenunav_el = $('.juxnav');
            var megamenu_el = megamenunav_el.find('.jux-easy-megamenu');
            var megamenu_container_el = $('#jux-admin-mm-container');

            $('#jux_ez_mm_orientation').on('change', function() {
                var menu_orientation_class = '';
                var menu_nav_class = '';
            	var menu_orientation = $(this).val();
                if(menu_orientation == 'horizontal') {
					var menuAlign = $('select#jux_mm_menu_bar_alignment').val();
					menu_nav_class += 'jux-'+$(this).val();
					menu_nav_class += '-'+$('#jux_ez_mm_horizontal_dropdown').val();
					menu_nav_class += ' jux-align-' + menuAlign;
					menu_orientation_class += 'horizontal';
					$('li.mega-align-justify').children('.jux-nav-child').removeAttr('data-width style');
				} else {
					menu_nav_class += 'jux-'+$(this).val();
					menu_orientation_class += 'vertical';
					var menuAlign = $('select#jux_mm_menu_bar_alignment').val();
					var liMegaItem = $('li.mega');
						liMegaItem.removeClass('mega-align-center').addClass('mega-align-left');

				}
				megamenunav_el.removeClass('jux-horizontal-up jux-horizontal-down jux-vertical-ltr jux-vertical-rtl');
				megamenunav_el.removeClass('jux-horizontal-up jux-horizontal-down jux-vertical xxx');
                megamenu_el.removeClass('horizontal vertical');
                megamenunav_el.addClass(menu_nav_class);
                megamenu_el.addClass(menu_orientation_class);
			});

            $('#jux_ez_mm_horizontal_dropdown').on('change', function() {
                var menu_orientation_class = '';
                var menu_nav_class = 'jux';
                menu_nav_class += '-'+$('#jux_ez_mm_orientation').val();
                menu_nav_class += '-'+$(this).val();
                menu_orientation_class += ' horizontal';
                megamenunav_el.removeClass('jux-horizontal-up jux-horizontal-down jux-vertical xx');
                megamenu_el.removeClass('horizontal vertical');
                megamenunav_el.addClass(menu_nav_class);
                megamenu_el.addClass(menu_orientation_class);
			});

            $('select#jux_ez_mm_animation').on('change', function () {
                $('.jux-easy-megamenu').removeClass("animate fading slide zoom elastic").addClass('animate').addClass($(this).val());
            });

            $('select#jux_mm_top_menu_icon_position').on('change', function() {
            	var icon_pos = $(this).val();
                $('.jux-easy-megamenu .meganav >  li > a').each( function(index) {
					var jux_icon = $(this).find('.jux-icon');
					var jux_img = $(this).find('.jux-img');
                    if(icon_pos == 'right')
                    {
                        jux_icon.insertAfter($(this).find('.jux-menu-item-title'));
						jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-r');
						//img
						jux_img.insertAfter($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-r');
                    } else if(icon_pos == 'left') {
                        jux_icon.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-l');
						//img
                        jux_img.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-l');
                    } else {
                        jux_icon.insertBefore($(this).find('.jux-menu-item-title'));
						jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-above');
						//img
                        jux_img.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-above');
                    }
				});
                $('.jux-easy-megamenu .meganav >  li > .separator').each( function(index) {
					var jux_icon = $(this).find('.jux-icon');
					var jux_img = $(this).find('.jux-img');
                    if(icon_pos == 'right')
                    {
                        jux_icon.insertAfter($(this).find('.jux-menu-item-title'));
						jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-r');
						//img
						jux_img.insertAfter($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-r');
                    } else if(icon_pos == 'left') {
                        jux_icon.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-l');
						//img
                        jux_img.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-l');
                    } else {
                        jux_icon.insertBefore($(this).find('.jux-menu-item-title'));
						jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-above');
						//img
                        jux_img.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-above');
                    }
                });
			});
            $('select#jux_mm_sm_icon_position').on('change', function() {
                var icon_pos = $(this).val();

                $('.jux-easy-megamenu .jux-dropdown-menu li > a').each(function(index) {
					var jux_icon = $(this).find('.jux-icon');
					var jux_img = $(this).find('.jux-img');
                    if(icon_pos == 'right')
                    {
                        jux_icon.insertAfter($(this).find('.jux-menu-item-title'));
						jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-r');
						//img
						jux_img.insertAfter($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-r');
                    } else if(icon_pos == 'left') {
                        jux_icon.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-l');
						//img
                        jux_img.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-l');
                    } else {
                        jux_icon.insertBefore($(this).find('.jux-menu-item-title'));
						jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-above');
						//img
                        jux_img.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-above');
                    }
				});
                $('.jux-easy-megamenu .jux-dropdown-menu li > .separator').each( function(index) {
                    var jux_icon = $(this).find('.jux-icon');
                    var jux_img = $(this).find('.jux-img');
                    if(icon_pos == 'right')
                    {
                        jux_icon.insertAfter($(this).find('.jux-menu-item-title'));
						jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-r');
						//img
						jux_img.insertAfter($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-r');
                    } else if(icon_pos == 'left') {
                        jux_icon.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-l');
						//img
                        jux_img.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-l');
                    } else {
                        jux_icon.insertBefore($(this).find('.jux-menu-item-title'));
						jux_icon.removeClass('jux-icon-l jux-icon-r jux-icon-above').addClass('jux-icon-above');
						//img
                        jux_img.insertBefore($(this).find('.jux-menu-item-title'));
                        jux_img.removeClass('jux-img-l jux-img-r jux-img-above').addClass('jux-img-above');
                    }
                });
            });

            $('select.google-fonts').on('change', function () {
                var id = $(this).attr('id');
                $("#jux-google-font" + id).remove();
                if ($(this).val() != 'inherit') {

                    var url = $(this).find('option:selected').data('url');
                    $(this).next('input').val(url).attr('value', url);
                    var rel = '<link id="jux-google-font' + id + '" media="all" type="text/css" href="//fonts.googleapis.com/css?' + url + '" rel="stylesheet">';
                    $(rel).appendTo('head');
                }
            });
            $('select.google-fonts').each(function () {
                var id = $(this).attr('id');
                if ($(this).val() != 'inherit') {
                    var url = $(this).find('option:selected').data('url');
                    $(this).next('input').val(url).attr('value', url);
                    var rel = '<link id="jux-google-font' + id + '" media="all" type="text/css" href="//fonts.googleapis.com/css?' + url + '" rel="stylesheet">';
                    $("#jux-google-font" + id).remove();
                    $(rel).appendTo('head');
                } else {
                    $("#jux-google-font" + id).remove();
				}
            });
            $('select#jux_mm_menu_bar_alignment').on('change', function() {
            	var menu_nav = $('.juxnav');
            	var menu_nav_align = 'jux-align-'+$(this).val();
                menu_nav.removeClass('jux-align-left jux-align-center jux-align-right');
                menu_nav.addClass(menu_nav_align);
			});

			var menuOrientation = $('select#jux_ez_mm_orientation').val();
			var alignDiv = $('select#jux_mm_menu_bar_alignment');
			if(menuOrientation == 'horizontal') {
				alignDiv.prop('disabled', false).trigger("liszt:updated");
			} else {
				alignDiv.prop('disabled', true).trigger("liszt:updated");
			}
			$('select#jux_ez_mm_orientation').on('change', function() {
				var orientation = $(this).val();
				if(orientation == 'horizontal') {
					alignDiv.prop('disabled', false).trigger("liszt:updated");
				} else {
					alignDiv.prop('disabled', true).trigger("liszt:updated");
				}
			});

			$('input#jux_easy_mm_rtl').on('change', function() {
				var juxMenuWrapper = $('#jux-admin-mm-container');
				if(this.checked) {
					juxMenuWrapper.removeClass('rtl').addClass('rtl');
				} else {
					juxMenuWrapper.removeClass('rtl');
				}
			});

			//drag & drop
			$( ".jux-ez-menu-item-options .sortable-top-item" ).sortable({
				items: "> li",
				revert: true,
				placeholder: "ui-state-highlight",
				start: function(e,ui) {
					ui.placeholder.height(ui.item.height());
					ui.placeholder.width(ui.item.width());
					if(ui.item.hasClass('mega-align-justify')) {
						ui.item.find('.jux-nav-child').first().css('min-width', '800px');
					}
				},
				stop: function(e,ui) {
					if(ui.item.hasClass('mega-align-justify')) {
						ui.item.css('position', 'static');
						ui.item.find('.jux-nav-child').first().css('min-width', '100px');
					} else {
						ui.item.css('position', 'inherit');
					}
				}
			}).disableSelection();

			$( ".jux-ez-menu-item-options .sortable-sub-item" ).sortable({
				items: "> li",
				placeholder: "ui-state-highlight",
				start: function(e,ui) {
					ui.placeholder.height(ui.item.height());
					ui.placeholder.width(ui.item.width());
				}
			}).disableSelection();

			$( ".jux-ez-menu-item-options .sortable-col" ).sortable({
				items: "> .mega-col-block",
			}).disableSelection();
			$( ".jux-ez-menu-item-options .sortable-juxr" ).sortable({
				items: "> .row-wrap",
				placeholder: "ui-state-highlight",
				start: function(e,ui) {
					ui.placeholder.height(ui.item.height());
					ui.placeholder.width(ui.item.width());
				}
			}).disableSelection();
		},

		initItemsControl:function(){
			var itemControl = $('#jform_params_show_items')
				,juxnav = $('ul.level0')
				,items = juxnav.find('[data-type="item"]');
			if(itemControl.find('input[checked=checked]').val() == 1){
				items.show();
				toggleinner(1);
			}else{
				items.hide();
				toggleinner();
			};
			itemControl.find('input[type=radio]').bind('click',function(){
				if($(this).val() == 1){
					juxnav.removeClass('hide-items');
					toggleinner(1);
					items.show();
				}else{
					juxnav.addClass('hide-items');
					toggleinner();
					items.hide();
				}

			});

			var item_num_control = $('#jform_params_show_num_items')
				,mega_num_item = $('.mega-num-item');
			if(item_num_control.find('input[checked=checked]').val() == 1){
				mega_num_item.removeClass('hide');
			}else{
				mega_num_item.addClass('hide');
			};

			item_num_control.find('input[type=radio]').bind('click',function(){
				if($(this).val() == 1){
					mega_num_item.removeClass('hide');
				}else{
					mega_num_item.addClass('hide');
				};
			});
		},
		initPreSubmit: function(){

			var form = document.adminForm;
			if(!form){
				return false;
			}

			var onsubmit = form.onsubmit;
			form.onsubmit = function(e){
				$('.toolbox-saveConfig').trigger('click');
				if($.isFunction(onsubmit)){
					onsubmit();
				}
			};

		},
		initColModule:function(){
			var mega_col_module = $('.mega-col-module');
			mega_col_module.each(function(){
				if($(this).data('position')){
					var el = $(this);
					$.ajax({
						url: MOD_ACTION,
						data:{'task':'module', 'mid': $(this).data('position'),'base_url':BASE_URL,'t':$.now()}
					}).done(function ( data ) {
						var inner = $('.mega-inner',el);
						inner.html(data).find('input,select,textarea').removeAttr('name').removeAttr('class').removeAttr('id').removeAttr('required');
                        inner.children('.moduletable').addClass('disabled');
                        inner.append('<span class="module-label">'+Joomla.JText._('MOD_JUX_MEGA_MENU_MODULE_LABEL', 'Module')+'</span>');
					});
				}
			});
		},
		initRadioGroup: function(){

			var juxmenu = $('.jux-admin-megamenu');

			juxmenu.find('.radio.btn-group label').addClass('btn');
			juxmenu.find('.btn-group label').unbind('click').click(function() {
				var label = $(this),
					input = $('#' + label.attr('for'));

				if (!input.prop('checked')){
					label.closest('.btn-group')
						.find('label')
						.removeClass('active btn-success btn-danger btn-primary');

					label.addClass('active ' + (input.val() == '' ? 'btn-primary' : (input.val() == 0 ? 'btn-danger' : 'btn-success')));

					input.prop('checked', true).trigger('change');
				}
			});

			juxmenu.on('update', 'input[type=radio]', function(){
				if(this.checked){
					$(this)
						.closest('.btn-group')
						.find('label').removeClass('active btn-success btn-danger btn-primary')
						.filter('[for="' + this.id + '"]')
							.addClass('active ' + ($(this).val() == '' ? 'btn-primary' : ($(this).val() == 0 ? 'btn-danger' : 'btn-success')));
				}
			});

			juxmenu.find('.btn-group input[checked=checked]').each(function(){
				if($(this).val() == ''){
					$('label[for=' + $(this).attr('id') + ']').addClass('active btn-primary');
				} else if($(this).val() == 0){
					$('label[for=' + $(this).attr('id') + ']').addClass('active btn-danger');
				} else {
					$('label[for=' + $(this).attr('id') + ']').addClass('active btn-success');
				}
			});
		},
	});

	$(document).ready(function(){
        var saveFlag = true;

        AdminMegamenu.prepare();
        AdminMegamenu.initItemsControl();
        AdminMegamenu.initPreSubmit();
        AdminMegamenu.initRadioGroup();
        AdminMegamenu.initColModule();

		var menuType = $('#jform_params_mod_menu').val();
        var urlParams = new URLSearchParams(location.search);

        var mm_container = $('#jux-admin-mm-container');
        var mm_nav = $('#jux-admin-mm-container .juxnav');
        var option_tabs_container = $('#jux-ez-mega-menu-generator');
        var current_mod_id = urlParams.get('id');


        $(document).on('change blur input', '.jux-field', function() {
            if(saveFlag) saveFlag = false;
        });
        $('.js-rslider').each(function() {
            var $this = $(this);
            $(document).on("slidestop", $this,  function(event, ui) { if(saveFlag) saveFlag = false; });
        });

        if(current_mod_id == null || mm_nav.find('.meganav').length < 1) {

            $('#jux-admin-megamenu').parent().css('position', 'relative').append('<div id="mega-menu-loader"><div class="lds-dual-ring"></div></div>');
            $.ajax({
                url: MOD_ACTION,
                data:{'task':'reloadMenuConfig', 'menu_type': menuType,'mod_id': current_mod_id,'base_url':BASE_URL,'t':$.now()}
            }).done(function ( data ) {
                var result = JSON.parse(data);

                mm_nav.html(result.menu_layout);
                option_tabs_container.html(result.menu_options);

                var menu_nav_class = '';
                var menu_nav_align_class = 'jux-align-left';
                menu_nav_class += ' jux-' + result.extra_data.menu_orientation;
                if (result.extra_data.menu_orientation === 'horizontal') {
                    menu_nav_class += '-' + result.extra_data.sm_horizontal_drop;
                } else {
                    menu_nav_class += '-' + result.extra_data.sm_vertical_drop;
                }
                var menu_align = result.extra_data.menubar_align;
                menu_nav_align_class = 'jux-align-' + menu_align;

				var juxAdminContainer = $('#jux-admin-mm-container');
				if(result.extra_data.rtl == 1) {
					juxAdminContainer.removeClass('rtl').addClass('rtl');
				} else {
					juxAdminContainer.removeClass('rtl');
				}
                $('.juxnav').removeClass('jux-align-left jux-align-center jux-align-right jux-vertical jux-horizontal-down jux-horizontal-up').addClass(menu_nav_align_class + menu_nav_class);

                //$('.field-media-wrapper').fieldMedia();
                AdminMegamenu.prepare();
                AdminMegamenu.initItemsControl();
                AdminMegamenu.initPreSubmit();
                AdminMegamenu.initRadioGroup();
                AdminMegamenu.initColModule();
                $('#mega-menu-loader').remove();
                $('#jux-admin-megamenu').parent().removeAttr('style');
                saveFlag = true;
            });
        }
        var previousModId = 0;
        $(document).on('click', '#jform_params_mod_menu_chzn a.chzn-single', function() {
            previousModId = $('#jform_params_mod_menu').val();
		});
        $('#jform_params_mod_menu').on('change', function() {
            var menuType = $(this).val();
            if(!saveFlag) {
            	var msg = confirm('You have unsaved data, when you switch to another menu, the unsaved data will be lost. To be sure, save it first. \n- OK: Switch to another menu without data saving. \n- Cancel: Stop switch to another menu.');
            	if(msg) {
                    $('#jux-admin-megamenu').parent().css('position', 'relative').append('<div id="mega-menu-loader"><div class="lds-dual-ring"></div></div>');
                    $('.juxnav').removeClass(function(index, css) {
                        return (css.match(/\bmenu_\S+/g) || []).join('');
                    });
                    $('.juxnav').addClass('menu_'+menuType);
                    $.ajax({
                        url: MOD_ACTION,
                        data:{'task':'reloadMenuConfig', 'menu_type': menuType,'mod_id': current_mod_id,'base_url':BASE_URL,'t':$.now()}
                    }).done(function ( data ) {
                        var result = JSON.parse(data);
                        mm_nav.html(result.menu_layout);
                        option_tabs_container.html(result.menu_options);

                        var menu_nav_class = '';
                        var menu_nav_align_class = 'jux-align-left';
                        menu_nav_class += ' jux-' + result.extra_data.menu_orientation;
                        if (result.extra_data.menu_orientation === 'horizontal') {
                            menu_nav_class += '-' + result.extra_data.sm_horizontal_drop;
                        } else {
                            menu_nav_class += '-' + result.extra_data.sm_vertical_drop;
                        }
                        var menu_align = result.extra_data.menubar_align;
                        menu_nav_align_class = 'jux-align-' + menu_align;

						var juxAdminContainer = $('#jux-admin-mm-container');
						if(result.extra_data.rtl == 1) {
							juxAdminContainer.removeClass('rtl').addClass('rtl');
						} else {
							juxAdminContainer.removeClass('rtl');
						}
                        $('.juxnav').removeClass('jux-align-left jux-align-center jux-align-right jux-vertical jux-horizontal-down jux-horizontal-up').addClass(menu_nav_align_class + menu_nav_class);
                        //$('.field-media-wrapper').fieldMedia();
                        AdminMegamenu.prepare();
                        AdminMegamenu.initItemsControl();
                        AdminMegamenu.initPreSubmit();
                        AdminMegamenu.initRadioGroup();
                        AdminMegamenu.initColModule();
                        $('#mega-menu-loader').remove();
                        $('#jux-admin-megamenu').parent().removeAttr('style');
                        saveFlag = true;
                        previousModId = menuType;
                    });
				} else {
                    $('#jform_params_mod_menu').val(previousModId).trigger("liszt:updated");

				}
            } else {
                $('#jux-admin-megamenu').parent().css('position', 'relative').append('<div id="mega-menu-loader"><div class="lds-dual-ring"></div></div>');
                $('.juxnav').removeClass(function(index, css) {
                    return (css.match(/\bmenu_\S+/g) || []).join('');
                });
                $('.juxnav').addClass('menu_'+menuType);
                $.ajax({
                    url: MOD_ACTION,
                    data:{'task':'reloadMenuConfig', 'menu_type': menuType,'mod_id': current_mod_id,'base_url':BASE_URL,'t':$.now()}
                }).done(function ( data ) {
                    var result = JSON.parse(data);
                    mm_nav.html(result.menu_layout);
                    option_tabs_container.html(result.menu_options);

                    var menu_nav_class = '';
                    var menu_nav_align_class = 'jux-align-left';
                    menu_nav_class += ' jux-' + result.extra_data.menu_orientation;
                    if (result.extra_data.menu_orientation === 'horizontal') {
                        menu_nav_class += '-' + result.extra_data.sm_horizontal_drop;
                    } else {
                        menu_nav_class += '-' + result.extra_data.sm_vertical_drop;
                    }
                    var menu_align = result.extra_data.menubar_align;
                    menu_nav_align_class = 'jux-align-' + menu_align;

					var juxAdminContainer = $('#jux-admin-mm-container');
					if(result.extra_data.rtl == 1) {
						juxAdminContainer.removeClass('rtl').addClass('rtl');
					} else {
						juxAdminContainer.removeClass('rtl');
					}
                    $('.juxnav').removeClass('jux-align-left jux-align-center jux-align-right jux-vertical jux-horizontal-down jux-horizontal-up').addClass(menu_nav_align_class + menu_nav_class);
                    //$('.field-media-wrapper').fieldMedia();

                    AdminMegamenu.prepare();
                    AdminMegamenu.initItemsControl();
                    AdminMegamenu.initPreSubmit();
                    AdminMegamenu.initRadioGroup();
                    AdminMegamenu.initColModule();
                    $('#mega-menu-loader').remove();
                    $('#jux-admin-megamenu').parent().removeAttr('style');
                    saveFlag = true;
                    previousModId = menuType;
                });
			}
        });

		$('#JUXMClearConfig').click(function(e){
			if(confirm('Clear configurations and options?')){
				$('#jform_params_mega_config').prop('value','');
                $('#jform_params_mega_options').prop('value','');
				var form = document.adminForm;
				if(!form){
					return false;
				}
				form.task.value = 'module.apply';
				form.submit();
			};
		});

        var navbar = $('#'+$('.jux-easy-megamenu').attr('id'));
        var sticky = navbar.offset().top;
        window.onscroll = function() {
            //sticky_menu(navbar, sticky);
        };


        $('#jux-preset-style-list').on('click', '.jux-menu-apply-preset-style', function (e) {
			e.preventDefault();
			var mm_nav = $('#jux-admin-mm-container .juxnav');
            var menuType = $('#jform_params_mod_menu').val();
            var urlParams = new URLSearchParams(location.search);
            var current_mod_id = urlParams.get('id');
            var option_tabs_container = $('#jux-ez-mega-menu-generator');
            $('#jux-admin-megamenu').parent().css('position', 'relative').append('<div id="mega-menu-loader"><div class="lds-dual-ring"></div></div>');
            $.ajax({
                url: MOD_ACTION,
                data:{'task':'loadPresetStyle', 'menu_type': menuType, 'mod_id':current_mod_id, 'preset_id': $(this).data('id'),'t':$.now()}
            }).done(function ( data ) {
                var result = JSON.parse(data);
                option_tabs_container.html(result.menu_options);

                var menu_nav_class = '';
                var menu_nav_align_class = 'jux-align-left';
                menu_nav_class += ' jux-' + result.extra_data.menu_orientation;
                if (result.extra_data.menu_orientation === 'horizontal') {
                    menu_nav_class += '-' + result.extra_data.sm_horizontal_drop;
                } else {
                    menu_nav_class += '-' + result.extra_data.sm_vertical_drop;
                }
                var menu_align = result.extra_data.menubar_align;
                menu_nav_align_class = 'jux-align-' + menu_align;

				var juxAdminContainer = $('#jux-admin-mm-container');
				if(result.extra_data.rtl == 1) {
					juxAdminContainer.removeClass('rtl').addClass('rtl');
				} else {
					juxAdminContainer.removeClass('rtl');
				}
                $('.juxnav').removeClass('jux-align-left jux-align-center jux-align-right jux-vertical jux-horizontal-down jux-horizontal-up').addClass(menu_nav_align_class + menu_nav_class);

                //$('.field-media-wrapper').fieldMedia();
                AdminMegamenu.prepare();
                AdminMegamenu.initItemsControl();
                AdminMegamenu.initPreSubmit();
                AdminMegamenu.initRadioGroup();
                AdminMegamenu.initColModule();
                $('#mega-menu-loader').remove();
                saveFlag = false;
            });
        });

        $('#jux-preset-style-list').on('click', '.jux-menu-del-preset-style', function (e) {
        	var preset_id = $(this).data('id');
        	var delConfirm = confirm("Delete " + $(this).prev().text() + '?');
        	var delBtn = $(this);
        	var preset = delBtn.parent();
            if(delConfirm) {
                $(this).parents('#jux-preset-style-list').css('position', 'relative').append('<div id="preset-loader"><div class="lds-dual-ring"></div></div>');
                $.ajax({
                    url: MOD_ACTION,
                    data:{'task':'deletePresetStyle', 'preset_id': preset_id,'t':$.now()}
                }).done(function ( data ) {
                    var result = JSON.parse(data);
                    preset.remove();
                    $('#preset-loader').remove();

                    console.log(result.status);
                });
			} else {
            	return false;
			}
			e.preventDefault();
        });

        $('#jux-menu-save-preset-style-btn').on('click', function (e) {
            var menuType = $('#jform_params_mod_menu').val();
        	var preset_name = prompt('Enter the Preset Name');
            $('#jform_params_mega_options').val(JSON.stringify(get_megamenu_options()));
        	if( preset_name.trim() !== "") {
                var options = JSON.parse($('#jform_params_mega_options').val());
                var menuOptions = options[menuType];
                $('#jux-preset-style-list').css('position', 'relative').append('<div id="preset-loader"><div class="lds-dual-ring"></div></div>');
                $.ajax({
                    url: MOD_ACTION,
                    data:{'task':'savePresetStyle', 'preset_name': preset_name, 'option_data': JSON.stringify(menuOptions), 'time':$.now()}
                }).done(function ( data ) {
                    var result = JSON.parse(data);
                    $('#jux-preset-style-list').append(result.item);
                    $('#preset-loader').remove();
                });
			}
			e.preventDefault();
        });
	});


}(jQuery);
