var isHurtSkinOn = false;

keepSessionActive = function()
{
	var url = '/session_keeper.xml?c='+Math.random();
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			keepSessionActive.delay(60);
		}
	});
}

// Addons
if (Prototype.Browser.IE) {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        Prototype.BrowserFeatures['Version'] = new Number(RegExp.$1);
    }
}
Array.prototype.shuffleRandom = function(){
    return this.sortBy(Math.random);
};

//Main Script
var lbl_SEARCH_ALERT = 'Wypełnij pole wyszukiwarki';

function preloader_img(){
    return new Element('img', {
        'src': '/images/loading.gif',
        'alt': '...',
        'border': '0',
        'class': 'preloader'
    });
}

function validateMiniSearch2(obj){
    if (validateMiniSearch(obj)) {
        obj.submit();
    }
}

function validateMiniSearch(obj){
    /*if (obj.search_keyword.value == '') {
        alert(lbl_SEARCH_ALERT);
        obj.search_keyword.focus();
        return false;
    }
    */
    return true;
}

function searchWidthHandler(){
	if ($('mini_search_from').search_width.value.length == 3)
	{
		$('mini_search_from').search_profil.value='';
		$('mini_search_from').search_profil.focus();
	}
}
function searchProfilHandler(){
	if ($('mini_search_from').search_profil.value.length == 2)
	{
		$('mini_search_from').search_diam.value='';
		$('mini_search_from').search_diam.focus();
	}
}
function searchDiamHandler(){
	if ($('mini_search_from').search_diam.value.length == 2)
	{
		$('mini_search_from').search_keyword.value='';
		$('mini_search_from').search_keyword.focus();
	}
}
function searchSubmit(){
	$('mini_search_from').submit();
}

function validateMiniSearchClick(){
}


FooterLogosMover = Class.create({
    initialize: function(element, options){
        this.options = $H(options) || new Hash();
        this.element = $(element);
        this.elementWidth = this.element.getWidth();
        this.subElement = this.element.down('div', 0);
        this.subElementWidth = this.subElement.getWidth();
        this.subElementTop = this.subElement.positionedOffset()[1];
        this.config = {};
        this.config.sleep = this.options.get('sleep') ? Number(this.options.get('sleep')) : 3000;
        this.config.padding = this.options.get('padding') ? Number(this.options.get('padding')) : 10;
        this.config.mod = this.options.get('mod') ? Number(this.options.get('mod')) : -1;
        this.config.current = this.options.get('current') ? Number(this.options.get('current')) : 0;
        if (this.subElementWidth > this.elementWidth) {
            this.logos = this.subElement.select('img');
            setTimeout(function(){
                this.moveFooterLogosThread();
            }
.bind(this), this.config.sleep);
        }
    },
    moveFooterLogosThread: function(){
        this.config.current += (this.config.mod * -1);
        this.newPos = -Math.abs(this.logos[this.config.current].positionedOffset()[0] - this.config.padding);
        new Effect.Move(this.subElement, {
            x: this.newPos,
            y: this.subElementTop,
            mode: 'absolute',
            transition: Effect.Transitions.spring,
            afterFinish: function(){
                if (this.subElementWidth - this.logos[this.config.current].positionedOffset()[0] <= this.elementWidth) 
                    this.config.mod = 1;
                if (this.config.current + 1 == this.logos.size()) 
                    this.config.mod = 1;
                else 
                    if (this.config.current == 0) 
                        this.config.mod = -1;
                setTimeout(function(){
                    this.moveFooterLogosThread();
                }
.bind(this), this.config.sleep);
            }
.bind(this)
        });
    }
});

function initTopMenu(){
    var tMElems = $$('div#topMenu div.tME');
    tMElems.each(function(elem){
        Event.observe(elem, 'mouseover', function(){
            var eId = elem.identify();
            Effect.Queues.get('mTS_' + eId).invoke('cancel');
            var eXY = elem.positionedOffset();
            new Effect.Move(eId, {
                x: eXY.left,
                y: 0,
                mode: 'absolute',
                transition: Effect.Transitions.sinoidal,
                duration: 0.2,
                queue: {
                    position: 'end',
                    scope: 'mTS_' + eId
                }
            });
        });
        Event.observe(elem, 'mouseout', function(){
            var eId = elem.identify();
            Effect.Queues.get('mTS_' + eId).invoke('cancel');
            var eXY = elem.positionedOffset();
            new Effect.Move(eId, {
                x: eXY.left,
                y: -30,
                mode: 'absolute',
                transition: Effect.Transitions.spring,
                duration: 0.8,
                queue: {
                    position: 'end',
                    scope: 'mTS_' + eId
                }
            });
        });
    });
}

function initTopMenuLoad(){
    var effectTMDone = 0;
    var tMElems = $$('div#topMenu div.tME');
    tMElems = tMElems.shuffleRandom();
    tMElems.each(function(elem, idx){
        var eId = elem.identify();
        elem.setStyle({
            'top': '-140px'
        });
        elem.show();
        var eXY = elem.positionedOffset();
        new Effect.Move(eId, {
            x: eXY.left,
            y: -30,
            mode: 'absolute',
            transition: Effect.Transitions.spring,
            duration: 1.0,
            delay: 0.1 * idx,
            afterFinish: function(){
                effectTMDone++;
                if (effectTMDone >= tMElems.size()) 
                    initTopMenu();
            }
        });
    });
}

function initZaslepkaLoad(){
	$('btnIsHurt').show();
}

function initPacholkiLoad(){
    var pachElems = $$('div#banner div[id^="btnPach"]');
    pachElems = pachElems.shuffleRandom();
    if (Prototype.Browser.IE && Prototype.BrowserFeatures['Version'] < 9) {
        //Bo w ie < 9 slabo dziala opacity na PNGach
        pachElems.each(function(elem, idx){
            var eId = elem.identify();
            elem.show();
            var eXY = elem.positionedOffset();
            elem.setStyle({
                'top': '-200px',
                'left': '785px'
            });
            new Effect.Move(eId, {
                x: eXY.left,
                y: eXY.top,
                mode: 'absolute',
                transition: Effect.Transitions.spring,
                duration: 1.5,
                delay: 0.2 * idx
            });
        });
    }
    else {
        pachElems.each(function(elem, idx){
            var eId = elem.identify();
            //elem.setOpacity(0);
            elem.show();
            
            /*
            var eXY = elem.positionedOffset();
            elem.setStyle({
                'top': '-200px',
                'left': '785px'
            });
            
            new Effect.Parallel([new Effect.Move(eId, {
                sync: true,
                x: eXY.left,
                y: eXY.top,
                mode: 'absolute',
                transition: Effect.Transitions.spring
            }), new Effect.Opacity(eId, {
                sync: true,
                from: 0,
                to: 1,
                transition: Effect.Transitions.linear
            })], {
                duration: 1.5,
                delay: 0.2 * idx
            });
            */
            
        });
    }
    initPacholkiJumpThreadT = setTimeout(initPacholkiJumpThread, 5000);
}

var initPacholkiJumpThreadT;
var initPacholkiJumpThreadC = 0;
function initPacholkiJumpThread(){
    clearTimeout(initPacholkiJumpThreadT);
    var pachElems = $$('div#banner div[id^="btnPach"]');
    elem = pachElems[initPacholkiJumpThreadC];
    var eId = elem.identify();
    var eXY = elem.positionedOffset();
    new Effect.Move(eId, {
        x: eXY.left,
        y: eXY.top - 10,
        mode: 'absolute',
        transition: Effect.Transitions.linear,
        duration: 0.3,
        afterFinish: function(){
            new Effect.Move(eId, {
                x: eXY.left,
                y: eXY.top,
                duration: 0.3,
                mode: 'absolute',
                transition: Effect.Transitions.linear
            });
        }
    });
    
    
    initPacholkiJumpThreadC++;
    if (initPacholkiJumpThreadC > pachElems.size() - 1) 
        initPacholkiJumpThreadC = 0;
    
    initPacholkiJumpThreadT = setTimeout(initPacholkiJumpThread, 5000);
}


function initSearchBarAdvBtn(){
    Event.observe('sAdvBtn', 'click', function(){
        $('sAdvBtn').stopObserving('click');
        initSearchBarAdvBtnFunction();
    });
}

function initSearchBarAdvWindow(event){
	Event.stop(event);
    if ($(Event.element(event)).up('div#searchBar')==undefined)
	{
		Event.stopObserving(document, 'click', initSearchBarAdvWindow);
		initSearchBarAdvBtnFunction();
	}
}

function initSearchBarAdvBtnFunction(){
	Effect.Queues.get('sAdvQueue').invoke('cancel');
    if ($('sAdv').visible()) {
        Effect.SlideUp('sAdv', {
            duration: 0.3,
            queue: {
                position: 'end',
                scope: 'sAdvQueue',
                limit: 1
            },
            transition: Effect.Transitions.sinoidal,
            afterFinish: function(){
                initSearchBarAdvBtn();
				Event.stopObserving(document, 'click', initSearchBarAdvWindow);

            }
        });
    }
    else {
        Effect.SlideDown('sAdv', {
            duration: 0.3,
            queue: {
                position: 'end',
                scope: 'sAdvQueue',
                limit: 1
            },
            transition: Effect.Transitions.sinoidal,
            afterFinish: function(){
                initSearchBarAdvBtn();
				Event.observe(document, 'click', initSearchBarAdvWindow);
            }
        });
    }
}

function initSearchBar(){
    $('searchBtn').observe('click', function(){
        validateMiniSearch2($('mini_search_from'));
    });
    //$('miniSearchInput').down('input', 0).observe('click', validateMiniSearchClick);

    $('mini_search_from').observe('submit', function(myEvent){
        if (!validateMiniSearch($('mini_search_from'))) {
            myEvent.stop();
        }
    });
    //initSearchBarAdvBtn();
}

function initBtns(){
    $$('div.blueBtn').each(function(elem){
        tmpElem = elem.down('div.blueBtn3', 0);
        tmpElemContent = tmpElem.innerHTML;
        if (tmpElemContent.charAt(0) != '<')
        {
	        tmpElemContent = tmpElemContent.sub(tmpElemContent.charAt(0), '<span>' + tmpElemContent.charAt(0) + '</span>');
	        tmpElem.update(tmpElemContent);
	       }
    });
}

function initH1(){
    $$('h1.orange').each(function(elem){
        tmpElemContent = elem.innerHTML;
        tmpElemContent = tmpElemContent.sub(tmpElemContent.charAt(0), '<span>' + tmpElemContent.charAt(0) + '</span>');
        elem.update(tmpElemContent);
    });
}

function initH2(){
    $$('h2.orange').each(function(elem){
        tmpElemContent = elem.innerHTML;
        tmpElemContent = tmpElemContent.sub(tmpElemContent.charAt(0), '<span>' + tmpElemContent.charAt(0) + '</span>');
        elem.update(tmpElemContent);
    });
}

function initLeftMenu(){
    $$('div#leftMenu div.panelAElem').each(function(elem){
        Event.observe(elem, 'mouseover', function(){
            elem.down('a', 0).addClassName('hover');
            var eId = elem.identify();
            Effect.Queues.get('leftMenu_' + eId).invoke('cancel');
            var eXY = elem.getStyle('backgroundPosition');
            if (eXY == undefined) {
                eXY = new Array(1);
                eXY[0] = elem.getStyle('background-position-x');
                eXY[1] = elem.getStyle('background-position-y');
            }
            else {
                eXY = eXY.split(' ');
            }
            eXY[0] = Number(eXY[0].replace('px', ''));
            new Effect.Tween(eId, eXY[0], 5, {
                duration: 0.1,
                queue: {
                    position: 'end',
                    scope: 'leftMenu_' + eId
                }
            }, function(p){
                this.setStyle({
                    'backgroundPosition': p + 'px ' + eXY[1]
                });
            });
        });
        Event.observe(elem, 'mouseout', function(){
            elem.down('a', 0).removeClassName('hover');
            var eId = elem.identify();
            Effect.Queues.get('leftMenu_' + eId).invoke('cancel');
            var eXY = elem.getStyle('backgroundPosition');
            if (eXY == undefined) {
                eXY = new Array(1);
                eXY[0] = elem.getStyle('background-position-x');
                eXY[1] = elem.getStyle('background-position-y');
            }
            else {
                eXY = eXY.split(' ');
            }
            eXY[0] = Number(eXY[0].replace('px', ''));
            new Effect.Tween(eId, eXY[0], 12, {
                duration: 0.1,
                queue: {
                    position: 'end',
                    scope: 'leftMenu_' + eId
                }
            }, function(p){
                this.setStyle({
                    'backgroundPosition': p + 'px ' + eXY[1]
                });
            });
        });
        Event.observe(elem, 'click', function(myEvent){
            myEvent.stop();
            window.location.href = elem.down('a', 0).readAttribute('href');
        });
    });
}

PromotionMover = Class.create({
    initialize: function(element, options){
        this.options = $H(options) || new Hash();
        this.element = $(element);
        this.elementWidth = this.element.getWidth();
		this.elementHeight = this.element.getHeight();
        this.subElements = this.element.select('div.pBItem');
		this.subElements.each(function(el){
			el.writeAttribute('image',el.readAttribute('title').split('|')[0]);
			el.writeAttribute('link',el.readAttribute('title').split('|')[1]);
			el.writeAttribute('date',el.readAttribute('title').split('|')[2]);
			el.writeAttribute('title',el.readAttribute('title').split('|')[3]);	
		});
		this.subElementsCount = this.subElements.size();
		if (this.subElementsCount <= 0) return;
		
		this.elementOverlay = this.element.down('div.pBOverlay',0);
		
		this.subElementPointers = new Array();
		this.subElementPointersEffects = new Array();
		this.currentElement = this.subElements[0];
		this.config = {};
		this.config.initSleep = this.options.get('initSleep') ? Number(this.options.get('initSleep')) : 2000;
        this.config.sleep = this.options.get('sleep') ? Number(this.options.get('sleep')) : 8000;
        this.config.current = this.options.get('current') ? Number(this.options.get('current')) : 0;
		this.config.currentForced = -1;
		this.timeoutHandler1 = undefined;
		if (this.currentElement.readAttribute('image') != undefined)
		{
			this.currentElement.setStyle({'top':'0px','backgroundImage':'url(\''+this.currentElement.readAttribute('image')+'\')'});
			this.currentElement.removeAttribute('image');
		}
		this.elementOverlay.stopObserving('click');
		if (this.currentElement.readAttribute('link') != undefined)
		{		
			this.elementOverlay.addClassName('pointer');
			Event.observe(this.elementOverlay, 'click', function(overlayClickEvent){
				window.location.href=this.currentElement.readAttribute('link');
			}.bind(this));
		}
		if ($$('table.promotionBarHeader div.nBDate').size() != 0)
		{
			$$('table.promotionBarHeader div.nBDate')[0].update(this.currentElement.readAttribute('date') != undefined ? this.currentElement.readAttribute('date') : '');
		}
		if ($$('table.promotionBarHeader div.nBText').size() != 0)
		{
			$$('table.promotionBarHeader div.nBText')[0].update(this.currentElement.readAttribute('title') != undefined ? this.currentElement.readAttribute('title') : '');
		}
		
		
		if (this.subElementsCount > 1) {
			setTimeout(function(){
				this.subElements.each(function(elem,idx){
					if (elem.readAttribute('image') != undefined)
					{
						elem.setStyle({'backgroundImage':'url(\''+elem.readAttribute('image')+'\')'});
						elem.removeAttribute('image');
					}
					pointElem = new Element('div');
					pointElem.addClassName('pBTab');
					if (idx==0) pointElem.addClassName('pBTabActive');
					this.element.insert(pointElem);
					var pointElemId = pointElem.identify();
					this.subElementPointers.push(pointElem);
					pointElemPOFF = pointElem.positionedOffset();
					this.subElementPointersEffects.push(new Effect.Move(pointElemId, {
			            sync: true,
			            x: pointElemPOFF[0] - (((this.subElementsCount-1)-idx)*20),
			            y: pointElemPOFF[1],
			            mode: 'absolute',
			            transition: Effect.Transitions.linear
			        }));
					Event.observe(pointElemId, 'click', function(pointerClickEvent){
        				pointerClickEvent.stop();
						if (this.config.current!=idx && this.config.currentForced!=idx)
						{
							this.config.currentForced = idx;
							this.promotionMoverThread();
						}
					}.bind(this));
					this.pointerElementsTop = pointElemPOFF[1];
					Event.observe(pointElemId, 'mouseover', function(){
					    Effect.Queues.get('promotionMover_' + this.element.identify() + '_' + $(pointElemId).identify()).invoke('cancel');
						var eT = $(pointElemId).positionedOffset()[1];
					    new Effect.Tween(pointElemId, eT, this.pointerElementsTop-3, {
					        duration: 0.1,
					        queue: {
					            position: 'end',
					            scope: 'promotionMover_' + this.element.identify() + '_' + $(pointElemId).identify()
					        }
					    }, function(p){
					        this.setStyle({
					            'top': p + 'px'
					        });
					    });
					}.bind(this));
					Event.observe(pointElemId, 'mouseout', function(){
					    Effect.Queues.get('promotionMover_' + this.element.identify() + '_' + $(pointElemId).identify()).invoke('cancel');
						var eT = $(pointElemId).positionedOffset()[1];
					    new Effect.Tween(pointElemId, eT, this.pointerElementsTop, {
					        duration: 0.1,
					        queue: {
					            position: 'end',
					            scope: 'promotionMover_' + this.element.identify() + '_' + $(pointElemId).identify()
					        }
					    }, function(p){
					        this.setStyle({
					            'top': p + 'px'
					        });
					    });
					}.bind(this));
					
					
				}.bind(this));
		        new Effect.Parallel(this.subElementPointersEffects, {
		            duration: 0.3
		        });
			}.bind(this), this.config.initSleep);
            this.timeoutHandler1 = setTimeout(function(){
                this.promotionMoverThread();
            }.bind(this), this.config.sleep);
        }
    },
    promotionMoverThread: function(){
		clearTimeout(this.timeoutHandler1);
		Effect.Queues.get('promotionScope_' + this.element.identify()).invoke('cancel');
		this.elementOverlay.stopObserving('click');
		this.elementOverlay.removeClassName('pointer');
		this.subElements.each(function(elem,idx){
			if (idx != this.config.current) {
				elem.setStyle({
					'top': '0px',
					'left': this.elementWidth + 'px'
				});
			}
			else{
				elem.setStyle({
					'top': '0px',
					'left': '0px'
				});				
			}
		}.bind(this));
		if (this.config.currentForced > -1) {
			this.config.current = this.config.currentForced;
			this.config.currentForced = -1;
		}
		else{
			this.config.current++;
			if (this.config.current > this.subElementsCount - 1) 
				this.config.current = 0;			
		}
        new Effect.Parallel([new Effect.Move(this.currentElement, {
            sync: true,
            x: -this.elementWidth,
            y: 0,
            mode: 'absolute',
            transition: Effect.Transitions.linear
        }), new Effect.Move(this.subElements[this.config.current], {
            sync: true,
            x: 0,
            y: 0,
            mode: 'absolute',
            transition: Effect.Transitions.linear
        })], {
            duration: 0.3,
            afterFinish: function(){
				this.currentElement = this.subElements[this.config.current];
				if (this.currentElement.readAttribute('link') != undefined)
				{		
					this.elementOverlay.addClassName('pointer');
					Event.observe(this.elementOverlay, 'click', function(overlayClickEvent){
						window.location.href=this.currentElement.readAttribute('link');
					}.bind(this));
				}
				if ($$('table.promotionBarHeader div.nBDate').size() != 0)
				{
					$$('table.promotionBarHeader div.nBDate')[0].update(this.currentElement.readAttribute('date') != undefined ? this.currentElement.readAttribute('date') : '');
				}
				if ($$('table.promotionBarHeader div.nBText').size() != 0)
				{
					$$('table.promotionBarHeader div.nBText')[0].update(this.currentElement.readAttribute('title') != undefined ? this.currentElement.readAttribute('title') : '');
				}
				this.subElementPointers.each(function(elem){
					elem.removeClassName('pBTabActive');
				});
				this.subElementPointers[this.config.current].addClassName('pBTabActive');
				
				
	            this.timeoutHandler1 = setTimeout(function(){
	                this.promotionMoverThread();
	            }.bind(this), this.config.sleep);
			}.bind(this),
			queue: {
                position: 'end',
                scope: 'promotionScope_' + this.element.identify()
            }
        });
    }
});


function initCommunityBar(elemContainer){
	elemContainer.select('a.commBItem img').each(function(elem){
		Event.observe(elem, 'mouseover', function(){
		    var eId = elem.identify();
		    Effect.Queues.get('communityBar_' + eId).invoke('cancel');
			var eMt = Number(elem.getStyle('marginTop').replace('px',''));
		    new Effect.Tween(eId, eMt, 3, {
		        duration: 0.1,
		        queue: {
		            position: 'end',
		            scope: 'communityBar_' + eId
		        }
		    }, function(p){
		        this.setStyle({
		            'marginTop': p + 'px'
		        });
		    });
		});
		Event.observe(elem, 'mouseout', function(){
		    var eId = elem.identify();
		    Effect.Queues.get('communityBar_' + eId).invoke('cancel');
			var eMt = Number(elem.getStyle('marginTop').replace('px',''));
		    new Effect.Tween(eId, eMt, 6, {
		        duration: 0.1,
		        queue: {
		            position: 'end',
		            scope: 'communityBar_' + eId
		        }
		    }, function(p){
		        this.setStyle({
		            'marginTop': p + 'px'
		        });
		    });
		});
	});
}

initSetCorrectHeight = function()
{
	//tylko dla strony glownej
	if (aliasDocument == 'index') {
		var correncElems = $$('div[class="panelA"]','div[class="panelB"]','div[class="panelC"]');
		if (correncElems != undefined) {
			var lastCorrencElems = new Array();
			//szukamy ostatnich w kolumnach
			correncElems.each(function(el){
				if (el.next('div[class="panelA"]')!=undefined) $continue;
				else if (el.next('div[class="panelB"]')!=undefined) $continue;
				else if (el.next('div[class="panelC"]')!=undefined) $continue;
				else{
					lastCorrencElems.push(el);	
				}
			});
			var wholeHeight = $('contentSwitchTable').getHeight()+$('contentSwitchTable').positionedOffset().top;
			//omijamy tego ktory ma "dowodzenie" i ustawiamy height na pozostalych 
			lastCorrencElems.each(function(el){
				var elHeight = el.getHeight()+el.positionedOffset().top;
				if (elHeight<wholeHeight)
				{
					var elCurr = el.down('div[class^="panel"][class$="Elems"]',0);
					if (elCurr!=undefined)
					{
						elCurr.setStyle({
							'height':(elCurr.getHeight() + (wholeHeight - elHeight)) + 'px'
							});
					}
				}
			});
		}
	}
}


function initFilterBtn(id){
    Event.observe(id, 'click', function(){
        $(id).stopObserving('click');
        initFilterMovement(id);
    });
}

function initFilterWnd(event,id){
	Event.stop(event);
    if ($(Event.element(event)).up('div.filterDrop')==undefined)
	{
		Event.stopObserving(document, 'click');
		initFilterMovement(id);
	}
}

function initFilterMovement(id){
	Effect.Queues.get('filterDropQueue_'+id).invoke('cancel');
    if ($(id+'_drop').down('div.filterDropI',0).visible()) {
        Effect.SlideUp($(id+'_drop').down('div.filterDropI',0), {
            duration: 0.3,
            queue: {
                position: 'end',
                scope: 'filterDropQueue_'+id,
                limit: 1
            },
            transition: Effect.Transitions.sinoidal,
            afterFinish: function(){
			    initFilterBtn(id);
				Event.stopObserving(document, 'click');

            }
        });
    }
    else {
        Effect.SlideDown($(id+'_drop').down('div.filterDropI',0), {
            duration: 0.3,
            queue: {
                position: 'end',
                scope: 'filterDropQueue_'+id,
                limit: 1
            },
            transition: Effect.Transitions.sinoidal,
            afterFinish: function(){
                initFilterBtn(id);
				Event.observe(document, 'click', function(event){
					initFilterWnd(event,id);
				});
            }
        });
    }
}
			
function initFilter (id)
{
	var aLeft = $(id).positionedOffset()[0]+$(id).getWidth();
	var aTop = $(id).up('div.panelD',0).positionedOffset()[1] + $(id).up('div.panelD',0).getHeight();
	
	$(id+'_drop').setStyle({
		'top':aTop + 'px',
		'left':(aLeft - $(id+'_drop').getWidth())+'px'
	});
	
    Event.observe(id, 'click', function(){
        $(id).stopObserving('click');
        initFilterMovement(id);
    });				
}

initCart = function()
{
	if ($('cart')==undefined)
	{
	    new Ajax.Request('/box_cart.dhtml?action=cart&c=' + Math.random(1), {
	        asynchronous: true,
	        encoding: 'iso-8859-1',
	        method: 'post',
	        evalScripts: true,
	        onComplete: function(transport){
				if (transport.responseText.indexOf('boxCart')>-1)
				{
					Effect.Queues.get('cartBoxScope').invoke('cancel');
					var cartElem = new Element('div',{'id':'cart'});
					cartElem.setStyle({'top':'-200px'});
					cartElem.update(transport.responseText);
					$('banner').insert(cartElem);

					new Effect.Move(cartElem, {
			            x: cartElem.positionedOffset()[0],
			            y: 115,
			            mode: 'absolute',
			            transition: Effect.Transitions.spring,
						queue: {position: 'end',scope: 'cartBoxScope'}
						});
				}	            
	        }
	    });
	}
}

reloadCart = function()
{
	if ($('cart')!=undefined)
	{
	    new Ajax.Request('/box_cart.dhtml?c=' + Math.random(1), {
	        asynchronous: true,
	        encoding: 'iso-8859-1',
	        method: 'post',
	        evalScripts: true,
	        onComplete: function(transport){
				if (transport.responseText.indexOf('boxCart')>-1)
				{
					Effect.Queues.get('cartBoxScope').invoke('cancel');
					new Effect.Move($('cart'), {
			            x: $('cart').positionedOffset()[0],
			            y: -$('cart').getHeight(),
						duration: 0.1,
			            mode: 'absolute',
			            transition: Effect.Transitions.linear,
						queue: {position: 'end',scope: 'cartBoxScope'},
						afterFinish: function() {
								$('cart').remove();
								initCart.delay(0.1);
							}
						});
				}	            
	        }
	    });
	}
}


add2CartBtn = function(btn, prodId, quantity){
	add2Cart(prodId,quantity,function(transport){
		btn.hide();
		if (transport.responseText == 'OK')
		{
			btn.next().show();
			setTimeout(function(){
				btn.next().hide();
				btn.show();
			},1000);
		}
		else
		{
			btn.next().next().show();
			setTimeout(function(){
				btn.next().next().hide();
				btn.show();
			},1000);
		}
	});
}

add2Cart = function (prodId,quantity,customAction){
	    new Ajax.Request('/box_cart.dhtml?action=add2cart&id='+ prodId + '&quantity=' + quantity + '&c=' + Math.random(1), {
        asynchronous: true,
        encoding: 'iso-8859-1',
        method: 'post',
        evalScripts: true,
        onComplete: function(transport){
				if (customAction!=undefined)
				{
					customAction(transport);
				}
				reloadCart.delay(0.1);	            
        	}
   		});
}


initGoogleApi = function (key,callback) {
  var script = document.createElement('script');
  script.src = 'https://www.google.com/jsapi?key='+ key + (callback!=undefined ? '&callback='+callback : '');
  script.type = 'text/javascript';
  document.getElementsByTagName('head')[0].appendChild(script);
}

initGoogleMapsApi = function (callback) {
  var script = document.createElement('script');
  script.src = 'https://maps-api-ssl.google.com/maps/api/js?v=3&sensor=false' + (callback!=undefined ? '&callback='+callback : '');
  script.type = 'text/javascript';
  document.getElementsByTagName('head')[0].appendChild(script);
}

function checkNull(str)
{
	return !(str!=null && str!=undefined && str!='');
}

setHurtSkin = function()
{
	
}

initHurtSkin = function()
{
	isHurtSkinOn = true;
}

initLeftCategories = function()
{
	var urlParams = $('catalog').serialize();
	if (urlParams!='') urlParams = '&'+urlParams;
	
	new Ajax.Request('/box_categories.xml?c=' + Math.random(1) + urlParams, {
	        asynchronous: true,
	        encoding: 'iso-8859-1',
	        method: 'post',
	        evalScripts: true,
			onComplete: function(transport){
				if (transport.responseText.indexOf('leftCategories')>-1)
				{
					
					var catElem = new Element('div',{'id':'leftCategoriesWrapper'});
					catElem.update(transport.responseText);
					$('contentSwitchTableC1').insert({top:catElem});

					
				}	            
	        }
		});		
}

initBestSellers = function()
{
	var urlParams = 'limit=3';
	if (urlParams!='') urlParams = '&'+urlParams;
	
	new Ajax.Request('/box_bestsellers.xml?c=' + Math.random(1) + urlParams, {
	        asynchronous: true,
	        encoding: 'iso-8859-1',
	        method: 'post',
	        evalScripts: true,
			onComplete: function(transport){
				if (transport.responseText.indexOf('panelCElem')>-1)
				{					
					$('bestSellerWrapper').update(transport.responseText);
				}	            
	        }
		});		
}

getQuantityNumber = function(formElem)
{
	var elementVal = formElem.getValue();
	elementVal = Number(elementVal.replace(',','').replace('.','').replace(' ',''));
	//FIXME: te 10000 to do bani.. ale...
	if (!elementVal>0 || elementVal>10000)
	{
		elementVal = 1;
	}
	return elementVal;
}

initUserRating = function()
{
	Event.observe($('user_rating').down('div.ratingCover',0),'mouseover',userRatingOver);
	Event.observe($('user_rating').down('div.ratingCover',0),'mouseout',userRatingOut);
}

userRatingOut = function(event)
{
	$('user_rating').down('div.ratingCover',0).stopObserving();
	initUserRating.defer();
}

userRatingOver = function(event)
{
	Event.observe($('user_rating').down('div.ratingCover',0),'click',userRatingClick);
	Event.observe($('user_rating').down('div.ratingCover',0),'mousemove',userRatingMove);
}

userRatingMove = function(event)
{
	var elt = $('user_rating');
	if (elt != document)
	{
		var pX = Event.pointerX(event);
		var eX = elt.cumulativeOffset().left;
		var eW = elt.getWidth();
		
		var posX = pX - eX;
		if(posX > (eW-10)){ posX = (eW-10);}
		var percent = parseInt(Math.ceil((posX * 100)/eW)+"");
		
		elt.down('div').setStyle({'width':percent+'%'});
	}
}

userRatingClick = function(event)
{
	if(Event.isLeftClick(event))
	{
		var elt = $('user_rating');
		elt.down('div.ratingCover',0).stopObserving();
		var pX = Event.pointerX(event);
		var eX = elt.cumulativeOffset().left;
		var eW = elt.getWidth()-10;
		
		var posX = pX - eX;
		if(posX > eW){ posX = eW;}
		var percent = parseInt(Math.ceil((posX * 100)/eW)+"");
		
		$('catalog').rating.value = percent;
		$('catalog').submit();
		
		
		initUserRating.defer();
	}
}


Event.observe(document, 'dom:loaded', function(){
    initSearchBar();
    initBtns();
	initH1();
	initH2();
    initLeftMenu();
	$$('div.communityBar').each(function(elem){
		initCommunityBar(elem);
	});
	if ($('bestSellerWrapper')!=undefined)
	{
		initBestSellers();
	}
	if ($('user_rating')!=undefined)
	{
		initUserRating();
	}
	
	
	keepSessionActive.delay(60);
});

Event.observe(window, 'load', function(){
	initSetCorrectHeight();
    initTopMenuLoad();
	if (!isHurtSkinOn) initPacholkiLoad();
	if (isHurtSkinOn) initZaslepkaLoad();
    new FooterLogosMover('footerLogos');
	$$('div.promotionBar').each(function(elem){
		new PromotionMover(elem.identify());
	});
	initCart.delay(1);
});

/*
 * Metoda generowania selecta z wyborem lat
 */
function autoYear(currentYear, pastYears, selectedYear)
{
	var year = currentYear;
	
	if (year < 1900) {
		year = year + 1900;
	}

	var date = year - pastYears;
	var future = year + 0;

	//document.writeln ("<select class=\"formText\">")
	document.writeln ("<option value=\"\">Wybierz rok");
	do {
		date++;
		
		if(selectedYear != 'undefined' && selectedYear != '' && date == selectedYear)
		{
			document.write ("<option value=\""+date+"\" selected=\"1\">"+date+"</option>");
		}
		else
		{
			document.write ("<option value=\""+date+"\">"+date+"</option>");
		}
	}
	while (date < future)
	//document.writeln ("</select>");
}

function checkDate(inputYear, inputMonth, inputDay)
{
	var validDayFormat = /^\d{2}$/;
	var validMonthFormat = /^\d{2}$/;
	var validYearFormat = /^\d{4}$/;
	
	if(!validYearFormat.test(inputYear.value)){ return false; }
	if(!validMonthFormat.test(inputMonth.value)){ return false; }
	if(!validDayFormat.test(inputDay.value)){ return false; }
	
	var yearfield = inputYear.value;
	var monthfield = inputMonth.value;
	var dayfield = inputDay.value;
	
	var dayobj = new Date(yearfield, monthfield-1, dayfield);
	
	if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield)){ return false; }
	
	return true;
}

function chgFV ()
{
	if ($('send_fv').checked)
	{
		$$('.fvclass').invoke ('show');
	}
	else
	{
		$$('.fvclass').invoke ('hide');
	}
}

function getURLParam(param)
{
   var search = window.location.search.substring(1);
   if(search.indexOf('&') > -1) {
      var params = search.split('&');
      for(var i = 0; i < params.length; i++) {
          var key_value = params[i].split('=');
          if(key_value[0] == param) return key_value[1];
      }
   } else {
      var params = search.split('=');
      if(params[0] == param) return params[1];
   }
   return null;
}

function addEnterHandler(e, handler)
{  
	if (!e)
	{
		var e = window.event;
		window.event.cancelBubble = true;
	}
	var code;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if (code==13) setTimeout (handler, 0);
}

function setSearchColors(force)
{
 	if (force == undefined && $('mini_search_from').search_width.value == '195' &&
 			$('mini_search_from').search_profil.value == '65' &&
 			$('mini_search_from').search_diam.value == '15' &&
 			$('mini_search_from').search_keyword.value == 'michelin')
	{
		$('mini_search_from').search_width.setStyle('color:#a8b6d3');
		$('mini_search_from').search_profil.setStyle('color:#a8b6d3');
		$('mini_search_from').search_diam.setStyle('color:#a8b6d3');
		$('mini_search_from').search_keyword.setStyle('color:#a8b6d3');
	}
	else
	{
		$('mini_search_from').search_width.setStyle('color:#405580');
		$('mini_search_from').search_profil.setStyle('color:#405580');
		$('mini_search_from').search_diam.setStyle('color:#405580');
		$('mini_search_from').search_keyword.setStyle('color:#405580');
	}
}

function setSearchEmpty()
{
	if ($('mini_search_from').search_width.value == '' &&
			$('mini_search_from').search_profil.value == '' &&
			$('mini_search_from').search_diam.value == '' &&
			$('mini_search_from').search_keyword.value == '')
	{
		$('mini_search_from').search_width.value = '195';
		$('mini_search_from').search_profil.value = '65';
		$('mini_search_from').search_diam.value = '15';
		$('mini_search_from').search_keyword.value = 'michelin';
		
		setSearchColors();
	}
}

