jQuery.noConflict();
jQuery(document).ready(function($){

	//==================================
	// Dodawanie produktów do koszyka - podstrona = hosting
	//==================================
	$(".productPriceWrapRight a.host, .productPriceWrapRightDomain a img.host").click(function() {
		var productIDValSplitter 	= (this.id).split("_");
		var productIDVal 				= productIDValSplitter[1];
		var productRegtimeVal 		= productIDValSplitter[3];
		var productTypeVal 			= productIDValSplitter[2];
		var ProductName				= $(this).attr('title');
		var productX 					= $("#productImageWrapID_" + productIDVal).offset().left;
		var productY 					= $("#productImageWrapID_" + productIDVal).offset().top;
		var basketX 					= $("#basketTitleWrap").offset().left;
		var basketY 					= $("#basketTitleWrap").offset().top;
		var gotoX 						= basketX - productX;
		var gotoY 						= basketY - productY;
		var newImageWidth 			= $("#productImageWrapID_" + productIDVal).width() / 3;
		var newImageHeight			= $("#productImageWrapID_" + productIDVal).height() / 3;

		$("#BasketResponse").removeClass("error").removeClass("valid").html("");

		$("html, body").animate({ scrollTop: 0 }, 1500);
		setTimeout(function(){
			$("#productImageWrapID_" + productIDVal + " img")
			.clone()
			.prependTo("#productImageWrapID_" + productIDVal)
			.css({'position' : 'absolute'})
			.css('display','block')
			.animate({opacity: 0.4}, 100 )
			.animate({opacity: 0, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1000, function() {
				$.ajax({
					type: "POST",
					url: "modules/basket.php",
					data: { productID: productIDVal, productType: productTypeVal, productRegtime: productRegtimeVal, productName: ProductName, action: "dodaj"},
					success: function(theResponse) {
						$("li#li_map img").animate({opacity:0.4},150).animate({opacity:1},150);
						$("#BasketResponse").animate({opacity:0.01},1);
						if (theResponse == "hosting_added") {
							$("#BasketResponse").addClass("valid").html("Usługa została dodana.");
						} else if (theResponse == "full_hosting") {
							$("#BasketResponse").addClass("error").html("Usługa hostingowa<br /> znajduje się już w koszyku.");
						} else if (theResponse == "system_error") {
							$("#BasketResponse").addClass("error").html("Błąd systemu.<br /> Prosimy o kontakt.");
						} else if (theResponse == "time_error") {
							$("#BasketResponse").addClass("error").html("Nie możesz dodać kilku<br />usług w tym samym czasie!");
						} else if (theResponse == "full_basket") {
							$("#BasketResponse").addClass("error").html("Twój koszyk jest pełny!");
						}
						$("#BasketResponse").animate({opacity:1},800);
						setTimeout(function(){
							$("#BasketResponse").animate({opacity:0.01},800).removeClass("error").removeClass("valid").html("");
						}, 30000);
					}
				});
				$(this).remove();
			});
		}, 1000);
	});

	//==================================
	// Dodawanie produktów do koszyka - podstrona = domena
	//==================================
	$(".productPriceWrapRight a.domain, .productPriceWrapRightDomain a img.domain").live('click', function() {
		var id = this.id;
		var productIDValSplitter 	= (this.id).split("_");
		var productIDVal 				= productIDValSplitter[1];
		var productRegtimeVal 		= productIDValSplitter[3];
		var productTypeVal 			= productIDValSplitter[2];
		var ProductName				= $(this).attr('title');
		var productX 					= $("#productImageWrapID_" + productIDVal).offset().left;
		var productY 					= $("#productImageWrapID_" + productIDVal).offset().top;
		var basketX 					= $("#basketTitleWrap").offset().left;
		var basketY 					= $("#basketTitleWrap").offset().top;
		var gotoX 						= basketX - productX;
		var gotoY 						= basketY - productY;
		var newImageWidth 			= $("#productImageWrapID_" + productIDVal).width() / 3;
		var newImageHeight			= $("#productImageWrapID_" + productIDVal).height() / 3;

				$.ajax({
					type: "POST",
					url: "modules/basket.php",
					data: { productID: productIDVal, productType: productTypeVal, productRegtime: productRegtimeVal, productName: ProductName, action: "dodaj"},
					success: function(theResponse) {
						$("li#li_map img").animate({opacity:0.4},150).animate({opacity:1},150);
						$("#BasketResponse").animate({opacity:0.01},1);

						if (theResponse == "domain_error") {
							$('#'+id).before('<span class="red">Ta domena juz jest w koszyku</span>').remove();
							$('.'+id).addClass('error').css({'width':'180px'}).fadeIn();
						} else if (theResponse == "domain_added") {
							$('#'+id).before('<span class="green">Dodano do koszyka</span>').remove();
							$('.'+id).addClass('valid').css({'width':'180px'}).fadeIn();
						} else if (theResponse == "system_error") {
							$('#'+id).before('<span class="red">Błąd systemu.<br /> Prosimy o kontakt.</span>').remove();;
							$('.'+id).addClass('error').fadeIn();
						} else if (theResponse == "time_error") {
							$("."+ProductName).show().addClass("error").html("Nie możesz dodać kilku<br />usług w tym samym czasie!");
						} else if (theResponse == "full_basket") {
							$('#'+id).before('<span class="red">Koszyk jest zapałeniony</span>').remove();
							$('.'+id).addClass('error').fadeIn();
						}

					}
				});
				$('.add').live('click',function(){
			$(this).hide();
		});
	});



	//==================================
	// Dodawanie produktów do koszyka - strona główna
	//==================================
	$(".productPriceWrapRightHome a").click(function() {
		var productIDValSplitter 	= (this.id).split("_");
		var productIDVal 				= productIDValSplitter[1];
		var productRegtimeVal 		= productIDValSplitter[3];
		var productTypeVal 			= productIDValSplitter[2];
		var ProductName				= $(this).attr('title');
		var productX 					= $("#productImageWrapID_" + productIDVal).offset().left;
		var productY 					= $("#productImageWrapID_" + productIDVal).offset().top;
		var basketX 					= $("#basketTitleWrap").offset().left;
		var basketY 					= $("#basketTitleWrap").offset().top;
		var gotoX 						= basketX - productX;
		var gotoY 						= basketY - productY;
		var newImageWidth 			= $("#productImageWrapID_" + productIDVal).width() / 3;
		var newImageHeight			= $("#productImageWrapID_" + productIDVal).height() / 3;

		$.ajax({
			type: "POST",
			url: "modules/basket.php",
			data: { productID: productIDVal, productType: productTypeVal, productRegtime: productRegtimeVal, productName: ProductName, action: "dodaj"},
			success: function(theResponse) {
				$("li#li_map img").animate({opacity:0.4},150).animate({opacity:1},150);
				$("#BasketResponse").animate({opacity:0.01},1);
				if (theResponse == "hosting_added") {
					//$("#BasketResponse").addClass("valid").html("Usługa została dodana.");
					$("."+ProductName).show().addClass("valid").html("Dodano do koszyka");
				} else if (theResponse == "full_hosting") {
					//$("#BasketResponse").addClass("error").html("Usługa hostingowa<br /> znajduje się już w koszyku.");
					$("."+ProductName).show().addClass("error").html("Hosting już jest w koszyku.");
				} else if (theResponse == "system_error") {
					$("."+ProductName).show().addClass("error").html("Błąd. Prosimy o kontakt.");
				} else if (theResponse == "time_error") {
					$("#BasketResponse").addClass("error").html("Nie możesz dodać kilku<br />usług w tym samym czasie!");
				} else if (theResponse == "full_basket") {
					$("#BasketResponse").addClass("error").html("Twój koszyk jest pełny!");
				}
				$("#BasketResponse").animate({opacity:1},800);
				setTimeout(function(){
					$("#BasketResponse").animate({opacity:0.01},800).removeClass("error").removeClass("valid").html("");
					$("."+ProductName).hide('slow').removeClass("error").removeClass("valid").html("");
				}, 5000);


			}
		});

		$('.add').click(function(){
			$(this).hide();
		});
	});

	//==================================
	// Usuwanie z koszyka
	//==================================
	$(".basketItemsWrap ul li img").live("click", function(event) {
		var productTimeValSplitter = (this.id).split("_");
		var productTimeVal = productTimeValSplitter[1];
		$.ajax({
			type: "POST",
			url: "modules/basket.php",
			data: { Time: productTimeVal, action: "usun"},
			success: function(theResponse) {
				var ResponseData = (theResponse).split("_");
				var elements = ResponseData[0];

				if (elements == 0) {
					jQuery("#BasketContent, .submit").animate({opacity:0.01},300);
					setTimeout(function(){
						$("#BasketContent").html('<p><div class="error">Brak produktów w Twoim koszyku.</div></p>');
						$(".submit").css("display","none");
						$(".error").corner("6px");
					},300);
					setTimeout(function(){
						$("#BasketContent").animate({opacity:1},300);
					},100);
				} else if (elements != 1) {
					jQuery("#codepromo label, #codepromo input, #PromoCodeInfo").animate({opacity:0.01},300);
					setTimeout(function(){
						$("#codepromo label, #codepromo input").css("display","none");
						$("#PromoCodeInfo").css("display","block");
					},300);
					setTimeout(function(){
						$("#PromoCodeInfo").animate({opacity:1},300);
					},100);
				} else {
					jQuery("#codepromo label, #codepromo input, #PromoCodeInfo").animate({opacity:0.01},300);
					setTimeout(function(){
						$("#codepromo label, #codepromo input").css("display","inline");
						$("#PromoCodeInfo").css("display","none");
					},300);
					setTimeout(function(){
						$("#codepromo label, #codepromo input").animate({opacity:1},300);
					},100);
				}

				$("#productTime_" + productTimeVal).animate({opacity:0},800).css({'background' : '#F7DAD8'}).hide(400);
				$("#prices").html('<div class="netto">Cena netto: ' + ResponseData[1] + ' PLN</div><div class="brutto">Cena brutto: ' + ResponseData[2] + ' PLN</div>');

				if (ResponseData[3]) {
					$('#hosting-price').html(ResponseData[3]);
					$('#org-price').remove();
					$('#host-price').remove();
				}
			}
		});
	});

	$(".basketItemsWrap ul li select").live("change", function(event) {
		var value = this.value;
		var id = this.name;
		var time = id.split('_');

		$.ajax({
			type: "POST",
			url: "modules/basket.php",
			data: { time: time[1], value: value, action: "regtime"},
			success: function(theResponse) {
				var ResponseData = (theResponse).split("_");

				// Zamówienie nie istnieje
				if (ResponseData[1] == '0')
				{
					var elements = ResponseData[0];
					// Gdy koszyk pusty
					if (elements == 0) {
						jQuery("#BasketContent, .submit").animate({opacity:0.01},300);
						setTimeout(function(){
							$("#BasketContent").html('<p><div class="error">Brak produktów w Twoim koszyku.</div></p>');
							$(".submit").css("display","none");
							$(".error").corner("6px");
						},300);
						setTimeout(function(){
							$("#BasketContent").animate({opacity:1},300);
						},100);
					}
					// W koszyku jest jeszcze cos innego
					else
					{
						$('#productTime_'+time[1]).html('Produkt nie istnieje w koszyku');
						$("#prices").html('<div class="netto">Cena netto: ' + ResponseData[2] + ' PLN</div><div class="brutto">Cena brutto: ' + ResponseData[3] + ' PLN</div>');
					}
				}
				// Dla istniejącego zamówienia
				else
				{
					$("#prices").html('<div class="netto">Cena netto: ' + ResponseData[1] + ' PLN</div><div class="brutto">Cena brutto: ' + ResponseData[2] + ' PLN</div>');
					// Dla systuacji gdy host jest za 1 zł, ale klient zmienił okres na mniejszy niż 12 miechów, lub gdy zmienia na większy okres czasu, by otrzymac promocje
					if (ResponseData[3] == '0')
					{
						// By otrzymac promocje
						if (ResponseData[4] == '1.00')
						{
							$('#productTime_'+time[1]+' #hosting-price').html('<p id="host_promo"><img src="http://www.joi.pl/templates/images/promotion.png"></p><span id="org-price">'+ResponseData[5]+' PLN</span> 1.00 PLN');
						}
						// Rezygnacja z promocji
						else
						{
							$('#productTime_'+time[1]+' #hosting-price').html(ResponseData[4] + ' PLN');
						}
					}

					// Aktuzaliacja wyjściowej ceny hostingu, gdy klient korzysta z promocji
					$('#productTime_'+time[1]+' #org-price').html(ResponseData[5] + ' PLN');

					var PromoTime = ResponseData[6]/3;

					if (PromoTime < 1)
					{
						$('#msc-promo-div').html('');
					}
					else if ($('#productTime_'+time[1]+' #msc-promo').length)
					{
						// Aktualizacja obrazka o promocji dodatkowych miesięcy hostingu
						$('#productTime_'+time[1]+' #msc-promo').attr('src', 'templates/images/'+PromoTime+'mc.png');
					}
					else
					{
						$('#msc-promo-div').html('<img src="templates/images/'+PromoTime+'mc.png" id="msc-promo">');
					}
				}
			}
		});
	});

	// Round the prices
	Math.decimal = function(n, k) {
		var factor = Math.pow(10, k+1);
		n = Math.round(Math.round(n*factor)/10);
		return n/(factor/10);
	}

	// ============================
	// Aktualizacja cen koszyku przy promoji
	// ============================
	$("#checkCode").live("click", function() {
		var PromoCode = $('#PromoCode').val();
		var RTime = $('.basket-desc').attr('title');
		var PName = $('.basket-name').attr('title');
		var PPrice = $('.basket-price').attr('title');
		if (PromoCode == "") {
			$('#CheckResponse').text('Musisz wprowadzić kod promocyjny.').removeClass('error').removeClass('info').addClass('error').corner('6');
		} else {
			$.ajax({
				type: "POST",
				url: "pages/ajax/check-promo.php",
				data: {Code: PromoCode, RegTime: RTime, PlanName: PName, PlanPrice: PPrice},
				success: function(theResponse) {
					var RespData = theResponse.split("|");
					if (RespData[0] == "error") $('#CheckResponse').text(RespData[1]).removeClass('error').removeClass('info').addClass('error').corner('6');
					else {
						$('#CheckResponse').text('').removeClass('error').removeClass('info').corner('0');
						if (RespData[2] == "1") {
							var NettoPrice = parseFloat(RespData[3].replace(",","."));
							NettoPrice = Math.decimal(NettoPrice,2);
							var BruttoPrice = Math.decimal(1.22*NettoPrice,2);

							$('.basket-price').text(NettoPrice+' PLN');
							$('.netto').text('Cena netto: '+NettoPrice+' PLN');
							$('.brutto').text('Cena brutto: '+BruttoPrice+' PLN');

							if (RespData[5] == "1") var jedn = "%";
							else var jedn = " PLN";
							$('#CheckResponse').html('<strong>Nazwa promocji:</strong> '+RespData[1]+'<br /><strong>Typ promocji:</strong> Obniżka ceny pakietu o '+RespData[4]+jedn).removeClass('error').removeClass('info').addClass('info').corner('6');
						} else if (RespData[2] == "2") {
							var NettoPrice = parseFloat(RespData[3].replace(",","."));
							NettoPrice = Math.decimal(NettoPrice,2);
							var BruttoPrice = Math.decimal(1.22*NettoPrice,2);

							$('.basket-price').text(NettoPrice+' PLN');
							$('.netto').text('Cena netto: '+NettoPrice+' PLN');
							$('.brutto').text('Cena brutto: '+BruttoPrice+' PLN');
							$('#CheckResponse').html('<strong>Nazwa promocji:</strong> '+RespData[1]+'<br /><strong>Typ promocji:</strong> Nowa cena pakietu - '+RespData[4]+' PLN').removeClass('error').removeClass('info').addClass('info').corner('6');
						} else if (RespData[2] == "3") {
							$('.basket-desc').html('12 mc<br />+ '+RespData[3]+' mc gratis');
							$('#CheckResponse').html('<strong>Nazwa promocji:</strong> '+RespData[1]+'<br /><strong>Typ promocji:</strong> Darmowe przedłużenie ważności konta o '+RespData[3]+' miesięcy').addClass('info').corner('6');
						} else if (RespData[2] == "4") {
							if (RespData[4] == "1") var jedn1 = "%";
							else var jedn1 = " GB";

							if (RespData[6] == "1") var jedn2 = "%";
							else var jedn2 = " GB";
							$('#CheckResponse').html('<strong>Nazwa promocji:</strong> '+RespData[1]+'<br /><strong>Typ promocji:</strong> Darmowa zmiana parametrów konta:<br />Pojemność o '+RespData[3]+jedn1+'<br />Transfer o '+RespData[5]+jedn2).removeClass('error').removeClass('info').addClass('info').corner('6');
						}
					}
				}
			});
		}
	});


	//==================================
	// Nawigacja Paneli Klienta
	//==================================
	$(".panel_loader").live("click", function(event) {
		$('#fix-left').removeClass("full-content");
		$('#fix-right').css("display","inline");
		var pageName = (this.id);
		if (pageName == "dane_klienta") {
			var pageTitle = "Moje dane";
		} else if (pageName == "faktury") {
			var pageTitle = "Moje faktury";
		} else if (pageName == "hosting") {
			var pageTitle = "Moje serwery";
		} else if (pageName == "domeny") {
			var pageTitle = "Domeny";
		} else if (pageName == "inbox") {
			var pageTitle = "Wiadomości";
		} else if (pageName == "statystyki") {
			var pageTitle = "Statystyki";
		} else {
			var pageTitle = "Panel klienta";
		}

		$('#panel-content').html('<p class="center preloader"><img src="templates/images/icon/ajax-loader.gif" alt="" /><br />Wczytywanie danych...</p>');
		$('#panel-content').load("pages/panel.php?panel_page="+pageName);
		$('#service').html(pageTitle);
	});

	//==================================
	// Różne
	//==================================
	$("#BlockIE").css("opacity", "0.93");
	//$(".tip").simpletooltip();
	$(".tip").tipTip();
	$("select.nice, input:checkbox.nice, input:radio.nice, input:file.nice").uniform();
	$(".small").css("opacity", "0.6");
	$("#simpleTooltip").animate({opacity:0.7},1000);
	$("#progressBar1").progressBar({showText:false});
	$('.schowaj').animate({opacity:0.01},3500).hide(800);
	$('#s-domains2').slideDown(800);


	// ============================
	// Włączanie/Wyłączanie Cache
	// ============================
	$("#SwitchCache input[type=checkbox]").live("click", function(event) {
		$.ajax({
			type: "POST",
			url: "pages/ajax/cloud-switch-cache.php",
			data: {Action: "Switch"},
			success: function(theResponse) {
				$("#SwitchCache label span.switch").fadeOut("fast");
				$("#SwitchCache label span.switch").html("Uaktualniono!");
				$("#SwitchCache label span.switch").fadeIn("fast");
				$("#ClearCache").removeClass().fadeOut("fast");
				$("#ClearCache .o .m strong").html("Wyczyść Cache");
				$("#ClearCache").addClass("RedButton").fadeIn("fast");
			}
		});
	});


	$('#Cloud #CloudStart').click(function() {
		$('#Cloud #CloudDynamic').slideToggleWidth();
	});

	jQuery.fn.extend({
		slideRight: function() {
			return this.each(function() {
				$(this).animate({width: 'show'});
				$('#Cloud #CloudStart').removeClass('inactive').addClass('active');
			});
		},
		slideLeft: function() {
			return this.each(function() {
				$(this).animate({width: 'hide'});
				$('#Cloud #CloudStart').removeClass('active').addClass('inactive');
			});
		},
		slideToggleWidth: function() {
			return this.each(function() {
				var el = $(this);
				if (el.css('display') == 'none') {
					el.slideRight();
				} else {
					el.slideLeft();
				}
			});
		}
	});

	// ============================
	// Czyszczenie Cache
	// ============================
	$("#ClearCache").live("click", function(event) {
		$.ajax({
			type: "POST",
			url: "pages/ajax/cloud-clear-cache.php",
			data: {Action: "Clear"},
			success: function(theResponse) {
				$("#ClearCache").removeClass("RedButton").fadeOut("fast");
				$("#ClearCache .o .m strong").html("Uaktualniono!");
				$("#ClearCache").addClass("GrayButton").fadeIn("fast");
			}
		});
	});

	//==================================
	// Górna nawigazja
	//==================================
	$("#li_home a").mouseover(function(){$("#li_home a img").animate({opacity:0.4},300);});
	$("#li_home a").mouseout(function(){$("#li_home a img").animate({opacity:1},300);});
	$("#li_map a").mouseover(function(){$("#li_map a img").animate({opacity:0.4},300);});
	$("#li_map a").mouseout(function(){$("#li_map a img").animate({opacity:1},300);});
	$("#li_help a").mouseover(function(){$("#li_help a img").animate({opacity:0.4},300);});
	$("#li_help a").mouseout(function(){$("#li_help a img").animate({opacity:1},300);});
	$("#li_contact a").mouseover(function(){$("#li_contact a img").animate({opacity:0.4},300);});
	$("#li_contact a").mouseout(function(){$("#li_contact a img").animate({opacity:1},300);});

	//==================================
	// Buttony po zalogowaniu do panelu klienta
	//==================================
	$("#logino ul #wyloguj a").mouseover(function(){$("#logino ul #wyloguj a img").animate({opacity:0.01},300);});
	$("#logino ul #wyloguj a").mouseout(function(){$("#logino ul #wyloguj a img").animate({opacity:1},300);});
	$("#logino ul #uslugi a").mouseover(function(){$("#logino ul #uslugi a img").animate({opacity:0.01},300);});
	$("#logino ul #uslugi a").mouseout(function(){$("#logino ul #uslugi a img").animate({opacity:1},300);});

	//==================================
	// Buttony logowania
	//==================================
	$(".UserLoginSubmit, .UserLoginSubmit2").mouseover(function(){$(this).animate({opacity:0.4},300);});
	$(".UserLoginSubmit, .UserLoginSubmit2").mouseout(function(){$(this).animate({opacity:1},300);});

	//==================================
	// SlideShow z ofertą na stronie głównej
	//==================================
	var currentPosition = 0;
	var slideWidth = 760;
	var slides = $('.slide');
	var numberOfSlides = slides.length;
	$('#slidesContainer').css('overflow', 'hidden');
		slides
		.wrapAll('<div id="slideInner"></div>')
		.css({
			'float' : 'left',
			'width' : slideWidth
		});
	$('#slideInner').css('width', slideWidth * numberOfSlides);
	$('#slideshow')
		.prepend('<a class="control tip" id="leftControl" title="Kliknij aby przewinąć w lewo"> </a>')
		.append('<a class="control tip" id="rightControl" title="Kliknij aby przewinąć w prawo"> </a>');
		manageControls(currentPosition);
	$('.control')
		.bind('click', function(){
			currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
			manageControls(currentPosition);
		$('#slideInner').animate({
			'marginLeft' : slideWidth*(-currentPosition)
		});
	});
	function manageControls(position){
		if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
		if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
	}
	$("a.tab").click(function () {
		$(".active").removeClass("active");
		$(this).addClass("active");
		$(".slidetable").animate({opacity:0},100).slideUp();
		var content_show = $(this).attr("rel");
		$("#"+content_show).animate({opacity:0},10).slideToggle("slow").animate({opacity:1},300);
	});
	$(".paging").show();
	$(".paging a:first").addClass("active");
	var imageWidth = $(".window").width();
	var imageSum = $(".image_reel img").size();
	var imageReelWidth = imageWidth * imageSum;
	$(".image_reel").css({'width' : imageReelWidth});
	rotate = function(){
		var triggerID = $active.attr("rel") - 1;
		var image_reelPosition = triggerID * imageWidth;
		$(".paging a").removeClass('active');
		$active.addClass('active');
		$(".image_reel").animate({
			left: -image_reelPosition
		}, 850 );

	};
	rotateSwitch = function(){
		play = setInterval(function(){
			$active = $('.paging a.active').next();
			if ( $active.length === 0) {
				$active = $('.paging a:first');
			}
			rotate();
		}, 6000);
	};
	rotateSwitch();
	$(".image_reel a").hover(function() {
		clearInterval(play);
	}, function() {
		rotateSwitch();
	});
	$(".paging a").click(function() {
		$active = $(this);
		clearInterval(play);
		rotate();
		rotateSwitch();
		return false;
	});

});

//==================================
// Animowany Collapse do całej strony
//==================================
var animatedcollapse={
	divholders: {},
	divgroups: {},
	statusholders: {},
	lastactiveingroup: {},
	show:function(divids){
		if (typeof divids=="object"){
			for (var i=0; i<divids.length; i++)
				this.showhide(divids[i], "show")
		}
		else
			this.showhide(divids, "show")
	},
	hide:function(divids){
		if (typeof divids=="object"){
			for (var i=0; i<divids.length; i++)
				this.showhide(divids[i], "hide")
		}
		else
			this.showhide(divids, "hide")
	},
	toggle:function(divid){
		if (typeof divid=="object")
			divid=divid[0]
		this.showhide(divid, "toggle")
	},
	addDiv:function(divid, attrstring){
		this.divholders[divid]=({id: divid, $divref: null, attrs: attrstring})
		this.divholders[divid].getAttr=function(name){
			var attr=new RegExp(name+"=([^,]+)", "i")
			return (attr.test(this.attrs) && parseInt(RegExp.$1)!=0)? RegExp.$1 : null
		}
		this.currentid=divid
		return this
	},
	showhide:function(divid, action){
		var $divref=this.divholders[divid].$divref
		if (this.divholders[divid] && $divref.length==1){
			var targetgroup=this.divgroups[$divref.attr('groupname')]
			if ($divref.attr('groupname') && targetgroup.count>1 && (action=="show" || action=="toggle" && $divref.css('display')=='none')){ //If current DIV belongs to a group
				if (targetgroup.lastactivedivid && targetgroup.lastactivedivid!=divid)
					this.slideengine(targetgroup.lastactivedivid, 'hide')
					this.slideengine(divid, 'show')
				targetgroup.lastactivedivid=divid
			}
			else{
				this.slideengine(divid, action)
			}
		}
	},
	slideengine:function(divid, action){
		var $divref=this.divholders[divid].$divref
		if (this.divholders[divid] && $divref.length==1){
			var animateSetting={height: action}
			if ($divref.attr('fade'))
				animateSetting.opacity=action
			$divref.animate(animateSetting, $divref.attr('speed')? parseInt($divref.attr('speed')) : 500, function(){
				if (animatedcollapse.ontoggle){
					try{
						animatedcollapse.ontoggle(jQuery, $divref.get(0), $divref.css('display'))
					}
					catch(e){
						alert("An error exists inside your \"ontoggle\" function:\n\n"+e+"\n\nAborting execution of function.")
					}
				}
			})
			return false
		}
	},
	generatemap:function(){
		var map={}
		for (var i=0; i<arguments.length; i++){
			if (arguments[i][1]!=null){
				map[arguments[i][0]]=arguments[i][1]
			}
		}
		return map
	},
	init:function(){
		var ac=this
		jQuery(document).ready(function($){
			animatedcollapse.ontoggle=animatedcollapse.ontoggle || null
			var urlparamopenids=animatedcollapse.urlparamselect()
			var persistopenids=ac.getCookie('acopendivids')
			var groupswithpersist=ac.getCookie('acgroupswithpersist')
			if (persistopenids!=null)
				persistopenids=(persistopenids=='nada')? [] : persistopenids.split(',')
			groupswithpersist=(groupswithpersist==null || groupswithpersist=='nada')? [] : groupswithpersist.split(',')
			jQuery.each(ac.divholders, function(){
				this.$divref=$('#'+this.id)
				if ((this.getAttr('persist') || jQuery.inArray(this.getAttr('group'), groupswithpersist)!=-1) && persistopenids!=null){
					var cssdisplay=(jQuery.inArray(this.id, persistopenids)!=-1)? 'block' : 'none'
				}
				else{
					var cssdisplay=this.getAttr('hide')? 'none' : null
				}
				if (urlparamopenids[0]=="all" || jQuery.inArray(this.id, urlparamopenids)!=-1){
					cssdisplay='block'
				}
				else if (urlparamopenids[0]=="none"){
					cssdisplay='none'
				}
				this.$divref.css(ac.generatemap(['height', this.getAttr('height')], ['display', cssdisplay]))
				this.$divref.attr(ac.generatemap(['groupname', this.getAttr('group')], ['fade', this.getAttr('fade')], ['speed', this.getAttr('speed')]))
				if (this.getAttr('group')){
					var targetgroup=ac.divgroups[this.getAttr('group')] || (ac.divgroups[this.getAttr('group')]={})
					targetgroup.count=(targetgroup.count||0)+1
					if (jQuery.inArray(this.id, urlparamopenids)!=-1){
						targetgroup.lastactivedivid=this.id
						targetgroup.overridepersist=1
					}
					if (!targetgroup.lastactivedivid && this.$divref.css('display')!='none' || cssdisplay=="block" && typeof targetgroup.overridepersist=="undefined")
						targetgroup.lastactivedivid=this.id
					this.$divref.css({display:'none'})
				}
			})
			jQuery.each(ac.divgroups, function(){
				if (this.lastactivedivid && urlparamopenids[0]!="none")
					ac.divholders[this.lastactivedivid].$divref.show()
			})
			if (animatedcollapse.ontoggle){
				jQuery.each(ac.divholders, function(){
					animatedcollapse.ontoggle(jQuery, this.$divref.get(0), this.$divref.css('display'))
				})
			}
			$(window).bind('unload', function(){
				ac.uninit()
			})
		})
	},
	uninit:function(){
		var opendivids='', groupswithpersist=''
		jQuery.each(this.divholders, function(){
			if (this.$divref.css('display')!='none'){
				opendivids+=this.id+','
			}
			if (this.getAttr('group') && this.getAttr('persist'))
				groupswithpersist+=this.getAttr('group')+','
		})
		opendivids=(opendivids=='')? 'nada' : opendivids.replace(/,$/, '')
		groupswithpersist=(groupswithpersist=='')? 'nada' : groupswithpersist.replace(/,$/, '')
		this.setCookie('acopendivids', opendivids)
		this.setCookie('acgroupswithpersist', groupswithpersist)
	},
	getCookie:function(Name){
		var re=new RegExp(Name+"=[^;]*", "i");
		if (document.cookie.match(re))
			return document.cookie.match(re)[0].split("=")[1]
		return null
	},
	setCookie:function(name, value, days){
		if (typeof days!="undefined"){
			var expireDate = new Date()
			expireDate.setDate(expireDate.getDate()+days)
			document.cookie = name+"="+value+"; path=/; expires="+expireDate.toGMTString()
		}
		else //else if this is a session only cookie
			document.cookie = name+"="+value+"; path=/"
	},
	urlparamselect:function(){
		window.location.search.match(/expanddiv=([\w\-_,]+)/i)
		return (RegExp.$1!="")? RegExp.$1.split(",") : []
	}
}

//==================================
// Blokowanie błedów JS
//==================================
// function blockError(){return true;}
// window.onerror = blockError;
