(function($) {
	$.widget("ui.bwMessages", {
		options: {
			autoClose: true,
			autoCloseTime: 6000,
			template: {
							messageList:'<ul class="system_messages">${MessageList}</ul>',
							messageItem:'<li class="${Type}"><div class="top"><span></span></div><div class="middle"><span>${Message}</span></div><div class="bottom"><span></span></div><span class="icon"></span><a class="btnClose"></a></li>'
			}
		},

		_create: function() {
			var self = this;

			this.messageListCreated = false;
			this.messageList = $.tmpl(this.options.template.messageList, {MessageList:null});
			//this.messageList.appendTo(this.element);

			$.ui.bwMessages.instances.push(this.element);
		},

		_init: function() {
		},

		add: function(message) {
			var self = this;

			if(false === this.messageListCreated) {
				this.messageList.appendTo(this.element);
				this.messageListCreated = true;
			}
			this.messageList.slideDown();

			var text;
			if($.isPlainObject(message.items)) {
				text = message.text;
				$.each(message.items, function(field, msg){
					text = text+"<br/>"+"- "+msg;
				});
			}
			var messageItem = $.tmpl(this.options.template.messageItem, {Type:message.type, Message:message.text});

			if(this.options.autoClose) {
				console.log(this.options.autoCloseTime);
				var t = setTimeout(function() {self._closeItem(messageItem);}, this.options.autoCloseTime); 
			}

			messageItem.find('a.btnClose').bind('click', {messageItem:messageItem}, function(event) {
				self._closeItem(event.data.messageItem);
			});

			messageItem.prependTo(this.messageList);
		},

		_closeItem: function(item) {
			var self = this;

			$(item).slideUp('slow', function() {
				$(item).remove();
				if($('li', self.messageList).length === 0) {
					self._removeMessageList();
				}
			});
		},

		_removeMessageList: function() {
			var self = this;

			this.messageList.slideUp('slow', function(){ 
				$(this).slideUp();
				self.messageListCreated = false;
			});
		},
	
    	destroy: function() {
			$.widget.prototype.destroy.call( this );
		},

		_setOption: function( key, value ) {
			switch( key ) {
				case "clear":
				break;
			}

			$.widget.prototype._setOption.apply(this, arguments);
      	this._super("_setOption", key, value);
    	}
	});

	$.extend($.ui.bwMessages, {
		instances: []
	});
}( jQuery ) );

jQuery.fn.bwRenameItem = function(url)
{
	var $link = url;

	$(this).bind('click', function() {
		var element = $(this);

		if(element.data('rename')) {
			return;
		} else {
			element.data('rename', true);
		}

		var oRow = $(this).parents("tr");
		var iId = oRow.attr('rel')
		var oTitle = oRow.find('.title');
		var tOldName = oTitle.html();

		oTitle.addClass('fRename').html(
			$('<input type="text" />').attr({ name:'new_title' }).val(oTitle.html())
		);
		var oButtons = $('<div />').addClass('buttons').append(
			$('<a />').addClass('btnSmall orange').html('zapisz').bind('click', function() {
				$.getJSON($link, {id:iId, name:$('input', oTitle).val()}, function(data) {
					if(data.state) {
						var newTitle = $('input', oTitle).val();
						oTitle.removeClass('fRename').html(newTitle).next('.error').remove();
						element.data('rename', false);
						oButtons.remove();
						$('#messages').bwMessages('add', data.message);
					} else {
						oTitle.after(
							$('<div />').addClass('error').html(data.message.items.name)
						);
					}
				});
			})
		).append(
			$('<a />').addClass('btnSmall black last').html('anuluj').bind('click', function() {
				oTitle.removeClass('fRename').html(tOldName);
				oButtons.remove();
				element.data('rename', false);
			})
		);
		oTitle.after(oButtons);
	});
}





jQuery.fn.bwRename = function (url) {
	var $link = url;

	$(this).bind('click', function() {
		var element = $(this);

		if(element.data('rename')) {
			return;
		} else {
			element.data('rename', true);
		}
		
		var iId = $(this).attr('rel');
		var oTitle = $(this).parent().parent().parent().find('.title');
		var oldName = oTitle.html();
		var rename = $('<div />').addClass('fRename').append(
			$('<span />').append(
				$('<input type="text" />').attr({ name:'new_title' }).val(oTitle.html())
			)
		);
		var buttons = $('<div />').addClass('buttons rename').append(
			$('<a />').addClass('btnSmall orange').html('zapisz').bind('click', function() {
				$.getJSON($link, {id:iId, name:$('input', rename).val()}, function(data) {
					if(data.state) {
						oTitle.html($('input', rename).val());
						element.data('rename', false);
					} else {
						oTitle.append(
							$('<div />').addClass('error').html(data.msg.name)
						);
					}
				});
			})
		).append(
			$('<a />').addClass('btnSmall black').html('anuluj').bind('click', function() {
				oTitle.html(oldName);
				element.data('rename', false);
			})
		)
		oTitle.html(rename);
		oTitle.append(buttons);
	});
}

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}
jQuery.fn.centerByElement = function (element) {
	var element = $(element);
    this.css("position","absolute");
    this.css("top", ((element.height() - this.outerHeight()) / 2) + element.scrollTop() + "px");
    this.css("left", ((element.width() - this.outerWidth()) / 2) + element.scrollLeft() + "px");
    return this;
}
jQuery.fn.acoCheckbox = function () {
	this.bind('click', function() {
		if($(this).hasClass('on')) {
			$(this).removeClass('on');
		} else {
			$(this).addClass('on');
		}
	});
}

jQuery.fn.centerElements = function () {
	var width = 0;
	$(this).children().each(function(i) {
		if($(this).css('display') != 'none') {
			width = width + $(this).outerWidth(true);
		}
	});
	$(this).css({ marginLeft: ($(this).width() - width)/2+'px', visibility:'visible' });
}

jQuery.fn.autoWidth = function (padding) {
	var width = 0;
	$(this).children().each(function(i) {
		width = width + $(this).outerWidth();
	});
	$(this).css({
		width: width +'px'
	});
	//padding: padding
}

$(function() {
	jQuery.widget("custom._window", {
		options: {
			title: 255,
			width: 400,
			content: null
		},

		_create: function() {
			this.overlay = $('<div>', {
				'class': 'overlay',
				'css': {opacity:0.7}
			})
			.appendTo($('body'));

			this.element
				.addClass("abs window")
				.width(this.options.width)
				.attr('id', 'window_' + this.options.id)
				.attr('rel', '_window')
			;

			this.title = $("<div>", {
				text: this.options.title,
				"class": "title"
			})
			.appendTo( this.element );

			this.content = $("<div>", {
				text: "",
				"class": "content"
			})
			.appendTo( this.element );

			this.iframe = $("<iframe style='border:0;' frameborder='0' ALLOWTRANSPARENCY='true' />")
				.addClass('iframe')
				.attr('src', this.options.content);
			
			this.iframe.appendTo( this.content );

			this.element.appendTo($('body'));
			this.element.center();
			var ttt = this.element;
			$(window).resize(function() {
				ttt.center();
			});

			var ttt2 = this.overlay;
			$(window).scroll(function() {
				$(ttt2).height($(document).height());
				ttt.center();
			});
			$(ttt2).height($(document).height());

			this._load();
		},

		_load: function() {
			//this.iframe.attr('src', this.options.content);
			var fr = this.iframe;
			//console.log($(fr, '>document').height())
			$(this.iframe, '>document').resize(function() {
				//console.log($(fr, '>window').height())
			});
		},

		_refresh: function() {
			this._refresh();
		},

		destroy: function() {	
			$.Widget.prototype.destroy.call( this );
			this.element.remove();
			this.overlay.remove();
		},

		// _setOptions is called with a hash of all options that are changing
		// always refresh when changing options
		_setOptions: function() {
			// in 1.9 would use _superApply
			$.Widget.prototype._setOptions.apply( this, arguments );
			this._refresh();
		}
	});
})
