String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function switchLogo() {
	$('#logos ul li:first').css({top: 100}).animate({top: 0, opacity: 100}, 2200, 'easeOutCubic').animate({top: 0}, 2800).animate({top: 100, opacity: 0}, 1400, 'easeOutCubic', function () {
		$('#logos ul').append($(this).css({top: 100, opacity: 0}).remove())
	})
}

$(function () {
	
	$(function () {
		$('#logos ul li').css({top: 100, opacity: 0})
		switchLogo();
		setInterval('switchLogo();', 6500)
	})

	initButtons()
	initNewsletter()
	initProducts()
	initFastLinks()
	initDefaultForms()
	initMainMenu()
	initFlash()
	initShowcase()
	initMap()
	initFormsLeft()
	initFiles()

	$('body.laur-konsumenta-odkrycie-roku-2010 h1.header').css({'font-size': '20px', 'line-height': '22px'}).html('Laur konsumenta - Odkrycie roku 2010')
	$('body.laur-konsumenta-odkrycie-roku-2010 h1.header').after('<h3 id="sub-title">Bo jakość jest naszą domeną</h3>')
	$('body.najlepsze-w-polsce h1.header').after('<h3 id="sub-title">Stawiamy na jakość, doceniają to Klienci</h3>')
	
	if ($('.navigation-bottom .pagination a').size() > 0) {
		$('.navigation-bottom .pagination').prepend('<span class="label">'+_T['Wybierz stronę']+':</span>')
	}
	
	$("a[rel^='prettyPhoto'], .gallery a, #product-photos a, .lightbox").prettyPhoto({animationSpeed:'slow',theme:'light_square',slideshow:800});
	
	$('a.ml').each(function () {
		var rel = $(this).attr('rel')
		var mail = rel.split(';').join('@')
		$(this).html(mail)
		$(this).attr('href', 'mailto:'+mail)
	})
	
	$('#contact-map').css({height: $('#contact-wrapper').height()-100})
	
})

function initButtons() {
	
	$('.btn-recommend').click(function () {
		$('#dialog-recommend').remove()
		$('<div>').attr('id', 'dialog-recommend').appendTo('body')
		$('#dialog-recommend').load(CONST_APP_URL+CONST_LANGUAGE['symbol']+'/offer/recommend', function () {
			$('#dialog-recommend form').submit(function () { return false })
			$('#dialog-recommend form textarea').val(
				_T['Witaj,\n\nPolecam Ci produkt ']+$('h1.product-name').html()+_T[' firmy Metal-Bud z kategorii ']+$('.category-path a').eq(0).html()+'.\n\n'+
				_T['Oto jego krótki opis:\n']+$('#product-description p').html()+
				_T['\n\nWięcej na temat tego produktu możesz dowiedzieć się tutaj:\n']+window.location
			)
			$('#dialog-recommend').dialog({
				title: _T['Poleć ten produkt znajomemu'],
				resizable: false,
				modal: true,
				width: 450,
				height: 420,
				close: function(event, ui) {
					$('#dialog-recommend').dialog('destroy')
					$('#dialog-recommend').remove()
				},
				buttons: {
					'Wyślij wiadomość': function () {
						$('.ui-dialog-buttonpane button').attr('disabled', 'disabled')
						$.ajax({
							type: 'POST',
							url: CONST_APP_URL+CONST_LANGUAGE['symbol']+'/offer/recommend',
							data: $('#dialog-recommend form').serializeArray(),
							success: function (data) {
								if (data == 'OK') {
									$('#dialog-recommend').html(_T['<h4>Dziękujemy!</h4><p>Twoja wiadomość została wysłana.</p>'])
									$('.ui-dialog-buttonpane button').remove()
									$('<button>'+_T['Zamknij']+'</button>').click(function () {
										$('#dialog-recommend').dialog('destroy')
									}).appendTo('.ui-dialog-buttonpane')
								} else {
									$('#dialog-recommend').html(data)
								}
								$('.ui-dialog-buttonpane button').removeAttr('disabled')
							},
							complete: function () {
								$('.ui-dialog-buttonpane button').removeAttr('disabled')
							}
						})
					}
				}
			})
			
			$('.ui-dialog-buttonpane button[type=button]').html(_T['Wyślij wiadomość'])
		})
		return false
	})
	
	$('.btn-ask, #btn-ask-for').click(function () {
		$('#dialog-ask').remove()
		$('<div>').attr('id', 'dialog-ask').appendTo('body')
		$('#dialog-ask').load(CONST_APP_URL+CONST_LANGUAGE['symbol']+'/offer/ask', function () {
			$('#dialog-ask form').submit(function () { return false })
			$('#dialog-ask form textarea').val(_T['Zapytanie o produkt ']+$('h1.product-name').html()+_T[' dostępny pod adresem: ']+window.location+'.\n\n')
			$('#dialog-ask').dialog({
				title: _T['Zapytaj o ten produkt'],
				resizable: false,
				modal: true,
				width: 450,
				height: 340,
				close: function(event, ui) {
					$('#dialog-ask').dialog('destroy')
					$('#dialog-ask').remove()
				},
				buttons: {
					'Wyślij zapytanie': function () {
						$('.ui-dialog-buttonpane button').attr('disabled', 'disabled')
						$.ajax({
							type: 'POST',
							url: CONST_APP_URL+CONST_LANGUAGE['symbol']+'/offer/ask',
							data: $('#dialog-ask form').serializeArray(),
							success: function (data) {
								if (data == 'OK') {
									$('#dialog-ask').html(_T['<h4>Dziękujemy!</h4><p>Twoja wiadomość została wysłana.</p>'])
									$('.ui-dialog-buttonpane button').remove()
									$('<button>'+_T['Zamknij']+'</button>').click(function () {
										$('#dialog-ask').dialog('destroy')
									}).appendTo('.ui-dialog-buttonpane')
								} else {
									$('#dialog-ask').html(data)
								}
								$('.ui-dialog-buttonpane button').removeAttr('disabled')
							},
							complete: function () {
								$('.ui-dialog-buttonpane button').removeAttr('disabled')
							}
						})
					}
				}
			})
			
			$('.ui-dialog-buttonpane button[type=button]').html(_T['Wyślij zapytanie'])
		})
		return false
	})
	
}

function initNewsletter() {
	$('#newsletter-form').submit(function () {
		$('#newsletter-email').removeClass('error').removeAttr('title')
		$.post('/newsletter/zapisz', {'email': $('#newsletter-email').val()}, function (data) {
			//console.log(data)
			if (typeof data.errors == 'undefined') {
				$('#newsletter-email').remove()
				$('#newsletter-submit').remove()
				$('<p>').html(_T['Dziękujemy za dodanie adresu.']).attr('id', 'newsletter-complete').appendTo('#newsletter-form')
			} else {
				if (typeof data.errors.email != 'undefined') {
					$('#newsletter-email').addClass('error').attr('title', data.errors.email)
				}
			}
		}, 'json')
		return false
	})
}

function initFiles() {
	$('#files li.collapsed ul').hide()
	$('#files li.collapsed').live('click', function () {
		$(this).removeClass('collapsed').addClass('expanded')
		$('ul:first', this).each(function () {
			if ($('li', this).size() > 0) {
				$(this).stop().slideDown(700, 'easeOutQuad')
			}
		})
	})
	$('#files li.expanded').live('click', function () {
		$(this).removeClass('expanded').addClass('collapsed')
		$('ul', this).each(function () {
			$(this).stop().slideUp(700, 'easeInQuad')
		})
	})
}

function initFormsLeft() {
	$('#product-search-submit, #newsletter-submit, #form-catalog-btn-order').hover(
		function () { $(this).addClass('hover') },
		function () { $(this).removeClass('hover') }
	)
}

function initMap() {
	if ($("#map").size() > 0) {
		var map = new google.maps.Map2(document.getElementById("map"));
		map.setMapType(G_HYBRID_MAP);
		map.setCenter(new google.maps.LatLng(49.931627, 19.973775), 15);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		
		var point = new GLatLng(49.931627, 19.973775);
		map.addOverlay(new GMarker(point));
	}
}

function initProducts() {
	var q = []
	
	$('body.produkty #content .product-list li, body.szukaj #content .product-list li, body.landing #content .product-list li, body.nowosci #content .product-list li').each(function () {
		$(this).css({opacity: 0})
		q.push($(this))
	})
	
	function appearNext(product) {
		product.animate({opacity: 1}, '200', function () {
			$(this).css({opacity: ''})
		})
		
		setTimeout(function () {
			if (q.length > 0) {
				appearNext(q.shift())
			}
		}, 150)
	}
	if (q.length > 0) {
		appearNext(q.shift())
	}
}

function initShowcase() {
	// Showcase
	
	$('#product-showcase .switcher a').click(function () {
		var rel = $(this).attr('rel')
		$('#product-showcase-carousel ul').animate({opacity: .3})
		$.getJSON(CONST_APP_URL+CONST_LANGUAGE['symbol']+'/showcase_json/'+rel+'?callback=?', function (data) {
			
			$('#product-showcase-carousel').carousel('destroy')
			
			$('<div>', {
				'class': 'slider',
				html: $('<ul>')
			}).appendTo('#product-showcase-carousel')
			
			var q = []
			
			for (i in data) {
				var p = data[i]
				var li = $('<li>', {
					'class': 'ribbon-'+rel,
					html: $('<a>', {
						href: CONST_APP_URL+CONST_LANGUAGE['symbol']+'/'+CONST_ROUTES['offer_product'][CONST_LANGUAGE['locale']]+'/'+p.product_id+'/'+p.product_slug+'.html',
						title: p.product_name
					})
				})
				li.appendTo('#product-showcase-carousel div.slider ul').css({opacity: 0})
				
				//console.log(li)
				li[0].style.filter = 'alpha(opacity=0)'
				
				$('<span>', {'class': 'product-image', css: {'background-image': 'url('+p.product_photo+')'}}).appendTo($('a', li))
				$('<span>', {'class': 'product-name', html: p.product_name}).appendTo($('a', li))
				$('<span>', {'class': 'product-description', html: p.product_subtitle}).appendTo($('a', li))
				$('<span>', {'class': 'ribbon', html: '&nbsp;'}).appendTo($('a', li))
				q.push(li)
			}
			
			function appearNext(product) {
				product.animate({opacity: 1}, '200', function () {
					$(this).css({opacity: ''})
				})
				
				setTimeout(function () {
					if (q.length > 0) {
						appearNext(q.shift())
					}
				}, 150)
			}
			if (q.length > 0) {
				appearNext(q.shift())
			}
			
			$('#product-showcase-carousel').carousel()
			
		})
		$('#product-showcase .switcher a').removeClass('active')
		$(this).addClass('active')
		return false
	})
	
	$('#product-showcase-carousel').carousel()
}

function initFlash() {
	// Flash
	//alert('/autopromo/flash?l='+CONST_LANGUAGE['locale'])
	$('#intro').flash({
		src: '/static/flash/mb.swf',
		width: 719,
		wmode: 'transparent',
		height: 320,
		flashvars: { xml: '/autopromo/flash?l='+CONST_LANGUAGE['locale']+'&s='+CONST_LANGUAGE['symbol'], mLoading: _T['Trwa ładowanie...'], mWait: _T['proszę czekać'], cat: _T['/static/images/katalog.png'], catalog_href: CONST_APP_URL+'katalog'/*'public/Katalogi i Ulotki/KATALOG_PRODUKTOW_AKTUALNY_2012.pdf'*/ }
	})
	initIntro();
	
	$('#logo-side').flash({
		src: '/static/flash/logo.swf',
		width: 200,
		wmode: 'transparent',
		height: 200
	})
}

function initDefaultForms() {
	// Ustawianie domyślnego tekstu w polach formularza
	$('input.not-empty').each(function () {
		$(this)
			.data('value', $(this).val())
			.focus(function () {
				var val = $(this).val()
				val = val.trim()
				if (val == '' || val == $(this).data('value')) {
					$(this).val('')
				}
			})
			.blur(function () {
				var val = $(this).val()
				val = val.trim()
				if (val == '') {
					$(this).val($(this).data('value'))
				}
			})
	})
	$('input.empty').val('')
}

function initMainMenu() {
	// Menu główne
	$('#menu .main-menu li a').each(function () {
		if ($(this).css('text-decoration') == 'underline') {
			$(this).parent().attr('rel', 'current')
		}
	})
	$('#menu .main-menu li').hover(
		function () {
			$(this).parent().find('a').css({'background-position': '0 0'})
			$('a', this).css({'background-position': '0 -70px'})
		},
		function () {
			$(this).parent().find('a').css({'background-position': '0 0'})
			$('#menu .main-menu li[rel=current] a').css({'background-position': '0 -70px'})
		}
	)
}

function initFastLinks() {
	// Linki szybkiego dostępu
	/*$('#fast-access ul').css({height: $('#fast-access ul li').size()*44})*/
	var flNum = $('#fast-access ul li').size()
	$('#fast-access ul li').each(function () {
		var text = $('a span', this).text()
		$(this).css({opacity: 0, 'z-index': flNum})
		$('a span', this).html('')
		$('<em>').css({display: 'block', float: 'left', width: '100%', height: '39px'}).addClass('caption').appendTo($('a span', this))
		var url = CONST_APP_URL+'static/label/medium/210/17/12/ffffff/de4500/1/1/'+text.toUpperCase().replace(/\ /ig, '%20')
		$('a span em', this).css({'background': 'no-repeat url('+url+') 0 center'})
		flNum--
	})
	
	// Animacja linków szybkiego dostępu
	flAppear($('#fast-access ul li'))
	function flAppear(el) {
		el
			.eq(0)
			.animate({top: $(el).index()*44+3, opacity: 1}, 250,
				function() {
					flAppear(el.slice(1))
				}
			)
	}
}

$.widget("ui.carousel", {
	_init: function() {
		var self = this
		var rewind = $('<a href="#" class="button-rewind" title="'+_T['Do tyłu']+'">&laquo;</a>').appendTo(this.element)
		var forward = $('<a href="#" class="button-forward" title="'+_T['Do przodu']+'">&raquo;</a>').appendTo(this.element)
		
		this.target = 0
		
		var ribb = $('<div>', {'class': 'ribbons'}).appendTo(this.element)
		ribb.wrap('<div class="ribbons-wrapper"></div>')
		
		var i = 0
		var w = 0
		$('ul', this.element).css({left: 0})
		$('ul li', this.element).each(function () {
			var li = $(this)
			var ribbon = $('.ribbon', this).remove()
			
			ribbon.addClass($(this).attr('class'))
			ribbon.css({position: 'absolute', top: '61px', left: i*$(this).width()+i})
			ribbon.data('left', i*$(this).width()+i)
			
			w += $(this).css({position: 'absolute', left: i*($(this).width()+1)}).width()
			
			ribbon.click(function () {
				document.location = $('a', li).attr('href')
				$('a:first', li).click()
			})
			
			$('div.ribbons', self.element).append(ribbon)
			i++
		})
		
		this.lap = $('ul', this.element).width()-w
		
		rewind.click(function () {
			self.untick()
			self.rewind()
			self.tick()
			return false
		})
		forward.click(function () {
			self.untick()
			self.forward()
			self.tick()
			return false
		})
		
		this.tick()
	},
	untick: function() {
		var self = this
		clearTimeout(self.timeout)
	},
	tick: function() {
		var self = this
		self.timeout = setTimeout(function () {
			if (self.forward() == false) {
				$('ul', self.element).animate({left: 0}, 600)
				$('.ribbons .ribbon', self.element).each(function () {
					$(this).animate({left: ($(this).data('left'))}, 600)
					self.target = 0
				})
			}
			self.tick()
		}, 3000)
	},
	forward: function() {
		var self = this
		if (this.target > this.lap) {
			this.target -= $('ul li', this.element).width()
			$('ul', this.element).animate({left: '-='+($('ul li', this.element).width()+1)}, 300, function () {
				/*if ($(this).position().left < 0) {
					$('li', this).eq((-Math.round($(this).position().left/$('li', this).eq(0).width())-1)).animate({opacity: 0, left: '-=5'}, 10).addClass('hidden')
				}*/
			})
			$('.ribbons .ribbon', this.element).animate({left: '-='+($('ul li', this.element).width()+1)}, 300)
			
			return true
		}
		else
		{
			return false
		}
	},
	rewind: function() {
		var self = this
		if (this.target < 0) {
			//$('ul li.hidden:last', this.element).removeClass('hidden').animate({opacity: 1, left: '+=5'}, 10)
			$('ul', this.element).animate({left: '+='+($('ul li', this.element).width()+1)}, 300, function () {})
			$('.ribbons .ribbon', this.element).animate({left: '+='+($('ul li', this.element).width()+1)}, 300)
			this.target += $('ul li', this.element).width()
			
			return true
		}
		else
		{
			return false
		}
	},
	destroy: function() {
		var self = this
		self.untick()
		$(self.element).empty()
		$.widget.prototype.destroy.apply(this, arguments)
	}
});
/* $.extend($.ui.mywidget, {
   getter: "value length",
   defaults: {
     option1: "defaultValue",
     hidden: true
   }
 });*/

