;(function($j){

	window.esd = { fn: {} };
	
	/* disable selection
	$j(function() {
            $j(this).bind("contextmenu", function(e) {
                e.preventDefault();
            });
        }); 
        */
        
        $j.fn.extend({
        	center: function () {
	   	 	this.css("position","absolute");
	    		this.css("top", (( $j(window).height() - this.height()) - 300 ) / 2+$j(window).scrollTop() + "px");
	    		this.css("left", ( $j(window).width() - this.width()  ) / 2+$j(window).scrollLeft()  + "px");
	    		return this;
	    	}
	});
        
	$j.esdAjax = function() {

		var loading = $j("<div style='display:none' id='loading'>Wczytuje...</div>");	
		$j('body').append(loading);		
		$j.extend($j.esdAjax, {
		
			showLoading: function() {
				loading.center().show();
			}, 

			hideLoading: function() {
				loading.hide();
			}
		});
		
		$j.fn.extend({
		
			 esdAjaxLoad: function(url, callback) {
	        		var self = this;
	        		$j.esdAjax.showLoading();

	        		$j.ajax({
	        			url: url,
	        			async: true,
	        			success: function(data) {
						if (callback) callback(data);
						$j.esdAjax.hideLoading();
						return self.html(data);
					}
				});
			},
			
			 esdAjaxLoadSync: function(url, callback) {
	        		var self = this;
	        		$j.esdAjax.showLoading();

	        		$j.ajax({
	        			url: url,
	        			async: false,
	        			success: function(data) {
						if (callback) callback(data);
						$j.esdAjax.hideLoading();
						return self.html(data);
					}
				});
			}
		});
	}

	esd.fn.infowindow = function(url) {

		$j.superbox.wait(function() {
			$j.get(url, function(data){
				jQLCt = $j(data);
				$j.superbox.open(jQLCt,{
					boxWidth:'800',
					boxHeight:'600',
					overlayOpacity:'.8'
				});
		
			});
		});	
	
	}
	
	esd.fn.initProductPreview = function(elements, button ,top, left) {
		
		$j(elements).each( function() {
		
			var jButton = $j(button);
			var jElem = $j(this);
			$j(this).append(jButton);

			$j(this).bind('mouseenter', function(){
					var pos = $j(this).offset();
					jButton.css( { "left": (left) + "px", "top": top + "px" } );
					jButton.show().stop().animate({opacity:'1'},300);
			});
			
			$j(this).bind('mouseleave', function(){
				jButton.hide().css({opacity:'0'});
			});
	
			jButton.bind('click', function(e){
				sUrl = '/obj/product-preview/?idproduct='+ jElem.attr('rel');
				e.preventDefault();
				
				$j.superbox.wait(function(){
					$j.get(sUrl, function(data){
						jQLCt = $j(data);
						$j.superbox.open(jQLCt,{
							    boxWidth:'990',
							    boxHeight:'600',
							    overlayOpacity:'.8'
						});
					});
				});
				
			});
		});
	}

	esd.fn.initNav = function() {

		var 	jNav = $j('#navigation'),
			jTabNavs = jNav.find('> li'),
			jTabNavCts = jNav.find('.nav-content'),
			tTabTimer,
			jTabSelected,
			jTabAnimateSpeed;
			
		jTabNavs.each(function(){
			
			var 	jTabNav = $j(this),
				sTabNavPos = jTabNav.position(),
				sTabNavWidth = jTabNav.outerWidth(),
				jRelCt = jTabNav.find('.nav-content'),
				sRelCtWidth = jRelCt.width(),
				sCtHeight = jRelCt.height();
	            
			if ( $j.browser.msie && $j.browser.version < 7 ){
			
				// var jSection = jRelCt.find('.section'),
				// sSectionLength = jSection.length,
				// sSectionWidth = jSection.outerWidth();
				// sRelCtWidth = sSectionLength*sSectionWidth
				// jRelCt.css({width:sRelCtWidth+'px'});
			}
			            
	
			var sRelCtLeft = (sTabNavPos.left  + (sTabNavWidth/2) - (sRelCtWidth / 2));
			if (sRelCtLeft < 0) jRelCt.css({ left: 0 + 'px'});
			else if ((sRelCtLeft + sRelCtWidth) > 980) jRelCt.css({ left: (980 - sRelCtWidth) + 'px'});
			else jRelCt.css({ left: sRelCtLeft + 'px'});
			            
			jTabNav.bind({
				expand : function(){
				    jTabNav.addClass('active');
				    jRelCt.show().stop().animate({opacity:1}, jTabAnimateSpeed);
				    jTabSelected = true;
				}, 
				
				collapse : function(){
				    jTabNavCts.stop().hide().css({opacity:0});
				    jTabSelected = false;
				}, 
	
				mouseenter : function(){ 
				    window.clearTimeout(tTabTimer);
				    
				    if (jTabSelected) {
				    	time2 = 100;
				    	jTabAnimateSpeed = 150;
				    } else {
				    	time2 = 200;
				    	jTabAnimateSpeed = 150;
				    }
				    
				    jTabNavs.removeClass('active');

				    tTabTimer = window.setTimeout(function(){ 
				    	jTabNavCts.not(jTabNav).trigger('collapse');
				        jTabNav.trigger('expand');
				    }, time2);
				    
	//			    var time2 = jTabSelected ? 1 : 200;
	//			    tTabTimer = window.setTimeout(function(){ 
	//			        jTabNavCts.not(jTabNav).trigger('collapse');
	//			        jTabNav.trigger('expand');
	//			    }, time2);
				},
				
				mouseleave : function(){ 
				    window.clearTimeout(tTabTimer);
				    tTabTimer = window.setTimeout(function(){ 
				    	jTabNavs.removeClass('active');
				    	jTabNav.trigger('collapse');
				    },300);
				}
			})
			.find('a')
			.focus(
				function(){ jTabNav.trigger('expand'); });
				jTabNav.find('a:last').blur(function(){ jTabNav.trigger('collapse'); });
				// if ( !($j.browser.msie && $j.browser.version < 7) ) jRelCt.find('.section').css({height: sCtHeight - 25 + 'px'});
			
		});
	        
	        jTabNavCts.hide();
	}
	
	esd.fn.initTooltips = function(class2, idtooltip) {
	
		var jTooltip = $j("<div id='"+ idtooltip  +"'><div class='tooltip-arrow'><img src='/img/tooltip_arr.png' width='10' height='27'></div><div id='tooltip-content'></div></div>");
		$j('body').append(jTooltip);
		

		$j(class2).live('mouseover', function(e) {
				var 	pos = $j(this).offset(),
					width = $j(this).width();
					
				jTooltip.find('#tooltip-content').html( $j(this).attr('tooltip-title') );
				jTooltip.css( { "left": (pos.left + width + 5) + "px", "top": pos.top + "px" } );
				jTooltip.show().stop().animate({opacity:'1'},300);
			});
		$j(class2).live('mouseout', function(e) {
				jTooltip.hide().css({opacity:'0'});
			});
		
		
	}
	
	esd.fn.initGalleryList = function(box, maxlen) {
		var jGallery = $j(box),
			jGalleryItems = jGallery.find('li'),
            		sGalleryLength = jGalleryItems.length;
		
		if ( sGalleryLength > maxlen ) 
			
			jGallery.carousel({
				dispItems: maxlen, 
				scroll: maxlen,
				showEmptyItems: false, 
				animation: 600,
				wrap: 'both',
				easing : 'easeInOutQuad'
	        	});
	}

		
	esd.fn.initGallery = function(gallery, imagebox, params){
        
	        var jGallery = $j(gallery),
	            jPrdImgCt = $j(imagebox),
	            jGalleryItems = jGallery.find('li'),
	            sGalleryLength = jGalleryItems.length,
	            jCurrentItem = jPrdImgCt.find('.item'),
	            tServiceTimer;
	
		if ( sGalleryLength > 5 ) {
			
			jGallery.carousel({
				dispItems: 5,
				scroll: 5,
				direction: params.direction,
				nextBtn: '<div></div>',
				prevBtn: '<div></div>',
				loop: true,
				showEmptyItems: false, 
				animSpeed: 600, 
				slideEasing : 'easeOutQuart'
			});	
	        }
	
	        jGalleryItems.each(function(i){
	            var jItem = $j(this).find('a'),
	                sRelItem = jItem.attr('href'),
	                sRelItemAlt = jItem.attr('alt'),
	                jRelItem,
	                jLastItem;
	            
	            if (i > 0) jRelItem = $j('<img src="'+sRelItem+'" class="item item-'+i+'"/>');
	                else jRelItem = jPrdImgCt.find('.item:first').addClass('item-0');
	            
	            jItem.click(function(e){
	                e.preventDefault();
	                jCurrentItem.css({zIndex:'2'});
	                jPrdImgCt.find('.item').not(jCurrentItem,jRelItem).hide().css({zIndex:'1'});
	                if ( !(jPrdImgCt.find('img.item-'+i).length) ) jRelItem.hide().css({zIndex:'2'}).prependTo(jPrdImgCt);
	                jCurrentItem.fadeOut(450);
	                jRelItem.hide().css({zIndex:'3'}).fadeIn(450);
	                jCurrentItem = jPrdImgCt.find('.item-'+i);
	                if (jCurrentItem.width() && jCurrentItem.height()) {
	               		//jCurrentItem.css({left: 220 - (jCurrentItem.width())/2 });
	               		//jCurrentItem.css({top: 175 - (jCurrentItem.height())/2 });
	               	}
	
	                jGalleryItems.not(':eq('+i+')').removeClass('active');
	                jGalleryItems.eq(i).addClass('active');
	            });
	            
	        });
	        
//		var jPrdImgBtnNext = $j("<div class='product-image-btn-next'></div>");
//		var jPrdImgBtnPrev = $j("<div class='product-image-btn-prev'></div>");
//		
//		jPrdImgCt.append(jPrdImgBtnNext);
//		jPrdImgCt.append(jPrdImgBtnPrev);
//	        
//		jPrdImgBtnNext.click( function() {
//			id = jCurrentItem.attr('rel');
//			if (id == sGalleryLength)
//				jPrdImgBtnNext.addClass('disabled');
//	        	else {
//	        		
//	        	}
//	        		
//	        });
//	        
//	        jPrdImgBtnPrev.click( function() {
//	        	console.log(jCurrentItem);
//	        });
        
        }
        
        esd.fn.AddToCart = function(idproduct) {
        
		$j('#cart-short').esdAjaxLoad('/obj/cart-short/?add='+idproduct, 
			function() {
				$j('.cart_btn_'+idproduct).each( function() {
					$j(this).html($j('#cart-added').html());
				});
			}
		);
		
	}
	
	 esd.fn.setProductList = function(page_uri, listnr, hash, params) {
	
		var perpage = $j('#perpage'+listnr).val();
		var sortme = $j('#sort'+listnr).val();
		var listtype_pos = ''; //(listtype > 0) ? '&listtype='+listtype : '';

		var dataStr = 'page=1&perpage='+perpage+'&sort='+sortme+listtype_pos+'&'+params;
		var url = page_uri+'?'+dataStr+ hash;

		document.location.href = url;
	}

        
	esd.fn.productCompare = function(box, idcategory) {

		
		$j.extend(esd.fn.productCompare, {
			
			idcategory: 0,
			
			Compare: function() {
				var sUrl = '/obj/prd-compare/?option=compare&idcategory='+idcategory;
				$j.superbox.wait(function() {				
					$j.get(sUrl, function(data){
						jQLCt = $j(data);
						$j.superbox.open(jQLCt,{
							boxWidth:'920',
							boxHeight:'600',
							overlayOpacity:'.8'
						});
				
					});
				});
			},
			
			CompareSwitch: function(elem) {
			
				var 	jPrdBtn = $j(elem),
					idproduct = jPrdBtn.attr('rel');
				
				if (!jPrdBtn.is(':checked'))
					esd.fn.productCompare.DeleteFromCompare(idproduct);
				else
					esd.fn.productCompare.AddToCompare(idproduct);
				
				esd.fn.productCompare.OpenCompareBar(1500);
				
			},
			
			AddToCompare: function(idproduct) {
				if ($j('#prd-compare-products').find('li').length >= 5) {
					$j('.prd-compare-btn_'+idproduct).each( function(i) { 
						$j(this).find('input').attr('checked', false);
					});
					esd.fn.productCompare.tooManyInfo();
					return;
				}
			
				jPrdList.esdAjaxLoad('/obj/prd-compare/?option=add&idproduct='+idproduct+'&idcategory='+idcategory, function() { 
					$j('#prd-compare-btn-compare').show();
					$j('.prd-compare-btn_'+idproduct).each( function(i) { 
						$j(this).find('input').attr('checked', true);
						$j(this).find('span').html($j('#prd-compare-added').html()).css({'font-weight': 'bold'});
					});
				});
				
			},
			
			DeleteFromCompare: function(idproduct) {
			
				$j('#prd-compare-prdpos_'+idproduct).empty();
			
				jPrdList.esdAjaxLoad('/obj/prd-compare/?option=del&idproduct='+idproduct+'&idcategory='+idcategory, function() {
				
					$j('.prd-compare-btn_'+idproduct).each( function(i) { 
						$j(this).find('input').attr('checked', false);
						$j(this).find('span').html($j('#prd-compare-add').html()).css({'font-weight': 'normal'});
					});
					

					if ( $j('#product-list').has('div').length == 0) {
						esd.fn.productCompare.CloseCompareBar(true);
						
					}
				 });
			},
			
			GetProducts: function(callback) {
				jPrdList.load('/obj/prd-compare/?idcategory='+idcategory,
					function() { 
					
						if ( $j('#prd-compare-products').find('li').length > 0) {							
							$j('#prd-compare-btn-compare').show();
							jbottomBar.css({"display": "block"});
						}
											
						if (callback) callback(); 
					
					}
				);
			},
			GetProductsFromCategory: function(idcat) {
				idcategory = idcat;
				esd.fn.productCompare.GetProducts();
			},
			OpenCompareBar: function(time) {
				window.clearTimeout(tBarTimer);
				jbottomBar.css({"display": "block"});
				jbottomBar.stop().animate({"bottom": "0px"}, 'fast');
				if (time) {
					tBarTimer = window.setTimeout(function(){ 
						esd.fn.productCompare.CloseCompareBar();
			    		}, time);
				}
			},
			CloseCompareBar: function(hide) {
				jbottomBar.stop().animate({"bottom": "-114px"}, 'fast', function() {
					
					if (hide) { 
						jbottomBar.css({"display": "none"});
						$j('#prd-compare-btn-compare').hide();
					}
				});
			},
			
			tooManyInfo: function() {
				jQLCt = $j('#prd-compare-info').html();
				$j.superbox.open(jQLCt,{
					boxWidth:'400',
					boxHeight:'150',
					overlayOpacity:'1'
				});
			}
			
		});
		
		var 	jbottomBar = $j(box),
			jbottomBarHead = jbottomBar.find('#top'),
			jPrdList = jbottomBar.find('#product-list'),
			tBarTimer;
		
		$j('.prd-compare-btn-check').each ( function(i) {
		
			$j(this).attr('id', 'prd-compare-btn-checknr_'+i);

			$j('#prd-compare-btn-checknr_'+i).bind('click', function(e) {
					esd.fn.productCompare.CompareSwitch($j(this));
				});
		 });
				
		jbottomBar.mouseenter( function(e) {

			window.clearTimeout(tBarTimer);
			if (jbottomBar.css("bottom") != "0px") {
				esd.fn.productCompare.OpenCompareBar();
			}
		});
		
		jbottomBar.mouseleave( function(e) {
		
			tBarTimer = window.setTimeout(function(){ 
				esd.fn.productCompare.CloseCompareBar();
			    }, 800);
		
		});
		
		esd.fn.productCompare.GetProducts( );
	}
        
        esd.fn.InitTabs = function(idtab, idcontainer, params) {
        	
        	var 	jTab = $j(idtab),
        		jTabs = jTab.find("> li"),
        		jTabContent = $j(idcontainer),
        		jOpened = false;
        		
	        	var GotoTab = function(tab, slide) {
	        		jTab.find("> li").removeClass("active"); //Remove any "active" class
				tab.addClass("active"); //Add "active" class to selected tab
				jTabContent.find(".tab_content").hide(); 
				var activeTab = tab.find("a").attr("href");
				$j(activeTab).fadeIn('fast');
				if (slide == 'slide') {
					$j('html,body').animate({scrollTop: $j(activeTab).offset().top - 40},'slow');
				}
				// document.location.hash = 'btn_' + tab.find("a").attr("href").replace('#','');
	        	}
			
			var GetAnchor = function() {
				var urlAnchor = document.location.hash.toString();
				if (urlAnchor) {
					urlAnchor = urlAnchor.replace('btn_','');
					jTabs.each( function (i) {
						 if(urlAnchor == $j(this).find('a').attr('href')) {
							GotoTab($j(this));
							return;	
						 }
					});
				} else {
					jTab.find("li:first").addClass("active").show();
					jTabContent.find(".tab_content:first").show();
				}
			}

			jTabContent.find(".tab_content").hide(); 
			
			GetAnchor();
						
	//		$j(window).bind('hashchange', function() {
	//			GetAnchor();
	//		});
			
			$j('a').each(function() {
			
					$j(this).click(function(e) {
						var a = $j(this);
						jTabs.each( function (i) {
							 if(a.attr('href') == $j(this).find('a').attr('href')) {
								e.preventDefault();
								
								GotoTab($j(this), a.attr('rel'));
								return false;
							 }
						});
					});
			});
        }
        
	$j.fn.slideTo = function(options) {
		
		var defaults = {
				target : false,
				speed  : 1500 
		};
		
		var opts = $j.extend({}, defaults, options);
		var elem = (this.length > 0) ? this : 'a';
		// Element instance specific actions
		$j(elem).each(function() {
			var e = $j(this);
			var o = $j.meta ? $j.extend({}, opts, e.data()) : opts;
			var url = $j(e).attr("href");
			
			
			$j(e).bind('click', function(){
				
				var anchor = '';
				if(url && url.indexOf("#") != -1 && url.indexOf("#") == 0) {
					var pieces = url.split("#",2);
					anchor = $j("a[name='"+pieces[1]+"']");
					$j(this).attr('href', 'javascript:void(0);');
				} else
					anchor = $j(o.target);
				
				$j('html, body').animate({
					scrollTop: anchor.offset().top,
					scrollLeft: anchor.offset().left
				}, o.speed);
			});
		});
		
		// Allow jQuery chaining
		return this;
	};


})(jQuery);

(function($) {
    
    // Public: jScroll Plugin
    $.fn.jScroll = function(options) {

        var opts = $.extend({}, $.fn.jScroll.defaults, options);

        return this.each(function() {
			var $element = $(this);
			var $window = $(window);
			var locator = new location($element);

			$window.scroll(function() {
				$element
					.stop()
					.animate(locator.getMargin($window), opts.speed);
			});
        });

		// Private 
		function location($element)
		{
			this.min = $element.offset().top;
			this.max = $element.parent().height() - $element.outerHeight();
			this.originalMargin = parseInt($element.css("margin-top"), 10) || 0;

			this.getMargin = function ($window)
			{
				var margin = this.originalMargin;

				if ($window.scrollTop() >= this.min)
					margin = margin + opts.top + $window.scrollTop() - this.min; 

				if (margin > this.max)
					margin = this.max;

				return ({"marginTop" : margin + 'px'});
			}
		}	   

    };

    // Public: Default values
    $.fn.jScroll.defaults = {
        speed	:	"slow",
		top		:	10
    };

})(jQuery);

function sprintf () {
	var a, f = arguments[0], fi= '', i = 1, m = [''], o = '', p;
	while (f = f.substring (m[0].length)) {
	m = /^([^\%]*)(?:(\x25)((\x25)|(?:(\d+)\$)?(\+)?(0|'([^$]))?(-|\^)?(\d+)?(?:\.(\d+))?([bcdefosuxX])))?/.exec(f);
	if (a = m[12]) {
	if (arguments.length < (i = m[5] || i))
	throw("sprintf '" + m[0] + "' : No argument " + i);
	a = arguments[i++];
	s = (/[def]/.test(m[12]) && m[6] && a > 0) ? '+':'';
	switch (m[12]) {
	case 'b': a = a.toString(2); break;
	case 'c': a = String.fromCharCode(a); break;
	case 'd': a = parseInt(a); break;
	case 'e': a = m[11] ? a.toExponential(m[11]) : a.toExponential(); break;
	case 'f': a = m[11] ? parseFloat(a).toFixed(m[11]) : parseFloat(a); break;
	case 'o': a = a.toString(8); break;
	case 's': a = ((a = String(a)) && m[11] ? a.substring(0, m[11]) : a); break;
	case 'u': a = Math.abs(a); break;
	case 'x': a = a.toString(16); break;
	case 'X': a = a.toString(16).toUpperCase(); break;
	}
	if (m[10] && (m[10] > a.length)) {
	fir=fil=str_repeat(m[7] ? m[8] || '0' : ' ', m[10]-a.length);
	if (m[9] == '^') {
	fil = fil.substr(0, fil.length / 2);
	fir = fir.substr(fil.length);
	} else
	m[9] == '-' ? (fil = '') : (fir = '');
	a = fil + a + fir;
	}
	}
	o += m[1] + ((m[3] ? m[4] || (s + a) : m[2]) || '');
	}
	return o;
}

