$(function() {
	/**
	 * termék menü
	 */

	$('ul#product_list li:has(ul)')
		.click(function(event) {
			var speed = 250;
			var par = $(event.target).parent().get(0);
			if (this == par)
			{
				if ($(this).children('ul').is(':hidden'))
				{
					$(this)
						.children('div')
							.css('background-image', 'url(' + BASE_URL + 'images/folder_minus.gif)')
						.end()
						.children('ul').slideDown(speed);
				}
				else
				{
					$(this)
						.children('div')
							.css('background-image', 'url(' + BASE_URL + 'images/folder_plus.gif)')
						.end()
						.children('ul').slideUp(speed);
				}
			}
		})
		.children('ul').hide()
		.end()
		.children('div')
			.css('background-image', 'url(' + BASE_URL + 'images/folder_plus.gif)')
			.css('cursor', 'pointer');

	$('ul#product_list li.selected')
		.children('ul').show()
		.end()
		.children('div.folder')
			.css('background-image', 'url(' + BASE_URL + 'images/folder_minus.gif)')

	/**
	 * Listaelemek min-height-jének beállítása explorer 6-on
	 */
	if (jQuery.browser.msie)
	{
		var version = parseInt(jQuery.browser.version);
		if (version < 7)
		{
			$('#content div.product')
				.each(function() {
					if ($(this).height() < 80)
					{
						$(this).height(80);
						$(this).children('div').height(80);
					}

				})

			$('#content div.head')
				.each(function() {
					var h = $(this).height() + 16;
					$(this).css('height', h + 'px');
				})
		}
	}

	$('div.share a').each(function() {
		var $this = $(this);
		var url = $this.attr('href');
		$this.attr('href', 'javascript:void(0)').data('url', url);
		$this.click(function() {
			window.open($(this).data('url'), 'iwiwshare', 'toolbar=0,status=0,location=1, width=580,height=440,scrollbars=1');
			return false;
		})
	});

	/**
	 * Termék fotók
	 */
	var panel_latency = 0;
	var panel_id = 0;
	$('#content a.preview_image')
		.click(function() {
			return false;
		})
		.each(function() {
			var href = $(this).attr('href');
			var size = '';
			if (href.indexOf('?') >= 0)
			{
				var dim = href.split('?').pop().split('x');
				$(this).attr('panel', 'panel' + panel_id)
				$('body')
					.append(
						'<div id="panel' + panel_id + '" class="preview_panel" style="width:' + dim[0] + 'px; height:' + dim[1] + 'px;">'
							+ '<img src="' + href + '" width="' + dim[0] + '" height="' +  dim[1] + '" />'
						+ '</div>'
					)
				++ panel_id;
			}
		})
		.hover(function() {
			var speed = 'fast';
			var latency = 250;
			var this_a = this;
			panel_latency = setTimeout(function() {
				$('div.preview_panel:visible').hide();

				var panel = $('#' + $(this_a).attr('panel')).get(0);

				var item_top = $(this_a).offset().top;
				var panel_height = $(panel).height();
				var item_bottom = item_top + panel_height;
				var win_top = $(document).scrollTop();
				var win_bottom = win_top + $(window).height();

				if (win_bottom < item_bottom)
					$(panel).css('top', (win_bottom - panel_height) + 'px');
				else if (item_top < win_top)
					$(panel).css('top', win_top + 'px');
				else
					$(panel).css('top', item_top + 'px');

				$(panel).css('left', $(this_a).offset().left + 'px');


				$(panel)
					.hover(function() {}, function() {
							$(this)
								.hide(speed)
						})
					.fadeIn(speed);
			}, latency);

		}, function() {
			if (panel_latency) clearTimeout(panel_latency);
		});

	$('div#back')
		.each(function() {
			if (history.length > 0)
				$(this).html(
					'<p><a href="javascript:history.back()">'
						+ '&laquo;&laquo; Vissza</a></p>');
		});

	/**
	 * JQuery.suggest inicializálása
	 */
	$('#search_query').suggest('/webshop/search.php', {prefix:$('#search_type'), prefixGlue:'-'});

	/**
	 * Listaméret állító
	 */
	$('#list_sizer')
		.find('select')
			.change(function() {
				$(this).parent().submit();
			})
		.end()
		.find('input')
			.hide();

	/**
	 * Kosár
	 */
	var in_cart = false;
	$('form#ordered_items, form#cart_items')
		.submit(function() {
			return false;
		})
		.each(function() {
			in_cart = ($(this).attr('id') == 'cart_items');
		});


	$('div.order')
		.each(function() {

			// order div
			var order = this;

			// termék adatok
			var product_name =
				$(order).find('input[name^=product_name]').val();
			var product_price =
				$(order).find('input[name^=product_price]').val();
			var product_weight =
				$(order).find('input[name^=product_weight]').val();
			var product_data =
				$(order).find('input[name^=product_data]').val();

			// amount text mező
			var amount_field = $(order).find(':text').get(0);

			// ha az amountnak a megnevezése helyes
			if (amount_field
				&& $(amount_field).attr('name').match(/amounts\[(.+)\]/g))
			{
				// kiszedi a termék azonosítóját
				var product_id = RegExp.$1;
				var amount = parseInt($(amount_field).attr('value')) || 1;
				$(order).empty();

				$('<div></div>')
					.hide()
					.addClass('message')
					.appendTo(order);

				$('<div class="toolbar"></div>')
					.appendTo(order);

				$('<div>Adatok feldolgozása...</div>')
					.hide()
					.addClass('ajaxload')
					.appendTo(order);

				var ajaxload = $(order).find('div.ajaxload');

				var toolbar = $(order).find('div.toolbar');
				var timer = null;
				$('<div></div>')
					.addClass('minus')
					.mousedown(function() {
						var el = $(order).find('div.amount span').get(0);
						var min_amount = in_cart ? 0 : 1;
						var amount = parseInt($(el).text()) || min_amount;
						if (amount > min_amount)
							$(el).text(amount - 1);

						if (in_cart)
						{
							if (min_amount == 0
									&& (amount - 1) <= min_amount)
								$(order).find('div.order_button')
									.html('<strong>Töröl</strong>');
							else
								$(order).find('div.order_button')
									.html('<span>Módosít</span>');
						}

						var thisButton = this;
						timer = setTimeout(function() {
							$(thisButton).mousedown();
						}, 250)
						return false;
					})
					.mouseup(function() {
						if (timer) clearTimeout(timer);
						return false;
					})
					.mouseout(function() {
						if (timer) clearTimeout(timer);
						return false;
					})
					.appendTo(toolbar);

				$('<div><span>' + amount + '</span></div>')
					.addClass('amount')
					.appendTo(toolbar);

				$('<div></div>')
					.addClass('plus')
					.mousedown(function() {
						var el = $(order).find('div.amount span').get(0);
						var min_amount = in_cart ? 0 : 1
						var amount = parseInt($(el).text()) || min_amount;
						$(el).html(amount + 1);

						if (in_cart)
							$(order).find('div.order_button')
								.html('<span>Módosít</span>')

						var thisButton = this;
						timer = setTimeout(function() {
							$(thisButton).mousedown();
						}, 250)
						return false;
					})
					.mouseup(function() {
						if (timer) clearTimeout(timer);
						return false;
					})
					.mouseout(function() {
						if (timer) clearTimeout(timer);
						return false;
					})
					.appendTo(toolbar);

				var label = in_cart ? 'Módosít' : 'Kosárba';
				$('<div><span>' + label + '</span></div>')
					.addClass('order_button')
					.click(function() {

						var el = $(order).find('div.amount span').get(0);
						var min_amount = in_cart ? 0 : 1;
						var amount = parseInt($(el).text()) || min_amount;

						var cart_command = 'add';
						if (in_cart)
							if (amount > 0)
								cart_command = 'modify';
							else
								cart_command = 'remove';

						$(toolbar).fadeOut('fast', function() {
							$(ajaxload).fadeIn('fast');
						});

						args = {
							product_id: product_id,
							product_name: product_name,
							product_price: product_price,
							product_weight: product_weight,
							product_data: product_data,
							amount: amount,
							cart_command: cart_command
						};
						$.post('/item.php?'
							+ Math.random().toString().substring(2),
							args,
							function(data) {
								data = data.split(';');
								if (data.length != 2)
								{
									var response = 0;
									var callback = function() {};
								}
								else
								{
									var response = parseInt(data[0]);
									var callback = function() {
										$('#order_total').text(data[1]);

										if (cart_command == 'remove')
										{
											var count_num = $('#count_num');
											var n =
												parseInt(
													$(count_num).text())
												|| 0;
											if ((n - 1) >= 0)
											{
												$(count_num).text(n - 1);
												if (n - 1 == 0)
													$('.remove_if_empty')
														.remove();
											}
										}
									}

								}

								setTimeout(function() {
									if (response < 1)
										order_message(
											'Váratlan hiba, ismételje '
											+ 'meg a kérést újra.',
												order, callback);
									else if (response < 3)
										order_message(
											'A terméket nem sikerült '
											+ 'berakni a kosárba.',
												order, callback);
									else if (response < 5)
										order_message(
											'A termék bekerült a kosárba.',
											order, callback);
									else if (response < 7)
										order_message(
											'A rendelési mennyiséget nem '
											+ 'sikerült módosítani.',
											order, callback);
									else if (response < 9)
										order_message(
											'A rendelési mennyiség '
											+ 'módosítva lett.',
											order, callback);
									else if (response < 12)
										order_message(
											'Nem sikerült a terméket '
											+ 'törölni a kosárból.',
											order, callback);
									else if (response < 14)
										order_message(
											'A termék törölve lett a '
											+ 'kosárból',
											order, callback, true);
								}, 1000);
							},
							'text');
					})
					.appendTo(toolbar);

				$('<div class="clearer"></div>')
					.appendTo(order);
			}
		})

	$('#cart_command').remove();

	function order_message(message, order, callback, remove)
	{
		if (typeof remove == 'undefined')
			remove = false;

		$(order)
			.find('div.ajaxload')
				.fadeOut('fast', function() {
					$(order).find('div.message')
						.text(message)
						.fadeIn('fast', function() {
							var thisEl = this;
							setTimeout(function() {
								$(thisEl)
									.fadeOut('fast', function() {
										if (remove)
										{
											$(order).parent().parent()
												.hide('normal')
												.remove();
										}
										else
										{
											$(order).find('div.toolbar')
												.fadeIn('fast');
										}
										callback();
								});
							}, 2000);
						});
				})
	}
});
