﻿jQuery(document).ready(
	function($) {
		$("a#logo_link").click(
			function(event)
			{
				if ((event.ctrlKey && event.shiftKey))
					event.preventDefault();
					location.href = $(this).attr("href") + "admin/index";
			}
		);
		
		$("ul.bubblewrap").imgbubbles({ factor: 1.33 });
		
		/* Wiadomości */
		
		$("dd.read_more").live(
			"click",
			function ()
			{
				var clicked = $(this);

				$("ul#news> li > dl").each(function() { $(this).children().removeAttr("style"); });
				clicked.hide();
				clicked.next().show("slow");
			}
		);
		
		if ($("#overlay").length) {
			$("#overlay").overlay({
				mask: {
					loadSpeed: 200,
					opacity: .5,
					color: "#FFF"
				},
				load: true,
				top: "center"
			});		
		}
		
		function renderAccordion()
		{
			var oAccordionElement = $("div#accordion"), 
				oAccordionWidget,
				sAccordionHeader;
			
			oAccordionWidget = oAccordionElement.accordion({
				fillSpace: true,
				header: "h3"
			});
			if (oAccordionWidget) {
				$("div.ctrlPanel").append("<a href=\"#\" class=\"prev\">Poprzedni</a><a href=\"#\" class=\"next\">Następny</a>");
				if ($("div.ctrlPanel > a.register").length)
					$("div.ctrlPanel > a.register").button({ icons: { primary: "ui-icon-cart" } });
				$("div.ctrlPanel a.prev").button(
					{
						icons: { primary: "ui-icon-arrowthick-1-n" },
						text: false
					}
				).next().button(
					{ icons: { primary: "ui-icon-arrowthick-1-s" } }
				);
				$("div.ctrlPanel a.prev, div.ctrlPanel a.next").live(
					"click",
					function() {
						var iActiveContent	= oAccordionElement.accordion("option", "active"),
							iAccordionPanes	= oAccordionElement.children("h3").length;
						
						if (iActiveContent < 0)
							iActiveContent = 0;
						if (iActiveContent > iAccordionPanes)
							iActiveContent = --iAccordionPanes;
						if ($(this).hasClass("prev"))
							oAccordionElement.accordion("activate", --iActiveContent);
						else
							oAccordionElement.accordion("activate", ++iActiveContent);
					}
				)
				$("div#accordion a[href^=\"http://\"]").each(function(index, element) {
					$(this).attr("target", "_new");
				});
			}
		}
		
		function renderTreeView(isDynamic)
		{
			var  oCatOffersTV	= new YAHOO.widget.TreeView("treeView");
			
			if (isDynamic) {
				oCatOffersTV.setDynamicLoad(function (node, fnLoadComplete) {
					var nodeId = node.data.id;
					
					YAHOO.util.Connect.asyncRequest(
						"GET",
						"/admin/nodes/view/id/" + nodeId + "/format/json",
						{
							success: function (oResponse) {
								var lang = YAHOO.lang,
									oResult;
								
								if (oResponse.responseText !== undefined) {
									try {
										oResult = lang.JSON.parse(oResponse.responseText);
										
										if (lang.isArray(oResult.NodesSet.Nodes)) {
											for (var i = 0, j = oResult.NodesSet.Nodes.length; i < j; i++)
												new YAHOO.widget.TextNode(oResult.NodesSet.Nodes[i], node, false);
										}
										oResponse.argument.fnLoadComplete();
									} 
									catch (e) { alert("Błąd podczas parsowania węzłów podrzędnych"); }
									oResponse.argument.fnLoadComplete();
								}
							},
							failure: function (oResponse) {
								if (oResponse.responseText !== undefined) {
									oResponse.argument.fnLoadComplete();
									alert("Błąd przy pobieraniu węzłów podrzędnych " + oResponse.argument.node.label.toUpperCase());
								}
							},
							argument: {
								"node": node,
								"fnLoadComplete": fnLoadComplete
							}
						}
					);
				});
			}
			oCatOffersTV.render();
			oCatOffersTV.subscribe(
				"expandComplete",
				function (node)
				{
					var aSection	= new RegExp(/.*(lato|zima|studenci|firma|galeria).*/).exec(location.pathname),
						iExpandedId = YAHOO.util.Cookie.getSub("tv", aSection[aSection.length-1]),
						oExpanded;
					
					if (!isNaN(iExpandedId)) {
						if (iExpandedId && (node.data.id != iExpandedId)) {
							if (oExpanded = oCatOffersTV.getNodeByProperty("id", iExpandedId)) {
								oExpanded.expand();
							}
						}
					} else {
						if (node.getElId() != iExpandedId) {
							if (oExpanded = oCatOffersTV.getNodeByElement(document.getElementById(iExpandedId))) {
								oExpanded.expand();
							}
						}
					}
				}
			)
			oCatOffersTV.subscribe(
				"expand",
				function(node)
				{
					var aSection	= new RegExp(/.*(lato|zima|studenci|firma|galeria).*/).exec(location.pathname),
						iNodeId		= (node.data.id !== undefined) ? node.data.id : node.getElId(),
						oNow		= new Date(),
						iNextWeek	= oNow.getTime() + 7 * 24 * 60 * 60 * 1000; 
					
					YAHOO.util.Cookie.setSub(
						"tv",
						aSection[aSection.length-1],
						iNodeId,
						{
							path: "/",
							expires: new Date(iNextWeek)
						}
					);
				}
			);
		}
		
		function ajaxifyForm()
		{
			var ajaxifzForm = function() {
					var options = {
							target: "div#yui-main div.yui-b",
							success: function (responseText, statusText, xhr, $form) { ajaxifyForm(); }
						};
				
					$("form").ajaxForm(options);
				};
				
			$(document).ready(ajaxifzForm);
		}
		
		if ($("div#accordion").length) {
			renderAccordion();
		}
		
		oScrollableNearestOffers = $(".scrollableNearestOffers");
		if (oScrollableNearestOffers.length && oScrollableNearestOffers.find(".items > div").length > 1) {
			oScrollableNearestOffers
				.css( { "height": "94px" } )
				.scrollable({
					circular: true,
					mousewheel: true
				})
				.navigator()
				.autoscroll( { interval: 5000 } );
		}
		
		oScrollablePlaces = $(".scrollablePlaces");
		if (oScrollablePlaces.length && oScrollablePlaces.find(".items > div").length > 1) {
			oScrollablePlaces
				.css( { "height": "194px" } )
				.scrollable({
					circular: true,
					mousewheel: true
				})
				.navigator()
				.autoscroll( { interval: 7500 } );
		}
		
		oScrollable = $(".scrollable");
		if (oScrollable.length) {
			switch (oScrollable.parent().attr("id")) {
				case "weather":
					oScrollable.css({
						"height": "62px",
						"overflow": "hidden",
					});
					oScrollable
						.scrollable({ circular: true, mousewheel: true})
						.navigator()
						.autoscroll({ interval: 5000 });
					break;
				
				case "films":
					oScrollable.css({
						"height": "112px",
						"overflow": "hidden",
					});
					$("a.yt").click(function(event) {
						var aHref	= $(this).attr("href").split("/"),
							oVideo	= {
								title: $(this).attr("title"),
								video: aHref[aHref.length - 1]
							};
						
						event.preventDefault();
						$("#spotlight").html($("#spotlightTemplate").tmpl(oVideo));
					});
					oScrollable
						.scrollable({ circular: true, mousewheel: true })
						.navigator();
					break;
			}
			$("a.prev").button({ icons: { primary: "ui-icon-triangle-1-w" } });
			$("a.next").button({ icons: { primary: "ui-icon-triangle-1-e" } });
		}
		
		$("a#contact").live(
			"click",
			function (event)
			{
				var href = $(this).attr("href");
				
				event.preventDefault();
				$.ajax({
					url: href,
					beforesend: function(XMLHttpRequest) { XMLHttpRequest.setRequestHeader("X-Requested-With", "XmlHttpRequest"); },
					success: function(data, textStatus, XMLHttpRequest) {
						$("div#yui-main > div.yui-b").html(data);
						$("input:submit").button();
						ajaxifyForm();
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); }
				});
			}
		);
		
		if ($("form#registration").length) {
			$("#address_1_prefix").change(function() {
				if ($(this).attr("value") === "Brak") {
					$("#BrakHint").show();
					$("#address_1_name").keyup(function() {
						$("#city").attr("value", $(this).attr("value"));
					})
				} else {
					$("#BrakHint").hide();
					$("#address_1_name").unbind("keyup");
					$("#city").attr("value", "");
				}
			});
		}
		
		if ($("form#contact").length) {
			ajaxifyForm();
		}
		
		if ($("div#topsidebox > div#treeView").length) {
			if ($("div#treeView").hasClass("dynamic")) 
				renderTreeView(true);
			else
				renderTreeView(false);
		}

		$("input:submit").button();
	}
);
