if (!console) {
	var console = {
        info: function() {},
        debug: function() {},
        error: function() {},
        warn: function() {},
        dir: function() {},
        dirxml: function() {},
        time: function() {},
        timeEnd: function() {},
        trace: function() {},
        profile: function() {},
        profileEnd: function() {},
        group: function() {},
        groupEnd: function() {}
    };
}

Ajax = {
    init: function(sXMLFile/*, iThreadNum*/){
        // inicjowanie obiektu do obslugi Ajaxa
        // nazwa pliku do ktorego jest wysylane zapytanie
        // ilosc wotkow ktore na raz obsuguje aplikacja
        this.sXMLFile = sXMLFile;
        this.aQueue = new Array; // kolejka zadan
        this.aInProgressQueue = new Array;
        this.iJobID = 0; //identyfikator w kolejce
        
        this.iIntervalTime = 500;
        this.oRequestInterval = null; // obiekt setTimeout        
        
        this.bActive = false; //okresla stan czy obiekt ma dzialac czy nie
        this.iThreadNum = 1;
        if (arguments.length > 1) { // pobiera argumnet
            var iThreadNum = arguments[1];
            if (parseInt(iThreadNum) > 0) {
                this.iThreadNum = parseInt(iThreadNum);
            } else if (iThreadNum === 0) {
                this.iThreadNum === undefined;
            }
        }
        //this.bAsynchronous = true; // za pomoca zmiennej ustawia sie czy zapytania do serwera maja byc wysylane synchronicznie czy asynchronicznie
        // asynchronicznie czyli wiele zapytan na raz
    },
    oXMLHttpRequest: {
        length: 0,        
        add: function(iID, oXMLHttpRequest) {  
            this[iID] = oXMLHttpRequest;
            this.length++;
        },        
        drop: function(iID) {
            delete this[iID];
            this.length--;
        }
    },
    
    start: function() { // odpala Ajaxa
        this.bActive = true;
        this._startSend();
    },
    
    stop: function() { // zatrzymuje Ajaxa
        this.bActive = false;
    },
    
    setInterval: function(iTime){
        if (parseInt(iTime)) {
            this.iIntervalTime = parseInt(iTime);
            return true;
        }
        return false;
    },
    
    addToQueue: function(sMode, iPriority, aSendValue, aHandlerValue, oHandlerFunction, bPageInstance) {
        // funkcja dodaje zadanie do ajaxowej kolejki
        // sMode - jaki modul ma byc wywolywany (dodawany)
        // iPriority - priorytet w kolejce
        // aSendValue - wartosci wysylane w get do skryptu
        // aHandlerValue - wartosci przekazywane do funkcji
        // oHandlerFunction - funkcja wywolywana po poprawynym wykonaniu zapytania
        var aTmp = {
            iID: ++this.iJobID,
            sMode: sMode,
            iPriority: iPriority,
            aSendValue: aSendValue,
            aHandlerValue: aHandlerValue,
            oHandlerFunction: oHandlerFunction,
            bPageInstance: (bPageInstance?1:0)
        }
        
        if (!this._insertToQueue(aTmp)) {
            return false;
        }
        
        this._startSend();
        
        return this.iJobID; //zwraca identyfiaktor zadania
    },
    
    dropFromQueue: function(iJobID){
        for (var i=0; i < this.aQueue.length; i++ )
        {
            if(this.aQueue[i].iID == iJobID){
                delete this.aQueue.slice(i,i+1);
                return true;                
            }
        }
        return false;
    },
    
    clearQueue: function(){
        // czyszczenie kolejki
        this.aQueue = new Array;
        this.aInProgressQueue = new Array;
        this.iJobID = 0;
    },
    
    _insertToQueue: function(oElement) {
        // dodawanie zadania do kolejki zgodnie z jego priorytetem
        for (var i=0; i < this.aQueue.length; i++ )
        {
            if(this.aQueue[i+1] && this.aQueue[i].iPriority < oElement.iPriority){
                this.aQueue.splice(i, 0, oElement);
                return true;                
            }
        }
        this.aQueue[this.aQueue.length] = oElement;
        return true;
    },
    
    _startSend: function(){
        if (this.aQueue.length && this.bActive && (this.iThreadNum === undefined || this.oXMLHttpRequest.length < this.iThreadNum)/*&& (!this.oXMLHttpRequest || this.oXMLHttpRequest.readyState == 0 || this.oXMLHttpRequest.readyState == 4)*/) {
            this._send(this.aQueue.shift());
            this._startSend();
        } else {
            if (this.aQueue.length) {
                if (this.oRequestInterval) {
                    clearTimeout(this.oRequestInterval);
                }
                setTimeout('Ajax._startSend()', this.iIntervalTime);
            }
            return true;
        }
    },
    
    _send: function(aCurrentJob){
    try{
        if (!(oXMLHttpRequest = this.createXMLHttpRequest())){ // tworzy element HttpRequest
            echo("Błąd podczas tworzenia obiektu XMLHttpRequest");
            return false;
        }
        this.oXMLHttpRequest.add(aCurrentJob.iID, oXMLHttpRequest);
        //this.oXMLHttpRequest[aCurrentJob.iID] = oXMLHttpRequest;
        
        var aPostValue = new Array('thread_id=' + aCurrentJob.iID, 'thread_mode=' + aCurrentJob.sMode, 'thread_page_instance=' + aCurrentJob.bPageInstance);
        for(var sName in aCurrentJob.aSendValue)
        {
            if ($type(aCurrentJob.aSendValue[sName]) == 'array' || $type(aCurrentJob.aSendValue[sName]) == 'object') {
                aPostValue[aPostValue.length] = sName + '=' + JSON.encode(aCurrentJob.aSendValue[sName]);
            } else {
                aPostValue[aPostValue.length] = sName + '=' + aCurrentJob.aSendValue[sName];
            }
        }
        
        oXMLHttpRequest.onreadystatechange = function() {Ajax._handle(Ajax.oXMLHttpRequest[eval(aCurrentJob.iID)])};
        oXMLHttpRequest.open('POST', this.sXMLFile, true);
        oXMLHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        oXMLHttpRequest.setRequestHeader("Content-length", aPostValue.length);
        oXMLHttpRequest.setRequestHeader("Connection", "close");
        this.aInProgressQueue[aCurrentJob.iID] = aCurrentJob;
        oXMLHttpRequest.send(aPostValue.join('&'));
    } catch(e) {/*alert(e);*/}
    },
    
    _handle: function(oXMLHttpRequest){
        var iReadyState = oXMLHttpRequest.readyState;
        if (iReadyState == 1 || iReadyState == 2 || iReadyState == 3) {
            //alert(iReadyState);
        } else if(iReadyState == 4) {
        try{
            try{ 
                var oResponse = eval('(' + oXMLHttpRequest.responseText + ')');
                var sResponse = null;
                var aInfo = {iID : oResponse.thread_id, sMode : oResponse.thread_mode}
                delete oResponse.thread_id,oResponse.thread_mode;
            } catch(e) {
                var oResponse = null;
                var aTmp = oXMLHttpRequest.responseText.split(':', 3);
                var aInfo = {iID : aTmp[0], sMode : aTmp[1]};
                var sResponse = aTmp[2];
            }
            
            if (!(aInfo.iID.match(/^[0-9]+$/) && aInfo.sMode.match(/^[0-9a-z_-]+$/))) {
                echo(oXMLHttpRequest.responseText.replace(/<[^>]+>/gi,''));
                return false;
            }
            
            if (this.aInProgressQueue[aInfo.iID]) {
                if (this.aInProgressQueue[aInfo.iID].sMode == aInfo.sMode) {
                    if (typeof this.aInProgressQueue[aInfo.iID].oHandlerFunction == 'string') {
                    	eval( this.aInProgressQueue[aInfo.iID].oHandlerFunction + '(this.aInProgressQueue[aInfo.iID].aHandlerValue, oResponse, sResponse);');
                    } else {
                        this.aInProgressQueue[aInfo.iID].oHandlerFunction(this.aInProgressQueue[aInfo.iID].aHandlerValue, oResponse, sResponse);
                    }

                } else {
                    echo('_handle: Bledny mode');
                }
                delete this.aInProgressQueue[aInfo.iID];
            } else {
                echo('_handle: Brak obiektu w tablicy');
                return false;
            }
            
            this.oXMLHttpRequest.drop(aInfo.iID);
            //this._startSend();
        }catch(e){echo('Ajax._handle: '+e)}
        }
    },
    
    createXMLHttpRequest: function()
    {
    	var xmlHttp;
    	try {
    		xmlHttp = new XMLHttpRequest();
    	} catch(e) {
    		var XmlHttpVersions = new Array(
    		"MSXML2.XMLHTTP.5.0",
    		"MSXML2.XMLHTTP.4.0",
    		"MSXML2.XMLHTTP.3.0",
    		"MSXML2.XMLHTTP",
    		"Microsoft.XMLHTTP");
    		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
    			try {
    				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
    			} catch(e) {}
    	}
    	if (!xmlHttp)
    		return false;
    	else
    		return xmlHttp;
    }    
}
var echo = $empty;

window.addEvent('domready', function() {
	// Ajax = new AjaxObj(window.location.protocol+'//'+window.location.host+'/ajax.php', 1);
	Ajax.init(window.location.protocol+'//'+window.location.host+'/ajax.php', 5);
    Ajax.start();
});



var ModalWindow = new Class({
    initialize: function(o) {
        this.oContent = o.oContent;
        this.sContent = o.sContent;
        this.oWindowCss = o.oWindowCss;
    	this.sWindowClassName = o.sWindowClassName || 'modal-window';
        this.sHiddenClassNameForSelects = o.sHiddenClassNameForSelects || 'hide';
        this.bBackground = o.bBackground || 0;
        this.iOpacity = o.iOpacity || 60;
        this.bgColor = o.bgColor || '#000';
        this.position = o.position;
        
        this.window = {};
        this.bg = null;
        this.width = 0;
        this.height = 0;

        this.createWindow();
    },
    
    init: function() {
        this.appendWindow();
        this.getPosition();
        this.setPosition();
        if (Browser.Engine.trident4) {this.selects = $$('select'); this._handleSelects();}
        
        if (this.bg) {
            var This = this;
            
            this.scrollEvent = window.addEvent('scroll', function() {
                This.setPosition();
                This.setBackgroundPosition();
            });
            this.scrollEvent = window.addEvent('resize', function() {
                This.setPosition();
                This.setBackgroundPosition();
            });
        }
    },
    
    /**
        * Metoda do zamykania okna
    */
    close: function() {
    	if (this.bg)
    		this.bg.dispose();

        this.insertContent('');
        this.window.dispose();
        window.removeEvent('scroll', this.scrollEvent);
        window.removeEvent('resize', this.resizeEvent);
        
        if (Browser.Engine.trident4) this._showSelects();
    },
    
    flash: function(i) {
        this.init();
        var This = this;
    	setTimeout(function() {This.close();}, i);
    },
    
    /**
        * Jak widac, wstawia html'a do okna
    */
    insertContent: function(content) {
    	this.window.innerHTML = content;
    },
    
    insertObject: function(o) {
    	this.window.innerHTML = '';
        this.window.appendChild(o);
    },
      
    getPosition: function() {
        this.width = this.window.getStyle('width').toInt();
    	this.height = this.window.getStyle('height').toInt();
        
        if (isNaN(this.width) || isNaN(this.hieght)) {
        	var size = this.window.getSize();
            this.width = size.x;
            this.height = size.y;
        }
    },
    
    setPosition: function() {
        if (!this.position) {
            this.placeCenter();
            return;
        }       
            
        if (this.position.absolute) this.placeAbsolute(this.position.absolute);
        if (this.position.center) this.placeRelativeCenter(this.position.center);
    },
    
    placeAbsolute: function(o) {
    	this.window.style.top = o.y + 'px';
        this.window.style.left = o.x + 'px';
    },
    
    placeRelativeCenter: function(o) {
    	this.window.style.top = o.y - (this.height / 2) + 'px';
        this.window.style.left = o.x - (this.width / 2) + 'px';
    },
    
    placeCenter: function() {
    	var obszar = window.getSize();
        var scroll = window.getScroll();
        
        var l = Math.ceil(obszar.x / 2 - (this.width/2));
        var t = Math.ceil(obszar.y / 2 - (this.height/2));
             
        this.window.style.top = t + scroll.y + 'px';
        this.window.style.left = l + scroll.x + 'px';
    },
    
    createWindow: function() {
    	this.window = new Element('div', {'class': this.sWindowClassName});
        if (this.oContent) this.window.appendChild(this.oContent);
        else if (this.sContent) this.insertContent(this.sContent);
        else this.insertContent('');
        
        if (this.oWindowCss) {
            for (var key in this.oWindowCss) {
                this.window.style[key] = this.oWindowCss[key];
            }
        }
    },
    
    appendWindow: function() {
    	var place = document.body;
        if (this.bBackground) this.createBackground();
        place.insertBefore(this.window, place.firstChild);
    },
    
    createBackground: function() {
    	this.bg = new Element('div', {
            'styles': {
                'position' : 'absolute',
                'background-color' : this.bgColor,
                'z-Index' : '9998',
                'overflow' : 'hidden'
            }
        });
        
        this.setBackgroundPosition();
        
        if (Browser.Engine.trident)
        	this.bg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+this.iOpacity+')';
        else
            this.bg.style.opacity = this.iOpacity / 100;
        
        this.bg.inject(document.body, 'top');
    },
    
    setBackgroundPosition: function() {
        var zxc = window.getScrollSize();
        this.bg.setStyles({
            'top': 0,
            'left': 0,
            'width': zxc.x + 'px',
            'height': zxc.y + 'px'
        });
    },
   
    _handleSelects: function() {
        if (this.bBackground) {
            this._hideSelects();
            return;
        }
        var c = this.window.getCoordinates(), sc, s;
        var w = {x1: c.left,x2: c.left+c.width,y1: c.top,y2: c.top+c.height};
        this.selects.each(function(select, i) {
            sc = select.getCoordinates();
            s = {x1: sc.left,x2: sc.left+sc.width,y1: sc.top,y2: sc.top+sc.height};
            if ((s.x1 > w.x2) || (s.x2 < w.x1) || (s.y1 > w.y2) || (s.y2 < w.y1)) {
            	select.removeClass(this.sHiddenClassNameForSelects);
            } else {
                select.addClass(this.sHiddenClassNameForSelects);
            }
        }, this);
        
    },
   
    _hideSelects: function() {
        this.selects.each(function(select, i) {
        	select.addClass(this.sHiddenClassNameForSelects);
        }, this);
    },
    
    _showSelects: function() {
        this.selects.each(function(select, i) {
        	select.removeClass(this.sHiddenClassNameForSelects);
        }, this);
    }
});


var PioPres = new Class({
	Implements: [Events, Options],

	options: {
		slidesWidth: 518,
		slidesCN: 'pp-slide',
		slideshowTime: 7000
	},

	initialize: function(slider, options) {
		this.setOptions(options);
		this.slider = $(slider);
		this.current = 0;
		this.total = this.slider.getElements('.' + this.options.slidesCN).length; 
        this.slider.setStyle('width', this.options.slidesWidth * this.total);
        this.fx = new Fx.Tween(this.slider, {link: 'chain'});
	},
	
	go: function(num, time) {
		if (num != this.current) this._change(num, time);
	}, 
	
	slideshow: function(time) {
		if (this.timeout) $clear(this.timeout);
		this.timeout = this.next.delay($pick(time, this.options.slideshowTime), this);
	},
	
	next: function() {
        var next = this.current + 1;
    	if (this.current >= this.total - 1) next = 0;
        this._change(next);
    },
	
    _change: function(num, time) {
		this.fireEvent('change', [num, this.current]);
        this.current = num;
        this.fx.start('left', - num * this.options.slidesWidth);
		this.slideshow(time);
    }
});

/* ustawiania prezentacji */
window.addEvent('domready', function() {
	if (!document.getElementById('pio-pres-slider')) return;
	var piopres = new PioPres('pio-pres-slider', {slideshowTime: 7000}); /* globalny timeout */
	var triggers = $$('.pp-menu-item');
	
	triggers.each(function(trigger, i) {
		trigger.addEvent('click', function(e) {
			e.stop(); piopres.go(i, 10000); /* liczba to czas (timeout) dla kolejnego slajdu, po kliknieciu */
		});
	});

	piopres.addEvent('change', function(to, from) {
		triggers[to].addClass('active');
		triggers[from].removeClass('active');
	});
	
	piopres.slideshow();
});

var MenuListy = new Class({
	initialize: function() {
		var items = $('menu-listy').getElement('.ml-list').getElements('a');
		var targets = $('menu-listy').getElement('.ml-images').getElements('a');
		var active = items[0];
		items.each(function(el, i) {
			el.addEvent('mouseenter', function(e) {
				this.handle(active);	
				active = el;
				this.handle(active);
			}.bind(this));
		}, this);
	},
	
	handle: function(el) {
		var num = el.id.replace('ml-trigger_', '');
		el.getParent().toggleClass('active');
		$('ml-image_' + num).toggleClass('hide');
	}
});

/* menu-listy */
window.addEvent('domready', function() {
	if (!document.getElementById('menu-listy')) return;
	new MenuListy();
});

var ChangeSearchForm = new Class({
    initialize: function() {        
        $('wysz-zaaw').addEvent('click', function(e) {
            this.handleAdv();
        }.bind(this));
            
        $('wysz-stand').addEvent('click', function(e) {
            this.handleStand();
        }.bind(this));
    },
    handleAdv: function() {
        if ($('step1').hasClass('noadvCh')) {
            $('step1').removeClass('noadvCh');
            $('step1').addClass('advCh');
            $('wyzyw').toggleClass('hide');
            $('stand').toggleClass('hide');
            $('typ').toggleClass('hide');
            $('ponaz').toggleClass('hide');
            $('adults').toggleClass('hide');
            $('child1').toggleClass('hide');
            $('child2').toggleClass('hide');
			$('lastminute').toggleClass('hide');
        }
    },
    handleStand: function() {        
        if ($('step1').hasClass('advCh')) {
            $('step1').removeClass('advCh');
            $('step1').addClass('noadvCh');
            $('wyzyw').toggleClass('hide');
            $('stand').toggleClass('hide');
            $('typ').toggleClass('hide');
            $('ponaz').toggleClass('hide');
            $('adults').toggleClass('hide');
            $('child1').toggleClass('hide');
            $('child2').toggleClass('hide');
			$('lastminute').toggleClass('hide');
        }       
    }
});

window.addEvent('domready', function() {
	if (!document.getElementById('wysz-stand')) return; 
	new ChangeSearchForm();
});

var PolecZnajomemu = new Class({
    initialize: function(o) {
    	this.ob = $(o.oObszar);
        this.loader = '<img src="'+window.location.protocol+'//'+window.location.host+'/templates/grecos/images/ajax-loader-purple.gif" />';
		
		this.ob.getElements('a.' + o.sLinkCN).each(function(el) {
			el.addEvent('click', this.handleEvent.bindWithEvent(this, [el]));
		}, this);
    },
    
    handleEvent: function(e, oLink) {
        e.preventDefault();
		var This = this;
        var o = {This: this, oLink: oLink, oLinkText: oLink.innerHTML};
        oLink.innerHTML = oLink.innerHTML + this.loader;
        
        Ajax.addToQueue('turystyka_wycieczki', 1, {form: true, state: 'tellAFriend'}, o, This.getForm, 1); 
    },
    
    getForm: function(o, oRes, sRes) {
        try {
            o.oLink.innerHTML = o.oLinkText;
            var con = '<a id="modal-window-close" href="javascript:void(0);">zamknij</a><h2>Poleć tą wycieczkę znajomemu</h2>';
            con += oRes.form;
            o.This.modal = new ModalWindow({
                sContent: con, 
                bBackground: 1, 
                sWindowClassName: 'modal-polec-znajomemu',
                bHideSelects: 1,
                sHiddenClassNameForSelects: 'hide'
            }); o.This.modal.init();
            
            var close = $('modal-window-close');
            close.addEvent('click', function() {o.This.modal.close(); o.This.modal = null;});
            
            o.This.addEventToForm(o.oLink);
        } catch(e) {console.error('PolecZnajomemu.getForm zwraca wyjatek: %s',e)}
    },
    
    addEventToForm: function(oLink) {
        var This = this;
        var form = $('polec-znajomemu-form');
        form.getElement('input[name="submit"]').addEvent('click', function(e) {This.handleFormEvent(e, form, oLink);});
    },
    
    handleFormEvent: function(e, form, oLink) {
    	e.preventDefault();
        var This = this, url = encodeURIComponent(oLink.href);
        var email = form['email_odbiorcy'].value;
        var nadaw = form['wysylajacy'].value;
        var info = document.getElementById('polec-znajomemu-form-info');
        
        info.innerHTML = this.loader;
        
        var o = {This: this, info: info};
        var s = {state: 'tellAFriend', email_odbiorcy: email, wysylajacy: nadaw, url_wycieczka: url};
        Ajax.addToQueue('turystyka_wycieczki', 1, s, o, This.readStatus, 1); 
    },
    
    readStatus: function(o, oRes, sRes) {
        try {
            if (oRes.status) {
                o.This.modal.insertContent('<span class="message-sent">'+oRes.message+'</span>');
                setTimeout(function() {o.This.modal.close(); o.This.modal = null;}, 2000);
            } else {
            	o.info.innerHTML = oRes.message;
            }
        } catch(e) {console.error('PolecZnajomemu.readStatus zwraca wyjatek: %s',e);}
    }
});



window.addEvent('domready', function() {
	var terminy = $('term');
	if (terminy) {
		var p = new PolecZnajomemu({oObszar: terminy, sLinkCN: 'polec-znajomemu'});
	}
});

/**
 * 18:43 2008-11-11 /pio
 */
var CountTrips = new Class({
    Implements: Options,
    options: {
        iGlobalTimeOut: 10,
        loader: '',
		state: 'countTrips'
    },
    
	initialize: function(req, options) {
		this.oForm = req.oForm;
        this.aFields = req.aFields;
        this.oContainer = req.oContainer;
        this.setOptions(options);
        
        this.aItems = [];
        this.oDataToSend = {};
        this.timeout;
	},
    
    init: function() {
        this.getItems();
        this.addEvents();
        this.prepareDataAndSend();
    },
    
    addEvents: function() {
    	var This = this;
        this.aItems.each(function(item, i) {
        	if (item.conf.event == 'change') {
                item.obj.addEvent('change', function() {
                    This.handleEvent(item);
                });
        	} else if (item.conf.event == 'keypress') {
        		// Dopisac
        	}
            if (item.conf.specialEvent) {
            	item.obj.addEvent(this.aItems[i].conf.specialEvent, function() {
                    This.handleEvent(item);
            	});
            }
        }, this);
    },
    
    handleEvent: function(oItem) {
    
        clearTimeout(this.timeout);
        oItem.value = this.getValue(oItem.obj);
        this.prepareDataAndSend(oItem);
    },
    
    prepareDataAndSend: function(oItem) {
        var This = this, time;
        this.oContainer.set('html', this.options.loader);
        this.oDataToSend = {};
        this.oDataToSend['state'] = this.options.state;
        for (var i=0; i<this.aItems.length; i++) {
    		this.oDataToSend[this.aItems[i].name] = this.aItems[i].value;
    	}
        
        if (oItem)
            time = (oItem.conf.time) ? oItem.conf.time : this.options.iGlobalTimeOut;
        else 
        	time = this.options.iGlobalTimeOut;
        
        this.timeout = setTimeout(function() {This.send();}, time);
    },
    
    send: function() {
        var This = this, o = {This: this}; 
        Ajax.addToQueue('turystyka_wycieczki', 1, this.oDataToSend, o, This.getResponse, 1);
    },
    
    getResponse: function(o, oRes, sRes) {
        try {
        	o.This.oContainer.set('html', oRes.count);
        } catch (e) {console.error('CountTrips.getResponse wyrzuca wyjatek: %o', e);}
    },
    
    getValue: function(o) {
    	var form = new Form(this.oForm);
        return form.getValue(o);
    },
    
    getItems: function() {
        var val;
		for (var i=0; i<this.aFields.length; i++) {
			if (!this.oForm[this.aFields[i].name]) continue;
			val = this.getValue(this.oForm[this.aFields[i].name]);
            this.aItems.push({
                obj: $(this.oForm[this.aFields[i].name]),
                name: this.aFields[i].name,
                value: val,
                conf: this.aFields[i].conf
            });
		}
    }
});

//wylaczone tymczasowo na polcenie Jacka - GK 2009.12.01
// CountTrips.grecos = new Class({
    // Extends: CountTrips,
    // prepareDataAndSend: function(oItem) {
        // var This = this, time;
        // this.oContainer.set('html', this.options.loader);
        // this.oDataToSend = {};
        // this.oDataToSend['state'] = this.options.state;
        // for (var i=0; i<this.aItems.length; i++) {
            // if (this.aItems[i].value == 'Tylko po nazwie') this.aItems[i].value = '';
    		// this.oDataToSend[this.aItems[i].name] = this.aItems[i].value;
    	// }
        
        // if (oItem)
            // time = (oItem.conf.time) ? oItem.conf.time : this.options.iGlobalTimeOut;
        // else 
        	// time = this.options.iGlobalTimeOut;
        
        // this.timeout = setTimeout(function() {This.send();}, time);
    // }
// }); 

/**
 * Klasa ulatwiajaca pobieranie i ustawianie wartosci pol formularzy
 * le: 10:32 2008-09-15 by pio
 * @parm oForm - obiekt formularza
 */
var Form = new Class({
    initialize: function(oForm) {
        this.oForm = oForm;
        this.aElements = []; 
    },
    
    /**
     * @parm o - DOM Element
     * @return - string
     */    
    getValue: function(o) {
        switch (o.type) {
            case 'checkbox':
                if (o.checked == true) {
                    return o.value;
                } else {
                	return 0;
                }
                break;
            case undefined: // radio
                for (var j=0; j<o.length; j++) {
                    if (o[j].checked == true) {
                        return o[j].value;
                    }
                }    
                break;
            default: 
                return o.value;
        }    	
    },
    
    /**
     * @parm o -DOM Element
     * @parm val - mixed - wartosc pola
     */
    setValue: function(o, val) {
        switch (o.type) {
            case 'checkbox':
                if (val != 0) {
                    o.checked = true;
                } else {
                	o.checked = false;
                }
                break;
            case undefined: // radio
                for (var j=0; j<o.length; j++) {
                    if (o[j].value == val) {
                        o[j].checked = true;
                    }
                }    
                break;
            default: 
                return o.value = val;
        }        	
    },

    /**
     * przepisuje wartosci pol formularza do tablicy aElements;
     */
    getAllElements: function() {
        var aNames = [];
        var aEl = this.oForm.elements;
        
        add: for (var i=0; i<aEl.length; i++) {
            if (aEl[i].name) {
            	for (var j=0; j<aNames.length; j++) {
                    if (aEl[i].name == aNames[j]) {
                       continue add;
                    }
                }
                aNames.push(aEl[i].name);
            }
        }
            
        for (var i=0; i<aNames.length; i++) {
            if (this.oForm[aNames[i]]) {
                var o = {};
                o.obj = this.oForm[aNames[i]];
                if ($type(o.obj) == 'array') o.obj = o.obj[o.obj.length-1];
                o.name = aNames[i];
                o.value = this.getValue(o.obj);
                this.aElements[i] = o;
            }
        }
    },  
    
    /**
     * nadaje wartosci hurtem dla wszystkich pol.
     * @parm a - array - tablica obiektow {name: 'FildName', value: 'FildValue'}
     * @return - void
     */    
    setValues: function(a) {
    	if (!a) return;
        this.getAllElements();
        
                
        for (var i=0; i<a.length; i++) {
        	for (var j=0; j<this.aElements.length; j++) {
                if (a[i].name == this.aElements[j].name) {
            		this.aElements[j].value = a[i].value;
            	}
            }
        }
        this._setValues();
    },    
    
    _setValues: function() {
    
    	for (var i=0; i<this.aElements.length; i++) {
    		switch (this.aElements[i].obj.type) {
                case 'checkbox':
                    if (this.aElements[i].value == 0) {
                        this.aElements[i].obj.checked = false;
                    } else {
                        this.aElements[i].obj.checked = true;
                    }
                    break;
                case undefined: // radio
                    for (var j=0; j<this.aElements[i].obj.length; j++) {
                    	if (this.aElements[i].obj[j].value == this.aElements[i].value) {
                            this.aElements[i].obj[j].checked = true;
                    	}
                    }
                    break;
                default: 
                    this.aElements[i].obj.value = this.aElements[i].value;
                    
    		}
    	}
    }  
    
});

window.addEvent('domready', function() {
	var form = $('step1');
    //wylaczone tymczasowo na polcenie Jacka - GK 2009.12.01
	if (false && form && document.getElementById('wysz-stand')) {
        var container = $('tripsCount-container');       
		var kaka = new CountTrips.grecos({// required
			oForm: form,
			oContainer: container,
			aFields: [
				{name: 'tripCountryName', conf: {event: 'change'}}, 
				{name: 'tripStartflight', conf: {event: '', specialEvent: 'blur', iLitera: 3, time: 1000}}, 
				{name: 'tripTrip_range', conf: {event: 'change'}}, 
				{name: 'tripFrom', conf: {event: 'change'}}, 
				{name: 'tripPrice', conf: {event: 'change'}}, 
				{name: 'tripHotel_category', conf: {event: 'change'}}, 
				{name: 'tripTransport', conf: {event: 'change'}}, 
				{name: 'tripBoard', conf: {event: 'change'}}, 
				{name: 'tripAdults', conf: {event: 'change'}},
				{name: 'tripChild1', conf: {event: 'change'}},
				{name: 'tripChild2', conf: {event: 'change'}},
				{name: 'trip_onlyLM', conf: {event: 'change'}},
				{name: 'catalog', conf: {event: 'change'}},
				{name: 'nazwaKodHotelu', conf: {event: '', specialEvent: 'blur', iLitera: 3, time: 1000}}
			]
		}, { // options
			iGlobalTimeOut: 1000,
			loader: '<img src="'+window.location.protocol+'//'+window.location.host+'/imgLib/ajax-loader-purple.gif" />',
			state: 'countTrips'
		}); kaka.init();

	}
    var form2 = $('frm-sidebar');
    //wylaczone tymczasowo na polcenie Jacka - GK 2009.12.01
	if (false && form2) {
        var container = $('tripsCount-container2');        
		var kaka = new CountTrips.grecos({// required
			oForm: form2,
			oContainer: container,
			aFields: [
				{name: 'tripCountryName', conf: {event: 'change'}}, 
				{name: 'tripStartflight', conf: {event: '', specialEvent: 'blur', iLitera: 3, time: 1000}}, 
				{name: 'tripTrip_range', conf: {event: 'change'}}, 
				{name: 'tripFrom', conf: {event: 'change'}}, 
				{name: 'tripPrice', conf: {event: 'change'}}, 
				{name: 'tripHotel_category', conf: {event: 'change'}}, 
				{name: 'tripTransport', conf: {event: 'change'}}, 
				{name: 'tripBoard', conf: {event: 'change'}}, 
                {name: 'tripAdults', conf: {event: 'change'}},
				{name: 'tripChild1', conf: {event: 'change'}},
				{name: 'tripChild2', conf: {event: 'change'}},
                {name: 'trip_onlyLM', conf: {event: 'change'}},
                {name: 'catalog', conf: {event: 'change'}},
				{name: 'nazwaKodHotelu', conf: {event: '', specialEvent: 'blur', iLitera: 3, time: 1000}}
			]
		}, { // options
			iGlobalTimeOut: 1000,
			loader: '<img src="'+window.location.protocol+'//'+window.location.host+'/imgLib/ajax-loader-purple.gif" />',
			state: 'countTrips'
		}); kaka.init();
	}
});



/**
 * 14:41 2009-02-19 /pio
 */
var Validation = new Class({
    Implements: [Options, Events],
    options: {
        errorClass: 'validation-element-error',
        errorContainerClass: 'validation-branch-error',
        submitButtonName: 'submit'
    },
    initialize: function(sFormId, conf, options) {
    	this.setOptions(options);
        this.oForm = $(sFormId);
        this.submit = this.oForm.getElement('input[name="'+this.options.submitButtonName+'"]');
        this.conf = conf;
        this.aItems = [];
        this.aErrors = [];
    },
    
    init: function() {
        this._getItems();
        this._addEvents();
        this._createBranchContainer();    	
    },
    
    _addEvents: function() {
    	this.aItems.each(function(item, i) {
    		if (item.type == 'radio') {
                var arr = this._getRadios(item);
                arr.each(function(radio, i) {
                    radio.addEvent('blur', this._checkItem.bindWithEvent(this, [item, 1]));
                }, this);
            } else
                item.addEvent('blur', this._checkItem.bindWithEvent(this, [item, 1]));
    	}, this);
        this.submit.addEvent('click', function(e) {
        	this.checkAll(e);
        }.bind(this));
    },
    
    checkAll: function(e) {
        this.aErrors = [];
    	for (var i=0; i<this.aItems.length; i++) {
    		this._checkItem(e, this.aItems[i], 0);
    	}
        
        if (this.aErrors.length != 0) {
            e.preventDefault();
            this.fireEvent('onBranchErrors', [this.aErrors, this.aItems]);
        	this.showBranchOfErrorMsgs();
            return;
        }
        this.branchContainer.empty();
    },    
    
    _checkItem: function(e, item, b) {
        item.store('errorMsg', 0);
        
        var rules = item.retrieve('rules');
        for (var metoda in rules) {
            $try(function() {
                this[metoda](item, rules[metoda]);
            }.bind(this));
        }
        
        this.fireEvent('onError', [item, b]);
        this._handleError(item, b);
    },
    
    setError: function(item, s) {
        var msg = item.retrieve('errorMsg', 0); 
        if (!msg) msg = s;
        else msg += ' ' + s;
        item.store('errorMsg', msg);
        this.aErrors.include(item);
    },
    
    _handleError: function(item, b) {
        if (item.retrieve('errorMsg') != 0) {
    		this._handleClassName(item, 'add');
            if (b == 1) this._handleErrorMsg(item, 'add');
    	} else {
    		this._handleClassName(item, 'remove');
            if (b == 1) this._handleErrorMsg(item, 'remove');
    	}    	
    },
    
    _handleClassName: function(item, action) {
    	var target;
        if (item.type == 'radio')
    		target = this.oForm.getElement('label[for="'+item.name+'"]');
        else if (item.type == 'checkbox')
            target = this.oForm.getElement('label[for="'+item.id+'"]');
        else
            target = item;
            
        if (!target) return;       
        if (action == 'add')
        	target.addClass(this.options.errorClass);
        else if (action == 'remove')
        	target.removeClass(this.options.errorClass);
    },
        
    _handleErrorMsg: function(item, action) {
    	var span = $('validation-error-'+item.name);
        if (action == 'add') {
            if (span)
                span.set('text', item.retrieve('errorMsg'));
            else {
            	span = new Element('span', {
                    'id' : 'validation-error-'+item.name,
                    'text': item.retrieve('errorMsg')
                }).inject(this.branchContainer);
            }
    	} else if (action == 'remove') {
    		if (span) span.dispose();
    	}
    },
    
    _createBranchContainer: function() {
        this.branchContainer = new Element('div', {
            'class': this.options.errorContainerClass
        }).inject(this.submit.getParent(), 'top');
    },
    
    showBranchOfErrorMsgs: function() {
        this.branchContainer.empty();
        var f = document.createDocumentFragment();
        for (var i=0; i<this.aErrors.length; i++) {
            var s = document.createElement('span');
            s.id = 'validation-error-' + this.aErrors[i].name;
            s.innerHTML = this.aErrors[i].retrieve('errorMsg');
            f.appendChild(s);
        }
        this.branchContainer.appendChild(f);
    },    
    
    _getItems: function() {
        var o;
        for (var i=0; i<this.conf.stale.length; i++) {
            o = this.oForm.getElement('[name="'+this.conf.stale[i].name+'"]');
            if (!o) continue;
            o.store('rules', this.conf.stale[i].rules);
            o.store('clientName', this.conf.stale[i].clientName);
            this.aItems.push(o);
        } 
    },
    
    _getRadios: function(el) {
    	return this.oForm.getElements('[name="'+el.name+'"]');
    }
});

Validation.implement({
    notNull: function(item) {
        if (item.value == '') 
            this.setError(item, 'Pole '+item.retrieve('clientName')+' nie może być puste.');
    },
    
    post_code: function(item) {
    	var res = item.value.match(/^[\d]{2}-[\d]{3}$/);
        if (!res && item.value != '') 
            this.setError(item, item.retrieve('clientName')+' jest błędnie wpisany.');
    },
    
    number: function(item) {
    	var res = item.value.match(/^[\d]+$/);
        if (!res && item.value != '')  
            this.setError(item, 'W polu '+item.retrieve('clientName')+' mogą występować tylko liczby.');
    },
    
    onlyLetters: function(item) {
    	var res = item.value.match(/^[a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+$/);
        if (!res && item.value != '')
            this.setError(item, 'W polu '+item.retrieve('clientName')+' mogą występować tylko litery.');
    },

    minSize: function(item, num) {
        if (item.value.length < num)
            this.setError(item, item.retrieve('clientName')+' musi mieć minium '+num+' znaków.');
    },

    email: function(item) {
    	var res = item.value.match(/^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/);
        if (!res)
            this.setError(item, item.retrieve('clientName')+' ma nieprawidłową formę.');
    },
    
    //for radio
    chosen: function(item) {
        var b = 0, arr = this._getRadios(item);
    	for (var i=0; i<arr.length; i++) {
    		if (arr[i].checked == true) b = 1;
    	}
        if (b == 0) this.setError(item, 'Pole '+item.retrieve('clientName')+' musi być zaznaczone.');
    },
    
    //for checkbox
    checked: function(item) {
        if (item.checked == false)
            this.setError(item, 'Pole '+item.retrieve('clientName')+' musi być zaznaczone.');
    },
    
    //for selects
    selected: function(item) {
        if (item.value == '0')
            this.setError(item, 'W polu '+item.retrieve('clientName')+' musi być wybrana opjca.');
    },
    
    custom: function(item, obj) {
    	if (!item.value.match(obj.re)) this.setError(item, obj.msg);
    }
});

/**
 * 23:48 2008-11-22 /pio
 */
Validation.step5 = new Class({
    Extends: Validation,
    init: function() {
        this._getItems();
        this._getZmienne();
        this._addEvents();
        this._createBranchContainer();
    },
    
    _getZmienne: function() {
        if (!this.conf.zmienne) return;
        var p = this.conf.zmienne.persons, o, s;
        rooms = this._getRooms();
        for (var i=0; i<rooms.length; i++) {
        	for (var j=0; j<rooms[i]; j++) {
                for (var k=0; k<p.length; k++) {
                    s = 'room['+i+'][person]['+j+']['+p[k].name+']';
                    o = this.oForm.getElement('[name="'+s+'"]');
                    o.store('rules', p[k].rules);
                    o.store('clientName', p[k].clientName);
                    this.aItems.push(o); 
                }
        	}
        }
    },
    
    _getRooms: function() {
        var i = 0, rooms = [];
        while (this.oForm['room['+i+'][id]'] != null) {
            rooms[i] = this._countPersons(i);
            i++;
        }
        return rooms;
    },
    
    _countPersons: function(iRoomIndex) {
    	var i = 0;
        while (this.oForm['room['+ iRoomIndex +'][person]['+ i +'][type]'] != null) {
            i++;
        }
        return i;
    }
});

/**
 * Dodaje event onChange do selectow na step5
 * 16:37 2008-11-22
 */
var ReservActualisation = new Class({
    initialize: function(sFormId, oTriggers) {
    	this.oForm = $(sFormId);
        this.oTriggers = oTriggers;
        this.names = [];
    },
    
    init: function() {
        this.getNames();
        this.names.each(function(pole, i) {
        	$(this.oForm[pole]).addEvent('change', this.go.bind(this));
        }, this);
    },
	
	go: function() {
		var update = new Element('input', {'type': 'hidden', 'name': 'update', 'value': 1}).inject(this.oForm);
		this.oForm.submit();
	},
    
    getNames: function() {
        var iNumRooms = 1;
        
        //zmienne
        if (this.oTriggers.zmienne.room)
            iNumRooms = this._getNumRooms(this.oTriggers.zmienne.room[0]);
        
        for (var key in this.oTriggers.zmienne) {
            for (var i=0; i<this.oTriggers.zmienne[key].length; i++) {
                for (var j=0; j<iNumRooms; j++) {
                    if (this.oForm[key+'['+j+']['+this.oTriggers.zmienne[key][i]+']'] != null)
                        this.names.push(key+'['+j+']['+this.oTriggers.zmienne[key][i]+']');
                }
            }
        }
        
        //stale
        for (var i=0; i<this.oTriggers.stale.length; i++) {
        	this.names.push(this.oTriggers.stale[i]);
        }
		
		//po klasie 
		 for (var i=0; i<this.oTriggers.changePoKlasie.length; i++) {
        	var els = this.oForm.getElements('.' + this.oTriggers.changePoKlasie[i]);
			els.addEvent('change', function() {
				var update = new Element('input', {'type': 'hidden', 'name': 'update', 'value': 1}).inject(this.oForm);
                this.oForm.submit();
			}.bind(this));
        }
    },

    _getNumRooms: function(s) {
        var i = 0;
        while (this.oForm['room['+i+']['+s+']'] != null) {
            i++;
        }
        return i;
    }
});


window.addEvent('domready', function() {
	var id = 'frm-booking'; 
	var form = $(id);
	if (!form) return;

	var przeladowanie = new ReservActualisation(id, {
        stale: ['trip[room_num]', 'trip[start_from_id]'],
        zmienne: { // pokoi moze byc kilka
            room: ['id', 'board_id', 'adult_child', 'infant', 'adult', 'child']
        },
		changePoKlasie: ['thisSubmit']
    }); przeladowanie.init();
	
	var trigg = $('step5-more-rooms');
	if (trigg) {
		trigg.addEvent('click', function(e) {
			e.stop();
			form.getElement('select[name="trip[room_num]"]').value = 2;
			przeladowanie.go();
		});
	}
	
	var stale = [
		{name: 'client[name]', clientName: 'imię', rules: {custom: {re: /^[^`~!@#$%|?&*()=_+{}:";,<>0-9]+$/i, msg: 'imię zawiera niedozwolone znaki'}}},
		{name: 'client[surname]', clientName: 'nazwisko', rules: {custom: {re: /^[^`~!@#$%|?&*()=_+{}:";,<>0-9]+$/i, msg: 'nazwisko zawiera niedozwolone znaki'}}},
		{name: 'client[street]', clientName: 'ulica', rules: {custom: {re: /^[^`~!@#$%|?*=_+:";<>{}]+$/i, msg: 'ulica zawiera niedozwolone znaki'}}},
		{name: 'client[street_nr0]', clientName: 'nr doumu', rules: {custom: {re: /^[^`~!@#$%|?*=_+:";<>{}&']+$/i, msg: 'nr domu zawiera niedozwolone znaki'}}},
		{name: 'client[street_nr1]', clientName: 'nr mieszkania', rules: {custom: {re: /^[^`~!@#$%|?*=_+:";<>{}&']*$/i, msg: 'nr mieszkania zawiera niedozwolone znaki'}}},
		{name: 'client[post_code]', clientName: 'kod pocztowy', rules: {custom: {re: /^[0-9a-z\-# ]{3,10}$/i, msg: 'kod pocztowy zawiera niedozwolone znaki'}}},
		{name: 'client[city]', clientName: 'miasto', rules: {custom: {re: /^[^`~!@#$%|?*=_+:";<>]+$/i, msg: 'miasto zawiera niedozwolone znaki'}}},
		{name: 'client[phone]', clientName: 'telefon kontaktowy', rules: {custom: {re: /^[\[\]0-9\-+()# ]{7,32}$/i, msg: 'telefon kontaktowy zawiera niedozwolone znaki'}}},
		{name: 'client[email]', clientName: 'email', rules: {notNull: 1, email: 1}},
		{name: 'trip[confirm_info]', clientName: 'potwierdzenie powrotu', rules: {checked: 1}},
		
		{name: 'pesel', clientName: 'pesel', rules: {custom: {re: /^[0-9]{11}$/, msg: 'pesel ma nieprawidłowy format'}}},
		{name: 'regulamin', clientName: 'regulamin', rules: {checked: 1}},
		{name: 'ochronadanych', clientName: 'ochrona danych', rules: {checked: 1}},
		{name: 'handlowainformacja', clientName: 'informacje handlowe', rules: {}},
		{name: 'club_number', clientName: 'nr karty klubowej', rules: {number: 1}}
	];

	var zmienne = {
		persons: [
			{name: 'name', clientName: 'imię uczestnika', rules: {custom: {re: /^[^`~!@#$%|?&*()=_+{}:";,<>0-9]+$/i, msg: 'imię zawiera niedozwolone znaki'}}},
			{name: 'surname', clientName: 'nazwisko uczestnika', rules: {custom: {re: /^[^`~!@#$%|?&*()=_+{}:";,<>0-9]+$/i, msg: 'imię zawiera niedozwolone znaki'}}},
			{name: 'day', clientName: 'dzień urodzenia uczestnika', rules: {notNull: 1, number: 1}},
			{name: 'month', clientName: 'miesiąc urodzenia uczestnika', rules: {notNull: 1, number: 1}},
			{name: 'year', clientName: 'rok urodzenia uczestnika', rules: {notNull: 1, number: 1}}
		]    
	};

	var request_only = form.getElement('input[name="trip[only_request]"]').value == '1';
	if (request_only) {
		stale = [
			{name: 'client[name]', clientName: 'imię', rules: {custom: {re: /^[^`~!@#$%|?&*()=_+{}:";,<>0-9]+$/i, msg: 'imię zawiera niedozwolone znaki'}}},
			{name: 'client[surname]', clientName: 'nazwisko', rules: {custom: {re: /^[^`~!@#$%|?&*()=_+{}:";,<>0-9]+$/i, msg: 'imię zawiera niedozwolone znaki'}}},
			{name: 'client[street]', clientName: 'ulica', rules: {custom: {re: /^[^`~!@#$%|?*=_+:";<>{}]*$/i, msg: 'ulica zawiera niedozwolone znaki'}}},
			{name: 'client[street_nr0]', clientName: 'nr doumu', rules: {custom: {re: /^[^`~!@#$%|?*=_+:";<>{}&']*$/i, msg: 'nr domu zawiera niedozwolone znaki'}}},
			{name: 'client[street_nr1]', clientName: 'nr mieszkania', rules: {custom: {re: /^[^`~!@#$%|?*=_+:";<>{}&']*$/i, msg: 'nr mieszkania zawiera niedozwolone znaki'}}},
			{name: 'client[post_code]', clientName: 'kod pocztowy', rules: {custom: {re: /(^[0-9a-z\-# ]{3,10}$)|(^\s*$)/i, msg: 'kod pocztowy zawiera niedozwolone znaki'}}},
			{name: 'client[city]', clientName: 'miasto', rules: {custom: {re: /^[^`~!@#$%|?*=_+:";<>]*$/i, msg: 'miasto zawiera niedozwolone znaki'}}},
			{name: 'client[phone]', clientName: 'telefon kontaktowy', rules: {custom: {re: /(^[\[\]0-9\-+()# ]{7,32}$)|(^\s*$)/i, msg: 'telefon kontaktowy zawiera niedozwolone znaki'}}},
			{name: 'client[email]', clientName: 'email', rules: {notNull: 1, email: 1}},
			{name: 'regulamin', clientName: 'regulamin', rules: {checked: 1}},
			{name: 'ochronadanych', clientName: 'ochrona danych', rules: {checked: 1}},
			{name: 'handlowainformacja', clientName: 'informacje handlowe', rules: {}},
			{name: 'club_number', clientName: 'nr karty klubowej', rules: {number: 1}}
		];
		zmienne = {
			persons: [
				{name: 'name', clientName: 'imię uczestnika', rules: {custom: {re: /^[^`~!@#$%|?&*()=_+{}:";,<>0-9]*$/i, msg: 'imię uczestnika zawiera niedozwolone znaki'}}},
				{name: 'surname', clientName: 'nazwisko uczestnika', rules: {custom: {re: /^[^`~!@#$%|?&*()=_+{}:";,<>0-9]*$/i, msg: 'nazwisko uczestnika zawiera niedozwolone znaki'}}},
				{name: 'day', clientName: 'dzień urodzenia uczestnika', rules: {number: 1}},
				{name: 'month', clientName: 'miesiąc urodzenia uczestnika', rules: {number: 1}},
				{name: 'year', clientName: 'rok urodzenia uczestnika', rules: {number: 1}}
			]    
		};
	}

	var validacja = new Validation.step5(form, {
		stale: stale,
		zmienne: zmienne
	}, {
		submitButtonName: 'booking'
	}); validacja.init();
});


/* pokaz ukryj na stronie last-minute */
window.addEvent('domready', function() {
	var triggers = $$('.lm-week-desc');
	if (triggers.length == 0) { return; }
	
	triggers.each(function(el) {
		el.addEvent('click', function(e) {
			var target = $(e.target),
				nr, table,
				id = 'lm-week_';
            
			e.stop();
			if (target.tagName.toLowerCase() == 'a') { 
				nr = target.href.match(/([0-9]+)$/)[1];
				if (target.hasClass('thisWeek')) {
					$(id + nr).toggleClass('hide');
				} else if (target.hasClass('nextWeek')) {
					table = $(id + nr);
					table.removeClass('hide');
					window.scrollTo(0, table.getPosition().y - 40);
				}				
			}
		});
	});
});


window.addEvent('domready', function() {
	var lm = $('trip_onlyLM'),
		date = $('tripStartflight'),
		cal = $('cal'),
		handle = function() {
			if (lm.checked == true) {
				date.disabled = true;
				cal.style.visibility = 'hidden';
			} else {
				date.disabled = false;
				cal.style.visibility = 'visible';
			}
		};
	
	if (!lm) { return; }
	lm.addEvent('change', handle);
	handle();
});

window.addEvent('domready', function() {
	var od = $('catalog'),
		date = $('tripStartflight'),
		cal = $('cal'),
		handle = function() {
			if (od.checked == true) {
				date.disabled = true;
				cal.style.visibility = 'hidden';
			} else {
				date.disabled = false;
				cal.style.visibility = 'visible';
			}
		};
	
	if (!od) { return; }
	od.addEvent('change', handle);
	handle();
});


var OfferCheckStep4 = new Class({
	Implements: [Events, Options],

	options: {
		ttl: 10000/*,
		onAvailable: $empty,
		onUnavailable: $empty */
	},
	
	initialize: function(nodes, options) {
		this.setOptions(options);
        for (var i = 0, l = nodes.length; i < l; i++) {
			this.send(nodes[i]);
		}
	},
	
	send: function(node) {
		
		var data = commentData(node),
			self = this;
		
		if ($type(data) != 'object') {
			console.error('OfferCheckStep4.send data nie jest obiektem');
			this.fireEvent('unavailable', [node]);
			return;
		}
		
		Ajax.addToQueue(
			'turystyka_wycieczki',
			1,
			data,
			{self: self, node: node},
			self.response,
			0
		);
		
	},
	
	response: function(o, res) {
		
		var self = o.self;
		
		if (res) {
			if (res.state > 0) {
				self.fireEvent('available', [o.node]);
			} else {
				self.fireEvent('unavailable', [o.node]);
			}
		} else {
			self.fireEvent('unavailable', [o.node]);
			console.error('OfferCheckStep4.send error');
		}
	}
	
});

window.addEvent('domready', function() {
	if (!document.getElementById('term')) { return; }
	
	var nodes = $('term').getElements('.offer-check');
	
	new OfferCheckStep4(nodes, {
		onAvailable: function(node) {
			node.getElement('.guzik-check').dispose();
			node.getElement('.guzik-reserv').removeClass('hide');
		},
		onUnavailable: function(node) {
			node.getElement('.guzik-check').dispose();
			node.getElement('.guzik-question').removeClass('hide');
		}
	});
});


var ModalWindow = new Class({
    
	ie: Browser.Engine.trident,
	ie6: Browser.Engine.trident4,
	
	initialize: function(o) {
        this.oContent = o.oContent;
        this.sContent = o.sContent;
        this.oWindowCss = o.oWindowCss;
    	this.sWindowClassName = o.sWindowClassName || 'modal-window';
        this.sHiddenClassNameForSelects = o.sHiddenClassNameForSelects || 'hide';
        this.bBackground = o.bBackground || 0;
        this.iOpacity = o.iOpacity || 60;
        this.bgColor = o.bgColor || '#000';
        this.position = o.position;
        
        this.window = {};
        this.bg = null;
        this.width = 0;
        this.height = 0;
        this.createWindow();
    },
    
    init: function() {
        this.appendWindow();
        this.getPosition();
        this.setPosition();
        if (this.ie6) {this.selects = $$('select'); this._handleSelects();}
        
        if (this.bg) {
            var This = this;
            
            this.scrollEvent = window.addEvent('scroll', function() {
                This.setPosition();
                This.setBackgroundPosition();
            });
            this.scrollEvent = window.addEvent('resize', function() {
                This.setPosition();
                This.setBackgroundPosition();
            });
        }
    },
    
    /**
        * Metoda do zamykania okna
    */
    close: function() {
    	if (this.bg)
    		this.bg.dispose();

        this.insertContent('');
        this.window.dispose();
        window.removeEvent('scroll', this.scrollEvent);
        window.removeEvent('resize', this.resizeEvent);
        
        if (this.ie6) this._showSelects();
    },
    
    flash: function(i) {
        this.init();
        var This = this;
    	setTimeout(function() {This.close();}, i);
    },
    
    /**
        * Jak widac, wstawia html'a do okna
    */
    insertContent: function(content) {
    	this.window.innerHTML = content;
    },
    
    insertObject: function(o) {
    	this.window.innerHTML = '';
        this.window.appendChild(o);
    },
      
    getPosition: function() {
        // this.width = this.window.getStyle('width').toInt();
    	// this.height = this.window.getStyle('height').toInt();
        
        // if (isNaN(this.width) || isNaN(this.hieght)) {
        	var size = this.window.getSize();
            this.width = size.x;
            this.height = size.y;
        // }
    },
    
    setPosition: function() {
        if (!this.position) {
            this.placeCenter();
            return;
        }       
            
        if (this.position.absolute) this.placeAbsolute(this.position.absolute);
        if (this.position.center) this.placeRelativeCenter(this.position.center);
    },
    
    placeAbsolute: function(o) {
    	this.window.style.top = o.y + 'px';
        this.window.style.left = o.x + 'px';
    },
    
    placeRelativeCenter: function(o) {
    	this.window.style.top = o.y - (this.height / 2) + 'px';
        this.window.style.left = o.x - (this.width / 2) + 'px';
    },
    
    placeCenter: function() {
    	var obszar = window.getSize();
        var scroll = window.getScroll();
        
        var l = Math.ceil(obszar.x / 2 - (this.width/2));
        var t = Math.ceil(obszar.y / 2 - (this.height/2));
             
        this.window.style.top = t + scroll.y + 'px';
        this.window.style.left = l + scroll.x + 'px';
    },
    
    createWindow: function() {
    	this.window = new Element('div', {'class': this.sWindowClassName});
        if (this.oContent) this.window.appendChild(this.oContent);
        else if (this.sContent) this.insertContent(this.sContent);
        else this.insertContent('');
        
        if (this.oWindowCss) {
            for (var key in this.oWindowCss) {
                this.window.style[key] = this.oWindowCss[key];
            }
        }
    },
    
    appendWindow: function() {
    	var place = document.body;
        if (this.bBackground) this.createBackground();
        place.insertBefore(this.window, place.firstChild);
    },
    
    createBackground: function() {
    	this.bg = new Element('div', {
            'styles': {
                'position' : 'absolute',
                'background-color' : this.bgColor,
                'z-Index' : '9998',
                'overflow' : 'hidden'
            }
        });
        
        this.setBackgroundPosition();
        
        if (this.ie)
        	this.bg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+this.iOpacity+')';
        else
            this.bg.style.opacity = this.iOpacity / 100;
        
        this.bg.inject(document.body, 'top');
    },
    
    setBackgroundPosition: function() {
        var zxc = window.getScrollSize();
        this.bg.setStyles({
            'top': 0,
            'left': 0,
            'width': zxc.x + 'px',
            'height': zxc.y + 'px'
        });
    },
   
    _handleSelects: function() {
        if (this.bBackground) {
            this._hideSelects();
            return;
        }
        var c = this.window.getCoordinates(), sc, s;
        var w = {x1: c.left,x2: c.left+c.width,y1: c.top,y2: c.top+c.height};
        this.selects.each(function(select, i) {
            sc = select.getCoordinates();
            s = {x1: sc.left,x2: sc.left+sc.width,y1: sc.top,y2: sc.top+sc.height};
            if ((s.x1 > w.x2) || (s.x2 < w.x1) || (s.y1 > w.y2) || (s.y2 < w.y1)) {
            	select.removeClass(this.sHiddenClassNameForSelects);
            } else {
                select.addClass(this.sHiddenClassNameForSelects);
            }
        }, this);
        
    },
   
    _hideSelects: function() {
        this.selects.each(function(select, i) {
        	select.addClass(this.sHiddenClassNameForSelects);
        }, this);
    },
    
    _showSelects: function() {
        this.selects.each(function(select, i) {
        	select.removeClass(this.sHiddenClassNameForSelects);
        }, this);
    }
});

var ModalWindow2 = new Class({
    
	ie: Browser.Engine.trident,
	ie6: Browser.Engine.trident4,
	
	initialize: function(o) {
        this.oContent = o.oContent;
        this.sContent = o.sContent;
        this.oWindowCss = o.oWindowCss;
    	this.sWindowClassName = o.sWindowClassName || 'modal-window2';
        this.sHiddenClassNameForSelects = o.sHiddenClassNameForSelects || 'hide';
        this.bBackground = o.bBackground || 0;
        this.iOpacity = o.iOpacity || 60;
        this.bgColor = o.bgColor || '#000';
        this.position = o.position;
        
        this.window = {};
        this.bg = null;
        this.width = 0;
        this.height = 0;
        this.createWindow();
    },
    
    init: function() {
        this.appendWindow();
        this.getPosition();
        this.setPosition();
        if (this.ie6) {this.selects = $$('select'); this._handleSelects();}
        
        if (this.bg) {
            var This = this;
            
            this.scrollEvent = window.addEvent('scroll', function() {
                This.setPosition();
                This.setBackgroundPosition();
            });
            this.scrollEvent = window.addEvent('resize', function() {
                This.setPosition();
                This.setBackgroundPosition();
            });
        }
    },
    
    /**
        * Metoda do zamykania okna
    */
    close: function() {
    	if (this.bg)
    		this.bg.dispose();

        this.insertContent('');
        this.window.dispose();
        window.removeEvent('scroll', this.scrollEvent);
        window.removeEvent('resize', this.resizeEvent);
        
        if (this.ie6) this._showSelects();
    },
    
    flash: function(i) {
        this.init();
        var This = this;
    	setTimeout(function() {This.close();}, i);
    },
    
    /**
        * Jak widac, wstawia html'a do okna
    */
    insertContent: function(content) {
    	this.window.innerHTML = content;
    },
    
    insertObject: function(o) {
    	this.window.innerHTML = '';
        this.window.appendChild(o);
    },
      
    getPosition: function() {
        // this.width = this.window.getStyle('width').toInt();
    	// this.height = this.window.getStyle('height').toInt();
        
        // if (isNaN(this.width) || isNaN(this.hieght)) {
        	var size = this.window.getSize();
            this.width = size.x;
            this.height = size.y;
        // }
    },
    
    setPosition: function() {
        if (!this.position) {
            this.placeCenter();
            return;
        }       
            
        if (this.position.absolute) this.placeAbsolute(this.position.absolute);
        if (this.position.center) this.placeRelativeCenter(this.position.center);
    },
    
    placeAbsolute: function(o) {
    	this.window.style.top = o.y + 'px';
        this.window.style.left = o.x + 'px';
    },
    
    placeRelativeCenter: function(o) {
    	this.window.style.top = o.y - (this.height / 2) + 'px';
        this.window.style.left = o.x - (this.width / 2) + 'px';
    },
    
    placeCenter: function() {
    	var obszar = window.getSize();
        var scroll = window.getScroll();
        
        var l = Math.ceil(obszar.x / 2 - (this.width/2));
        var t = Math.ceil(obszar.y / 2 - (this.height/2));
             
        this.window.style.top = t + scroll.y + 'px';
        this.window.style.left = l + scroll.x + 'px';
    },
    
    createWindow: function() {
    	this.window = new Element('div', {'class': this.sWindowClassName});
        if (this.oContent) this.window.appendChild(this.oContent);
        else if (this.sContent) this.insertContent(this.sContent);
        else this.insertContent('');
        
        if (this.oWindowCss) {
            for (var key in this.oWindowCss) {
                this.window.style[key] = this.oWindowCss[key];
            }
        }
    },
    
    appendWindow: function() {
    	var place = document.body;
        if (this.bBackground) this.createBackground();
        place.insertBefore(this.window, place.firstChild);
    },
    
    createBackground: function() {
    	this.bg = new Element('div', {
            'styles': {
                'position' : 'absolute',
                'background-color' : this.bgColor,
                'z-Index' : '9998',
                'overflow' : 'hidden'
            }
        });
        
        this.setBackgroundPosition();
        
        if (this.ie)
        	this.bg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+this.iOpacity+')';
        else
            this.bg.style.opacity = this.iOpacity / 100;
        
        this.bg.inject(document.body, 'top');
    },
    
    setBackgroundPosition: function() {
        var zxc = window.getScrollSize();
        this.bg.setStyles({
            'top': 0,
            'left': 0,
            'width': zxc.x + 'px',
            'height': zxc.y + 'px'
        });
    },
   
    _handleSelects: function() {
        if (this.bBackground) {
            this._hideSelects();
            return;
        }
        var c = this.window.getCoordinates(), sc, s;
        var w = {x1: c.left,x2: c.left+c.width,y1: c.top,y2: c.top+c.height};
        this.selects.each(function(select, i) {
            sc = select.getCoordinates();
            s = {x1: sc.left,x2: sc.left+sc.width,y1: sc.top,y2: sc.top+sc.height};
            if ((s.x1 > w.x2) || (s.x2 < w.x1) || (s.y1 > w.y2) || (s.y2 < w.y1)) {
            	select.removeClass(this.sHiddenClassNameForSelects);
            } else {
                select.addClass(this.sHiddenClassNameForSelects);
            }
        }, this);
        
    },
   
    _hideSelects: function() {
        this.selects.each(function(select, i) {
        	select.addClass(this.sHiddenClassNameForSelects);
        }, this);
    },
    
    _showSelects: function() {
        this.selects.each(function(select, i) {
        	select.removeClass(this.sHiddenClassNameForSelects);
        }, this);
    }
});

window.addEvent('domready', function() {
	
	var iframe = $('modal-katalog'),
		dontShow = Cookie.read('dontShowMeModal'),
		katalog_link = $('baner_katalog');
	
	if (!iframe) {
		return;
	}
	
	function showModal() {
		
		var modal, close, 
			iframeCopy = iframe.clone();
		
		modal = new ModalWindow({
			oContent: iframeCopy,
			sHiddenClassNameForSelects: 'hidden',
			bBackground: 1
		});
		
		close = new Element('div', {
			'class': 'modal-close',
			'text': 'X',
			'events': {
				'click': function(e) {
					modal.close();
				}
			}
		}).inject(modal.window, 'top');
		
		modal.init();
	}
	
	if (katalog_link) {
		katalog_link.addEvent('click', function(e) {
			e.stop();
			showModal();
		});
	}
	
	if (!dontShow) {
		showModal();
		Cookie.write('dontShowMeModal', '1', {duration: 7});
	}
	
});	

window.addEvent('domready', function() {
	
	var iframe = $('modal-katalog2'),
		dontShow = Cookie.read('dontShowMeModal'),
		katalog_link = $('baner_katalog2');
	
	if (!iframe) {
		return;
	}
	
	function showModal() {
		
		var modal, close, 
			iframeCopy = iframe.clone();
		
		modal = new ModalWindow2({
			oContent: iframeCopy,
			sHiddenClassNameForSelects: 'hidden',
			bBackground: 1
		});
		
		close = new Element('div', {
			'class': 'modal-close2',
			'text': 'X',
			'events': {
				'click': function(e) {
					modal.close();
				}
			}
		}).inject(modal.window, 'top');
		
		modal.init();
	}
	
	if (katalog_link) {
		katalog_link.addEvent('click', function(e) {
			e.stop();
			showModal();
		});
	}
	
});
