
$(function() {

	$(".widgetMainMenu li.lvl1").bind('mouseenter', function() {
		var  $this = $(this)
			,$subUl = $this.find("ul.lvl2")
			,liOffset = $this.offset()
			,liHeight = $this.height()
			,liPaddingLeft = parseInt($this.css('padding-left')) || 0
		;

		var width = 0;
		$subUl.find("li.lvl2").each(function() {
			width += $(this).width();
		});

		$subUl.css({
			 width: width // IE
			,top: liOffset.top + liHeight
			,left: liOffset.left + liPaddingLeft
		});
	});


	$(".widgetSearch input[name=q], .loginForm input[name=login], .loginForm input[name=password], .newsletterForm input[name=email], .searchPage input[type=text]").focus(function() {
		if (this.value == this.defaultValue) {
			$(this).val('');
		}
	}).blur(function() {
		if (!this.value.length) {
			$(this).val(this.defaultValue);
		}
	});

	/*$(".loginForm input[name=password]").focus(function() {
		if (this.value == this.defaultValue) {
			var $this = $(this);
			$this.clone(true).attr('type', 'password').val('').insertBefore(this).focus();
			$this.remove();
		}
	}).blur(function() {
		if (!this.value.length) {
			var $this = $(this);
			$this.clone(true).attr('type', 'text').val(this.defaultValue).insertBefore(this);
			$this.remove();
		}
	});*/


	Cufon.replace(".columnL h2.title, .columnR .boxTagi h2.title, .columnRight .boxTagi h2.title, .columnRight .boxMenu h2.title, .columnR .boxKonto h2.title, .columnRight .boxKonto h2.title, .columnR .boxForum h2.title, .columnR .boxNewsletter h2.title, .columnR .boxContact h2.title, .row3 h2.title, .columnLeft h2.title, #content .columnRight .boxMenu li a, .searchPage .searchInput h4");


	// jquery.tools
	if (jQuery.isFunction(jQuery.fn.scrollable)) {
		$(".boxScrollable div.scrollable").scrollable({
			 size: 5
			,clickable: false
			,keyboard: false
		});

		$(".wideBox div.scrollable").scrollable({
			 size: 11
			,clickable: false
			,keyboard: false
		});
	}

	if (jQuery.isFunction(jQuery.fn.tooltip)) {
		$(".boxKategorie .items a").tooltip({
			 tip: "#boxKategorieTooltip"
			,position: 'center left'
			,offset: [0, -10]
			,onShow: function() {
				$("#boxKategorieTooltip").wrapInner('<div class="b1" style="display: block;" />').wrapInner('<div class="b2" style="display: block;" />');
			}
		});

		var $tooltipImageActionBox = $("#tooltipImage .actionBox").clone(true);
		var tooltipConfig = {
			 tip: "#tooltipImage"
			,position: 'bottom right'
			,offset: [-45, -45]
			,lazy: false
			//,predelay: 50
			,onBeforeShow: function(e, offset) {
				var  $ttip = this.getTip()
					,$img = this.getTrigger()
					,src = $img.parent().nextAll("input[name=ttip_image]").val()
					,href = $img.parent().nextAll("input[name=ttip_notes]").val()
					,$triggerAnchor = $img.parent("a")
				;

				if ($triggerAnchor.length) {
					$ttip.find("img").attr('src', src).wrap(
						$("<a />").attr('href', $triggerAnchor.attr('href')).click(function(e) {
							if ($triggerAnchor.attr('rel') == 'fancybox') {
								e.preventDefault();
								$triggerAnchor.trigger('click');
							}
						})
					);
				}
				else {
					$ttip.find("img").attr('src', src);
				}
				$ttip.find("a.notes").attr('href', href);
			}
			,onBeforeHide: function() {
				$("#tooltipImage .actionBox").replaceWith($tooltipImageActionBox.clone(true));
				var $img = $("#tooltipImage img").attr('src', '');
				if ($img.parent().is('a')) {
					$img.unwrap();
				}
			}
		};

		if ($(".arrangementItemsRow, .galleryItemsRow, .pageProductCatalog .productItemsRow, .pageCompany .productItemsRow").length) {
			var  $firstRow = $(".arrangementItemsRow:first-child, .galleryItemsRow:first-child, .pageProductCatalog .productItemsRow:first-child")
				,$firstRowFirst = $firstRow.find(".arrangementItem:eq(0) img, .galleryItem:eq(0) img, .productItem:eq(0) img")
				,$firstRowLast = $firstRow.find(".arrangementItem:eq(4) img, .galleryItem:eq(5) img, .productItem:eq(4) img")
				,$firstRowRemaining = $firstRow.find(".arrangementItem img, , .galleryItem img, .productItem img").not($firstRowFirst.add($firstRowLast))

				,$lastRow = $(".arrangementItemsRow:last-child:not(:first-child), .galleryItemsRow:last-child:not(:first-child), .pageProductCatalog .productItemsRow:last-child:not(:first-child)")
				,$lastRowFirst = $lastRow.find(".arrangementItem:eq(0) img, .galleryItem:eq(0) img, .productItem:eq(0) img")
				,$lastRowLast = $lastRow.find(".arrangementItem:eq(4) img, .galleryItem:eq(5) img, .productItem:eq(4) img")
				,$lastRowRemaining = $lastRow.find(".arrangementItem img, .galleryItem img, .productItem img").not($lastRowFirst.add($lastRowLast))

				,middleRows = $(".arrangementItemsRow:not(:first-child, :last-child), .pageCompany .productItemsRow, .galleryItemsRow:not(:first-child, :last-child), .pageProductCatalog .productItemsRow:not(:first-child, :last-child)")
				,$middleRowFirst = middleRows.find(".arrangementItem:eq(0) img, .productItem:eq(0) img, .galleryItem:eq(0) img, .productItem:eq(0) img")
				,$middleRowLast = middleRows.find(".arrangementItem:eq(4) img, .productItem:eq(5) img, .galleryItem:eq(5) img, .productItem:eq(4) img")
				,$middleRowRemaining = middleRows.find(".arrangementItem img, .productItem img, .galleryItem img, .productItem img").not($middleRowFirst.add($middleRowLast))
			;
			$firstRowFirst.tooltip($.extend({}, tooltipConfig, {position: 'bottom right', offset: [-45, -45]})).tooltipCorrectPosition();
			$firstRowLast.tooltip($.extend({}, tooltipConfig, {position: 'bottom left', offset: [-45, 45]})).tooltipCorrectPosition();
			$firstRowRemaining.tooltip($.extend({}, tooltipConfig, {position: 'bottom center', offset: [-45, 0]})).tooltipCorrectPosition();

			$lastRowFirst.tooltip($.extend({}, tooltipConfig, {position: 'top right', offset: [45, -45]})).tooltipCorrectPosition();
			$lastRowLast.tooltip($.extend({}, tooltipConfig, {position: 'top left', offset: [45, 45]})).tooltipCorrectPosition();
			$lastRowRemaining.tooltip($.extend({}, tooltipConfig, {position: 'top center', offset: [45, 0]})).tooltipCorrectPosition();

			$middleRowFirst.tooltip($.extend({}, tooltipConfig, {position: 'center right', offset: [0, -45]})).tooltipCorrectPosition();
			$middleRowLast.tooltip($.extend({}, tooltipConfig, {position: 'center left', offset: [0, 45]})).tooltipCorrectPosition();
			$middleRowRemaining.tooltip($.extend({}, tooltipConfig, {position: 'center center', offset: [0, 0]})).tooltipCorrectPosition();
		}


		$(".offerListItem .imageContainer img").tooltip($.extend({}, tooltipConfig, {position: 'center center', offset: [0, 0]})).tooltipCorrectPosition();

		$(".pageListItemImage img").tooltip($.extend({}, tooltipConfig, {position: 'center right', offset: [0, -109]})).tooltipCorrectPosition();
	}


	$("a.sectionHide, a.sectionShow").bind('click', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,$divContents = $this.parents(".sectionBoxSlide").find(".sectionBoxContent")
		;

		if ($this.hasClass('sectionHide')) {
			$divContents.slideUp();
		}
		else {
			$divContents.slideDown();
		}

		$(this).toggleClass('sectionHide sectionShow');
	});

	$("a.subsectionHide, a.subsectionShow").bind('click', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,$divContents = $this.parents(".subsectionBoxName").next(".subsectionBoxContent")
		;

		if ($this.hasClass('subsectionHide')) {
			$divContents.slideUp();
		}
		else {
			$divContents.slideDown();
		}

		$(this).toggleClass('subsectionHide subsectionShow');
	});


	$("a.movie-delete").bind('click', function(e) {
		e.preventDefault();

		var $this = $(this);
		$this.parents(".formRow").remove();
		$("fieldset.companyVideos").find(".formRow").each(function(idx) {
			var $this = $(this);
			$this.find("label").attr('for', 'cef-videos' + idx);
			$this.find("input").attr('id', 'cef-videos' + idx);
		});
	});

	$("a.movie-new").bind('click', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,$new = $this.parents(".formRow").clone(true)
			,count = $("fieldset.companyVideos").find(".formRow").length
		;

		$new.find("label").attr('for', 'cef-videos' + count);
		$new.find("input").attr('id', 'cef-videos' + count).attr('value', '');
		$new.insertAfter($this.parents(".formRow"));
	});

	$("a.movie-move-up").bind('click', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,$formRow = $this.parents(".formRow")
			,$prev = $formRow.prev(".formRow")
		;

		if ($prev.length) {
			$formRow.insertBefore($prev);
		}
	});

	$("a.movie-move-down").bind('click', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,$formRow = $this.parents(".formRow")
			,$next = $formRow.next(".formRow:not(:last-child)")
		;

		if ($next.length) {
			$formRow.insertAfter($next);
		}
	});

	$("a.image-new").bind('click', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,$new = $this.parents(".formRowImage").clone(true)
			,count = $("fieldset.companyAbout").find(".formRowImage").length
		;

		$new.find("label").attr('for', 'cef-images' + count);
		$new.find("input").attr('id', 'cef-images' + count).attr('value', '');
		$new.insertAfter($this.parents(".formRowImage"));
	});

	$("a.file-new").bind('click', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,$new = $this.parents(".formRowFile").clone(true)
			,count = $("fieldset.companyFiles").find(".formRowFile").length
		;

		$new.find("label").attr('for', 'cef-files' + count);
		$new.find("input").attr('id', 'cef-files' + count).attr('value', '');
		$new.find(".fileDesc label").attr('for', 'cef-filesdesctiptions' + count);
		$new.find(".fileDesc input").attr('id', 'cef-filesdesctiptions' + count).attr('value', '');
		$new.insertAfter($this.parents(".formRowFile"));
	});


	$("#view-type").bind('change', function() {
		window.location = this.value;
	});


	// pokzaywanie/ukrywanie formularza komentowania
	$(".ratingsAndComments a.addCommentForm").bind('click', function(e) {
		e.preventDefault();

		$("div.addComment").slideToggle();
	});

	$(".commentList .commentTitle strong").bind('click', function(e) {
		$(this).parents(".comment").find(".commentBox").slideToggle();
	});



	//
	// aranzacja - admin
	//

	// zmiana typu produktu
	$("select[name=product_type]").bind('change', function() {
		var  $this = $(this)
			,pNumber = $this.parents(".selects_wrapper").attr('title')
		;
		$this.parents(".selects_wrapper").find(".products_select").hide().find("select").val(-1).end().end().find(".select_" + $this.val()).show();
		$("input[name=product\\[" + pNumber + "\\]\\[product_id\\]]").val('');
	});

	// zmiana produktu
	$("select[name=product_list]").bind('change', function() {
		var  $this = $(this)
			,pNumber = $this.parents(".selects_wrapper").attr('title')
			,productId = Number($this.val()) > 0 ? Number($this.val()) : ''
		;
		$("input[name=product\\[" + pNumber + "\\]\\[product_id\\]]").val(productId);
	});

	// pinezka
	$(".pageArrangementEdit .arrangementImage").delegate("div.marker", 'click', function(e) {
		var  $this = $(this)
			,pNumber = $this.text()
		;

		$("input[name^=product\\[" + pNumber + "\\]]").add($(".arrangementProducts div[title=" +  pNumber + "]")).add(this).remove();
		e.stopPropagation();
	});

	// tytuł lokalizujący pinezkę
	$(".selects_wrapper").delegate("div.markerTitle", 'click', function(e) {
		var pNumber = $(this).parent(".selects_wrapper").attr('title');
		$("div.marker.product" + pNumber).fadeOut('fast', function () {
			$(this).fadeIn('fast');
		});
	});


	// dodawanie pinezki
	var productsCount = $(".arrangementImage .marker").length || 0;
	$(".pageArrangementEdit .arrangementImage img").bind('click', function(e) {
		var  $this = $(this)
			,$container = $this.parent()
			,x = e.pageX - this.parentNode.offsetLeft
			,y = e.pageY - this.parentNode.offsetTop
		;

		// pinezka
		$("<div>")
			.text(productsCount)
			.attr('title', 'Pinezka ' + productsCount)
			.addClass('marker product' + productsCount)
			.css({left: x, top: y})
			.appendTo($container);

		// inputy z parametrami pinezki
		$("<input>").attr({
			 type: 'hidden'
			,name: 'product[' + productsCount + '][x]'
			,value: x
		}).appendTo($container);

		$("<input>").attr({
			 type: 'hidden'
			,name: 'product[' + productsCount + '][y]'
			,value: y
		}).appendTo($container);

		$("<input>").attr({
			 type: 'hidden'
			,name: 'product[' + productsCount + '][product_id]'
			,value: ''
		}).appendTo($container);

		// selecty do wyboru produktu
		$(".arrangementProducts div.set_of_selects").clone(true)
			.removeClass('set_of_selects').addClass('selects_wrapper').attr('title', productsCount)
			.prepend($("<div>").addClass('markerTitle').text('Produkt dla pinezki ' + productsCount))
			.appendTo($(".arrangementProducts"));

		++productsCount;
	});


	//
	// aranzacja - public
	//

	// pinezka
	var visibleProducts = 0;
	$(".pageArrangement div.marker").bind('click', function(e) {
		var  $this = $(this)
			,$img = $this.parent()
			,pNumber = $this.text()
			,$product = $("#product" + pNumber).css({
				 display: 'block'
				,visibility: 'hidden'
			})
			,imgOffset = $img.offset()
			,imgSize = {
				 width: $img.width()
				,height: $img.height()
			}
			,markerOffset = {
				 top: parseInt($this.css('top')) || 0
				,left: parseInt($this.css('left')) || 0
			}
			,productSize = {
				 totalWidth: $product.width()
					+ (parseInt($product.css('padding-left')) || 0) + (parseInt($product.css('padding-right')) || 0)
					+ (parseInt($product.css('border-left-width')) || 0) + (parseInt($product.css('border-right-width')) || 0)
				,totalHeight: $product.height()
					+ (parseInt($product.css('padding-top')) || 0) + (parseInt($product.css('padding-bottom')) || 0)
					+ (parseInt($product.css('border-top-width')) || 0) + (parseInt($product.css('border-bottom-width')) || 0)
				,width: $product.width()
				,height: $product.height()
				,paddingTop: parseInt($product.css('padding-top')) || 0
				,paddingBottom: parseInt($product.css('padding-bottom')) || 0
				,paddingLeft: parseInt($product.css('padding-left')) || 0
				,paddingRight: parseInt($product.css('padding-right')) || 0
				,borderTop: parseInt($product.css('border-top')) || 0
				,borderBottom: parseInt($product.css('border-bottom')) || 0
				,borderLeft: parseInt($product.css('border-left')) || 0
				,borderRight: parseInt($product.css('border-right')) || 0
			}
			,productOffset = {
				 top: imgOffset.top + markerOffset.top - productSize.totalHeight / 2
				,left: imgOffset.left + markerOffset.left - productSize.totalWidth / 2
			}
		;
		++visibleProducts;

		if (productSize.totalHeight > imgSize.height) {
			$product.css({
				 height: imgSize.height - 20 - productSize.borderTop - productSize.paddingTop - productSize.paddingBottom - productSize.borderBottom + 'px'
				,overflow: 'auto'
			});
			productOffset.top = 10
		}
		else if (productOffset.top < imgOffset.top) {
			productOffset.top = imgOffset.top + 10
		}
		else if (productOffset.top + productSize.totalHeight > imgOffset.top + imgSize.height) {
			productOffset.top = imgOffset.top + imgSize.height - productSize.totalHeight - 10
		}

		if (productSize.totalWidth > imgSize.width) {
			$product.css({
				 width: imgSize.width - 20 - productSize.borderLeft - productSize.paddingLeft - productSize.paddingRight - productSize.borderRight + 'px'
				,overflow: 'auto'
			});
			productOffset.left = 10
		}
		else if (productOffset.left < imgOffset.left) {
			productOffset.left = imgOffset.left + 10
		}
		else if (productOffset.left + productSize.totalWidth > imgOffset.left + imgSize.width) {
			productOffset.left = imgOffset.left + imgSize.width - productSize.totalWidth - 10
		}

		$product.css({
			 position: 'absolute'
			,top: productOffset.top
			,left: productOffset.left
			,'z-index': visibleProducts
			,visibility: 'visible'
		}).fadeIn('fast');
	});

	$(".arrangementProducts .product a.close").bind('click', function(e) {
		e.preventDefault();
		$(this).parents(".product").fadeOut('fast');
		--visibleProducts;
	});


	// zmiana kategorii na karuzeli
	$(".otherArrangements .selectCategory a").bind('click', function(e) {
		e.preventDefault();
		var  $this = $(this)
			,roomArrangementsIdx = $this.attr('rel')
			,scrollableApi = $(".otherArrangements .boxScrollable div.scrollable").scrollable()
			,$newItems = $("#r" + roomArrangementsIdx).children().clone()
		;

		scrollableApi.begin(1);
		scrollableApi.getItems().remove();
		scrollableApi.getItemWrap().append($newItems);
		scrollableApi.reload().end(1).begin(1);

		$this.parents(".selectCategory").find("a").removeClass('selected');
		$this.addClass('selected');
	});


	// dodawanie elementu do notesu
	$("a.notes").live('click', function(e) {
		e.preventDefault();
		var  $this = $(this)
			,$msg = $("<div>&nbsp;</div>")
		;

		$.ajax({
			 url: $this.attr('href')
			,type: "POST"
			,dataType: "json"
			,cache: false
			,beforeSend: function(XMLHttpRequest) {
				$this.unbind('click').bind('click', function(e) { e.preventDefault() });
				$msg.addClass('addNoteMsg addNoteMsgLoading').insertAfter($this);
			}
			,success: function(data, textStatus, XMLHttpRequest) {
				$this.remove();
				$msg.removeClass('addNoteMsgLoading');
				if (data.success) {
					$msg.text("Element zosta\u0142 zapisany w Twoim notesie.");
				}
				else {
					$msg.text(data.error);
				}
			}
			,error: function(XMLHttpRequest, textStatus, errorThrown) {
				$this.remove();
				$msg.removeClass('addNoteMsgLoading').txt("Podczas dodawania do notesu wyst\u0105pi\u0142 b\u0142\u0105d.");
			}
		});
	});

	// usuwanie elementu z notesu
	$("a.deleteNote").bind('click', function(e) {
		e.preventDefault();
		var  $this = $(this)
			,$msg = $("<div>&nbsp;</div>")
			,$td = $this.parent("td")
			,$tr = $this.parents("tr")
			,$tbody = $this.parents("tbody")
			,url = $this.attr('href')
		;

		$.ajax({
			 url: url
			,type: "POST"
			,dataType: "json"
			,cache: false
			,beforeSend: function(XMLHttpRequest) {
				$this.remove();
				$msg.addClass('addNoteMsg addNoteMsgLoading').appendTo($td);
			}
			,success: function(data, textStatus, XMLHttpRequest) {
				if (data.success) {
					$tr.remove();
					if (!$tbody.find("tr").length) {
						$('<td class="msg" colspan="5">Nie masz w tej chwili zapisanych żadnych notatek.</td>').appendTo($tbody);
					}
				}
				else {
					$msg.removeClass('addNoteMsgLoading').text(data.error);
				}
			}
			,error: function(XMLHttpRequest, textStatus, errorThrown) {
				$msg.removeClass('addNoteMsgLoading').txt("Podczas usuwania wyst\u0105pi\u0142 b\u0142\u0105d.");
			}
		});
	});

	// zwijanie/rozwijanie własnych notatek
	$(".ownNotes .header a").bind('click', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,text = $this.hasClass('toggleDown') ? 'Zwi\u0144' : 'Rozwi\u0144'
		;

		$this.text(text).toggleClass('toggleDown toggleUp').parents(".ownNotes").find(".content").slideToggle();
	});

	// zwijanie/rozwijanie "Twój notes - co to takiego?"
	$(".notesAbout a.toggle").bind('click', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,text = $this.hasClass('toggleDown') ? 'Zwi\u0144' : 'Dowiedz si\u0119 wi\u0119cej'
		;

		$this.text(text).toggleClass('toggleDown toggleUp').next(".content").slideToggle();
	})

	// zapisywanie własnych notatek
	$("form.ownNote").bind('submit', function(e) {
		e.preventDefault();

		var  $this = $(this)
			,$textarea = $this.find("textarea")
			,url = $this.attr('action')
		;

		$.ajax({
			 url: url
			,type: "POST"
			,data: ({
				note: $textarea.val()
			})
			,dataType: "json"
			,cache: false
			,beforeSend: function(XMLHttpRequest) {
				$this.find("textarea").attr('readonly', 'readonly').end()
					.find("input").attr('readonly', 'readonly');
			}
			,success: function(data, textStatus, XMLHttpRequest) {
				if (data.success) {
					$this.parents("div.form").hide()
						.nextAll("div.text").text($textarea.val()).show()
						.nextAll("div.actions").find("a.addOwn").text('Edytuj notatkę')
					;
				}
				else {
					alert(data.error);
				}

				$this.find("textarea").removeAttr('readonly').end()
					.find("input").removeAttr('readonly');
			}
			,error: function(XMLHttpRequest, textStatus, errorThrown) {
				$this.find("textarea").removeAttr('readonly').end()
					.find("input").removeAttr('readonly');
				alert('Podczas zapisywania wyst\u0105pi\u0142 b\u0142\u0105d.');
			}
		});
	});

	// wyświetlenie formularza dodawania własnej notatki
	$(".ownNotes a.addOwn").bind('click', function(e) {
		e.preventDefault();
		var  $this = $(this)
			,$divForm = $this.parents(".content").find("div.form").eq(0)
			,$divText = $this.parents(".content").find("div.text").eq(0).hide()
		;

		if ($divForm.is(":visible")) {
			return;
		}

		$divForm.show().find("textarea").text($divText.text());
	});

	// drukowanie notresu
	$(".notesActions a.printAll").bind('click', function(e) {
		e.preventDefault();
		$("tr.hide").removeClass('hide');
		window.print();
	});

	$(".notesActions a.printSelected").bind('click', function(e) {
		e.preventDefault();

		$(".notesContent table input[name=printRow]").each(function() {
			if (!$(this).is(":checked")) {
				$(this).parents("tr").addClass('hide');
			}
		});
		window.print();
	});

	// wysyłanie zapytania
	if (jQuery.isFunction($.fn.fancybox)) {
		$("a.sendQuestion").fancybox();
	}


	//
	// dodawanie produktu
	//

	// zmiana pomieszczenia
	$(".pageProductEdit select[name=room], .pageOfferEdit select[name=room]").bind('change', function() {
		var  $this = $(this)
		;
		$(".type_select").hide().find("select").val(-1);
		$("." + $this.val()).show();
		$("input[type=hidden][name=type]").val('');
	});

	// zmiana typu
	$(".pageProductEdit select[name=tmp_type], .pageOfferEdit select[name=tmp_type]").bind('change', function() {
		var  $this = $(this)
			,val = Number($this.val()) < 0 ? '' : $this.val()
		;
		$("input[type=hidden][name=type]").val(val);
	});
});

