var ulatwieniaDostepu;
function inicjujJs() {
	ulatwieniaDostepu = ($(document.body).getStyle('unicode-bidi') == 'bidi-override') ? false : true;
	inputyZTekstem();
	podpisyObrazkow();
	if (ulatwieniaDostepu != true) {
		menuRozwijane(); // latka dla :hover w ie
		popup(); // linki o klasie "popup" otwieraj w popup'ie
		drobnePoprawkiWygladu();
		szybkiPasek(); // marquee
		rotatory();
		animacjaTop(); // kalendarz animowany
	}
	document.documentElement.className = "jsOn";
}

function animacjaTop() {
	var idRodzica = 'animacjaTop';
	flashvars = '';
	var params = {};
	params.wmode = "transparent";
	params.menu = 'false';
	if (document.getElementById(idRodzica)) {
		swfobject.embedSWF("/p/kalendarz.swf", idRodzica, "204", "234", "9.0.0",false, flashvars, params);
	}
}

function szybkiPasek() {
	var Marquee;
	var szerokosc = 0;
	
	if(document.getElementById('marquee')) {
		$('jsMarquee').getElements('li').each(function(item){
			szerokosc = szerokosc + item.getSize().x;
		});
		szerokosc = szerokosc + 20;
		$('jsMarquee').setStyle('width', szerokosc);		
		Marquee = new marquee();
	} else {
		return false;
	}
	
	return Marquee;
}

var Rotator = new Class({
    Implements: Options,
    
    options: {
        rotuj: true, // domyslne dla wszystkich rotatorow. Nie rotuje, gdy ewentualne this.opcjeSmarty[2] == tytul ktorejs strony rotatora
        interwal_rotacji: 4000, // domyslny dla wszystkich. Mozna zmienic w module (title)
        klasaListyZakladek: 'paginacja', // paginacja budowana w js
        klasaAktywnejakladki: 'zakladkaAktywna', // paginacja budowana w js
        klasaOstatniejZakladki: 'ostatni', // paginacja budowana w js
        rodzicBoksow: 'rotator', // klasa css. Wewnatrz tych elementow budujemy rotator z dzieci o selektorze:
        boksySelektor: '.box', // z tych elementow budujemy rotator
        startowaZakladka: 0 // na starcie ustawiamy rotator na te zakladke
    },
    
    initialize: function(options) {
        this.setOptions(options);
        this.element = $(this.options.rodzicBoksow);
        // rotator pobiera ustawienia z modulu (ze smarty)
        this.opcjeSmarty = (this.element.getFirst('.zawartosc').get('title')) ? this.element.getFirst('.zawartosc').get('title').split(',') : [this.options.interwal_rotacji, 'fade'];
        this.element.getFirst('.zawartosc').erase('title');
        this.boksy = this.element.getElements(this.options.boksySelektor);
        this.jestSensBudowac = (this.boksy.length > 1) ? true : false; // budujemy this.zakladki, jesli jest ich wiecej niz 1
        this.zakladki = [];
        $$(this.boksy).each(function(boks) {
        	if((boks.get('title') & this.opcjeSmarty[2] & boks.get('title') == this.opcjeSmarty[2])) {
        		// "Teraz na antenie". Szukamy boksa o title takim, jak ew. opcjeSmarty[2]. Jesli jest, ustawiamy jako widoczny i nie rotujemy.
        		// this.rotowanySamoczynnie jest slabsze niz this.options.rotuj
                this.rotowanySamoczynnie = false;
            } else if (typeof(this.rotowanySamoczynnie) == 'undefined' || this.rotowanySamoczynnie == true) {
                this.rotowanySamoczynnie = true;
            }
        }.bind(this));
        // this.rotowanySamoczynnie jest slabsze niz this.options.rotuj
        this.rotowanySamoczynnie = (this.rotowanySamoczynnie == true & this.options.rotuj == false) ? false : this.rotowanySamoczynnie;
        this.startowaZakladka = this.options.startowaZakladka;
        this.rotacja = {};
        this.budujZakladki();
        this.rotuj();
        this.ustawCss();
    },
    
    budujZakladki: function() {
        if (this.jestSensBudowac) { // :)
            var ul = new Element('ul', {'class': this.options.klasaListyZakladek}).inject(this.element.getFirst('.zawartosc'));
            $$(this.boksy).each(function(boks) {
            	if (boks.get('title') && (boks.get('title') == this.opcjeSmarty[2])) {
            		this.rotowanySamoczynnie = false;
            	}
            }.bind(this));
            $$(this.boksy).each(function(boks,index) {
                boks.fade('hide');
                var a = new Element('a', {'html': index+1,'href': '#'}).addEvent('click', function(e) {
                    this.pokazBoks(index,'klik');
                    e.preventDefault();
                }.bind(this));
                var li = new Element('li').adopt(a).inject(ul);
                if (index + 1 == $$(this.boksy).length) {li.addClass(this.options.klasaOstatniejZakladki);}
                this.zakladki.push(li);
                if (this.rotowanySamoczynnie == true) {
                    boks.addEvents({
                        'mouseenter': function() {
                            $clear(this.period);
                        }.bind(this),
                        'mouseleave': function() {
                            this.period = this.rotacja.periodical(this.opcjeSmarty[0]);
                        }.bind(this)
                    });
                }
            }.bind(this));       
        }
    },
    
    pokazBoks: function(index,czyKlik) {
        $$(this.boksy).fade('out');
        //console.log(this.boksy);
        //console.log($$(this.boksy));
        //console.log($$(this.boksy)[index]);
        //console.log(index);
        $$(this.boksy)[index].fade('in');
    	if ($$(this.zakladki).length > 0) {
            $$(this.zakladki).removeClass(this.options.klasaAktywnejakladki);
            $$(this.zakladki)[index].addClass(this.options.klasaAktywnejakladki);
    	}
        if (typeof(czyKlik) != 'undefined' && this.rotowanySamoczynnie == true && this.opcjeSmarty[0] != 0) {
            $clear(this.period);
            this.zakladka = index;
            this.period = this.rotacja.periodical(this.opcjeSmarty[0]);
           
        }
    },
    
    rotuj: function() {
        this.zakladka = this.startowaZakladka;
        $$(this.boksy).each(function(boks,index) {
        	if (boks.get('title') && (boks.get('title') == this.opcjeSmarty[2])) {
        		this.zakladka = index;
        		this.rotowanySamoczynnie = false;
        	}
        }.bind(this));
        if (this.rotowanySamoczynnie == true && this.opcjeSmarty[0] != 0) {
            this.pokazBoks(this.zakladka);
            this.rotacja = function() {
                this.zakladka++;
                if (this.zakladka == this.boksy.length) {this.zakladka = 0;}
                this.pokazBoks(this.zakladka);
            }.bind(this);
            this.period = this.rotacja.periodical(this.opcjeSmarty[0]);   
        } else {
            this.pokazBoks(this.zakladka);
        }
    },
    
    ustawCss: function() {
		var poprawka = 0;
		var wysokoscDomyslna = 0;
		window.addEvent('load', function(){
			$$(this.boksy).each(function(item) {
				wysokoscDomyslna = (item.getSize().y > wysokoscDomyslna) ? item.getSize().y : wysokoscDomyslna; // zachowujemy najwieksza wartosc
			});
			if (this.element.getParent('.moduly')) {
				this.element.getFirst('.zawartosc').setStyle('height', wysokoscDomyslna+poprawka);	
			}			
		}.bind(this));
    }
});

function rotatory() {
    $$('.rotator').each(function(item){
        var r = new Rotator({rodzicBoksow: item});
    });
}

function inputyZTekstem() {
	var pola = []; // tablica zawierajaca id inputow majacych tekst domyslny
	var klasaNieaktywnego = 'inputNieaktywny'; // klasa inputa o pustym value (z tekstem ustawionym przez skrypt)

	pola['newsletterEmail'] = 'Adres e-mail';
	pola['fraza'] = 'Szukana fraza';
	
	for (var el in pola) {
		ustawValue(el,pola[el]);
	}

	function ustawValue(id,Value) {
		if ($(id)) {
			if ($(id).value == '' || $(id).value == Value) {
				$(id).value = Value;
				$(id).addClass(klasaNieaktywnego);
			}
			
			$(id).addEvents({
				'focus': function() {if($(id).value == Value) {$(id).removeClass(klasaNieaktywnego); $(id).value = '';}},
				'blur': function() {if($(id).value == '') {$(id).addClass(klasaNieaktywnego); $(id).value = Value;}}
			});
			
			if ($(id).getParent('form')) {
				$(id).getParent('form').addEvent('submit', function() { 
					$(id).fireEvent('focus', $(id)); // usuwa domyslna wartosc inputa (zeby np. form nie szukal frazy "wpisz fraze")
				});			
			}
			
		} // koniec if ($(id))
	}
}

function drobnePoprawkiWygladu() {
	var elementyGalerii = $$('#tresc-strony .zdjecieKont'); // przyciemnianie tych elementow po najechaniu kursorem
	var elementyUkrywane = '.doOdkrycia'; // te elementy beda ukryte
	var elementyOdkrywajace = '.odkryjNastepnyBlok'; // klikniecie w ten element spowoduje odkrycie nastepnego o klasie elementyUkrywane
	
	var poprawka = 0; // wartosc zmieniana przez skrypt, dla wyrownywqnych w pionie
	var wysokoscDomyslna = 0; // minimalna wysokosc boksow wyrownywanych w pionie
	var wyrownywaneWPionie = []; // tablica selektorow css dla elementow wyrownywanych w pionie
	// jesli napotkamy ponizsza klase, zerujemy wysokosc elementow (np konczy sie rzad zdjec, wiec obliczamy wysokosc od nowa)
	var resetujWysokoscGdy = 'ostatni';
	var temp = []; // tablica elementow czyszczona za kazdym razem, gdy "resetujWysokoscGdy"
	
	wyrownywaneWPionie.push('#stopkaWrap .srebrny .zawartosc');
	wyrownywaneWPionie.push('.zdjecieKont a');
	
	elementyGalerii.each(function(item,index) {
		item.fade(1);
		item.addEvents({
			'mouseenter': function() {elementyGalerii.erase(item).fade(0.5); elementyGalerii.push(item);},
			'mouseleave': function() {elementyGalerii.fade(1);}
		});
	});
	
	window.addEvent('load', function() {
		for (var i = 0; i < wyrownywaneWPionie.length; i++) {
			wysokoscDomyslna = 0;
			poprawka = 0;
			$$(wyrownywaneWPionie[i]).each(function(item, index) {
				if(poprawka == 0) {
					poprawka = poprawka + item.getStyle('padding-top').toInt() + item.getStyle('padding-bottom').toInt();
				}
				wysokoscDomyslna = (item.getSize().y > wysokoscDomyslna) ? item.getSize().y : wysokoscDomyslna;
				temp.push(item);
				if(item.getParent().hasClass(resetujWysokoscGdy) || index - 1 == $$(wyrownywaneWPionie[i]).length) {
					$$(temp).setStyle('height', wysokoscDomyslna-poprawka);
					temp.empty();
					wysokoscDomyslna = 0;
				}
			});
		}
	});

	
	$$(elementyOdkrywajace).each(function(item, index) {
		if(item.getNext(elementyUkrywane)) {
			var slideElement = new Fx.Slide(item.getNext(elementyUkrywane));
		} else if(item.getParent().getNext(elementyUkrywane)) {
			var slideElement = new Fx.Slide(item.getParent().getNext(elementyUkrywane));
		}
		slideElement.hide();
		item.addEvent('click', function() {
			slideElement.toggle();
			if(item.get('tag') == 'a'){return false;}
		});
	});
	
	if (Browser.Engine.name == 'trident') {
		$$('.box').setStyle('zoom','1');
	}
}

function popup() {
	var link;
	
	$$('.popup').each(function(item,index) {
		item.addEvent('click', function() {
			link = item.getAttribute('href');
			window.open(link, 'okno_pomocy', 'menubar=0,scrollbars=0,resizable=1,width=773,height=650');
			 return false;
		});
	});
}

function noweOkno(link,name,x,y) {
	window.open(link, name, 'menubar=0,scrollbars=0,resizable=1,width=850,height=600');
}

function podpisyObrazkow() {
	var tworzPodpisDla = '#tresc-strony .box img:not([class="adminModul"])[alt]'; // te obrazki otrzymaja podpis na podstawie atrybutu "alt"
	var imgAltWrap;
	var imgAlt;
	var _imgAltWrap = new Element('span', {'class': 'jsImgAltWrap'});
	var _imgAlt = new Element('span', {'class': 'jsImgAlt'});
	var tekstPodpisu = '';
	
	$$(tworzPodpisDla).each(function(obrazek) {
		if (!obrazek.getParent('.banner') && !obrazek.getParent('.spisArtow') && !obrazek.getParent('.miniatura')) {
			tekstPodpisu = (obrazek.get('alt') != '') ? obrazek.get('alt') : '';
			if(obrazek.get('longdesc') && obrazek.get('longdesc') != '') {
				tekstPodpisu += '<span> &copy; '+obrazek.get('longdesc')+'</span>';
			}
			if (tekstPodpisu != '') {
				imgAltWrap = _imgAltWrap.clone();
				if(obrazek.get('style')) {imgAltWrap.set('style', obrazek.get('style'));}
				if(obrazek.get('width')) {imgAltWrap.setStyle('width', obrazek.get('width')+'px');}
				imgAlt = _imgAlt.clone().set('html', tekstPodpisu);
				imgAltWrap.wraps(obrazek);
				imgAlt.inject(imgAltWrap, 'bottom');
			}			
		}
	});
}


var MenuRozwijane = new Class({
	Implements: Options,
	options: {
		rozwijaj: 'galaz', // konkretny znacznik LI
		rodzicBocznych: '.moduly', // rozroznianie zachowania na pdst. rodzicow (dla getParent() )
		domyslnieRozwiniete: 'aktywne', // rozwinieta kategoria menu bocznego
		rozwinieteJs: 'jsAktywne'
	},
	initialize: function(options) {
		this.setOptions(options);
		this.element = $(this.options.rozwijaj);
		this.animuj()
		
	},
	animuj: function() {
		if (this.element.getParent(this.options.rodzicBocznych)) { // jesli to menu boczne
			
			if (this.element.hasClass(this.options.domyslnieRozwiniete)) {
				if (this.element.getParent('li')) {
					this.element.getParent('li').addClass(this.options.rozwinieteJs);
					if (this.element.getParent('li').getParent('li')) {
						this.element.getParent('li').getParent('li').addClass(this.options.rozwinieteJs);
						if (this.element.getParent('li').getParent('li').getParent('li')) {
							this.element.getParent('li').getParent('li').getParent('li').addClass(this.options.rozwinieteJs);
						}
					}
				}
				
			}
			this.element.getFirst('a').addEvents({
				'click': function(e) {
					//this.element.toggleClass(this.options.rozwinieteJs);
					if (this.element.getElement('ul')) {
						e.preventDefault();
						this.element.getElement('ul').style.display = (this.element.getElement('ul').style.display == 'block') ? 'none' : 'block' ;
					}
				}.bind(this)
			});
			
		} else { // jesli to menu gorne
			
			if (this.element.getElement('ul')) {
				this.element.getElement('ul').fade('hide');
				this.element.addEvents({
					'mouseenter': function() {
						this.element.getElement('ul').fade('in');
					}.bind(this),
					'mouseleave': function() {
						this.element.getElement('ul').fade('out');
					}.bind(this)
				});					
			}
		}
		
	}
});
function menuRozwijane() {
	$$('.menuLinki li').each(function(menu) {
		var menuRozw = new MenuRozwijane({
			rozwijaj: menu
		});
	});
}

function przejdzDo(url) {
	if (ulatwieniaDostepu != true) { // obszar klikalny tylko gdy nie wlaczono ulatwien.		
		window.location = url;
	}
}

function maKlase (obj, klasaCss) {
    if (typeof obj == 'undefined' || obj==null || !RegExp) { return false; }
    var re = new RegExp("(^|\\s)" + klasaCss + "(\\s|$)");
    if (typeof(obj)=="string") {
      return re.test(obj);
    } else if (typeof(obj)=="object" && obj.className) {
      return re.test(obj.className);
    }
	return false;
}

function bannerStat(rekid, url, noweOkno) {	
	//zlicza kliknięcia bannerów i ew. przekierowuje
	var myRequest = new Request({
		method: 'get', 
		url: '/bannery/statystyki/',
			onSuccess: function( responseText ) {
				if(noweOkno) {
					var form = document.createElement("form");
					form.method = "GET";
					form.action = url;
					form.target = "_blank";
					document.body.appendChild(form);
					form.submit();
				} else {
					document.location.href = url;
				}
			}
	}).send('id='+rekid);
}

