﻿(function($)
{
	function Panel(container, options)
	{
		this.container = container;
		this.settings = $.extend(
		{
			title: '',
			content: undefined,
			onOpened: undefined,
			onClosed: undefined,
			onLoaded: undefined,
			opened: true,
			url: ''
		}, options);
		this.is_loaded = false;
		this.is_load = false;
	}

	Panel.prototype =
	{
		init: function()
		{
			this.container.addClass('panel');
			this.header = $('.panel-header', this.container);
			this.content = $('.panel-content', this.container).first();
			if (this.header.length == 0)
			{
				this.container.wrapInner('<div class="panel-content" />');
				this.content = $('div.panel-content', this.container).first();
				this.header = $('<div class="panel-header"></div>');
				this.header.html(this.settings.title);
				this.container.prepend(this.header);
			}
			if (this.settings.content)
				this.content.html(this.settings.content);
			this.opened = !this.settings.opened;
			var panel = this;
			this.header.click(function()
			{
				if (panel.opened)
					panel.close();
				else
					panel.open();
				return false;
			}).click();
		},

		open: function()
		{
			if (this.opened) return;
			this.container.addClass('opened');
			this.opened = true;
			if (!this.is_loaded && this.settings.url && !this.is_load)
			{
				var panel = this;
				this.is_load = true;
				this.content.html('Загрузка...');
				this.content.load(this.settings.url, {}, function(responseText, textStatus, XMLHttpRequest)
				{
					if (panel.settings.onLoaded)
						panel.settings.onLoaded(responseText, textStatus, XMLHttpRequest);
					panel.is_load = false;
				});
			}
			if (this.settings.onOpened)	this.settings.onOpened();
		},

		close: function()
		{
			if (!this.opened) return;
			this.container.removeClass('opened');
			this.opened = false;
			if (this.settings.onClosed)	this.settings.onClosed();
		}

	};


	$.fn.panel = function(options)
	{
		var elem = this[0];
		if (elem)
		{
			var panel = new Panel($(elem), options);
			panel.init();
			return panel;
		}
		return null;
	};

})(jQuery);
