(function($) {
    $.fn.dropmenu = function(options) {
    	var defaults = {
    	    // Наличие эффекта открывания
    	    effect: false,
        	// Скорость эффекта
            score: 'fast',
        	// URL адрес для подгрузки меню
        	url: null,
        	// Триггер, срабатывающий при выборе пункта меню
        	select: false,
        	// Html-код слева от заголовка меню
        	leftin: "&#9660;&nbsp;"
        };
        var opts = $.extend(defaults, options||{});
		var index = this.length * 2;

       	this.each(function() {

            if($(this).children("p.menu_head").length == 0) {

                var title = $(this).attr("title");
                if (title.length > 0) {
                    $(this).prepend("<p class='menu_head'>"+opts['leftin']+"<span>"+title+"</span></p>");
                    $(this).attr("title","");
                    opts['pl_title'] = true;
				} else {
                    opts['pl_title'] = false;
                    // Если есть элемент с id = current
                    if ($(this).find("li#current").length == 1) {
                        title = $(this).find("li#current").children("a").html();
                    } else {
                        title = $(this).find("li:first").children("a").html();
                    }
                    $(this).prepend("<p class='menu_head'>"+opts['leftin']+"<span>"+title+"</span></p>");
                }

				set_outline($(this).children(".menu_head"));

                // Добавляем индекс слоя
                $(this).children(".menu_head").css("z-index",index);
                index -= 1;
                $(this).children("ul").css("z-index",index);
                index -= 1;

                $(this).children("p").bind("click",function () {

					if ($(this).siblings("ul").length > 0) {
	    				if ($(this).next('ul').css("display")=="block") {
							set_outline(this);

							if (opts['effect']) {
								$(this).next('ul').slideUp(opts['score']);
							} else {
								$(this).next('ul').hide();
							}
						} else {
							remove_outline(this);

							if (opts['effect']) {
								$(this).next('ul').slideDown(opts['score']);
							} else {
								$(this).next('ul').show();
							}

						}
					} else {
						if (opts['url']) {
							var obj = $(this).parent();
							$(obj).append("<ul><li><p>Загрузка...</p></li></ul>");
							if (opts['effect']) {
								$(obj).children('ul').slideDown(opts['score']);
							} else {
								$(obj).children('ul').show();
							}
							remove_outline(this);

							$.get(opts['url'],{},function(answer) {
							    if (isValidJSON(answer)) {
							        var answer = eval('('+answer+')');
                                	var _flag = false;
                                    // Импортируем полученные данные
    							    for(prop in answer) {
    							        _flag = true;
    								    if (answer[prop]['url'] && answer[prop]['title']) {
        								    $(obj).children("ul").append("<li><a href='"+answer[prop]['url']+"'>"+answer[prop]['title']+"</a></li>");
    								    }
    							    }
    							    
                                    if (!_flag) {
                                        var title = $(obj).children("p.menu_head").children("span").text();
                                        $(obj).parent().html("<a href='"+window.location.href+"'>"+title+"</a>");
                                        return false;
                                    } else {
                                        $(obj).children("ul").children("li").eq(0).remove();
                                    }
                                } else {
                                    var title = $(obj).children("p.menu_head").children("span").text();
                                    $(obj).parent().html("<a href='"+window.location.href+"'>"+title+"</a>");
                                    return false;
                                }
                                
							});
						}
					}

					return false;
				});

				$(this).hover(null,function() {
					set_outline($(this).children(".menu_head"));
					if (opts['effect']) {
						$(this).children('ul').slideUp(opts['score']);
					} else {
						$(this).children('ul').hide();
					}
				});

                $(this).children('ul').children('li').click(function() {
    				if (opts['effect']) {
						$(this).parent().slideUp(opts['score']);
					} else {
						$(this).parent().hide();
					}

                    // Если заголовок формировался автоматически, то обновляем его
                    if (!opts['pl_title']) {
                        $(this).parent().siblings("p").html(opts['leftin']+$(this).html());
                    }

                    if (typeof (opts['select']) == 'function') {
                        return opts['select'].call(1,this);
                    }
                });
            }

		});
    };
})(jQuery);

function set_outline(obj) {
	if ($(obj).hasClass("menu_head")) {
		$(obj).bind("mouseover",function() {
			$(this).css({"outline":"1px solid #737373"});
		});
		$(obj).bind("mouseout",function() {
			$(this).css({"outline":"0px"});
		});
	}
}

function remove_outline(obj) {
	if ($(obj).hasClass("menu_head")) {
		$(obj).unbind("mouseover");
		$(obj).unbind("mouseout");
		$(obj).css({"outline":"0px"});
	}
}




