SearchEngine.sloneczne = new Class({
    Extends: SearchEngine,
    initialize: function(sFormId, oConfig) {
        this.oForm = $(sFormId);
        this.oConfig = oConfig || null;
        this.vars = getUrlVars();
        
        this.oTransport = $('tripTransport2');
        this.oKategoria = $('tripTransport');
        this.oKraj = $('tripCountryName');
        this.oWyjazd = $('tripFrom');
            
        if (_Browser.ie) { // i love ie
        	this.oTransport = $(this.oForm['tripTransport2']);
            this.oKategoria = $(this.oForm['tripTransport']);
            this.oKraj = $(this.oForm['tripCountryName']);
            this.oWyjazd = $(this.oForm['tripFrom']);
        }
        
        this.aKraje = arrCountries;
        this.aWyjazdy = arrWyjazdy;
        this.aTransporty = arrTransport;
        
        this.popular = arrPopularCountries;
    },
    
    init: function() {
        this._setFromUrl();
        this.updateKategoria();
        this.updateTransport();
        this.updateKraj();
        this.updateWyjazd(); 
        
        this.oKraj.addEvent('change', function() {
            this.updateTransport();
            this.updateWyjazd();
        }.bind(this));
        
        this.oTransport.addEvent('change', function() {
            this.updateKraj();
            this.updateWyjazd();
        }.bind(this));
        
        this.oKategoria.addEvent('change', function() {
            this.updateKraj();
        }.bind(this));
    },
    
    updateKategoria: function() {
        this.set(this.oKategoria, this.oConfig.kategoria);
    },
    
    updateTransport: function() {
        var aTmp = [], aNewTransporty = [];
        var lastValue = this.getFieldValue(this.oTransport);
        for (var i=0; i<this.aKraje.length; i++) {
    		if (this.aKraje[i].key == this.getFieldValue(this.oKraj)) {
    			for (var x in this.aKraje[i].transport) {
    				if (this.aKraje[i].transport[x] == 1) {
    					aTmp.push(x);
    				}
    			}
    		}
    	}
        for (var i=0; i<this.aTransporty.length; i++) {
            for (var j=0; j<aTmp.length; j++) {
                if (aTmp[j] == this.aTransporty[i].key) {
                    aNewTransporty.push({key: this.aTransporty[i].key, name: this.aTransporty[i].name});
                }
            }
        }
        
        if (aNewTransporty.length == 0) {
        	aNewTransporty = this.aTransporty;
        }
        
        var config = this.oConfig.transport;
        config.customValue = lastValue;
        this.update(this.oTransport, aNewTransporty, config);
    },    
    
    updateKraj: function() {
    	var aNewKraje = [];
        var lastValue = this.getFieldValue(this.oKraj);
        var tV = this.getFieldValue(this.oTransport);
        var kV = this.getFieldValue(this.oKategoria);
        
        if (kV != 0 && tV != 0) {
        	for (var i=0; i<this.aKraje.length; i++) {
            	if (this.aKraje[i].transport[tV] == 1 && this.aKraje[i].categories[kV] == 1) {
            		aNewKraje.push({
                        key: this.aKraje[i].key,
                        name: this.aKraje[i].name
                    });
            	}
            }
        } else if (kV != 0 && tV == 0) {
            for (var i=0; i<this.aKraje.length; i++) {
            	if (this.aKraje[i].categories[kV] == 1) {
            		aNewKraje.push({
                        key: this.aKraje[i].key,
                        name: this.aKraje[i].name
                    });
            	}
            }
        } else if (kV == 0 && tV != 0){
        	for (var i=0; i<this.aKraje.length; i++) {
            	if (this.aKraje[i].transport[tV] == 1) {
            		aNewKraje.push({
                        key: this.aKraje[i].key,
                        name: this.aKraje[i].name
                    });
            	}
            }
        } else {
        	aNewKraje = this.aKraje;
        }
        
        var pops = [];
        for (var i=0; i<aNewKraje.length; i++) {
        	if (this.popular.contains(aNewKraje[i].name))
                pops.push(aNewKraje[i]);
        }
        if (pops.length > 0) {
            pops.splice(0, 0, {name: 'najpopularniejsze', key: 0, style: 1});
            pops.push({name: 'wszystkie', key: 0, style: 1});
            aNewKraje = pops.extend(aNewKraje);
        }
        
        var config = this.oConfig.kraj;
        config.customValue = lastValue;
        this.update(this.oKraj, aNewKraje, config , 1);
    },

    updateWyjazd: function() {
        var v = this.getFieldValue(this.oTransport);
        var lastValue = this.getFieldValue(this.oWyjazd);
        var aNewWyjazdy = [];
    	for (var i=0; i<this.aWyjazdy.length; i++) {
            if (v != 0) {
        		if (this.aWyjazdy[i].transport[v] == 1) {
        			aNewWyjazdy.push({key: this.aWyjazdy[i].key, name: this.aWyjazdy[i].name});
        		}
            } else {
            	if (this.aWyjazdy[i].transport['BUS'] || this.aWyjazdy[i].transport['AIR']) {
        			aNewWyjazdy.push({key: this.aWyjazdy[i].key, name: this.aWyjazdy[i].name});
        		}
            }
    	}
        
        var config = this.oConfig.wyjazd;
        config.customValue = lastValue;
        this.update(this.oWyjazd, aNewWyjazdy, config);       
    },    
    
    update: function(oSelect, aNewSelectValues, oCustom) {
        this.fireEvent('onUpdateStart', [oSelect.name, aNewSelectValues]);
        var opt = {}; oSelect.length = 0;
             
        if (oCustom.blank) {
            opt = document.createElement('option');
            opt.value = oCustom.blank.value;
            opt.text = oCustom.blank.name;
            oSelect.options.add(opt);
        }
        
        for (var i=0; i<aNewSelectValues.length; i++) {
            opt = document.createElement('option');
            opt.value = aNewSelectValues[i].key;
            opt.text = aNewSelectValues[i].name;
            if (aNewSelectValues[i].style) {
            	opt = $(opt);
                opt.setStyles({
                    'color': '#fff',
                    'background-color': '#000',
                    'font-weight': 'bold'
                })
            }
            oSelect.options.add(opt);
    	}    
        
        if (oCustom.noSet) return;
        this.set(oSelect, oCustom);
    },
    
    _setFromUrl: function() {
        if (this.vars.length == 0) return;
        var arr = [];
        for (var x in this.vars) {
        	var o = {name: x, value: decodeURIComponent(this.vars[x])};
            // te wartosci sa ustawiane wczesniej, wiec je pomijamy
            if (o.name != this.oTransport.name && o.name != this.oKraj.name &&
                o.name != this.oWyjazd.name && o.name != this.oKategoria.name && o.name != 'pid' && o.name != 'step') {
                
                if (this.oConfig.formElements.step1) {
                	var a = this.oConfig.formElements.step1;
                    for (var i=0; i<a.length; i++) {
                    	if (o.name == a[i]) {
                    		arr.push(o);
                    	}
                    }
                } else {
                	arr.push(o);
                }
            }
        }
        var step1 = new Form(this.oForm);
        step1.setValues(arr);
    }
});

var OpinieFormularzLista = new Class({
    initialize: function(links, spliter, linkCN) {
    	this.links = links;
        this.spliter = spliter;
        this.linkCN = linkCN;
        this.links.each(function(link, i) {
        	link.addEvent('click', function(e) {
        		e.stop();
                var ids = link.id.split(this.spliter);
                $(ids[0]).addClass('hide');
                $(ids[1]).removeClass('hide');
                link.className = this.linkCN + ids[1];
        	}.bind(this));
        }, this);
    }
});


GalleryStep4.sloneczne_modal = new Class({
    Extends: GalleryStep4,
    initialize: function(id, options) {
        this.setOptions(options);
        this.gallery = $(id);
        this.images = this.gallery.getElements('img.'+this.options.imgsClass);
        this.iTotal = this.images.length;
        this.mainImg = $(this.options.mainImgId);
        this.mainImg.setStyle('z-Index', 5);
        this.subImg = new Element('img', {
            'styles': {'z-Index':10, 'display': 'none'},
            'src': this.mainImg.src
        });
        
        this.iCurrent = this.iThumbCurrent = this.options.startAt;
    	if (this.options.bNav) this.handleNav();
        if (this.options.bStatus) this.handleStatus();
        if (this.options.bThumbs) this.handleThumbnails();
        this.fireEvent('onStart');
        //this.fireEvent('onImgChange');
    },
    
    show: function(i) {
    	this.iCurrent = i;
        this.subImg.setProperty('src', this.images[i].src);
		if (this.subImg.width === 0) {
			var self = this;
			setTimeout(function() {
				self.fireEvent('onImgChange', [self.subImg]);
			}, 300);
		} else {
			this.fireEvent('onImgChange', [this.subImg]);
		}
    },
    
    handleNav: function() {
    	this.navNext = $(this.options.sNavNextId);
    	this.navPrev = $(this.options.sNavPrevId);
        
        this.navNext.addEvent('click', function() {this.show(this.iCurrent+1);}.bind(this));
        this.navPrev.addEvent('click', function() {this.show(this.iCurrent-1);}.bind(this));
        
        this.addEvents({
            'onImgChange': function() {
                if (this.iCurrent == 0)
                    this.navPrev.addClass(this.options.sInvisCN);
                else this.navPrev.removeClass(this.options.sInvisCN);
                if (this.iCurrent == (this.iTotal-1))
                    this.navNext.addClass(this.options.sInvisCN);
                else this.navNext.removeClass(this.options.sInvisCN);
            }.bind(this)
        });
    }
});

var Sloneczne_ModalGallery = new Class({
    initialize: function(gal) {
        this.gal = gal;
        this.gal.mainImg.getParent().addEvent('click', function(e) {
            if (this.open) return;
            this.start(this.gal.iCurrent);
        }.bind(this));
        this.top = 20;
    },
    
    start: function(iStart) {
        this.open = 1;
        var content = '';
        content += '<div id="modal-g-top"><div class="a"><div class="b">';
        content += '<span id="modal-g-status"><span id="modal-g-current"></span> / <span id="modal-g-total"></span></span>';
        content += '</div></div></div>';
        content += '<img id="placeholder2" />';
        content += '<a href="#" id="modal-g-previous"></a>';
        content += '<a href="#" id="modal-g-next"></a>';
        content += '<a href="#" id="modal-g-close"></a>';
        
        this.modal = new ModalWindow({
            sContent: content,
            sWindowClassName: 'modal-gallery',
            sHiddenClassNameForSelects: 'hide',
            bBackground: 1,
            iOpacity: 50,
            bgColor: '#666',
            oWindowCss: {position: 'absolute', zIndex: 9999, width: 100+'px', height: 100+'px'}
        }); 
		
		this.modal.init();
        
      	this.gallery = new GalleryStep4.sloneczne_modal('gallery', {
            mainImgId: 'placeholder2',
            imgsClass: 'minigal',
            bThumbs: 0,
            bNav: 1,
            sNavPrevId: 'modal-g-previous',
            sNavNextId: 'modal-g-next',
            bStatus: 1,
            sStatusId: 'modal-g-status',
            sStatusCurrentId: 'modal-g-current', 
            sStatusTotalId: 'modal-g-total'
        }); 
            
                    
        this.gallery.addEvent('onImgChange', function(subImg) {
            var size = this._getSize(subImg.width, subImg.height);
            
            this.modal.window.setStyles({'width': size.x+'px', 'height': size.y+'px'});
            this.gallery.mainImg.setStyles({'width': size.x+'px', 'height': size.y-this.top+'px'});
            
            this.modal.getPosition();
            this.modal.setPosition();
            this.gallery.mainImg.src = subImg.src;
            
            this.gallery.navNext.setStyles({
                'height': this.modal.height - this.top,
                'width': (this.modal.width / 2) - 1
            });
            
            this.gallery.navPrev.setStyles({
                'height': this.modal.height - this.top,
                'width': (this.modal.width / 2) - 1
            });
        }.bind(this));
        
        // window.addEvent('keydown', function(e){
            // if (e.key == 'esc') this.modal.close();
            // this.gal.show(this.gallery.iCurrent);
        // }.bind(this));
        
        $('modal-g-close').addEvent('click', function(e) {
        	e.stop(); this.modal.close();
            this.open = 0;
            this.gal.show(this.gallery.iCurrent);
        }.bind(this));
        
        this.gallery.show(iStart);
    },
    
    _getSize: function(x, y) {
    	var ws = window.getSize();
        var ms = {x: x, y: y+this.top};
        var margin = 20;
        var res = {};
        
        if (ms.x+margin < ws.x && ms.y+margin < ws.y) return ms;
        
        if (ms.x+margin - ws.x > ms.y+margin - ws.y) {
            res.x = ws.x - margin;
            res.y = Math.ceil((res.x / ms.x) * ms.y);
        } else {
        	res.y = ws.y - margin;
            res.x = Math.ceil((res.y / ms.y) * ms.x);
        }
        return res;
    }
});

var Kal = new Class({
    Implements: [Options, Events],
    
    options: {
        monthNames:['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'],
        weekNames:['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'N']
    },
    
    initialize: function(obj, options) {
    	this.setOptions(options);
        
        this.trigger = $(obj.trigger);
        this.target = $(obj.target);
        
        this.trigger.addEvent('click', function(e) {
            e.stop();
        	this.show();
        }.bind(this));
        
      
        this.calendar = new Element('div', { 
			'styles': {'display': 'none', position: 'absolute', zIndex: 1000 },
            'class': 'pio-calendar',
            'html': '<div class="left"></div><div class="right"></div><div class="close"><a href="javascript:void(0);">zamknij</a></div>'
		}).inject(document.body);
        
		if (_Browser.ie6) {
			this.iframe = new Element('iframe', { 
				'styles': {display: 'none', position: 'absolute', zIndex: 999}
			}).inject(document.body);
			this.iframe.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
		}

		if (window.Drag) {
			this.drag = new Drag.Move(this.calendar, { 
				onDrag: function() {
					if (_Browser.ie6) { this.iframe.setStyles({ left: this.calendar.style.left, top: this.calendar.style.top }); } 
				}.bind(this) 
			}); 
		}
        
        this.calendar.getElement('div.close a').addEvent('click', function(e) {
        	this.close();
        }.bind(this));
        
        this.start();
    },
    
    start: function(date) {
        if (!date) var date = new Date();
        this.createTable(date, 'left');
        this.createTable(date, 'right');
    },
    
    showDate: function(date) {
        var d = date.getDate().toString();
        if (d.length < 2) d = '0' + d;
        var m = (date.getMonth() + 1).toString();
        if (m.length < 2) m = '0' + m;
        var y = date.getFullYear();
    	var txt = d+'.'+m+'.'+y;
        this.target.value = txt;
        this.close();
    },
    
    close: function() {
    	this.calendar.setStyle('display', 'none');
        if (_Browser.ie6) this.iframe.setStyle('display', 'none');
    },
    
    show: function() {
    	var s = this.trigger.getCoordinates();
        this.calendar.setStyles({
            'left': s.left + s.width,
            'top': s.top,
            'display': 'block'
        });
        if (_Browser.ie6) {
            var calSize = this.calendar.getSize();
            this.iframe.setStyles({
                'left': s.left + s.width,
                'top': s.top,
                'width': calSize.x,
                'height': calSize.y,
                'display': 'block'
            });
        }
    },
    
    createTable: function(date, dir) {
        var arr = [];
        if (dir == 'left') {
        	var target = this.calendar.getElement('div.left');
        } else {
        	var target = this.calendar.getElement('div.right');
            date.setMonth(date.getMonth() + 1);
        }
        target.empty();
        
        date.setDate(1);
        var actualDate = new Date();
        var days = this.getDays(date);
        var prev = this.getPrevDays(date);
        var next = this.getNextDays(date, days);
        
        arr.extend(prev);
        for (var i=1; i<days+1; i++) arr.push(i);
        for (var i=1; i<next+1; i++) arr.push(i);
            
        var div = new Element('div', {
            'class': 'cal-header',
            'text': this.options.monthNames[date.getMonth()]+' '+ date.getFullYear()
        }).inject(target);    
        
        var table = new Element('table').inject(target);
        table.store('month', date.getMonth());
        table.store('year', date.getFullYear());
        var thead = new Element('thead').inject(table);
        var thead_tr = new Element('tr').inject(thead);
        for (var i=0; i<7; i++) {
            var th = new Element('th', {'text': this.options.weekNames[i]}).inject(thead_tr);
        }
        
        var tbody = new Element('tbody').inject(table);
        for (var i=0; i<arr.length; i++) {
            if (i == 0 || i % 7 == 0) {
            	var tr = new Element('tr').inject(tbody);
                var data = 0;
            }
            
            data++;
            
            if (i < prev.length || i >= prev.length + days) 
                var cl = 'inactive';
            else 
                var cl = 'active';
            
            if (
                date.getFullYear() == actualDate.getFullYear() && 
                date.getMonth() == actualDate.getMonth() && 
                arr[i] == actualDate.getDate()
            ) {
                cl += ' today';
            }
            
            if (data == 7) {
            	cl += ' sunday';
            }
            
            var td = new Element('td', {
                'text': arr[i], 
                'class': cl
            }).inject(tr);
            td.addEvents({
                'mouseenter': function(e) {
                    var tg = $(e.target);
                    if (tg.hasClass('active'))
                        tg.addClass('hover');
                },
                'mouseleave': function(e) {
                    var tg = $(e.target);
                    if (tg.hasClass('active'))
                        tg.removeClass('hover');
                },
                'click': function(e) {
                    var tg = $(e.target);
                    if (tg.hasClass('active')) {
                        this.showDate(new Date(table.retrieve('year'), table.retrieve('month'), tg.get('text')));
                    }
                }.bind(this)
            });
        }
        
        var span = new Element('span', {
            'class': 'cal-nav',
            'events': {
                'click': function(e) {
                    var i, month, year;
                    if (dir == 'right') i = 0; 
                    else i  = -1;
                    
                    month = table.retrieve('month');
                    year = table.retrieve('year');
                    month += i;
                    if (month < 0) {
                    	year--;
                        month = 12 + month;
                    }
                    if (month > 11) {
                    	year++;
                        month = month % 12;
                    }
                    var d = new Date(year, month, 1);
                    this.start(d);                    
                }.bind(this)
            }
        }).inject(target);
    },
    
    getPrevDays: function(oDate) {
        var arr = [];
        var d = new Date(oDate.getTime());
        var ile = (d.getDay() == 0) ? 6 : d.getDay() - 1;
        d.setMonth(d.getMonth()-1);
        var days = this.getDays(d);
        while (ile-- > 0) arr.push(days - ile);
        return arr;
    },
    
    getNextDays: function(oDate, days) {
    	var d = new Date(oDate.getTime());
        d.setDate(days);
        w = (d.getDay() == 0) ? 7 : d.getDay();
        return 7 - w;         
    },
    
    getDays: function(oDate) {
        var m = oDate.getMonth();
        var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if (m == 1) {
            var y = oDate.getFullYear();
            if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
                return 29;
            else return 28;
        } else
            return days[m];
    }
});


ReservActualisation.sloneczne = new Class({
    Extends: ReservActualisation,
    init: function() {
        var c = Cookie.read('scroll');
        if (c) window.scrollTo(0, c);
    
    	this.getNames();
        this.names.each(function(pole, i) {
        	$(this.oForm[pole]).addEvent('change', function(e){
                var scroll = window.getScroll().y;
                Cookie.write('scroll', scroll, {duration: 0.000694444444 / 3}); // 20 sek
                this._koleczko(e.target);
                var update = new Element('input', {'type': 'hidden', 'name': 'update', 'value': 1}).inject(this.oForm);
                setTimeout(function() {this.oForm.submit();}.bind(this), 2000);
        	}.bind(this));
        }, this);
    },
    
    _koleczko: function(el) {
    	var html = '<span class="koleczko"><img src="' +SiteConfig.urlSite+ 'templates/default/images/ajax-loader.gif" />';
        html += 'Sprawdzanie dostępności oferty</span>';
        var sp = new Element('span', {'html': html}).inject(el, 'before');
        el.addClass('hide');
    }
});

