function start(){
	setCarousel();
	setMenu();
	$('#keyword').example('Czego szukasz').keyup(function(event){if(event.keyCode == 13)searchForm();});
	$('#newsletter').keyup(function(event){if(event.keyCode == 13)newsletterSend('ADD');});
	newsletterEmail();
	if($.browser.version!='6.0')$('.orderBox').jNice();
	smallCart();
	lastSearch();
	lastVisited();
	textBox();
	menuHeaderHideShow();
	$('.tooltip').tooltip({
		track: true,
		showURL: false
	});
	$('.fancybox').fancybox();
	$('hr').after('<div class="hr"></div>').remove();
	
	jQuery(function($){
		$.datepicker.regional['pl'] = {
			closeText: 'Zamknij',
			prevText: '&#x3c;Poprzedni',
			nextText: 'Następny&#x3e;',
			currentText: 'Dziś',
			monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
			'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
			monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
			'Lip','Sie','Wrz','Pa','Lis','Gru'],
			dayNames: ['Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
			dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
			dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
			weekHeader: 'Tydz',
			dateFormat: 'yy-mm-dd',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: ''};
		$.datepicker.setDefaults($.datepicker.regional['pl']);
	});
	
	$('.has-datepicker').datepicker();
	$(".numberd").keyfilter((/[\d\,]/));
	$('table.compare td.productImage').css('float', 'none'); //usuwanie floatow w widoku porównywania
	if ($(".orderBox .se3 select").val()=='score') { //zamiana slowa popularnosc
		$(".orderBox .se3 select option:selected").html('popularność');
	}
	$(".orderBox .se3 select").focus(function(){
			$(".orderBox .se3 select option[value='score']").html('popularność malejąco');
	});
	$('#choosenCustomerDeliveryAddress').change(function(){ // odswieżenie 2 kroku przy zmianie adresu
		if ($(this).val()>0) {
			$('#order input, #order select').addClass('ignore');
			$('#eventId').val('refresh');
			$('#order').submit();
		}
	});
	
	$('.body_shops .shop-list a.btn-dokoszyka').remove(); // wygląd listy sklepów w nasze salony
	$('.body_shops .shop-list a.seeMap').removeClass('hide');
	$('a.seeMap').click(function(){
	var a=$(this).attr('rel');
	$.fancybox({
	href:'/www/ajax/get-shop-info.html?shopId='+a
	},{
	type:'ajax',
	onComplete:function(){
		$('#mapL').html('<iframe frameborder="0" scrolling="no" id="mapIframe" src="/www/googleMap.html?key='+$('#googleMapsKey').val()+'&address='+$('#mapAddress').text()+'"></iframe>');
	}
	});
	var ww=$('#regionList select option:selected').text();
	var ss=$(this).parents('li').find('.shop').text();
	_gaq.push(['_trackEvent',mapType,'Wizytówki: '+ww, ss+' - wizytówka']); 
	//console.log('Wizytówki: '+ww+'   '+ss+' - wizytówka');
	return false;
	});
	$('.zipCode').mask('99-999');
}
var mapType="Ścieżka zakupowa - Sklepy";
function emailValidator(email){
	var reg=/^[^@]+@([a-z0-9\-]+\.)+[a-z]{2,4}$/i;
	if (reg.test(email))return true;
	else return false;
}
function newsletterSend(typ){
	if(emailValidator($('#newsletter').val())){
		loadingStart();
		$.ajax({
			url:'/klient/ajax/newsletter.html',
			data:{
				mail:$('#newsletter').val(),
				action:typ
			},
			success:function(json){
				if (json.error == undefined){
					if (json.logged != undefined){
						fancyOkAction(json.result, "document.location.href='/klient/ustawienia.html'");
					} else {
						fancyOk(json.result);
					}
				} else {
					fancyOk(json.result+'<br />'+json.error);
				}
			},
			error:function(){
				fancyOk('Wystąpił błąd wewnętrzny. Jeśli błąd się będzie powtarzał prosimy o kontakt.');
			},
			cache:false
		});
	}else{
		fancyOk('Podaj poprawny adres e-mail');
	}
}
function shopsStart(){
	if(document.location.hash!='' && document.location.hash.length>1){
		loadingStart();
		$.ajax({
			url:'/www/ajax/shop.json?domain='+document.location.hash.substr(1),
			dataType: 'json',
			type:'GET',
			success:function(data){
				if(data.shop!=undefined && data.shop!=null){
					changeCity(data.city, data.shop, data.region);
					changeRegion(data.region,1);
				}
				loadingStop();
			},
			error:function(){
				loadingStop();
			}
		});
	}
	$('a.region, a.city').click(function(){
		var ul=$(this).next();
		if(ul.hasClass('v'))ul.slideUp().removeClass('v');
		else ul.addClass('v').slideDown();
	});
	shopShopDetail($('.region a.shop'));
}
function mainPageStart(){
	$('.categoryTable .moreContent').hover(function(){
		$(this).find('.moreBox').show().css('top',-2-$(this).find('.moreBox').height());
	},function(){
		$(this).find('.moreBox').hide();
	});
}
function indexBaner(nr, name){
	try{
		_gaq.push(['_trackEvent', 'Strona Główna – banner góra', 'Pozycja '+nr, name]);
	}catch(e){}
}
function isFrontUserLogged(){
	var returnValue = false;
	$.ajax({
		  url: '/klient/ajax/isUserLogged.html',
		  dataType: 'json',
		  async: false,
		  cache: false,
		  success:	function(data) {
			  if (data.logged == 'true') {
				  returnValue = true;
			  }
		  },
		  error:function(){
		  }
	});
	return returnValue;
}

function isB2C(){
	var returnValue = false;
	$.ajax({
		  url: '/klient/ajax/isB2C.html',
		  dataType: 'json',
		  async: false,
		  cache: false,
		  success:	function(data) {
			  if (data.isB2C == 'true') {
				  returnValue = true;
			  }
		  },
		  error:function(){
			  
		  }
	});
	return returnValue;
}

function changeCity(c,s,r){
	try{
		var flashMap = $('#map');
		flashMap.flash(
			function() {
				try{
					this.setCity(c);
				}catch(e){}
			}
		);
	}catch(e){}
	setCity(c,s,r);
}
function changeRegion(r,s){
	try{	
		var flashMap = $('#map');
		flashMap.flash(
			function() {
				try{
					this.setRegion(r);
				}catch(e){}
			}
		);		
	}catch(e){}
	setRegion(r,s);
}
function resetjNiceSelect(obj){
	obj.find('select').each(function(){
		$(this).removeClass('jNiceHidden').attr('style','');
		var c=$(this).clone();
		var p=$(this).parent();
		p.before(c).remove();
		p.children('.jNiceSelectWrapper').remove();
	});
	obj.jNice();
}

function setCity(c,s,r){
	var inShopDelivery=(($('#cart_column').length>0)||($('#productTab').length>0))||(typeof productId != "undefined") ? true:false;
	$.ajax({
		url:'/www/ajax/get-shop-list.html',
		data:{
			cityId:c,
			inShopDelivery:inShopDelivery
		},
		success:function(html){
			$('.shops .list').html(html);
			shopListStart();
			if(s!=undefined){
				$('#shopinfo-'+s+' a.shop').click();
				$('#shopinfo-'+s+' a.seeMap').click();
			}
		}
	});
	
	if(r==undefined)r=$('#regionList select').val();
	
	var url='/www/ajax/get-city-list.html?cityId='+c+'&voivodeshipCode='+r;
	var ww=$('#regionList select option[value='+r+']').text();
	var cc=$('#cityList select option[value='+c+']').text();
	_gaq.push(['_trackEvent', mapType, 'Wybór województwa: '+ww,  cc]); 
	$.ajax({
		url:url,
		success:function(html){
			$('#cityList').html(html);
		}
	});
	return false;
}
function setRegion(r, s){
	var inShopDelivery=(($('#cart_column').length>0)||($('#productTab').length>0))||(typeof productId != "undefined") ? true:false;
	if(s==undefined){
		$.ajax({
			url:'/www/ajax/get-city-list.html',
			data:{
				voivodeshipCode:r,
				inShopDelivery:inShopDelivery
			},
			success:function(html){
				$('#cityList').html(html);
			}
		});
	}
	$.ajax({
		url:'/www/ajax/get-voivodeship-list.html?voivodeshipCode='+r,
		success:function(html){
			$('#regionList').html(html);
			var ww=$('#regionList select option[value='+r+']').text();
			_gaq.push(['_trackEvent',mapType,'Wybór  województwa: '+ww, ww]);
		}
	});
}
function changeItemOnPage(v){
	$.cookie('ile',v,{ path: '/', expires: 10 });
	document.location.reload();
}
function changeOrder(v){
	$.cookie('sortuj',v,{ path: '/', expires: 10 });
	document.location.reload();
}
function fancyClose(text){
	$.fancybox('<div class="w300">'+
					'<div class="f12 tcenter bold">'+text+'</div>'+
					'<div class="h10"></div>'+
					'<div class="tcenter mB5 m0a">'+
						'<a class="buttonMR m0a fnone w50" href="javascript:void(0);" onclick="$.fancybox.close();">Zamknij</a>'+
						'<div class="clear"></div>'+
					'</div>'+
				'</div>');
}
function fancyOk(text){
	fancyOkAction(text, "");
}
function fancyOkAction(text, action){
	$.fancybox('<div class="w300"><div class="f12 bold tcenter">'+text+'</div><div class="mT10 h22"><a href="javascript:void(0);" onclick="$.fancybox.close();'+action+'" style="margin-left:133px;" title="Ok" class="buttonMR">Ok</a><div class="clear"></div></div></div>',{});
}
function searchForm(){
	var q=$('#keyword').val().replace('Czego szukasz','');
	if(q.length==0){
		fancyClose('Wpisz szukaną frazę');
		return false;
	}/*
	else if(q.length<3 && q.length>0){
		fancyClose('Wpisz co najmniej 3 znaki');
		return false;
	}*/
	else {
		addLastSearchKeyword();
		$('#searchForm input[name=q]').val(q);
		$('#searchForm').submit();
	}
	return false;
}
function noFlash(id){
	$('.bnr'+id).css({'height':'auto','text-align':'center'}).html('<div id="content-1c"><div class="center-top"></div><div class="center-content p10 f14 tcenter"><a class="pR10" target="_blank" href="http://www.adobe.com/go/getflashplayer"><img border="0" align="middle" alt="Get Adobe Flash Player" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif"/></a>Aby zobaczyć pełną wersję naszej strony, należy zainstalować aktualną wersję <a target="_blank" href="http://www.adobe.com/go/getflashplayer">wtyczki Adobe Flash Player</a></div><div class="center-bottom2"></div></div>');
}
function smallCart(t){	
	if($.browser.version!='6.0'){
		$.ajax({
			url:'/www/ajax/cart-block.html',
			cache: false,
			success:function(html){
				$('#smallCart').remove();
				$('#rightBoxes .first').append(html);
				$('#smallCart .tab').hover(function(){
					$('#smallCart .center').animate({left:-235},100,function(){
						$('.rightTab .center').not('.sC').css('left',61);
					});
				});
				$('#smallCart .center').hover(function(){},function(){
					$('#smallCart .center').animate({left:61},50,function(){
						$('.rightTab .center').not('.sC').css('left',61);
					});
				});
				if(t==1){
					$('#smallCart .center').animate({left:-235},100);
				}
			}
		});
	}
	$.ajax({
		url:'/www/ajax/top-cart-block.html',
		cache: false,
		success:function(html){
			$('#header #topCart').html(html);
		}
	});

}
function setSelectionPrice(from,to){
	$('#cena_od').val(from);
	$('#cena_do').val(to);
	$('.selectionSubmit:first').click();
}
function selectionSubmit(){
	
	$('.selectionSubmit').click(function(){
		var link='';
		var link2='';
		var cena=$('#cena_od').val();
		if(cena>0)link2+='?cena_od='+cena;
		var cena=$('#cena_do').val();
		if(cena>0){
			if(link2=='')link2+='?cena_do='+cena;
			else link2+='&cena_do='+cena;
		}
		if (query!=''){
			if(link2=='')link2+='?q='+query;
			else link2+='&q='+query;
		}
		if ($('#pokaz_niedostepne').attr('checked')) {
			if(link2=='')link2+='?pokaz_niedostepne=true';
			else link2+='&pokaz_niedostepne=true';
		}
		$('ul.checkbox').each(function(){
			var ul=$(this).attr('title');
			var li='';
			$(this).find('input:checked').each(function(){
				li+=':'+$(this).val();
			});
			if(li!='')link+=','+ul+'-'+li.substr(1);
		});
		
//		if(link!='' || link2!=''){
			var url=urlBase;
			if(link!='' && query=='')url+='lista'+link+'.html';
			else if(link!='' && query!='')url+='szukaj'+link+'.html';
			if(url=='/')url+='szukaj.html';
			
			
		 document.location.href=url+link2;
//		}
//		else {
//			if(document.location.pathname!=urlBase)document.location.href=urlBase;
//		}
	});
}
function selectionMore(){
	$('a.selectionMore').click(function(){
		if($.trim($(this).text())=='rozwiń'){
			$(this).children('span').text("zwiń").addClass("icoXM");
			$(this).parent().find('li.none').slideDown();
		}
		else {
			$(this).children('span').text("rozwiń").removeClass("icoXM");
			$(this).parent().find('li.none').slideUp();
		}
	});
	$('ul.checkbox').each(function(){
		var li=$(this).children('li.none');
		if(li.length<3){
			$(this).parent().children('.selectionMore').click();
		}
	});
}
function selectionLinks(){
	$('#left_column ul.checkbox a').click(function() {
		inputId=$(this).parent().attr('for');		
		$('#'+inputId).attr('checked',true);
		$('.selectionSubmit').click();
		return false;
	});	
}
function textBox(){
	$('.textBox').css('width',$('.topTabs').width() - 35 -$('.topTabs .y').width());
	$('.textBox .icoX').toggle(function(){
		$(this).parent().css({
			height:'auto',
			border:'1px solid silver'
	});
	},function(){
		$(this).parent().css({
			height:11,
			border:'1px solid #ffffff'
		});
	});
}
function normalView(){
	$('#content_column').removeClass('list').addClass('normal');
	$.cookie('viewType','normal', {expires: 20, path: '/'});
	if(!$('#content_column').hasClass('thumbDone')){
		resizeProductListShortItem();
	}
}
function listView(){
	$('#content_column').removeClass('normal').addClass('list');
	$.cookie('viewType','list',{expires: 20, path: '/'});
	if(!$('#content_column').hasClass('listDone')){
		resizeProductListItem();
	}
}

function userData(){
	$.ajax({
		url:'/klient/ajax/logowanie.html',
		cache: false,
		success:function(html){
			$('.userData').append(html);
		}
	});
}

function newsletterEmail(){
	$.ajax({
		url:'/klient/ajax/email.html',
		cache: false,
		success:function(html){
			if (html.indexOf('@')!=-1 && $('#newsletter').length>0){
				$('#newsletter').val(html);
			} else {
				$('#newsletter').example('Adres e-mail',{className: 'clightgrey'});
			}
		}
	});
}

function lastVisited(){
	if($.cookie('devType')!='true'){
		$.ajax({
			url:'/www/ajax/last-visited.html',
			cache: false,
			success:function(html){
				$('#rightBoxes .second').append(html);
				$('.lastVisited .tab').hover(function(){
					$('.lastVisited .center').animate({left:-61},100,function(){
						$('.rightTab .center').not('.lV').css('left',61);
					});
				});
				$('.lastVisited .center').hover(function(){},function(){
					$('.lastVisited .center').animate({left:61},0,function(){
						$('.rightTab .center').not('.lV').css('left',61);
					});
				});
			}
		});
	}
}
function addToBookmarks() {
	var url = window.document.location;
	var title = window.document.title;
	if(window.sidebar){ // Firefox
		window.sidebar.addPanel(title, url,'');
		return;
	}else if(navigator.userAgent.toLowerCase().indexOf('safari') != - 1){
		fancyOk("Naciśnij Ctrl + D aby dodać stronę do ulubionych");
		return;
	}else if(window.opera){ //Opera
		var a = document.createElement("A");
		a.rel = "sidebar";
		a.target = "_search";
		a.title = title;
		a.href = url;
		a.click();
	} else if(document.all){ //IE
		window.external.AddFavorite(url, title);
	};
}
function addToCart(id, shop, quantity){
	$.ajax({
		url:'/klient/ajax/add-to-cart.html',
		type: 'POST',
		cache: false,
		data: {productId: id,
			shopId: shop,
			quantity: quantity},
		success: function(html){
			if (html.redirect!=undefined && html.redirect!=''){
				document.location.href=html.redirect;
			} else {
				//alert(html.msg);
				smallCart(1);
			}
		}
	});
}
function lastSearch(){
	if($.cookie('devType')!='true'){
		$.ajax({
			url:'/www/ajax/last-search.html',
			cache: false,
			success:function(html){
				$('#rightBoxes .third').append(html);
				$('.lastSearch .tab').hover(function(){
					$('.lastSearch .center').animate({left:-61},100,function(){
						$('.rightTab .center').not('.lS').css('left',61);
					});
				});
				$('.lastSearch .center').hover(function(){},function(){
					$('.lastSearch .center').animate({left:61},0,function(){
						$('.rightTab .center').not('.lS').css('left',61);
					});
				});
			}
		});
	}
}
function setMenu(){
	$('#menu ul:first').children('li').hover(function(){
		$(this).addClass('activ');
		subleft = $(this).children('ul').offset().left - $(this).parent().offset().left;
		oversized = parseInt(subleft + $(this).children('ul').width() - $(this).parent().width());		
		if (oversized > 0 ) {			
			$(this).children('ul').css('left',- oversized -6);
		}
	},function(){
		$(this).removeClass('activ');
	});
}
function box920(){
	if ($('.box920').width() > 700) {
		$('.product .col0 .po').css('height',$('.box920 .col0').height()-$('.box920 .col0 .ba').height()-$('#bigPromotion').height()-10);
		$('.product .ab .col3 .ac').css('margin-top',$('.product .ab .col3').height()-$('.product .ab .col3 .ca').height()-$('.product .ab .col3 .ac').height()-10);
	}
}
function productStart(tab){
	$('.compareList a').click(function(){
		if($(this).hasClass('ch')){
			$(this).removeClass('ch');
		}else{
			$(this).addClass('ch');
		}
		showSimilar(productId);
	});
	var c1=$('.product .multimedia').height();
	var c2=$('.product .col0').height()+($('.product .promotionText')?$('.product .promotionText').height()+15:0);
	if(c1>c2)$('.product .col0').css('height',c1);
	else $('.product .multimedia').css('height',c2);
	box920();
	setMultimedia();
	startProductTabs(tab);
	productTabs();
	addLastVisitedProduct(productId);
	var hash=document.location.hash.substr(1).split('-');
	if(hash[0].length>3){
		if(hash[1]!=undefined)window.page=hash[1];
		else window.page='';
		$('.productTabs a span.'+hash[0]).parent().click();
	}
}
function askProductSubmit(){
	if ($('#askProductForm').valid()){
		$.post( 
			'/klient/ajax/askProduct.html', 
			$('#askProductForm').serialize(), 
			function(data){
				if (data.emailSendResult){
					alert('Wiadomość została wysłana');
				} else {
					alert('Nastąpił błąd podczas wysyłania wiadomości');
				}
				$.fancybox.close();
			}
		);
	}
}
function askProduct(){
	$.fancybox({
		href:'/klient/ajax/askProduct.html'
	},{
		onComplete:function(){
			$('#askI').val(productId);
			$('#askN').val($('h1.productName').text());
			$('#askProductForm').validate({
				rules:{
					email:{
						required:true,
						email:true
					},
					name:{
						required:true
					},
					text:{
						required:true
					}
				},
				messages:{
					email:{
						required:"Pole jest wymagane",
						email:"Adres jest niepoprawny"
					},
					name:{
						required:"Pole jest wymagane"
					},
					text:{
						required:"Uzupełnij treść wiadomości"
					}
				},
				errorPlacement : function(error, element) {
					error.appendTo(element.parent());
				}
			});
			$.fancybox.resize();
		}
	});
	
}
function productTabs(){
	$('.productTabs a').click(function(){
		if(!$(this).parent().hasClass('activ')){
			$('.productTabs li.activ').removeClass('activ');
			$(this).parent().addClass('activ');
			var c=$(this).children().attr('class');
			var data=new Object();
			data.ajax=true;
			if(show=='true')data.show='true';
			if(page!=''){document.location.hash='#'+c+'-'+page;data.page=page;
			}else document.location.hash='#'+c;
			if($('#productTab .'+c).hasClass('loaded'))showProductTabs(c);
			else {
				showProductTabs(c);
				$.ajax({
					url: $(this).attr('href'),
					data: data,
					success:function(html){
						$('#productTab .'+c).html(html).addClass('loaded');
						startProductTabs(c);
					},
					error:function(){
						alert('błąd wywołania zakładki');
					}
				});
				return false;
			}
			return false;
		}
		return false;
	});
}
function eWniosek(){
	if($('#lukasverify').is(':checked')){
		return true;
	}else{
		$.fancybox('<div class="w350 tcenter bold f13">Proszę zaznaczyć opcję: ‘Oświadczam, że zapoznałem/am się z informacją o warunkach i sposobie udzielania kredytu ratalnego Credit Agricole Bank Polska’</div><div class="h22 mT10"><a style="margin-left:140px;" href="javascript:void(0);" title="Zamknij" onclick="$.fancybox.close()" class="buttonMR">Zamknij</a><div class="clear"></div></div>');
		return false;
	}
}

function zagielVerify(){
	if($('#zagielConsent').is(':checked')){
		return true;
	}else{
		$.fancybox('<div class="w350 tcenter bold f13">Zanim złożysz zamówienie, zapoznaj się z procedurą udzielenia kredytu ratalnego eRaty Żagiel.</div><div class="h22 mT10"><a style="margin-left:140px;" href="javascript:void(0);" title="Zamknij" onclick="$.fancybox.close()" class="buttonMR">Zamknij</a><div class="clear"></div></div>');
		return false;
	}
}

function setMultimedia(){
	$('.multimedia .tabs a').click(function(){
		if(!$(this).hasClass('activ')){
			$('.multimedia .tabs a.activ').removeClass('activ');
			$(this).addClass('activ');
		}
	});
	var i=0;
	$('.col1 a[rel=galeria]').each(function(){
		$(this).attr('photo',i);
		i++;
	}).fancybox({}).hover(function(){
		var i=$(this).attr('photo');
		$('#productImage').attr('photo',i).attr('href',$('#photo'+i).val());
		$('#productImage .i').html('<img alt="" src="'+$('#photo'+i).val()+'"/>');
	});
	$('#productImage').click(function(){
		var i=$(this).attr('photo');
		if(i==undefined)i=0;
		$('.col1 a:eq('+i+')').click();
		return false;
	});
}

/**
 * Dodaje parametr id na początek tablicy
 * @param id
 * @return
 */
function addLastVisitedProduct(id) {
	
	var lastVisited = $.cookie('last-visited');
	var lastVisitedTable = (lastVisited == null) ? new Array() : lastVisited.split('|');
	var newT=new Array();
	$(lastVisitedTable).each(function(i,n){
		if(n!=id){
			newT.push(n);
		}
	});
	newT.push(id);
	var t=newT.length-15;
	for(var i=t;i>0;i--)newT.shift();
	$.cookie('last-visited', newT.join('|'), { expires: 30, path: '/'});
}

/**
 * Dodaje słowo kluczowe keyword na początku tablicy
 * @param keyword
 * @return
 */
function addLastSearchKeyword() {
	
	var keyword = $.trim($('#keyword').val());
	var lastSearch = $.cookie('last-search');
	var lastSearchTable = (lastSearch == null) ? new Array() : lastSearch.split('|');
	
	if(lastSearchTable.indexOf && lastSearchTable.indexOf(keyword) > -1) {
	
		lastSearchTable.splice(lastSearchTable.indexOf(keyword), 1);
	}	
	lastSearchTable.unshift(keyword);
	lastSearchTable = lastSearchTable.slice(0,10);
	
	$.cookie('last-search', lastSearchTable.join('|'), { expires: 30, path: '/'});
}
function shopListStart(){
	$('#shopList .shop').click(function(){
	    var p=$(this).parent();
	    if(!p.hasClass('activ')){
	        $('#shopList .activ').removeClass('activ').children('.hideText').hide();
	        p.addClass('activ').children('.hideText').show();
	        var ww=$('#regionList select option:selected').text();
	        _gaq.push(['_trackEvent',mapType,'Wizytówki: '+ww,  $(this).text()+' - rozwinięcie']); 
	        //console.log($(this).text()+' - rozwinięcie');
	    }
	});
	shopShopDetail($('#shopList .seeMap'));
	
}
function shopShopDetail(name){
	name.click(function(){
		var a=$(this).attr('rel');
		$.fancybox({
			href:'/www/ajax/get-shop-info.html?shopId='+a
		},{
			type:'ajax',
			onComplete:function(){
				$('#mapL').html('<iframe frameborder="0" scrolling="no" id="mapIframe" src="/www/googleMap.html?key='+$('#googleMapsKey').val()+'&address='+$('#mapAddress').text()+'"></iframe>');
			}
		});
		var ww=$('#regionList select option:selected').text();
		var ss=$(this).parents('li').find('.shop').text();
		_gaq.push(['_trackEvent',mapType,'Wizytówki: '+ww, ss+' - wizytówka']); 
		//console.log('Wizytówki: '+ww+'   '+ss+' - wizytówka');
		return false;
	});
}
function startProductTabs(c){
	switch(c){
		case 'opis':
			//alert('opis');
		break;
		case 'odbior':
			shopListStart();
			setTimeout("if($.browser.version!='6.0')$('#regionSelect');",100);
		break;
		case 'opinie':
			opinionStart();
		break;
		case 'akcesoria':
			//alert('akcesoria');
		break;
	}	
}
function opinionStart(){
	if($.browser.version!='6.0')$('#opinionForm .col2').jNice();
	$('#opinionText').example('Wpisz kilka słów');
	newOpinionValidate();
	$('#opinionForm input').keyup(function(event){if(event.keyCode == 13)$('#opinionForm').submit();});
	$('#opinionForm').ajaxForm({
		target: '#productTab .opinie',
		beforeSubmit: function() {
            return $('#opinionForm').validate().form();
        },
		success: function(){
			opinionStart();
		}
	});
	$('.opinion .hr:last').hide();
	$('#rate a').each(function(i){
		$(this).attr('i',i+1);
	}).hover(function(){
		rateHoverOn($(this).attr('i'));
	},function(){
		rateHoverOn($('#rateInput').val());
	}).click(function(){
		$('#rateInput').val($(this).attr('i'));
		$('#rate div').text($(this).attr('i')+' na 10');
		$('#opinionForm').validate().element('#rateInput');
	});
	$('#rate a.u'+$('#rateInput').val()).click();
	rateHoverOn($('#rateInput').val());
}
function showOpinionForm(){
	$('.opinion .hr:last').show();
	$('#opinionForm').show();
	$.scrollTo('#opinionForm',200);
	
}
function rateHoverOn(i){
	$('#rate a').each(function(){
		if(parseInt($(this).attr('i'))<=i)$(this).addClass('over');
		else $(this).removeClass('over');
	});
}
function newOpinionValidate(){
	$('#opinionForm').validate({
		rules:{
			title:{
				required:true,
				minlength:6
			},
			description:{
				required:true,
				minlength:20
			},
			authorName:{
				required:true,
				minlength:1
			},
			rate:{
				required:true
			}
		},
		messages:{
			title:{
				required:"Pole tytuł jest wymagany",
				minlength:"Tytuł powinien zawierać min. 6 znaków"
			},
			description:{
				required:"Pole opinia o produkcie jest wymagana",
				minlength:"Opinia powinna zawierać min. 20 znaków"
			},
			authorName:{
				required:"Pole autor jest wymagane"
			},
			rate:{
				required:"Podaj swoją ocenę produktu"
			}
		}
	});
}
function newOfferSubmit(){
	if ($('#offerWorth').val()) {
		if ($("#offerGenerator input[type='checkbox']:checked").attr('checked')) {
			$('#offerGeneratorForm').submit();
			}
		else {
			fancyClose('Wybierz przynajmniej jedno pokazywane pole');
		}
		}
	else {
		fancyClose('Wpisz wartość oferty');
	}
}
function showProductTabs(c){
	$('#productTab .productTab').hide().removeClass('activ');
	$('#productTab .'+c).show().addClass('activ');
}
function itemPaging(i){
	$('#similarList .it').hide();
	$('#similarListTop .paging a.span').removeClass('span');
	i--;
	$('#similarListTop .paging a:eq('+i+')').addClass('span');
	$('#similarList .it:eq('+i+')').show();
}
function showSimilar(productId) {
	var selected = [];
	$('.compareList a.ch').each(function() {
		selected.push($(this).attr('id').substr(7));
	});
	if (selected.length == 0) {
		$('#similarListTop').slideUp();
		$('#similarList').slideUp().html('');
	} else {
		$.ajax( {
			url : "/www/produkty-podobne.html",
			data : {
				id : productId,
				attribute : selected
			},
			traditional : true,
			success : function(result) {
				if($.trim(result)==''){
					$('#similarListTop').slideUp();
					$('#similarList').slideDown().html('<div class="p10 pT15 cred bold bT">Nie znaleziono podobnych produktów.</div>');
				}else{
					$('#similarListTop').slideDown();
					$('#similarList').html(result).slideDown('fast');
					$('#similarListTop .item .paging').html($('#hiddenPaging').html());
					$('#similarList .productCheckbox').click(function(){
						if($(this).hasClass('a')){
							$(this).removeClass('a');
						}else{
							if($('#similarList a.a').length==2){
								$.fancybox('Można wybrać tylko dwa produkty do porównywanego',{});
							}else{
								$(this).addClass('a');
							}
						}
					});
				}
			}
		});
	}
}
function resizeProductListShortItem(){
	$('.shortRow').each(function(){
		var h=0;
		var o=$(this).find('.ab');
		o.each(function(){
			var hh=$(this).height();
			if(hh>h)h=hh;
		});
		o.css('height',h).each(function(){
			if($(this).children('.productStatus').length){
				$(this).children('.ca').css({
					'height':h-28,
					'overflow':'hidden'
				});
			}
		});
	});
	$('#content_column').addClass('thumbDone');
}
var vloadingFrame=1;

function fancybox_animate_loading(){
	$('#fancybox-loading div').css('top', (vloadingFrame * -40) + 'px');
	vloadingFrame = (vloadingFrame + 1) % 12;
}

function loadingStop(){
	if($.browser.version!='6.0'){
		$('#fancybox-overlay').hide();
		$('#fancybox-loading').hide();
	}
}
function loadingStart(){
	if($.browser.version!='6.0'){
		$('#fancybox-wrap').hide();
		$('#fancybox-overlay').css('opacity',0.2).show();
		$('#fancybox-loading').unbind('click').css('cursor','auto').show();
		setInterval(fancybox_animate_loading, 80);
	}
	else $.fancybox.close();
}
function deleteComparisionProduct(id){
	compare(id);
	var s="";
	var y=[];
	var t=$('#p').val().split("|");
	$(t).each(function(i,n){
		if(n!=id){
			y.push(n);
			s+='&p='+n;
		}
	});
	if(y.length>1){
		document.location='/www/product-compare.html?'+s.substr(1)+'&g='+$('#groupId').val();
	}else{
		document.location=$('#back').attr('href');
	}
}

function resizeProductListItem(){
	
	$('.productList').each(function(){
		var vm=0;
		var v=$(this).children('.col1').height();
		if(v>vm)vm=v;
		var v=$(this).children('.col2').height();
		if(v>vm)vm=v;
		var v=$(this).children('.col3').height();
		if(v>vm)vm=v;
		$(this).children('.col2, .col3').css('height',vm);
		$(this).children('.col1').css('height',vm+4);
		
		var c2=$(this).children('.col2');
		c2.children('.ba').css('margin-top',vm-c2.children('.ab').height()-c2.children('.ba').height()-15);
		var c3=$(this).children('.col3');
		c3.children('.ac').css('margin-top',vm-c3.children('.ac').height()-c3.children('.ca').height()-9);
		
	});
	
	$('#content_column').addClass('listDone');
}
function productListStart(){
	if($('#content_column').hasClass('list') || $.cookie('viewType')=='list')listView();
	else  resizeProductListShortItem();
	startCompare();
	selectionMore();
	selectionLinks();
	selectionSubmit();
	$('#cena_od').example('-- od --',{className: 'clightgrey'});
	$('#cena_do').example('-- do --',{className: 'clightgrey'});
	$("input.float, input.number").keyfilter(/[\d.]/);
	$("#quantity").keyfilter((/[0-9]/i));
}
function startCompare(){
	$('.compareP').click(function(){
		var p=$(this).attr('prodid');
		if(p>0){
			compare(p);
		}
	});
	var group=$('#groupId').val();
	var c=$.cookie('compare_'+group);
	var img=$.cookie('compareI_'+group);
	if((c=='' || c==null) || (img=='' || img==null)){

	}else{
		var t=$.cookie('compare_'+group).split('|');
		var im=$.cookie('compareI_'+group).split('|');
		var n=$.cookie('compareN_'+group).split('|');
		var lt=t.length;
		if(lt>0){
			for(var i=0;i<lt;i++){
				$('.compareI'+i+' img').remove();
				$('.compareI'+i).removeClass('on');
				if(t[i]!=''){
					$('.compareBox').show();
					$('.compareI'+i).addClass('on').append('<img src="'+im[i]+'" alt="Usuń z porównania '+n[i]+'"/>').attr('prodId',t[i]).attr('title','Usuń z porównania '+n[i]);
					$('#p'+t[i]+',#s'+t[i]).addClass('a');
				}
			}
		}
	}
}
function compa(id){	
	var add=0;
	var g=$('#groupId').val();
	var c=$.cookie('compare_'+g);
	if(c=='' || c==null){
		$.cookie('compare_'+g, '||');
		c=$.cookie('compare_'+g);
	}
	var t=c.split('|');
	var lt=t.length;
	var co=0;
	for(var i=0;i<lt;i++){
		if(t[i]!='')co++;
	}
	if (co==2 || (co==3 & add==0)) {
		$.cookie('lastPage',document.location.href,{path:'/'});
		document.location='/www/product-compare.html?p='+t[0]+'&p='+t[1]+'&p='+t[2]+'&g='+g;
        /*$.fancybox({
 			href:'/www/product-compare.html?ajax=true&p='+t[0]+'&p='+t[1]+'&p='+t[2]
 		},{});*/
	}
	else {
		fancyClose('Wybierz co najmniej dwa produkty');
	}
}
function nextPhoto(){
	var i=parseInt($('#shopGallery').attr('i'));
	var a=parseInt($('#shopGallery').attr('a'));
	if(i<a){
		i++;
		$('#shopGallery img').hide();
		$('#shopGallery img:eq('+(i-1)+')').show();
		$('#shopGallery').attr('i',i);
		if(i==a){
			$('#shopGallery .next').hide();
		}else{
			$('#shopGallery .next').show();
		}
		$('#shopGallery .prev').show();
	}
}
function prevPhoto(){
	var i=parseInt($('#shopGallery').attr('i'));
	var a=parseInt($('#shopGallery').attr('a'));
	if(i>1){
		i--;
		$('#shopGallery img').hide();
		$('#shopGallery img:eq('+(i-1)+')').show();
		$('#shopGallery').attr('i',i);
		if(i==1){
			$('#shopGallery .prev').hide();
		}else{
			$('#shopGallery .prev').show();
		}
		$('#shopGallery .next').show();
	}
}
function showC(){
	$('#showB').hide();
	$('#hideB').show();
	$('table.compare .different').addClass('diff');
}
function hideC(){
	$('#showB').show();
	$('#hideB').hide();
	$('table.compare .different').removeClass('diff');
}
function compareSimilar(){
	$.cookie('lastPage','javascript:$.fancybox.close();')
	var link = '/www/product-compare.html?ajax=true&g='+groupId+'&p='+productId;
	$('#similarList .a').each(function(){
		link += '&p='+$(this).attr('id').substr(2);
	});
	$.fancybox({
		href:link
	},{});
}

function compare(id,img,name){
	function StripTags(str)
	{
	    //wyrażenie regularne na usuwanie tagów i pozostawianie tekstu wewnątrz nich
		var tagREG=new RegExp('<[a-zA-Z/]{1,15}.*?>','g');
		return str.replace(tagREG,'');
	}
	if (name) {name=StripTags(name);}
	$('.compareBox').show();
	var g=$('#groupId').val();
	var c=$.cookie('compare_'+g);
	var o=$.cookie('compareI_'+g);
	var n=$.cookie('compareN_'+g);
	if((c=='' || c==null) || (o=='' || o==null)){
		$.cookie('compare_'+g, '||',{expires: 2, path: '/'});
		$.cookie('compareI_'+g, '||',{expires: 2, path: '/'});
		$.cookie('compareN_'+g, '||',{expires: 2, path: '/'});
		c=$.cookie('compare_'+g);
	}
	var t=c.split('|');
	var im=$.cookie('compareI_'+g).split('|');
	var n=$.cookie('compareN_'+g).split('|');
	
	var del=0;delP='';
	for(var i=2;i>=0;i--){
		if(t[i]=='')var l=i;
		if(t[i]==id){var del=1;delP=i;t[i]='';im[i]='';n[i]='';}
	}
	if(del==1){
		if(delP==0){
			t[0]=t[1];t[1]=t[2];t[2]='';
			im[0]=im[1];im[1]=im[2];im[2]='';
			n[0]=n[1];n[1]=n[2];n[2]='';
		}
		if(delP==1){
			t[1]=t[2];t[2]='';
			im[1]=im[2];im[2]='';
			n[1]=n[2];n[2]='';
		}
		$('.compareP img').remove();
		$('.compareP').removeClass('on');
		$('.compareP').attr('prodId',0).attr('title','');
		for(var i=0;i<3;i++){
			if(t[i]!=''){
				$('.compareI'+i).addClass('on').append('<img src="'+im[i]+'" alt="Usuń z porównania '+n[i]+'"/>').attr('prodId',t[i]).attr('title','Usuń z porównaniaa '+n[i]);
			}
		}
		$('#p'+t[i]+',#s'+t[i]).attr('checked',false);
		$.cookie('compare_'+g, t[0]+'|'+t[1]+'|'+t[2],{expires: 2, path: '/'});
		$.cookie('compareI_'+g, im[0]+'|'+im[1]+'|'+im[2],{expires: 2, path: '/'});
		$.cookie('compareN_'+g, StripTags(n[0])+'|'+StripTags(n[1])+'|'+StripTags(n[2]),{expires: 2, path: '/'});
		$('#s'+id+',#p'+id).removeClass('a');
		
	}else{
		if(t[2]!=''){
			fancyClose('Wybrano już trzy produkty');
			$('#p'+id+',#s'+id).removeClass('a');
		}else{
			t[l]=id;
			im[l]=img;
			n[l]=name;
			$('.compareI'+l+' img').remove();
			$('.compareI'+l).removeClass('on');
			$('.compareI'+l).addClass('on').append('<img src="'+img+'" alt="Usuń z porównania '+name+'"/>').attr('prodId',id).attr('title','Usuń z porównania '+name);
			
			$.cookie('compare_'+g, t[0]+'|'+t[1]+'|'+t[2],{expires: 2, path: '/'});
			$.cookie('compareI_'+g, im[0]+'|'+im[1]+'|'+im[2],{expires: 2, path: '/'});
			$.cookie('compareN_'+g, n[0]+'|'+n[1]+'|'+n[2],{expires: 2, path: '/'});
			$('#s'+id+',#p'+id).addClass('a');
		}
	}
}
function removeCompareProduct(i){
	compare(i);
	$('#compareProduct'+i).remove();
	if($('.compareProduct tr').length){
		$.fancybox.resize();
		$('.compareTitle').text('Porównywane produkty:');
	}
	else $.fancybox.close();
}
function setCarousel(){
	$('.carousel').each(function(){
		var hmax=0;
		var w=$(this).children('.li:first').width();
		var l=$(this).children('.li');
		l.each(function(){
			var htmp=parseInt($(this).height());
			if(htmp>hmax)hmax=htmp;
		}).css('height',hmax);
		
		var ll=parseInt(l.length);
		var ww=Math.ceil($(this).width()/w);
		$(this).css({
			height:hmax,
			width:$(this).width(),
			overflow:'hidden'
		}).attr('carousel','0|'+ll+'|'+ww+'|'+w);
		if(ll>ww){
			$(this).wrapInner('<div class="container" />').append('<a class="carousel-left" href="javascript:void(0);"/>').append('<a class="carousel-right" href="javascript:void(0);"/>');
			$(this).children('.carousel-left').click(function(){
				var t=$(this).parent();
				var c=t.attr('carousel').split('|');
				if(c[0]>0){
					c[0]--;
					t.attr('carousel',c[0]+'|'+c[1]+'|'+c[2]+'|'+c[3]);
					//if(c[0]==0)t.children('.carousel-left').hide('fast');
					if(c[0]==0)t.children('.carousel-left').css('background-position','0 -78px');
					//if(c[1]-c[2]>c[0]) t.children('.carousel-right').show('fast');
					if(c[1]-c[2]>c[0]) t.children('.carousel-right').css('background-position','0 -39px');
					t.children('.container').animate({left: '+='+c[3]},300,function(){});
				}
			});
			$(this).children('.carousel-right').click(function(){
				var t=$(this).parent();
				var c=t.attr('carousel').split('|');
				if(c[1]-c[2]>c[0]){
					c[0]++;
					t.attr('carousel',c[0]+'|'+c[1]+'|'+c[2]+'|'+c[3]);
					//if(c[0]>0)t.children('.carousel-left').show('fast');
					if(c[0]>0)t.children('.carousel-left').css('background-position','0 -117px');
					//if(c[1]-c[2]==c[0]) t.children('.carousel-right').hide('fast');
					if(c[1]-c[2]==c[0]) t.children('.carousel-right').css('background-position','0 0');
					t.children('.container').animate({left: '-='+c[3]},300,function(){});
				}
			});
		}
	});
}
function menuHeaderHideShow() {
	
	$('.menu-header-hideshow').hover(
			function() {
				//var pos = $(this).position();
				$('.hidden-menu-item-box', this).show();
			},
			function() {
				$('.hidden-menu-item-box', this).hide();
			}
	)
	
}

function offerGeneratorShowHide() {
	
	$('.shgo').toggleClass('hide');
	$('#offerGenerator').slideToggle();
	
}
