var $last_id = 0; 

$.extend($urls, $last_id);

$(document).ready(function ()
{
	if ($('div#box').length > 0)
	{
		var items = $('#move').children().length;
		
		if (items == 0)
		{
			$('div#dzial-box').hide();
			$('h1.box').hide();
		}
		
		var items_per_page = 9;
		var box = 92;
		var wait = false;
			
		$('#move').width(100 * items);
		
		var pos = (box * items) - (-$('#move').position().left);
			
		if (pos > items_per_page * box)
		{
			$('#next').fadeIn(300);
		}
	}
	
	$('.close').click(function()
	{
		box_hide($('div#box-info'));
	});
	
	$('.pngfix').pngFix({blankgif:'templates/img/blank.gif'});
	
	$('#move img, #wybrane img, .wybrane img').mouseover(function ()
	{			
		var $box = $('#box-info');
		var $timer = $('body');
		
		$timer.stopTime();
		
		if ($last_id == $(this).attr('id').substr(1))
		{
			return 0;
		}
		else
		{
			$last_id = $(this).attr('id').substr(1);
		}
			
		ajax($urls.prezent, 'POST', {id: $last_id}, 'json',
		function ()
		{
			$box.children().not('.pngfix, .close').hide();
			$box.css('background', '#fff url(templates/img/loading.gif) center no-repeat').fadeIn(300);
			$box.find('.pngfix, .close').show();
		},
		function ()
		{
			
		},
		function (data)
		{
			var img = load_image('var/fotos/' + data.zdjecia['normal']);
			var a = 1;

			$box.everyTime(100, function ()
			{	
				if (img.hasClass('ready') || data.zdjecia['normal'] == '-1' || a == 50)
				{
					$box.stopTime();
					$box.css('background', '#fff');
					$('div#box-foto').css('background', '#fff url(var/fotos/' + data.zdjecia['normal'] + ') center no-repeat');
					$('div#box-left .nazwa').html(data.nazwa);
					$('div#box-left .opis').html(data.opis);
					$('div#box-left .cena span').html(data.cena);
					$('div#box-left .wymiary span').html(data.rozmiar);
					$('div#box-left .producent span').html(data.producent);
					$('div#box-left .link a').attr('rel', data.id);
						
					$('div#box-left .link a').unbind('click').click(function ()
					{
						ajax($urls.dodaj, 'POST', {id: $(this).attr('rel')}, 'json', null, null,
						function (data)
						{
							switch (data.code)
							{
								case '1':
									/*alert('Prezent został pomyślnie dodany do listy.');*/
									var count = $('span.wybrane').text();
									$('span.wybrane').text(++count);
									
									break;
										
								case '-1':
									alert('Prezent został już dodany do listy.');
									break;
									
								default:
									alert('Wystąpił nieoczekiwany błąd podczas próby dodania prezentu do listy.\nProszę spróbować za chwilę.');
							}
							box_hide($box);
						},
						function ()
						{
							alert('Wystąpił nieoczekiwany błąd podczas próby dodania prezentu do listy.\nProszę spróbować za chwilę.');
						});
						
						return false;
					});
					
					$(document).unbind('keydown').keydown(function (e)
					{
						switch (e.keyCode)
						{
							case 27:
								box_hide($box);
								break;	
						}
					});
					
					if (data.ukryj == 1)
					{
						$('div#box-left .link').css('left', '-1000px');
					}
					else
					{
						$('div#box-left .link').css('left', '0px');
					}
					
					$box.children().fadeIn(300);
					
					$timer.oneTime(10000, function ()
					{
						box_hide($box);
					});
					
					img.remove();
				}
				a++;
			});
		},
		function ()
		{
			$box.hide();
			alert('Wystąpił nieoczekiwany błąd podczas próby odebrania danych z serwera.\nProszę spróbować za chwilę.');
		});
	});
		
	$('div#prev').click(function ()
	{			
		if (-$('#move').position().left > 0 && !wait)
		{
			wait = true;
			$('#move').animate({left: (items_per_page*box)+$('#move').position().left}, 1000, function()
			{
				wait = false;
				
				if (!(-$('#move').position().left > 0))
				{
					$('#prev').fadeOut(200);
					$('#next').animate({left: $('#box').width()}, 300);
					$('#box').animate({left: 0}, 300, function() {});
				}
					
				var pos = (box*items)-(-$('#move').position().left);
					
				if (pos > items_per_page * box)
				{
					$('#next').css('left', $('#box').width() + $('#box').position().left);
					$('#next').fadeIn(200);
				}
			});
		}
	});
	
	$('div#next').click(function ()
	{
		var pos = (box*items)-(-$('#move').position().left);
			
		if (pos > items_per_page*box && !wait)
		{
			wait = true;
			$('#move').animate({left: (-items_per_page*box)+$('#move').position().left}, 1000, function()
			{
				$('#next').animate({left: $('#box').width() + 16}, 300);
				$('#box').animate({left: 16}, 300, function()
				{
					$('#prev').fadeIn(200);
				});
					
				wait = false;
				pos = (box*items)-(-$('#move').position().left);
				
				if (!(pos > items_per_page * box))
				{
					$('#next').fadeOut(200);
				}
			});				
		}
	});
		
	$('div#search a').hover(function ()
	{
		$('div#search').css('background-position', '0 -28px');
	},
	function ()
	{
		$('div#search').css('background-position', '0 0');
	});
	
	$('form#search-fm').submit(function ()
	{
		var q = $('#query');
		
		if (q.val().length < 3)
		{
			alert('Należy podać przynajmniej 3 znaki.');
			return false;
		}
		else
		{
			return true;
		}
	});
	
	$('div#search a').click(function ()
	{
		$('form#search-fm').submit();
		return false;
	});
	
	$('div.button').hover(function ()
	{
		$(this).css('background-position', '0 -22px');
	},
	function ()
	{
		$(this).css('background-position', '0 0');
	});
	
	if ($('div#index').length > 0)
	{
		if ($.cookie('index_num'))
		{
			index_animation(parseInt($.cookie('index_num'))+1);
		}
		else
		{
			index_animation(1);
		}
	}
	
	$('a.addrs').nospam({replaceText: true});
	
	$('div.wybrane a').unbind('click').click(function ()
	{
		var div = $(this);
		
		ajax($(this).attr('rel'), 'GET', null, 'text', null, null,
		function (data)
		{
			div.parents('.wybrane').fadeOut(200);
			div.oneTime(200, function ()
			{
				div.parents('.wybrane').remove();
			});
			var count = $('span.wybrane').text();
			$('span.wybrane').text(--count);
		},
		function ()
		{
			alert('Wystąpił nieoczekiwany błąd podczas próby dodania prezentu do listy.\nProszę spróbować za chwilę.');
		});		
		
		return false;
	});
	
	var podpowiedzi = [
		{'n': 'profil-odbiorcy', 'v': 'kobiety w wieku 35-50 lat, średnie i duże miasta, tradycyjne, średnie wykształcenie'},
		{'n': 'profil-klienta', 'v': 'FMCG'},
		{'n': 'naklad', 'v': '2 000 produktów na pierwszą promocję, planowane 2 promocje rocznie przez 3 lata'},
		{'n': 'uslugi-inne', 'v': 'prosimy o propozycję opakowania na promocję konsumencką'},
		{'n': 'dostawa', 'v': 'Warszawa, pierwsza partia 1 000 szt. w przeciągu 3 miesiecy'},
		{'n': 'budzet', 'v': '60 PLN/szt.'},
		{'n': 'uwagi', 'v': [
			'proszę o zaproponowanie produktów pasujących do siebie, aby nasi konsumenci',
			'mogli zbierać kolejne elementy, zestawy Villeroy & Boch']}
	];
	
	$.each(podpowiedzi, function(a)
	{
		if (this.n == 'uwagi')
		{
			$('form#zapytaj :text[name=uwagi\\[0\\]]').val(this.v[0]);
			$('form#zapytaj :text[name=uwagi\\[1\\]]').val(this.v[1]);
		}
		else
			$('form#zapytaj :text[name='+this.n+']').val(this.v);
	});
	
	$('form#zapytaj .pod :text').focus(function()
	{
		var obj = $(this);
		var name = $(this).attr('name');
		var id;
		
		if (obj.attr('title') != '')
			return 0;

		if (name == 'uwagi[0]' || name == 'uwagi[1]')
		{			
			id = name.substr(6, 1);
			name = name.substr(0, 5);
		}
		
		$.each(podpowiedzi, function(a)
		{
			if (this.n == name)
			{
				if (name == 'uwagi')
				{
					if (this.v[id] == obj.val())
					{
						obj.attr('title', 'Podpowiedź: ' + obj.val());
						obj.val('');
					}
					else
					{
						return 0;
					}
				}				
				else if (this.v == obj.val())
				{
					obj.attr('title', 'Podpowiedź: ' + obj.val());
					obj.val('');
				}
				else
				{
					return 0;
				}
			}
			
		});			
	});
	
	$('oldform#zapytaj .pod :text').blur(function()
	{
		var obj = $(this);
		var name = $(this).attr('name');
		var id;

		if (name == 'uwagi[0]' || name == 'uwagi[1]')
		{			
			id = name.substr(6, 1);
			name = name.substr(0, 5);
		}
		
		$.each(podpowiedzi, function(a)
		{
			if (this.n == name)
			{
				if (name == 'uwagi')
				{
					if (obj.val() == '')
					{
						obj.val(this.v[id]);
					}
					else
					{
						return 0;
					}
				}				
				else if (obj.val() == '')
				{
					obj.val(this.v);
				}
				else
				{
					return 0;
				}
			}
			
		});			
	});
	
	$('form#zapytaj').submit(function ()
	{
		var $fail = false;
		var $alert = '';
		
		$('form#zapytaj .pod :text').focus();
		
		$('form#zapytaj .req').each(function ()
		{
			if ($(this).find(':text').val() == '')
			{
				$(this).css('color', 'red');
				$fail = true;
				$alert = 'Należy wypełnić wszystkie wymagane pola.\n';
			}
		});
		
		if ($(this).find(':text[name=telefon]').val() == '' && $(this).find(':text[name=email]').val() == '')
		{
			$(this).find(':text[name=telefon]').parents('.form').css('color', 'red');
			$(this).find(':text[name=email]').parents('.form').css('color', 'red');
			$fail = true;
			$alert += 'Należy podać telefon lub adres e-mail.\n';
		}
		
		if ($(this).find(':text[name=email]').val() != '' && !checkEmail($(this).find(':text[name=email]').val()))
		{
			$fail = true;
			$alert += 'Należy podać prawidłowy adres e-mail.\n';
			$(this).find(':text[name=email]').parents('.form').css('color', 'red');
		}
		
		if ($fail)
		{
			alert($alert);
		}
		else
		{			
			var data = $(this).serialize() + '&ok=1';

			ajax($urls.zapytaj, 'POST', data, 'json', null, null,
			function (res)
			{
				switch (res.code)
				{
					case '0':
						alert('Wystąpił błąd podczas próby wysłania formularza.\nProszę spróbować za chwilę.');
						break;
					
					case '1':
						alert('Formularz został pomyślnie wysłany.');
						window.location = '/';
						break;
						
					case '-1':
						alert(res.data);
						break;
									
					default:
						alert('Wystąpił nieoczekiwany błąd podczas próby wysłania formularza.\nProszę spróbować za chwilę.');
				}
			},
			function ()
			{
				alert('Wystąpił nieoczekiwany błąd podczas próby wysłania formularza.\nProszę spróbować za chwilę.');
			});
		}
		
		return false;
	});
	
	$('form#zapytaj .req :text').change(function ()
	{
		if ($(this).val() != '')
		{
			$(this).parents('.req').css('color', '#595757');
		}
	});
	
	$('form#zapytaj .req-or :text').change(function ()
	{
		if ($(this).val() != '')
		{
			$('.req-or').css('color', '#595757');
		}
	});
	
	$('form#zapytaj #wyczysc').click(function ()
	{
		$('form#zapytaj').each(function()
		{
			this.reset();
			$('form#zapytaj .req, form#zapytaj .req-or').css('color', '#595757');
		});
	});
	
	$('form#zapytaj #wyslij').click(function ()
	{
		$('form#zapytaj').submit();
	});
	
	$('a[rel=ext]').live('click', function ()
	{
		this.target = "_blank";
	});
	
	/*$('#popup').show().oneTime(10000, function ()
	{
		$(this).hide();
	})*/
});
	
function index_animation(id)
{
	if (id > 3) id = 1;

	var $index = $('div#i' + id);
	$.cookie('index_num', id, {expires: 1});		
	$index.find('div').not('.text, .white-block').fadeIn(700);
			
	$index.oneTime(4000, function ()
	{			
		$index.find('.center').oneTime(400, function ()
		{
			$index.find('.white-block, .text').show();
			$index.find('.white-block').fadeOut(300);	
			
			$index.find('.white-block').oneTime(8000, function ()
			{					
				$index.find('.white-block').oneTime(200, function ()
				{
					$index.find('.white-block, .text').hide();
					$index.find('div').fadeOut(700);
					index_animation(++id);
				}).fadeIn(200);
			});
		}).fadeOut(400);						
	});
}

function ajax(url, type, data, dataType, beforeSend, complete, success, error)
{	
	$.ajax(
	{
		type: type,
		url: url,
		cache: false,
		data: data,
		dataType: dataType,
		beforeSend: beforeSend,
		complete: complete,
		success: success,
		error: error
	});
}

function load_image(src)
{			
	var img = $('<img />');

	img.load(function()
	{
		$(this).addClass('ready');
	});
	
	img.attr('src', src);
	return img;
}

function box_hide($b)
{
	$b.find('.pngfix, .close').hide();
	$b.fadeOut(200);
	$last_id = 0;
}

function checkEmail(email)
{
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	if (!filter.test(email))
	{
		return false;
	}
	else
	{
		return true;	
	}
}
