(function($) {
	$.fn.switchList = function(opts) {
		var o = {
			changeHash : false, replaceMoreText : false, moreText : 'więcej',
			backText : 'zwiń',expandedSingle:false/*expand*/
		};
		if (opts) {
			$.extend(o, opts);
		}
		cms2.eventDispatcher.dispatchEvent({
			type : 'SWITCH_LIST_INIT', data : {}
		})
		return this
				.each(function(i) {
					var count=$(" > *", this).length;
					$(" > *", this)
							.each(
									function(j) {
										if(o.expandedSingle && count==1){
											$('.switchControllHook', this).remove()
											return
										}
										if ($('.hideableContent', this).length == 1) {
											if (o.changeHash){
												$(
														$('.hideableContent',
																this)[0].parentNode)
														.prepend(
																'<a name="sw_part'
																		+ j
																		+ '" class="sw_part"/>');
											};
											$('.hideableContent', this).css('display','none');
											$('.switchControllHook', this)
													.click(
															function() {
																switchBlock(this.parentNode)
															})
											if (o.replaceMoreText) {
												$('.switchControllHook', this)
														.html(o.moreText)
												$('.switchControllHook', this)
														.attr('moreText',
																o.moreText)
												$('.switchControllHook', this)
														.attr('backText',
																o.backText)
											}
											$(
													$('.hideableContent', this)[0].parentNode)
													.attr('expanded', 'false')
											if (o.changeHash
													&& location.hash
													&& location.hash.substr(1) == 'sw_part'
															+ j) {
												switchBlock($(
														'.hideableContent',
														this)[0].parentNode)
											}

										}
									})
				})
	};
	var lastBlockRef
	function switchBlock(blockRef) {
		if (lastBlockRef && $(lastBlockRef).attr('expanded') == 'true'
				&& lastBlockRef != blockRef) {
			switchExecute(lastBlockRef)
		}
		lastBlockRef = null
		lastBlockRef = blockRef
		switchExecute(blockRef)
		cms2.eventDispatcher.dispatchEvent({
			type : 'SWITCH_LIST_SWITCH', data : {}
		})
	}
	function switchExecute(blockRef) {
		var expanding;
		if ($(blockRef).attr('expanded') == 'false') {// show full
			expanding = true
			$('.hideableContent', blockRef).css('display', 'none').fadeIn(
					'slow')
		} else {// show small
			expanding = false
			$('.hideableContent', blockRef).css('display', 'none')
		}
		$(blockRef).attr('expanded', expanding ? 'true' : 'false')
		if (expanding && $('a.sw_part', blockRef).length > 0) {
			location = '#' + $('a', blockRef).attr('name')
		}
		if ($('.switchControllHook', blockRef).attr('moreText')) {
			$('.switchControllHook', blockRef).html(
					$(blockRef).attr('expanded') == 'true' ? $(
							'.switchControllHook', blockRef).attr('backText')
							: $('.switchControllHook', blockRef).attr(
									'moreText'))
		}
	}
})(jQuery);
