/*!
 * metalpedia.pl - scripts
 * http://metalpedia.pl/
 *
 * Copyright 2010, Tomasz Ernestowicz
 * http://d2m.pl
 *
 */


function prepare_id(given_id){
    given_id = given_id.replace(/\s/gi,"_");
    given_id = given_id.replace(/\./gi,"").toLowerCase();
    return given_id;
}


var submenuTween;
var submenuTimeout;

function makeFiltersRows()
{
		var $newFiltersCont = "<ul><li><ul>";
		$('.filters .filtersItem-inner2>ul>li').each(function(index){ $newFiltersCont+="<li>"+$(this).html()+"</li>";
																		if(index == 4 || index == 9 || index == 14 || index == 19 || index == 24 || index == 29 || index == 34 || index == 39 || index == 44 || index == 49) $newFiltersCont+="</ul></li><li><ul>" });
		$newFiltersCont += "</ul></li></ul>";
		
		$('.filters .filtersItem-inner2').html($newFiltersCont);
}

function newSelect(selectObject)
{
var downKeyBuffor = -1;

	selectObject.after('<div class="newSelectContener"><a href="javascript:void(0)" class="newSelectBtn"><span></span></a><div class="newSelect"><input class="search" name="search" type="text" size="20" value="szukaj opcji" /><ul></ul></div></div>');
	
	
	var children_array = new Array();
	var optgroup_array = new Array();
	var optInOptGr_array = new Array();

	$.each(selectObject.children("optgroup, option"), function(index,el){
                if($(el).attr('title') != ""){
                    children_array[index] = 'optGr';
                }    
                else {
                        children_array[index] = new Array();
                        children_array[index][0] = $(el).attr("value");
                        if($(el).attr('selected')) {
                                children_array[index][1] = 'selected="selected"';
                                children_array[index][3]='class="active"';
                                selectObject.next().find('.newSelectBtn span').text($(el).text())
                        }
                        else {
                                children_array[index][1] = "";
                                children_array[index][3]='';
                        }
                        children_array[index][2] = $(el).text();
                }
                });

	$.each(selectObject.children("optgroup"), function(index){
                optgroup_array[index] = $(this).attr('label');
                optInOptGr_array[index] = new Array();
                $.each($(this).children('option'),
                function(index2){
                        optInOptGr_array[index][index2] = new Array();
                        optInOptGr_array[index][index2][0] = $(this).attr("value");
                        if($(this).attr('selected')) {
                                optInOptGr_array[index][index2][1] = 'selected="selected"';
                                optInOptGr_array[index][index2][3]='class="active"';
                                selectObject.next().find('.newSelectBtn span').text($(this).text())
                        }
                        else {
                                optInOptGr_array[index][index2][1] = "";
                                optInOptGr_array[index][index2][3]='';
                        }
                        optInOptGr_array[index][index2][2] = $(this).text();
                }
                )
        }
		  );
	
	var newSelectCont = "";
	var optNumber = 0;

	for (i = 0; i < children_array.length; i++)
  	{
 	 	if(children_array[i] == 'optGr' && typeof(optInOptGr_array[optNumber]) != "undefined"){
			newSelectCont += '<li style="clear:both !important; float:none!important; padding: 4px 0 2px 0 !important; "><b>'+optgroup_array[optNumber]+'</b></li>';
                        for (j = 0; j < optInOptGr_array[optNumber].length; j++)
			{
                            var id = selectObject.attr("name")+selectObject.attr("title")+"_"+optInOptGr_array[optNumber][j][0];
                            id = prepare_id(id);
                            newSelectCont += '<li><input name="'+selectObject.attr("name")+'" type="radio" '+optInOptGr_array[optNumber][j][1]+' value="'+optInOptGr_array[optNumber][j][0]+'" id="'+id+'" /><label for="'+id+'" '+optInOptGr_array[optNumber][j][3]+'>'+optInOptGr_array[optNumber][j][0]+'</label></li>';
			}
			newSelectCont += '<li style="clear:both; float:none;" class="optLabel"></li>';
			optNumber++;
		}
		else{
			newSelectCont += '<li><input name="'+selectObject.attr("name")+'" type="radio" '+children_array[i][1]+' value="'+children_array[i][0]+'" id="'+selectObject.attr("name")+selectObject.attr("title")+"_"+children_array[i][0]+'" /><label for="'+selectObject.attr("name")+selectObject.attr("title")+"_"+children_array[i][0]+'" '+children_array[i][3]+'>'+children_array[i][2]+'</label></li>';
		}
		
 	}
	
	selectObject.next().find('ul').append(newSelectCont);	
	
	
	
	
	
	
	selectObject.next().first().find('ul li input').change( function(){
						$(this).closest('.newSelectContener').prev().val($(this).val()).change();
						downKeyBuffor = $(this).closest('li').index();
						$(this).closest('ul').find('li label').removeClass('active');
						$(this).next().addClass('active');
						if($(this).next().text()=="wszystkie") $(this).next().text("");
						$(this).closest('.newSelectContener').find('.newSelectBtn span').html($(this).next().text());
						$(this).closest('.newSelectContener').prev().prev().show(80);
						$(this).closest('.newSelectContener').find('.newSelectBtn span').removeClass("empty");
						$(this).closest('.newSelect').hide();
						$(this).closest('.newSelect').find('.newSelectBtn').css('border-color', '#999');
						} );
	selectObject.next().first().find('ul li label').click(function(){$(this).prev().change();});
	
	selectObject.next().click(function(){$(this).children('.newSelect').fadeIn(160); $(this).children('.newSelect').addClass("newSelectActive"); $(this).children('.newSelectBtn').addClass("newSelectBtnActive") } );
	selectObject.next().hoverIntent(function(){}, function(){
							$(this).children('.newSelect').fadeOut(70);
							$(this).find('.newSelect li').show();
							$(this).find('input.search').val("szukaj opcji");
							$(this).children('.newSelect').removeClass("newSelectActive");
							$(this).children('.newSelectBtn').removeClass("newSelectBtnActive");
					});
	selectObject.next().find('input.search').attr('autocomplete', "off");
	
	selectObject.next().find('input.search').focus(function(){ downKeyBuffor = -1 });
	selectObject.next().find('input.search').keyup(function(event){
										
										$.each($(this).parent().find('li'), function()
										{
											var b = new RegExp($(this).closest('.newSelect').children('input.search').val(), "i");
											var a = $(this).children('label').text().match(b);
											$(this).children('label').html($(this).children('label').text().replace(
																b,
																"<b>"+a+"</b>"));
											if(a || $(this).hasClass("optLabel") ) {
												$(this).show();
											} else {
												$(this).hide();
												if($(this).prev("li:visible").hasClass("optLabel") && $(this).next("li").hasClass("optLabel")){
												$(this).prev("li:visible").hide();
												}
											}

										} )
										
										})
										
	selectObject.next().find('input.search').keydown(function(event){
										if (event.keyCode == '40'){ downKeyBuffor++; $(this).parent().find('li:visible:eq('+downKeyBuffor+') input').change(); }
										else if (event.keyCode == '38'){ downKeyBuffor--; $(this).parent().find('li:visible:eq('+downKeyBuffor+') input').change(); }
	});
	
	selectObject.next().find('input.search').focus(function(){$(this).val("")});
	selectObject.next().find('input.search').blur(function(){ if($(this).val()== "") $(this).val("szukaj opcji")});
	
	var labelMaxWidth = 0;
	
	// layout
	
	selectObject.next().find('.search').hide();
	
	selectObject.next().find('li').css('clear', 'both');
	var labelMaxWidth = selectObject.next().find('.newSelect').width()-10;
	if(labelMaxWidth == -10) labelMaxWidth = 250;
	if(labelMaxWidth < 70) labelMaxWidth = 70;
	
	if(labelMaxWidth < 300) {
	  selectObject.next().find('label').width(labelMaxWidth);
	  selectObject.next().find('input.search').width(labelMaxWidth);
	  
	  if(Math.floor(300 / labelMaxWidth) > selectObject.next().find('li').length)
	  {
		  if(selectObject.next().find('li').length < 300 && labelMaxWidth ==70) selectObject.next().find('.newSelect').width(80);
		  else if(selectObject.next().find('li').length < 300 && labelMaxWidth >= 70) selectObject.next().find('.newSelect').width(labelMaxWidth+10);
		  else selectObject.next().find('.newSelect').width(selectObject.next().find('li').length*(labelMaxWidth+10));
	  }
	  else {
	    selectObject.next().find('.newSelect').width(Math.floor(300 / labelMaxWidth)*(labelMaxWidth+10));
	  }
	  
	} else {
	  selectObject.next().find('label').width(360);
	  selectObject.next().find('.newSelect').width(367);
	}
	
	selectObject.next().find('li').css('clear', 'none');
	selectObject.next().find('.search').show();
	
	if(selectObject.next().find('.newSelectBtn span').text()=="") {
		selectObject.next().find('.newSelectBtn span').html(selectObject.prev().text()); selectObject.prev().hide();
		selectObject.next().find('.newSelectBtn span').addClass("empty");
		selectObject.next().find('.newSelectBtn').css('border-color', '#444');
		}
	selectObject.hide();
	
	$('#mainContent .filtersItem').slideDown(300);
	
	
}
function hideSubmenu()
{
	
}

function hideOuterPanel(panelToHide)
{
	panelToHide.fadeOut(200);
	setTimeout("$('#externalPanelOuter').slideUp(200)", 200);
}
function showOuterPanel(panelToShow)
{
	$("#externalPanelOuter").slideDown(200);
	$("#externalPanelOuter .externalPanel").fadeOut(200);
	setTimeout(function(){ $(panelToShow).fadeIn(200); }, 200);
}
var choosenProdImage = 0;
function moveProdGallery(moveId, isExactPosition)
{
	if(isExactPosition) choosenProdImage = parseFloat(moveId) - 1;
	else choosenProdImage += moveId;
	if( choosenProdImage >= 0 && choosenProdImage < $('.prodGallery ul.imagesList').children('li').length )
	{
		var newPos = (choosenProdImage * -166).toString()+"px";
		$('.prodGallery ul.imagesList').animate({left: newPos}, 300);
		$('.prodGallery .nav li').removeClass("active");
		var num =  parseFloat(choosenProdImage)+1;
		$('.prodGallery .nav .photo'+num).addClass("active");
	}
}
function showSubmenu(choosenItem)
{
	choosenItem.parent().parent().children('li').removeClass("active");
	choosenItem.parent().addClass("active");
	
	choosenItem.parent().parent().children('li').each(function(index){
		if(!$(this).hasClass("active"))
		{
			$(this).children('ul').children('li').removeClass("active");
			$(this).children('ul').children('li').children('a').animate({backgroundPosition: '-230px 0px'}, 200).css('color', '#fff');
			$(this).children('a').animate({backgroundPosition: '-230px 0px'}, 200).css('color', '#fff');
			$(this).children('li').children('a').animate({backgroundPosition: '-230px 0px'}, 200).css('color', '#fff');
			$(this).children('ul').hide(200);
			$(this).children('ul').children('li').children('ul').hide(200);
		}
    });
	
	setTimeout(function(){ choosenItem.parent().children('ul').show(200); }, 200);
	
	setTimeout(function(){ 
						var m = parseFloat(choosenItem.parent().children("ul").offset().top) + parseFloat(choosenItem.parent().children("ul").height()) - 550;
						if(iniMainCategoriesHeight < m) $(".mainCategories").animate({height:  m+"px"}, 200);
						else $(".mainCategories").animate({height: iniMainCategoriesHeight+"px"}, 200);
						
					 }, 500);	
	
	
}

function removeProduct(prodObj, prodId)
{
	if(confirm("Czy na pewno chcesz usunąć produkt z koszyka?"))
	{
		deleteProductForBasket(prodId);
		prodObj.slideUp(200);
		choosenProdList = prodObj.parents(".prodList");
		choosenProdInfo = prodObj.parents("li");
		setTimeout(function(){ prodObj.remove(); countOrderAmount(choosenProdList); if(!choosenProdList.find('li').is('li')) choosenProdList.slideUp(200); }, 200);
		setTimeout(function(){ if(!choosenProdList.find('li').is('li')) { choosenProdList.remove(); choosenProdInfo.slideUp(200); } }, 400);
		setTimeout(function(){ if(!choosenProdList.find('li').is('li')) { choosenProdInfo.remove(); } }, 600);
		
	}
}
function countOrderAmount(choosenProdList)
{
	var newValueNetto;
	var newValueBrutto;
	
	newValueNetto = 0;
	newValueBrutto = 0;
	choosenProdList.find('.prodItem').each(function(index){
										  var a = $(this).children('.prodItem-inner').children('.price').children('.brutto').children('.value').text().replace(",",".").replace(" ","");
										  var b = $(this).children('.prodItem-inner').children('.price').children('.netto').children('.value').text().replace(",",".").replace(" ","");
										  newValueBrutto += parseFloat(a);
										  newValueNetto += parseFloat(b);
										   });
	newValueNetto = Math.round(newValueNetto * 100);
	newValueNetto += "";
	newValueNetto = newValueNetto.substr(0, newValueNetto.length-2)+","+newValueNetto.substr(-2);
	choosenProdList.find('.orderAmount .valueNetto').text(newValueNetto);
	
	newValueBrutto = Math.round(newValueBrutto * 100);
	newValueBrutto += "";
	newValueBrutto = newValueBrutto.substr(0, newValueBrutto.length-2)+","+newValueBrutto.substr(-2);
	choosenProdList.find('.orderAmount .valueBrutto').text(newValueBrutto);
	
	
	
	newValueNetto = 0;
	newValueBrutto = 0;
	
	$('#mainContent .prodList').each(function(index){
										  var a = $(this).find('.orderAmount').children('.valueBrutto').text().replace(",",".").replace(" ","");
										  var b = $(this).find('.orderAmount').children('.valueNetto').text().replace(",",".").replace(" ","");
										  newValueBrutto += parseFloat(a);
										  newValueNetto += parseFloat(b);
										   });
	
	if(newValueNetto==0) { $(".totalOrderValue").html("<strong style='color: #fff'>Twój koszyk jest pusty.</strong>"); $("#makingOrderNav").hide(100); }
	
	newValueNetto = Math.round(newValueNetto * 100);
	newValueNetto += "";
	newValueNetto = newValueNetto.substr(0, newValueNetto.length-2)+","+newValueNetto.substr(-2);
	newValueBrutto = Math.round(newValueBrutto * 100);
	newValueBrutto += "";
	newValueBrutto = newValueBrutto.substr(0, newValueBrutto.length-2)+","+newValueBrutto.substr(-2);

	
	$('#mainContent .totalOrderValue .valueNetto').text(newValueNetto);
	$('#mainContent .totalOrderValue .valueBrutto').text(newValueBrutto);
											  
}

var iniMainCategoriesHeight;

function ini()
{
	
		var tempInputValue;
		
		$('.prodItem .prodNumberInput').blur( function(){if($(this).attr('value') == "") $(this).attr('value', tempInputValue); } );
		
		$('.prodItem .prodNumberInput').focus( function(){ tempInputValue = $(this).attr('value'); $(this).attr('value', ''); } );
		
		$('.prodItem .prodNumberInput').keyup( function(){
													   if($(this).attr('value') != "")
													   {
														   var newPrice = parseFloat($(this).parent().parent().children('.price').children('.pricePerUnit').children('.value').text()) * parseFloat($(this).attr('value'));
														   newPrice = Math.round(newPrice * 100) / 100;
														   $(this).parent().parent().children('.price').children('.netto').children('.value').text(newPrice);
														   newPrice = newPrice + newPrice * parseFloat("0."+$(this).parent().parent().children('.price').children('.vat').children('.value').text());
														   newPrice = Math.round(newPrice * 100) / 100;
														   $(this).parent().parent().children('.price').children('.brutto').children('.value').text(newPrice);
														   countOrderAmount($(this).parents(".prodList"));
													   }
													   } );
		
		
		
		
		
		var choosenCategory= $('.mainCategories li');
		
		$('#content .bestsellers li').hover(function(){ $(this).children('a').children('.extraSpan').animate({top: '-20px'}, 100) },
										        function(){  $(this).children('a').children('.extraSpan').animate({top: '-100px'}, 200) });
		
		$('.sidebarList li').hover(function(){ $(this).children('a').animate({backgroundPosition: '-160px 0px'}, 120) },
										 function(){ $(this).children('a').animate({backgroundPosition: '-320px 0px'}, 200) }) ;
		
		$('#content .news ul.newsList li').hover(function(){ $(this).children('a').animate({backgroundPosition: '-350px 0px'}, 120) },
										 function(){ $(this).children('a').animate({backgroundPosition: '-585px 0px'}, 200) }) ;
		
		$('#content .newsListSp ul.newsList li').hover(function(){ $(this).children('a').animate({backgroundPosition: '-50px 0px'}, 120) },
										 function(){ $(this).children('a').animate({backgroundPosition: '-585px 0px'}, 200) }) ;
		
		$('#content .knowledgeListSp ul.knowledgeList li').hover(function(){ $(this).children('a').animate({backgroundPosition: '-50px 0px'}, 120) },
										 function(){ $(this).children('a').animate({backgroundPosition: '-585px 0px'}, 200) }) ;


		
		$('#mainMenu li').hoverIntent(
								function(){ $(this).children('div').slideDown(100); },
								function(){ $(this).children('div').fadeOut(100); }
								
								);
		
		
		$('.prodSuppliersList .supplierItem').hover(function(){ $(this).children('.supplierItem-inner').animate({backgroundPosition: '-218px 0px'}, 120);
																							 $(this).children('.supplierItem-inner').css('color', '#000'); },
										 function(){ if( !$(this).hasClass('promoted') )
										   {
											   if(!$(this).hasClass('withoutLogo'))
											   {
												 $(this).children('.supplierItem-inner').animate({backgroundPosition: '-753px 0px'}, 200);
										    	 $(this).children('.supplierItem-inner').css('color', '#fff') 
											   }
											   else
											   {
												 $(this).children('.supplierItem-inner').animate({backgroundPosition: '-893px 0px'}, 200);
												 $(this).children('.supplierItem-inner').css('color', '#fff')  
											   }
										   }
										 }) ;
										 
										 

										 
		
		
		
		$('#advBtn').toggle( function(){ $('#advSearchPanel').slideDown(300); $(this).removeClass("advPanelOpen").addClass("advPanelClose"); }, function(){ $('#advSearchPanel').slideUp(400); $(this).removeClass("advPanelClose").addClass("advPanelOpen"); } )
		
		$('#search .searchTerm').focus( function(){ if($(this).attr('value') == "nazwa produktu, firmy, kategorii...") $(this).attr('value', ''); } )
		$('#search .searchTerm').blur( function(){ if($(this).attr('value') == "") $(this).attr('value', 'nazwa produktu, firmy, kategorii...'); } )
		
		$('#promptTerm').focus( function(){ if($(this).attr('value') == "nazwa produktu, kategorii itp.") $(this).attr('value', ''); } )
		$('#promptTerm').blur( function(){ if($(this).attr('value') == "") $(this).attr('value', 'nazwa produktu, kategorii itp.'); } )


		$('#mainMenu li li').hover(function(){ $(this).children('a').animate({backgroundPosition: '-72px 0px'}, 60) },
										 function(){ $(this).children('a').animate({backgroundPosition: '-230px 0px'}, 200) }) ;
		
		// kategorie
		
		$('.mainCategories li').hover(function(){ if(!$(this).hasClass("active")) $(this).children('a').animate({backgroundPosition: '-70px 0px'}, 60).css('color', '#000');  },
										 function(){ if(!$(this).hasClass("active")) $(this).children('a').animate({backgroundPosition: '-230px 0px'}, 200).css('color', '#fff'); }) ;
		
		$('.mainCategories li a').click(function(){ showSubmenu($(this)); });
		
		$('.categories li a.showSubpages').click(function(){ if(!$(this).parent("li").children("ul").hasClass("active"))
															   {
																	$(this).parent("li").children("ul").show(150);
																	$(this).children("span").html("-");
																	$(this).parent("li").children("ul").addClass("active");
																}
																else
																{
																	$(this).parent("li").find("ul").hide(150).removeClass("active");
																	$(this).parent("li").find(".showSubpages span").html("+");
																}
														  });

		
		// produkty
               /* $().ready(function(){
                    $('.prodItem').each(function(){ 
                        $(this).children('.prodItem-inner').animate({backgroundPosition: '-208px 0px'}, 120);
                        $(this).children('.prodItem-inner').css('color', '#000');
                        $(this).find('.addToCartModule').show(150);
                    });
                });*/
                
		/*
		$('.prodItem').hoverIntent(function(){ 
                    $(this).children('.prodItem-inner').animate({backgroundPosition: '-208px 0px'}, 120);
                    $(this).children('.prodItem-inner').css('color', '#000');
                    $(this).find('.addToCartModule').show(150);
		},
		function(){ 
                    if( $(this).hasClass('active') == false ){
                        $(this).children('.prodItem-inner').animate({backgroundPosition: '-800px 0px'}, 200);
                        $(this).children('.prodItem-inner').css('color', '#fff');
                        $(this).find('.addToCartModule').hide(150);
                    }
		});*/
		
		
		$('.suppliersList .supplierItem').hover(function(){ 
                    $(this).children('.supplierItem-inner').animate({backgroundPosition: '-208px 0px'}, 120);
                    $(this).children('.supplierItem-inner').css('color', '#000');
                },
                function(){ 
                         if( !$(this).hasClass('active') )
                         {
                               if(!$(this).hasClass('withoutLogo'))
                               {
                                    $(this).children('.supplierItem-inner').animate({backgroundPosition: '-798px 0px'}, 200);
                                    $(this).children('.supplierItem-inner').css('color', '#fff') 
                               }
                               else
                               {
                                     $(this).children('.supplierItem-inner').animate({backgroundPosition: '-888px 0px'}, 200);
                                     $(this).children('.supplierItem-inner').css('color', '#fff')  
                               }
                       }
                  }) ;
		
		
		$('.ordersList .orderItem').hover(function(){ 
                    $(this).children('.orderItem-inner').animate({backgroundPosition: '-208px 0px'}, 120);
                    $(this).children('.orderItem-inner').css('color', '#000');
                },
                function(){ 
                    if( $(this).hasClass('active') == false )
                    {
                        $(this).children('.orderItem-inner').animate({backgroundPosition: '-768px 0px'}, 200);
                        $(this).children('.orderItem-inner').css('color', '#fff') 
                    }
                });

		
		//produkty filters
		
		 var filtersDiv = $('.filters .filtersItem').html();
		 $('.addFiltersBtn').click( function() { $('.filters').append("<div class=\"filtersItem\">"+filtersDiv+"</div>").append($(this)).append($(this).parent().children('.removeFiltersBtn')); } )
		 $('.removeFiltersBtn').click( function() { $(this).parent().children("div:last").remove() })
		 
		 
		 $('#supplierContentNav a').click( function(){ $(this).parent().parent().children('li').children('a').removeClass('active'); $(this).addClass('active'); $('.spContent-inner2').children('div').slideUp(100); $($(this).attr('title')).slideDown(150); } );
		 
		 //usuwanie produktów w koszyku
		
		$('.removeProd').each(function(){ var a = $(this).attr("href").slice(35, -2); $(this).click(function(){ removeProduct($(this).parent().parent(), a); }); $(this).attr("href", "javascript:void(0)"); });
		
		
		//toltip na strone główną
		
		$('#siteBanner .firstInfo').tooltip({ track: true, delay: 300, showURL: false, showBody: " - ", extraClass: "pretty", fixPNG: true, opacity: 0.95, left: 0, fade:100 });
		$('#siteBanner .secondInfo').tooltip({ track: true, delay: 300, showURL: false, showBody: " - ", extraClass: "pretty", fixPNG: true, opacity: 0.95, left: 0, fade:100 });
		
		$('.shippingInfo').tooltip({ track: true, delay: 300, showURL: false, showBody: " - ", extraClass: "pretty", fixPNG: true, opacity: 0.95, left: 0, fade:100 });
		
		$('#siteBanner .firstInfo').hover( function(){
													blinkingInterval1 = setInterval( function(){$('#prodBtnMainMenu').fadeOut(400).fadeIn(400);}, 1200 );
													blinkingInterval2 = setInterval( function(){$('#search').fadeOut(400).fadeIn(400);}, 1200 );
													},
											function(){ clearInterval(blinkingInterval1); clearInterval(blinkingInterval2); } );
		$('#siteBanner .secondInfo').hover( function(){
													blinkingInterval3 = setInterval( function(){$('#header .signInMenu .supplier').fadeOut(400).fadeIn(400);}, 1200 );
													},
											function(){ clearInterval(blinkingInterval3); } );
		
		$("#externalPanelOuter .exitBtn").each(function(){ $(this).attr('title', $(this).attr('href')); $(this).attr("href", "javascript:void(0)"); });
		$('#externalPanelOuter .exitBtn').click( function(){ hideOuterPanel($(this).parent().parent()); window.location.hash = ""; $("#loginInput").attr('value', ''); } );
		$(".loginPanelBtn").each(function(){ $(this).attr('title', $(this).attr('href')).attr("href", "javascript:void(0)")});
		$('#forgotMyPassword').attr("href", "javascript:void(0)");
		$('.loginPanelBtn').click( function(){ showOuterPanel($("#loginPanel")); document.location.hash = $(this).attr('title'); } );
		
		$('#forgotMyPassword').click( function(){ showOuterPanel($("#forgotMyPasswordPanel")); } );
		$('.newsletterBtn').click( function(){ showOuterPanel($("#newsletter")); } );
		$('#externalPanelOuter .backToLoginPanel').click( function(){ showOuterPanel($("#loginPanel")); } );
		$('.prodGallery .nav .next').click( function(){moveProdGallery(1, false)} );
		$('.prodGallery .nav .prev').click( function(){moveProdGallery(-1, false)} );
		$('.prodGallery .nav .photoItemBtn a').each(function(){ $(this).attr('title', $(this).attr('href')).attr("href", "javascript:void(0)")});
		$('.prodGallery .nav .photoItemBtn a').click( function(){ moveProdGallery($(this).attr("title").substr(1), true); document.location.hash = $(this).attr('title'); } );
		
		var $tempNumber = 1;
		$('.addToCart .number').focus(function(){ $tempNumber = $(this).attr('value'); $(this).attr('value', ''); });
		$('.addToCart .number').blur(function(){ if($(this).attr('value') == "") $(this).attr('value', $tempNumber); });
		
		$('#f_deliveryAddressBtn').toggle(function(){ $('#f_fieldset_deliveryAddress').slideDown(150)}, function(){$('#f_fieldset_deliveryAddress').slideUp(150); });
		
		function changeFormPart(btnObj, partObj)
		{
			$(".formPartsNav li").removeClass("active");
			btnObj.addClass("active");
			$(".formPart").slideUp("150");
			setTimeout(function(){ partObj.slideDown("150"); }, 150);
			
		}
		
		$('.general-FormPart-Btn').click(function(){ changeFormPart($(this), $(".general-FormPart"))});
		$('.contact-FormPart-Btn').click(function(){ changeFormPart($(this), $(".contact-FormPart"))});
		$('.description-FormPart-Btn').click(function(){ changeFormPart($(this), $(".description-FormPart"))});
		$('.payment-FormPart-Btn').click(function(){ changeFormPart($(this), $(".payment-FormPart"))});
		$('.sale-FormPart-Btn').click(function(){ changeFormPart($(this), $(".sale-FormPart"))});
		
		$('#sidebar .banner a').hover(function(){ $(this).animate({paddingTop: 5}, 50).animate({paddingBottom: 5}, 50) },
									  function(){ $(this).animate({paddingTop: 0}, 50).animate({paddingBottom: 0}, 50) });
		
		if(window.location.hash != ""){ $(".mainCategories #category"+window.location.hash.substr(2)).parents("ul").show();
										 $(".mainCategories #category"+window.location.hash.substr(2)).parents("li").addClass("active");
										 $(".mainCategories #category"+window.location.hash.substr(2)).children("ul").show();
										 $(".mainCategories #category"+window.location.hash.substr(2)).addClass("active");
										
										 var m = parseFloat($(".mainCategories #category"+window.location.hash.substr(2)).children("ul").offset().top) + parseFloat($(".mainCategories #category"+window.location.hash.substr(2)).children("ul").height()) - 550;
										 if( $(".mainCategories").height() < m) $(".mainCategories").height(m+"px");
										 
										 var newTop = parseFloat($(".mainCategories #category"+window.location.hash.substr(2)).position().top) - 100;
										// alert(newTop);
										setTimeout(function(){ $('html, body, window, document').animate( {scrollTop:newTop} , 400); }, 300);
										
										 
										 //if(iniMainCategoriesHeight < abc) 
										 
										 }
						

}

function sendingContactMail()
{	
	var valid = '';
	var name = $("#senderInput").val();
	var mail = $("#sendersEmailInput").val();
	var subject = $("#subject").val();
	var text = $("#massageInput").val();
	
	if (name.length<1) {
		valid += '<br />Podaj imię i nazwisko.';
	}
	if (!mail.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
		valid += '<br />Podaj prawidłowy adres e-mail.';
	}
	if (subject.length<1) {
		valid += '<br />Wybierz temat.';
	}
	if (text.length<1) {
		valid += '<br />Wpisz treść wiadomości.';
	}
	if (valid!='') {
		$(".sendingInfo").fadeIn("slow");
		$(".sendingInfo p").html(""+valid);
		
		setTimeout(function(){$(".sendingInfo").fadeOut("slow");},2000);
	}
	else {
		var datastr ='name=' + name + '&mail=' + mail + '&subject=' + subject + '&text=' + text;
		$(".sendingInfo p").html("Wysyłanie wiadomości .... ");
		$(".sendingInfo").fadeIn("slow");
		setTimeout("send('"+datastr+"')",2000);
	}
	return false;
	
}

function send(datastr){
	$.ajax({	
		type: "POST",
		url: "layout/ajax/contactMail.php",
		data: datastr,
		cache: false,
		success: function(html){
		$(".sendingInfo").fadeIn("slow");
		$(".sendingInfo p").html(html);
		setTimeout('$(".sendingInfo").fadeOut("slow")',2000);
	}
	});
}

function recountJM()
{
	
	var hundredWeight=jm;
	jm=String(jm).replace(",",".");
	
	var il=$("#count_szt").val();
	var kg=$("#count_kg").val();
	
	if(trim(String(il)))
	{
		il=trim(il);
		il=il.replace(",",".");
		
		resultSzt=Math.round(Number(il)*Number(jm)*100)/10000;
		
		resultSzt+=" kg";
		$(".sztResult strong").html(resultSzt);

	}
	if(trim(String(kg)))
	{
		kg=trim(kg);
		
		kg=kg.replace(",",".");
		resultKg=Math.floor(Number(kg)/Number(jm)*100);
		resultKg+=" szt.";
		$(".kgResult strong").html(resultKg);
	}
	
	
}



$(function()
	{
		
		$(".contactForm a.submit").click(function(){ sendingContactMail(); });
		$("#count_szt").keyup(function(){recountJM();});
		$("#count_kg").keyup(function(){recountJM();});
		
				
		$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 500
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};

		iniMainCategoriesHeight = $(".mainCategories").height();
		ini();

		var patt1=new RegExp("forcelog=1");
		if(patt1.test(window.location.href)){
			showOuterPanel($("#loginPanel"));
			$("#loginPanel").before("<div style='position:absolute; width: 100%; text-align: center; color: #fff; margin-top:180px;'>Niepoprawne dane. Spróbuj ponownie.</div>");
			}
		
		$('.imagesList a').lightBox({txtImage: 'Zdjęcie', txtOf: 'z'});
		
		
				
		
		
	}
)
    
    $(function() {

    $(".product_units")

        .mouseover(function(){
            $(this)
                .data("origWidth", $(this).css("width"))
                .css("width", "auto");
            $(this).css("position","absolute");
            $(this).attr('size',$(this).children().length);
        })

        .mouseout(function(){
            $(this).css("width", $(this).data("origWidth"));
            $(this).css("position","static");
            $(this).attr('size',1);
        })
        .change(function(){
            $(this).mouseout();
        });

});
