(function($) {
    
    
    var ddsmoothmenuEdicao = function(){
        //Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
        var arrowimages = {down:['downarrowclass', 'down.gif', 23], right:['rightarrowclass', 'right.gif']};
        var transition = {overtime:300, outtime:300}; //duration of slide in/ out animation, in milliseconds
        var shadow = {enable:false, offsetx:5, offsety:5}; //enable shadow?
        var showhidedelay = {showdelay: 100, hidedelay: 300}; //set delay in milliseconds before sub menus appear and disappear, respectively
        ///////Stop configuring beyond here///////////////////////////
        var detectwebkit = navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1; //detect WebKit browsers (Safari, Chrome etc)
        var detectie6 = document.all && !window.XMLHttpRequest;
        var $menuItemSeleccionado = null;
        var menuAlterado = false;
        var $mainmenu = null;
        
        //Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
        var arrowimages = {down:['downarrowclass', 'down.gif', 23], right:['rightarrowclass', 'right.gif']};
        var transition = {overtime:300, outtime:300}; //duration of slide in/ out animation, in milliseconds
        var shadow = {enable:false, offsetx:5, offsety:5}; //enable shadow?
        var showhidedelay = {showdelay: 100, hidedelay: 300}; //set delay in milliseconds before sub menus appear and disappear, respectively
        ///////Stop configuring beyond here///////////////////////////
        var detectwebkit = navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1; //detect WebKit browsers (Safari, Chrome etc)
        var detectie6 = document.all && !window.XMLHttpRequest;
        
        this.init = function(settings){
            if (typeof settings.customtheme=="object" && settings.customtheme.length==5){ //override default menu colors (default/hover) with custom set?
		        var mainmenuid='#'+settings.mainmenuid;
		        var mainselector=(settings.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid;
	            $('<style type="text/css">\n'
	                +mainmenuid+' {visibility:visible;}\n'
		            +mainmenuid+' a {background:'+settings.customtheme[0]+';}\n'
		            +mainmenuid+' a:hover {background:'+settings.customtheme[0]+';}\n'
		            +mainmenuid+' * {border-color:'+settings.customtheme[2]+';}\n'
		            +mainmenuid+' * {color:'+settings.customtheme[2]+';}\n'
		            +mainmenuid+' a {font-family:'+settings.customtheme[3]+';}\n'
		            +mainmenuid+' a {font-size:'+settings.customtheme[4]+';}\n'
	            +'</style>').appendTo(mainmenuid);
	        }
			buildmenuExpanded(settings);
		}
		
		this.adicionarMenuItem = function(dadosNovoItem){
            if(dadosNovoItem != null && dadosNovoItem.length >= 8){
                dadosNovoItem[2] = 'null';
                dadosNovoItem[5] = $mainmenu.find('>li').length + 1;
                var $newMenuItem = $("<li><input type='hidden' value='"+dadosNovoItem.toString()+"' /><a>"+dadosNovoItem[4]+"</a></li>");
	            $mainmenu.append($newMenuItem);//insere em ultimo lugar no nivel 0
	            menuAlterado = true;
            }
        }

        this.guardaralteracoesMenuItem = function (dadosItem){
            if(dadosItem != null && dadosItem.length >= 8){
                var $parent = null;
                if($menuItemSeleccionado != null){
                    $menuItemSeleccionado.prev('input').val(dadosItem.toString());
                    $menuItemSeleccionado.text(dadosItem[4]);
                    menuAlterado = true;
	            }
            }
        }

        this.apagarMenuItem = function (hdfRegistoItemsApagadosID){
           if($menuItemSeleccionado != null){
                $menuItemSeleccionado.parent('li:first').next('li').each(function(){
                    decrementarOrdem(this);
                });
					$('#' +  hdfRegistoItemsApagadosID).val($('#' +  hdfRegistoItemsApagadosID).val() + new String($menuItemSeleccionado.prev('input:hidden').first().val()).split(",")[0] + '#');
                $menuItemSeleccionado.parent('li:first').find('li > input').each(function(){
                    $('#' +  hdfRegistoItemsApagadosID).val($('#' +  hdfRegistoItemsApagadosID).val() + new String($(this).val()).split(",")[0] + '#');
                })
                $mainMenu = $menuItemSeleccionado.parents('div:first');
                $menuItemSeleccionado.parent('li:first').remove();
                $mainMenu.find('li > ul:empty').remove();//bug no IE, se o <ul> estiver vazio coloca um espaço, remover os <ul> que possam ter ficado vazios
                $menuItemSeleccionado = null;
                menuAlterado = true;
           }  
        }
        
        this.gravarMenu = function(hdfID){
            $hdf = $('#' + hdfID);
            $mainmenu.parent().find('ul:first li > input:hidden').each(function(){
                $hdf.val($hdf.val()+'#'+$(this).val());
            });
        }
        
        this.MenuAlterado = function(){
            return menuAlterado;
        }
        
        selecionarMenuItem = function($menuItem, settings){
            if($menuItemSeleccionado != null){
                $menuItemSeleccionado.css('background-color', '');
            }if($menuItem.length){
                $menuItemSeleccionado = $menuItem;
                $menuItemSeleccionado.css('background-color',settings.customtheme[1]);
            }
        }
        
        identarMenuItens = function(settings){
            var $mainmenu=$("#"+settings.mainmenuid+">ul"); //reference main menu UL
            $mainmenu.find('a').css('padding-left', '20px');
            $mainmenu.find("ul").each(function(){//identar os menuitems
                var $this = $(this);
                if($this.find('a').length){
	                var padding = '0';
	                padding = $this.find('a').css('padding-left').replace('px', '');
	                padding = parseInt(padding) + 20;
	                $this.find('a').css('padding-left', padding + 'px');
	            }
            })
        }
        
        subirNivel = function($menuItem, $targetMenuItem){
           $menuItem.find('a').each(function(){
                var padding = '0';
                padding = $(this).css('padding-left').replace('px', '');
                if(parseInt(padding) > 20)
                    padding = parseInt(padding) - 20;
                $(this).css('padding-left', padding + 'px');
            });  
            var dataItemTarget = new String($targetMenuItem.find('input:hidden').first().val()).split(",");
            var ordem = parseInt(dataItemTarget[5]);
            var dataItemSubirNivel = new Array(8);
            dataItemSubirNivel = new String($menuItem.find('input:hidden').first().val()).split(",");
            dataItemSubirNivel[2] = dataItemTarget[2]; //WMenuItemPai
            dataItemSubirNivel[5]=++ordem;
            $menuItem.find('input:hidden').first().val(dataItemSubirNivel.toString());
            $menuItem.next('li').each(function(){
                incrementarOrdem(this);
            });
            menuAlterado = true;
        }
        
        descerNivel = function($menuItem, $targetMenuItem){
           $menuItem.find('a').each(function(){
                var padding = '0';
                padding = $(this).css('padding-left').replace('px', '');
                padding = parseInt(padding) + 20;
                $(this).css('padding-left', padding + 'px');
            });
            var dataItemTarget = new String($targetMenuItem.find('input:hidden').first().val()).split(",");
            var ordem = parseInt(dataItemTarget[5]);
            var dataItemDescerNivel = new Array(8);
            dataItemDescerNivel = new String($menuItem.find('input:hidden').first().val()).split(",");
            dataItemDescerNivel[2] = dataItemTarget[0];
            dataItemDescerNivel[5]=parseInt($menuItem.index())+1;//ordem
            $menuItem.find('input:hidden').first().val(dataItemDescerNivel.toString());
            menuAlterado = true;
        }
        
        decrementarOrdem = function(liElement)
        {
            var dataItemDecrementarOrdem = new String($(liElement).find('input:hidden').first().val()).split(",");
            dataItemDecrementarOrdem[5]=parseInt(dataItemDecrementarOrdem[5])-1;//ordem
            $(liElement).find('input:hidden').first().val(dataItemDecrementarOrdem.toString());
        }
        
        incrementarOrdem = function(liElement)
        {
            var dataItemIncrementarOrdem = new String($(liElement).find('input:hidden').first().val()).split(",");
            dataItemIncrementarOrdem[5]=parseInt(dataItemIncrementarOrdem[5])+1;//ordem
            $(liElement).find('input:hidden').first().val(dataItemIncrementarOrdem.toString());
        }
        
        buildmenuExpanded = function(settings){
	        $mainmenu=$("#"+settings.mainmenuid+">ul"); //reference main menu UL
	        identarMenuItens(settings);
	        $("#"+settings.mainmenuid+" ul li a ").die('click');
	        $("#"+settings.mainmenuid+" ul li a ").live('click',function(){
	            selecionarMenuItem($(this), settings);
	        });
	        if($menuItemSeleccionado != null)
	            $menuItemSeleccionado.trigger('click');
            $('.btNivelAbaixo').click(function(){
                if($menuItemSeleccionado != null){
                    var $curMenuItem = $menuItemSeleccionado.parents('li:first');
                    var $targetMenuItem = $curMenuItem.prevAll('li:first');
                    if($targetMenuItem.length){
                        $curMenuItem.next('li').each(function(){
                            decrementarOrdem(this);
                        });
                        if(!$targetMenuItem.find('ul:first').length)
                            $targetMenuItem.append('<ul></ul>');
                        $curMenuItem.hide('fast', function(){
                            $curMenuItem.detach();
                            $targetMenuItem.find('ul:first').append($curMenuItem);
                            descerNivel($curMenuItem, $targetMenuItem);
                            $curMenuItem.show('fast');
                        });
                    }
                }
                return false;
            })
            $('.btCima').click(function(){
                if($menuItemSeleccionado != null){
                    var $targetMenuItem = $menuItemSeleccionado.parents('li:first').prev('li');
                    if($targetMenuItem.length){
                        var $curMenuItem = $menuItemSeleccionado.parents('li:first');
                        $curMenuItem.hide('fast',function(){
                            $curMenuItem.detach();
                            $curMenuItem.insertBefore($targetMenuItem);
                            decrementarOrdem($curMenuItem.get(0));
                            incrementarOrdem($targetMenuItem.get(0));
                            menuAlterado = true
                            $curMenuItem.show('fast')
                        });                
                    }
                }
                return false;
            });
            $('.btBaixo').click(function(){
                if($menuItemSeleccionado != null){
                    var $targetMenuItem = $menuItemSeleccionado.parents('li:first').next('li');
                    if($targetMenuItem.length){
                        var $curMenuItem = $menuItemSeleccionado.parents('li:first');
                        $curMenuItem.hide('fast', function(){
                            $curMenuItem.detach();
                            $curMenuItem.insertAfter($targetMenuItem);
                            incrementarOrdem($curMenuItem.get(0));
                            decrementarOrdem($targetMenuItem.get(0));
                            menuAlterado = true;
                            $curMenuItem.show('fast');
                        });
                    }
                }
                return false;
            });
            $('.btNivelAcima').click(function(){
                var $targetMenuItem = $menuItemSeleccionado.parents('li:first');
                if($targetMenuItem.parents('ul:first').parents().attr('id') != settings.mainmenuid){
                    $targetMenuItem = $targetMenuItem.parents('ul:first').parent();
                    var $curMenuItem = $menuItemSeleccionado.parents('li:first');
                    $curMenuItem.next('li').each(function(){
                        decrementarOrdem(this);//Decrementar a ordem de todos os items que estão a seguir ao $itemParaSubirNivel
                    });
                    $curMenuItem.hide('fast', function(){
                            $curMenuItem.detach();
                            $curMenuItem.insertAfter($targetMenuItem);
                            subirNivel($curMenuItem, $targetMenuItem);  
                            $mainmenu.find('li>ul:empty').remove();//bug no IE, se o <ul> estiver vazio coloca um espaço, remover os <ul> que possam ter ficado vazios
                            $curMenuItem.show('fast');
                        });
                }
                return false;
            });
            $('.btEditarMenuItem').click(function(){
                if($menuItemSeleccionado != null){
                    eval(settings.editarMenuItemClientCallback + '($menuItemSeleccionado.parents(\'li:first\'))');
                }
            });
            $("#"+settings.mainmenuid+" ul li a ").live('dblclick', function(){
                if($menuItemSeleccionado != null){
                    eval(settings.editarMenuItemClientCallback + '($menuItemSeleccionado.parents(\'li:first\'))');
                }
            });
        }
    };
    
    var ddsmoothmenu = function(){
    
        //Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
        var arrowimages = {down:['downarrowclass', 'down.gif', 23], right:['rightarrowclass', 'right.gif']};
        var transition = {overtime:0, outtime:0}; //duration of slide in/ out animation, in milliseconds
        var shadow = {enable:false, offsetx:5, offsety:5}; //enable shadow?
        var showhidedelay = {showdelay: 50, hidedelay: 100}; //set delay in milliseconds before sub menus appear and disappear, respectively
        ///////Stop configuring beyond here///////////////////////////
        var detectwebkit = navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1; //detect WebKit browsers (Safari, Chrome etc)
        var detectie6 = document.all && !window.XMLHttpRequest;
        
        this.init = function(settings){
            if (typeof settings.customtheme=="object" && settings.customtheme.length==5){ //override default menu colors (default/hover) with custom set?
		        var mainmenuid='#'+settings.mainmenuid;
		        var mainselector=(settings.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid;
	            $('<style type="text/css">\n'
	                +mainmenuid+' {visibility:visible;}\n'
		            +mainselector+' ul li a {background:'+settings.customtheme[0]+';}\n'
		            +mainmenuid+' ul li a:hover {background:'+settings.customtheme[1]+';}\n'
		            +mainmenuid+' * {border-color:'+settings.customtheme[2]+';}\n'
		            +mainmenuid+' * {color:'+settings.customtheme[2]+';}\n'
		            +mainmenuid+' a {font-family:'+settings.customtheme[3]+';}\n'
		            +mainmenuid+' a {font-size:'+settings.customtheme[4]+'px;}\n'
	            +'</style>').appendTo(mainmenuid);
		       
	        }
	        //$(mainmenuid).css('visibility', 'visible');
			buildmenu(settings);
		}
		
        function buildmenu(settings){
	        var $mainmenu=$("#"+settings.mainmenuid+">ul") //reference main menu UL
	        $mainmenu.parent().get(0).className=settings.classname || "ddsmoothmenu"
	        var $headers=$mainmenu.find("ul").parent()
	        $headers.hover(
		        function(e){
			        $(this).children('a:eq(0)').addClass('selected')
		        },
		        function(e){
			        $(this).children('a:eq(0)').removeClass('selected')
		        }
	        )
	        $headers.each(function(i){ //loop through each LI header
		        var $curobj=$(this).css({zIndex: 50-i}) //reference current LI header
		        var $subul=$(this).find('ul:eq(0)').css({display:'block'})
		        $subul.data('timers', {})
		        this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
		        this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
		        $subul.css({top:this.istopheader && settings.orientation!='v'? this._dimensions.h+"px" : -2})
		        if (shadow.enable){
			        this._shadowoffset={x:(this.istopheader?$subul.offset().left+shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+shadow.offsety : $curobj.position().top)} //store this shadow's offsets
			        if (this.istopheader)
				        $parentshadow=$(document.body)
			        else{
				        var $parentLi=$curobj.parents("li:eq(0)")
				        $parentshadow=$parentLi.get(0).$shadow
			        }
			        this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'})  //insert shadow DIV and set it to parent node for the next shadow div
		        }
		        $curobj.hover(
			        function(e){
			            var $targetul=$subul //reference UL to reveal
			            var header=$curobj.get(0) //reference header LI as DOM object
			            clearTimeout($targetul.data('timers').hidetimer)
			            $targetul.data('timers').showtimer=setTimeout(function(){
				            header._offsets={left:$curobj.offset().left, top:$curobj.offset().top}
				            if($('.divBarraLateral:first').css('float') == 'left')
				                var menuExpandToRight = true;
				            else
				                var menuExpandToRight = false;
				            var menuleft=header.istopheader && settings.orientation!='v'? 0 : header._dimensions.w
				            if(!menuExpandToRight)
				            {
				               menuleft = -header._dimensions.subulw;
				            }
				            //menuleft= ((header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && settings.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft) //calculate this sub menu's offsets from its parent
				            if ($targetul.queue().length<=1){ //if 1 or less queued animations
					            $targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, transition.overtime)
					            if (shadow.enable){
						            var shadowleft=header.istopheader? $targetul.offset().left+shadow.offsetx : menuleft
						            var shadowtop=header.istopheader?$targetul.offset().top+shadow.offsety : header._shadowoffset.y
						            if (!header.istopheader && detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
							            header.$shadow.css({opacity:1})
						            }
						            header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, transition.overtime)
					            }
				            }
			            }, showhidedelay.showdelay)
			        },
			        function(e){
			            var $targetul=$subul
			            var header=$curobj.get(0)
			            clearTimeout($targetul.data('timers').showtimer)
			            $targetul.data('timers').hidetimer=setTimeout(function(){
				            $targetul.animate({height:'hide', opacity:'hide'}, transition.outtime)
				            if (shadow.enable){
					            if (detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
						            header.$shadow.children('div:eq(0)').css({opacity:0})
					            }
					            header.$shadow.css({overflow:'hidden'}).animate({height:0}, transition.outtime)
				            }
			            }, showhidedelay.hidedelay)
			        }
		        ) //end hover
	        }) //end $headers.each()
	        $mainmenu.find("ul").css({display:'none', visibility:'visible'})
        }
        
    };
   
    $.fn.ddsmoothmenu = function(settings){
        //return this;
         return this.each(function(){
            var element = $(this);
          
            // Return early if this element already has a plugin instance
            if (element.data('menu')) return;
            
            //var menu = new ddsmoothmenu(settings);
            var menu = new ddsmoothmenu();
            menu.init(settings);

            // Store plugin object in this element's data
            element.data('menu', menu);
         })
    };
    
    $.fn.ddsmoothmenuEdicao = function(settings){
        //return this;
         return this.each(function(){
            var element = $(this);
          
            // Return early if this element already has a plugin instance
            if (element.data('menu')) return;
            
            //var menu = new ddsmoothmenu(settings);
            var menu = new ddsmoothmenuEdicao();
            menu.init(settings);

            // Store plugin object in this element's data
            element.data('menu', menu);
         })
    };

})(jQuery);