var SiteConfig = {};

function echo(sMessage) {
    var a = getUrlVars();    
    if (a['dev'] || Cookie.read('dev')) alert(sMessage);
}

function openUrl(new_url) {window.location=new_url;}

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() {}
    };
}

var _Browser = {
	ie: Browser.Engine.trident,
	ie6: Browser.Engine.trident4,
	ie7: Browser.Engine.trident5
};

/* zwraca obiekt zawierajacy zmienne z url'a */
function getUrlVars() {
    var vars = {}, hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        if (vars[hash[0]]) continue;
        vars[hash[0]] = hash[1];
    }
    var i = 0;
    for (var x in vars) i++;
    vars.length = i;
    return vars;
}

var Scroll = {
    doScroll: function() {
    	var c = Cookie.read('scroll');
        if (c) {
            window.scrollTo(0, c);
            Cookie.dispose('scroll');
        }
    },
    
    add: function(time) {
        var scroll = window.getScroll().y;
        var sec = 0.000694444444 / 60;
        Cookie.write('scroll', scroll, {duration: $pick(time, 60)*sec});
    }
};

/**
 * przeladowanie strony po zmianie selecta. uzywac jako atrybut 'onchange' selectow.
 * dziala z przyjaznymi linkami.
 * @parm prefix [string] przerdrostek dla nazwy pol np. asd_tripCountryName
 */
function selectChange(formID, prefix) {
    var formObj, form, url, pos, tmp, name, vars = '';
    formObj = $(formID);
    if (!formObj) {throw new Error('nie ma formularza o id = '+formID); return false;}
    form = new Form(formObj);
    form.getAllElements();	
    
    url = window.location.href;
    pos = url.indexOf('?');
    if (pos != -1) url = url.slice(0, pos);
        
    for (var i=0; i<form.aElements.length; i++) {
        if (form.aElements[i].name != 'pidName') {
            if (prefix) name = form.aElements[i].name.match(new RegExp(""+prefix+"(.+)"),"")[1];
            else name = form.aElements[i].name;
            if (!name) {throw new Error('kazde pole formularza musi miec w nazwie prefix = '+prefix); return false;}
            vars += ((!tmp) ? '' : '&') + name + '=' + form.aElements[i].value;
            tmp = 1;
        }        	
    }
    document.location.href = url + '?' + vars;
}

var AjaxObj = new Class({
    initialize: function(url, numjobs) {
    	this.url = url;
        this.numjobs = numjobs;
        this.queue = [];
        this.jobs = new Hash(); // przechowuje aktualnie wykonywane zadania
        this.jobID = 0;
    },
    
    /**
     * @parm obj.mode (required) {string} - nazwa modulu
     * @parm obj.data (required) {object} - obiekt do wyslania np. {jakasZmienna: 'wartosc'}
     * @parm obj.priority {int} - priorytet w kolejce
     * @parm obj.instance {int} - 1: instancja, 0: core
     * @parm obj.ttl {int} - time to live - po tym czasie zadanie jest anulowane
     * @parm obj.onSuccess {fn} - dwa parametry: obiekt response, xml response
     * @parm obj.onCancel {fn} - uruchamia sie po ttl
     * @return id zadania
     */
    add: function(obj) {
    	obj.id = ++this.jobID;
        if (!obj.priority) obj.priority = 1;
        if (!obj.instance) obj.instance = 0;
        
        if (!obj.mode) {return false;}
        if (!this._insertToQueue(obj)) {return false;}
        
        this._send();
        return this.jobID;
    },
    
    /**
     * dla kompatybilnosci
     */
    addToQueue: function(mode, priority, data, parm, onSuccess, instance, onCancel) {
    	return this.add({
            mode: mode,
            priority: priority,
            data: data,
            onSuccess: onSuccess,
            parm: parm,
            instance: instance,
            onCancel: onCancel
        });
    },

    _send: function() {
        if (this.queue.length == 0) return false; // nie ma co wysylac
        if (this.jobs.getLength() >= this.numjobs) return false; // nie ma wolnych slotow 
        
        var job = this.queue.shift();
        this.jobs.include(job.id, job); // zajmuje wolny slot
        
        var postData = ['thread_id=' + job.id, 'thread_mode=' + job.mode, 'thread_page_instance=' + job.instance];
        for (var x in job.data) {
            var type = $type(job.data[x]);
        	if (type == 'array' || type == 'object') {
                postData.push(x + '=' + JSON.encode(job.data[x]));
            } else {
                postData.push(x + '=' + job.data[x]);
            }
        }
        
    	job.req = new Request({
            url: this.url, 
            onRequest: function() {if (job.onRequest) job.onRequest(); return false;},
            onComplete: function() {if (job.onComplete) job.onComplete(); return false;},
            onSuccess: function(text, xml) {
                var errorMsg = null, resObj;
                try {
                    resObj = JSON.decode(text);
                } catch (e) {}
                
                if (!resObj) errorMsg = 'Ajax: response jest null lub JSON.decode zwraca blad';
                
                if (!job.parm) {
                    if (job.onSuccess) job.onSuccess(resObj, errorMsg); 
                } else { // dla starej metody addToQueue
                    if (job.onSuccess) job.onSuccess(job.parm, resObj, errorMsg); 
                }
                
                this.jobs.erase(job.id);
                this._send();
                return false;
            }.bind(this),
            onCancel: function() {
                if (job.onCancel) job.onCancel(); 
                this.jobs.erase(job.id);
                this._send();
                return false;
            }.bind(this),
            onFailure: function(xhr) {if (job.onFailure) job.onFailure(xhr); return false;}
        });
        
        job.req.send(postData.join('&'));
        
        if (job.ttl) { // (int) time to live
        	job.timeout = setTimeout(function() {
        		if (job.req.running) job.req.cancel();
        	}, job.ttl.toInt());
        }
    },
    
    _insertToQueue: function(obj) {
        for (var i=0; i< this.queue.length; i++) {
            if (this.queue[i+1] && this.queue[i].priority < obj.priority) {
                this.queue.splice(i, 0, obj);
                return true;                
            }
        }
        this.queue.push(obj);
        return true;
    }
});


/**
 * Klasa do nawigacji 'zakladkowej' -  nawigacja opiera sie na hash'ach w linkach, ktore musza byc rowne ID elemenu na ktory wskazuja.
 * 14:03 2008-11-03 by pio
 * @parm oConfig - obiekt
 */
var TabNavigation = new Class({
    initialize: function(oConfig) {
        this.sNavId = oConfig.sNavId;
        this.sActiveClassName = oConfig.sActiveClassName || '';
        this.sDisplayNoneClassName = oConfig.sDisplayNoneClassName;
        this.bAddClassToParentElement = oConfig.bAddClassToParentElement || 0; // ustaw na true, jezeli klasa 'sActiveClassName' ma byc nadawana rodzicowi linka (np. elementowi li)    	
        this.aCustomElements = oConfig.aCustomElements;    
        this.prefix = oConfig.prefix || '';
            
        this.aItems = [];
        this.oActive;
    },
    
    init: function() {
        this.getItemsFromAnchors();
    	this.getItemsFromCustomElements();
        if (this.aItems.length == 0) return;
        
        this.addEvent();
        this.getActive();
        this.run();
    },
    
    run: function() {
        this.aItems.each(function(item, i) {
        	if (item == this.oActive) {
                this._show(item.target);
                if (this.sActiveClassName != '')
                    item.elWithClass.addClass(this.sActiveClassName);
                if (this.prefix != '')
                    location.replace('#' + item.prefix + item.target.id);
            } else {
            	this._hide(item.target);
                if (this.sActiveClassName != '')
                	item.elWithClass.removeClass(this.sActiveClassName);
            }
        }, this);
    },
    
    addEvent: function() {
    	var This = this;
        this.aItems.each(function(el, i) {
        	el.el.addEvent('click', function(e) {
        		This.handleEvent(e, el);
        	});
        });
    },
    
    handleEvent: function(e, oItem) {
        e.stop();
        this.oActive = oItem;
        this.run();
    },
   
    getItemsFromAnchors: function() {
        $(this.sNavId).getElements('a').each(function(el, i) {
            var id = el.hash.substring(1);
            var targetEl = $(id);
            
            if (targetEl) {
                this.aItems.push({
                    el: el,
                    target: targetEl,
                    prefix: this.prefix,
                    elWithClass: ((this.bAddClassToParentElement) ? el.getParent() : el)
                });
            }           
        }, this);    
    },
    
    getItemsFromCustomElements: function() {
    	if (!this.aCustomElements || this.aCustomElements.length == 0) return;
        this.aCustomElements.each(function(el, i) {
            this.aItems.push({
                el: $(el.el),
                target: $(el.target),
                prefix: (el.prefix) ? el.prefix : '',
                elWithClass: ((el.elWidthClass) ? el.elWidthClass : $(el.el))
            });
        }, this);
    },
    
    getActive: function() {
        var hash = window.location.hash.substring(1);
        if (hash != '') {
        	for (var i=0; i<this.aItems.length; i++) {
                if (this.aItems[i].prefix + this.aItems[i].target.id == hash) {
                    this.oActive = this.aItems[i];
                    return;
                }
    		}
        }
        
        if (this.sActiveClassName != '') {
    		for (var i=0; i<this.aItems.length; i++) {
                if (this.aItems[i].elWithClass.hasClass(this.sActiveClassName)) {
                    this.oActive = this.aItems[i];
                    break;
                }
    		}
    	} else {
    		this.oActive = this.aItems[0];
    	}
    },
       
    _show: function(el) {
        if (!this.sDisplayNoneClassName)
            el.style.display = "block";
        else
    	    el.removeClass(this.sDisplayNoneClassName);
    },
    
    _hide: function(el) {
        if (!this.sDisplayNoneClassName)
            el.style.display = "none";
        else
    	    el.addClass(this.sDisplayNoneClassName);
    }
});

/**
 * 18:43 2008-11-11 /pio
 */
var CountTrips = new Class({
    Implements: Options,
    options: {
        iGlobalTimeOut: 10,
        loader: ''
    },
    
	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'] = 'countTrips';
        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) {throw new Error('CountTrips.getResponse zwraca wyjatek - '+e);}
    },
    
    getValue: function(o) {
    	var form = new Form(this.oForm);
        return form.getValue(o);
    },
    
    getItems: function() {
        var val;
        this.aFields.each(function(item, i) {
        	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
            });
        }, this);
    }
});


/**
 * last edited: 18:43 2008-11-11 by pio
 */
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.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 (_Browser.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 (_Browser.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 SearchEngine = new Class({
    Implements: Events,
    initialize: function(sFormId, oConfig) {
    	this.oForm = $(sFormId);
        this.oConfig = oConfig || null;
        this.vars = getUrlVars();
    },
    
    /**
    * pobiera wartosc pola formularza. nie interesuje nas jakiego rodzaju jest to pole.
    * @parm o - DOM FORM ELEMENT
    * @return - wartosc pola
    */
    getFieldValue: function(o) {
        var formObject = new Form(this.oForm);
        return formObject.getValue(o);
    },    
    
    /**
    * Tworzy nowe options dla selectow i uruchamia metode do ustawiania
    * @parm oSelect - obiekt selecta zdefiniowany w 'konstruktorze'
    * @parm aNewSelectValues - tablica obiektow postaci: {key: costam, name: costam}
    * @parm oCustom - obiekt wartosci domyslnych dla selecta np. {blank: {name: 'domyslny', value: 0}}
    */
    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;
            oSelect.options.add(opt);
    	}    
        
        if (oCustom.noSet) return;
        this.set(oSelect, oCustom);
    },
    
    /**
     * Ustawia danego selecta, biorac pod uwage parametry w urlu i obiekt konfiguracyjny
     * @parm oSelect - obiekt selecta
     * @parm oCustom - obiekt wartosci domyslnych dla selecta np. {customValue: 0}
     */
    set: function(oField, oCustom) {
        var valueFromUrl = decodeURIComponent(this.vars[oField.name]);
        var valueToSet = (valueFromUrl != 'undefined') 
            ? valueFromUrl 
            : ((oCustom.customValue) 
                ? oCustom.customValue 
                : oCustom.blank.value);
        
        if (valueToSet) {
            var f = new Form(this.oForm);
            f.setValue(oField, valueToSet);
        }
        this.fireEvent('onSetEnd', [oField.name, valueToSet]);
    }
});


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ę.');
    },
    
    maxSize: function(item, num) { 
        if (item.value.length > num && item.value != '')
            this.setError(item, item.retrieve('clientName')+' moze mieć maksimum '+num+' znaków.');
    },
    
    size: function(item, num) {
        if (item.value.length != num && item.value != '')
            this.setError(item, item.retrieve('clientName')+' musi mieć '+num+' znaków.');
    },

    dateFormat: function(item, sep) {
        if (sep == ".")
            var reg_date = /[0-3][0-9].(0|1)[0-9].(19|20)[0-9]{2}/;
        else if (sep == "-")
            var reg_date = /[0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2}/;

        if (item.value.match(reg_date) && item.value != '') {
            var date_array = item.value.split(sep);
            var day = date_array[0];
            var month = date_array[1] - 1; 
            var year = date_array[2];
            
            source_date = new Date(year,month,day);

            if (year != source_date.getFullYear())
                this.setError(item, item.retrieve('clientName')+' ma niepoprawny rok (prawidłowy format daty: dd'+ sep +'mm'+ sep +'yyyy).');        

            if (month != source_date.getMonth())
                this.setError(item, item.retrieve('clientName')+' ma niepoprawny miesiąc (prawidłowy format daty: dd'+ sep +'mm'+ sep +'yyyy).');        

            if (day != source_date.getDate())
                this.setError(item, item.retrieve('clientName')+' ma niepoprawny dzień (prawidłowy format daty: dd'+ sep +'mm'+ sep +'yyyy).');        
        } else {
            this.setError(item, item.retrieve('clientName')+' ma niepoprawny format (prawidłowy format daty: dd'+ sep +'mm'+ sep +'yyyy).');
        }
    },
    
    //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);
    }
});


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) {
			
			var pole = this.oForm[pole];
			
			if (pole) {
				pole.addEvent('change', function(){
					var update = new Element('input', {'type': 'hidden', 'name': 'update', 'value': 1}).inject(this.oForm);
					this.oForm.submit();
				}.bind(this));
			}
			
        }, this);
    },
    
    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]);
        }
    },

    _getNumRooms: function(s) {
        var i = 0;
        while (this.oForm['room['+i+']['+s+']'] != null) {
            i++;
        }
        return i;
    }
});


/**
 * Klasa do koszyka / schowka  - wykorzystujaca ajaxa
 * le: 11:08 2008-11-13 by pio    
 */
var Basket = new Class({
    Implements: Options,
    
    options: {
        sCheckboxId: 'basket_',
        sCheckboxClassName: 'addToBasket',
        sRemoveLinkClassName: 'removeFromBasket',
        msg: {
            time: 1000,
            css: {border: '1px solid #ccc', background: '#fff', padding: '1em', position: 'absolute', zIndex: 9999},
            text: {add: 'dodano do schowka', remove: 'usunieto ze schowka'},
            iPlusPositionX: 25,
            iPlusPositionY: -12
        }
    },
    
    initialize: function(options) {
        this.setOptions(options);
        this.aChecks = [];
        this.aReoveLinks = [];
    },

    init: function() {
        var This = this, code;
        var check = $$('input.'+this.options.sCheckboxClassName);
        check.each(function(check, i) {
    		if (this._getOfferCodeFromId(check.id) != false) {
                check.disabled = false;
                check.addEvent('click', function(e) {
                    This._handleEvent(e, this, This._getOfferCodeFromId(check.id), 0);
                });
    		}
    	}, this);
      
        var link = $$('a.'+this.options.sRemoveLinkClassName);
        link.each(function(link, i) {
            if (this._getOfferCodeFromHref(link.href) != false) {
                link.addEvent('click', function(e) {
                    This._handleEvent(e, this, This._getOfferCodeFromHref(link.href), 1);
                });
    		}
    	}, this);
    },
    
    _handleEvent: function(e, el, val, isLink) {
        var sOperation, o = {This: this, isLink: isLink, el: el};
        if (!isLink) {
        	if (el.checked) {
        		sOperation = 'add';
                o.sText = this.options.msg.text.add;
        	} else {
        		sOperation = 'delete';
                o.sText = this.options.msg.text.remove;
            }
    	} else {
            e.stop();
            sOperation = 'delete';
    	}
        
        Ajax.addToQueue('turystyka_koszyk', 1, {offer: val, oper: sOperation}, o, o.This._getResponse);
    },
    
    _getResponse: function(o, oRes, sRes) {
        if (oRes['state'] != 0) {
            if (o.isLink != 1) { // checkbox
                o.This.showStatus(o.el, o.sText);
            } else { // link
            	if (oRes['state'] == 'del') o.This._removeRow(o.el);
            }
    	}
    },
 
    showStatus: function(el, sText) {
    	var p = el.getPosition();
        var s = el.getSize();
        var m = new ModalWindow({
            sContent: sText,
            oWindowCss: this.options.msg.css,
            sWindowClassName: 'basket-modal-window',
            position: {absolute: {x: p.x+this.options.msg.iPlusPositionX, y: p.y+this.options.msg.iPlusPositionY}}
        }); m.flash(this.options.msg.time);
    },
 
    _removeRow: function(o) {
        o = o.getParent('tr');
        if (o.getParent().getChildren('tr').length > 1) {
            (new Fx.Tween(o)).start('opacity', 0).chain(function() {o.dispose();});
        } else {
            o = o.getParent('table');
            var h = new Element('h2', {
                'class': 'error',
                'text': 'Showek jest pusty'
            });
            
            (new Fx.Tween(o)).start('opacity', 0).chain(function() {
                h.inject(o, 'before');
                o.dispose();
            });
        }
    },
    
    _getOfferCodeFromId: function(s) {
        var res = s.match(new RegExp("" + this.options.sCheckboxId + "(.+)", "i"));
        if (!res) return false;
        return res[1];
    },
    
    _getOfferCodeFromHref: function(s) {
        var res = s.match(new RegExp("del=(.+)", "i"));
        if (!res) return false;
        return res[1];    	
    }
});


/**
 * mozna tym zrobic zaawansowana nawigacje po galerii
 * 15:56 2008-12-16 pio
 */
var GalleryStep4 = new Class({
    Implements: [Events, Options],
    options: {
        mainImgId: 'placeholder',
        imgsClass: 'minigal',
        startAt: 0,
        bThumbs: 1,
        iThumbsNum: 3,
        iThumbsActive: 2,
        iThumbRealWidth: 101,
        sThumbActiveCN: 'active',
        sThumbsPrevId: 'gallery-left', 
        sThumbsNextId: 'gallery-right', 
        sThumbsSliderId: 'slider',
        bNav: 1,
        sNavId: 'gallery-top-nav',
        sNavPrevId: 'gallery-previous',
        sNavNextId: 'gallery-next',
        bStatus: 1,
        sStatusId: 'gallery-status',
        sStatusCurrentId: 'gallery-current-no', 
        sStatusTotalId: 'gallery-total-no', 
        sInvisCN: 'invisible'        
    },
    
    initialize: function(id, options) {
        this.setOptions(options);
        this.gallery = $(id);
        this.images = document.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},
            // 'src': this.mainImg.src
        // }).inject(this.mainImg, 'after');
        
        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.fireEvent('onImgChange');
        this.mainImg.setProperty('src', this.images[i].src);
        // this.subImg.setStyle('opacity', 1);
        // var fx = new Fx.Tween(this.subImg, {duration: 400}).start('opacity',1 , 0).chain(function() {
        	// this.subImg.setProperty('src', this.images[i].src);
        // }.bind(this));
    },
    
    handleStatus: function() {
        this.statusCurrent = $(this.options.sStatusCurrentId);
        this.statusTotal = $(this.options.sStatusTotalId);
        this.statusTotal.set('text', this.iTotal);
        this.addEvents({
            'onStart': function() {
                $(this.options.sStatusId).removeClass(this.options.sInvisCN);
            }.bind(this),
            'onImgChange': function() {
            	this.statusCurrent.set('text', this.iCurrent+1);
            }.bind(this)
        });
    },
    
    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({
            'onStart': function() {
                $(this.options.sNavId).removeClass(this.options.sInvisCN);
            }.bind(this),
            '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)
        });
    },
    
    handleThumbnails: function() {
        this.thumbs = this.images;
        this.slider = $(this.options.sThumbsSliderId);
        this.slider.setStyle('left', 0+'px');
    	this.thumbPrev = $(this.options.sThumbsPrevId);
    	this.thumbNext = $(this.options.sThumbsNextId);
        this.thumbFx = new Fx.Tween(this.slider);
              
        this.thumbNext.addEvent('click', function(e) {
        	e.stop();
            var pos = this.slider.getStyle('left').toInt();
            var ile = this.options.iThumbsNum;
            
            while (this.thumbRight + ile > this.iTotal-1) ile--;
            this.thumbRight = this.thumbRight + ile;
            this.thumbLeft = this.thumbRight - (this.options.iThumbsNum-1);
            
            this.thumbFx.start('left', pos+'px', -this.thumbLeft*this.options.iThumbRealWidth+'px');
            
            this._handleThumbArrows();
        }.bind(this));
        
        this.thumbPrev.addEvent('click', function(e) {
        	e.stop();
            var pos = this.slider.getStyle('left').toInt();
            var ile = this.options.iThumbsNum;
            
            while (this.thumbLeft - ile < 0) ile--;
            this.thumbLeft = this.thumbLeft - ile;
            this.thumbRight = this.thumbLeft + (this.options.iThumbsNum - 1);
            
            this.thumbFx.start('left', pos+'px', -this.thumbLeft*this.options.iThumbRealWidth+'px');
            
            this._handleThumbArrows();
        }.bind(this));
        
        this.slider.addEvent('click', function(e) {
        	var tg = e.target;
            if (tg.tagName.toLowerCase() != 'img') return;
            var nr = this.thumbs.indexOf(tg);
            this.show(nr);
        }.bind(this));
        
        
        this.addEvents({
            'onStart': function() {
            	this.thumbs[this.iCurrent].addClass(this.options.sThumbActiveCN);
            }.bind(this),
            'onImgChange': function() {
                if (this.iCurrent != this.iThumbCurrent) {
                	this.thumbs[this.iCurrent].addClass(this.options.sThumbActiveCN);
                	this.thumbs[this.iThumbCurrent].removeClass(this.options.sThumbActiveCN);
                }
                this._checkThumbsNav();
                this._moveByImgChange();
                this.iThumbCurrent = this.iCurrent;
            }.bind(this)
        });
    },
    
    _handleThumbArrows: function() {
    	if (this.thumbRight == this.iTotal-1) this.thumbNext.addClass(this.options.sInvisCN);
        else this.thumbNext.removeClass(this.options.sInvisCN);
        if (this.thumbLeft == 0) this.thumbPrev.addClass(this.options.sInvisCN);
        else this.thumbPrev.removeClass(this.options.sInvisCN);
    },
    
    _moveByImgChange: function() {
        var act = this.slider.getStyle('left').toInt();
        var pre = -this.thumbLeft * this.options.iThumbRealWidth;
        if (pre - act != 0) this.thumbFx.start('left', act+'px', pre+'px');
        this._handleThumbArrows();
    },
    
    _checkThumbsNav: function() {
        var c = this.iCurrent, a , b, p;
        
        if (this.iTotal <= this.options.iThumbsNum) {
        	this.thumbLeft = 0;
            this.thumbRight = this.iTotal - 1;
            return;
        } 
        
        a = this.options.iThumbsActive - 1;
        b = this.options.iThumbsNum - a - 1;
        if (c < a) p = 0;
        else if (c >= this.iTotal - b - 1) p = this.iTotal - this.options.iThumbsNum;
        else p = c - a;
        
        this.thumbLeft = p;
        this.thumbRight = p + this.options.iThumbsNum - 1;
    }
});


/**
 * Ajaxowe zapytanie na step4
 * linki aktywujace musza miec w linku hash'a termin_id np. href="#1231231423"
 * @parm conf.obszarID - id elementu w ktorym znajduja sie linki aktywacyjne
 * @parm conf.linkCN - klasa linków aktywacyjnych 
 * @parm options - zobacz ponizej
 * 11:36 2008-12-29 by pio
 */
var Zapytanie = new Class({
    Implements: Options,
    options: {
        modalConfig: {
            sWindowClassName: 'zapytanie-modal',
            bBackground: 1,
            sHiddenClassNameForSelects: 'hide'
        },
        endMessage: 'Zapytanie zostało wysłane.',
        endTriggerText: 'wysłano',
        endMessageTimeout: 2000,
        submitValue: 'wyślij',
        headerText: 'Wyślij zapytanie',
        closeText: 'zamknij',
        ajaxPriority: 1,
        ajaxLocal: 1 // 1 lub null - zapytanie idzie do instancji lub do core'a
    },
    
    initialize: function(conf, options) {
        this.setOptions(options);
    	this.obszar = $(conf.obszarID);
        this.cn = conf.linkCN;
        
        this.modal = new ModalWindow(this.options.modalConfig);
        
        this.obszar.addEvent('click', function(e) {
        	var t = $(e.target);
            if (!t.hasClass(this.cn)) return;
            e.stop();
            
            t.store('text', t.get('text'));
            t.set('text', 'ładuję...');
            
            var termin_id = t.href.match(/#(.+)$/)[1];
            var o = {This: this, trigger: t, termin_id: termin_id};
            Ajax.addToQueue('turystyka_wycieczki', this.options.ajaxPriority, {
                state: 'zapytanie', 
                action: 'get_form', 
                termin_id: termin_id
            }, o, o.This._getResponse, this.options.ajaxLocal);
        }.bind(this));
    },
    
    _getResponse: function(o, res, sRes) {
    	if (!res) {throw new Error('Zapytanie._getResponse: nie ma zmiennej res'); return;}
        if (res['state'] == 'form') o.This._createForm(res['result'], o.trigger, o.termin_id);
        if (res['state'] == 'sent') o.This._handleSent(o.trigger, res['result']);
        if (res['state'] == 'error') o.This._showError(res['result']);
    },
    
    _handleSent: function(trigger, resultHtml) {
    	this.inner.set('html', this.options.endMessage + resultHtml);
        trigger.set('text', this.options.endTriggerText);
        var t = setTimeout(function() {this.modal.close();}.bind(this), this.options.endMessageTimeout);
    },
    
    _showError: function(s) {
    	this.message.set('text', s);
    },
    
    _createForm: function(obj, trigger, termin_id) {
        trigger.set('text', trigger.retrieve('text'));
        var hash = new Hash(obj);
        var con = '';
        
        var h2 = new Element('h2', {'text': this.options.headerText}).inject(this.modal.window);
        var close = new Element('a', {
            'text': this.options.closeText,
            'class': 'zapytanie-close',
            'events': {
                'click': function(e) {
                	this.modal.close();
                }.bind(this)
            }
        }).inject(this.modal.window);
        
        this.inner = new Element('div', {'class': 'inner'}).inject(this.modal.window);
        con += '<form action="" method="post">';
        hash.each(function(field, i) {
            con += '<div class="form-line">';
            con += '<label for="'+ field.name +'">'+ field.label +'</label>';
            con += '<div>';
            switch (field.type) {
            	case 'text': 
                    con += '<input type="text" class="text" name="'+ field.name +'" id="'+ field.name +'" />';
                    break;
                case 'textarea':
                    con += '<textarea name="'+ field.name +'" id="'+ field.name +'" ></textarea>';
                    break;
            }
            con += '</div></div>';
        }, this);
        con += '<div class="submit"><input type="submit" name="submit" value="'+this.options.submitValue+'" /></div>';
        con += '</form>';
        
        this.inner.set('html', con);
        var submit = this.inner.getElement('input[name="submit"]');
        this.message = new Element('span', {'class': 'zapytanie-message'}).inject(submit, 'after');
        
        submit.addEvent('click', function(e) {
        	e.stop();
            var arr = [];
            var formObj = this.modal.window.getElement('form');
            var form = new Form(formObj);
            form.getAllElements();
            
            for (var i=0; i<form.aElements.length; i++)
            	arr.push({name:form.aElements[i].name, value:form.aElements[i].value});
            
            var o = {This: this, trigger: trigger};
            Ajax.addToQueue('turystyka_wycieczki', this.options.ajaxPriority, {
                state: 'zapytanie', 
                action: 'form_elements', 
                form_elements: arr,
                termin_id: termin_id
            }, o, o.This._getResponse, this.options.ajaxLocal);
            
            this.message.set('text', 'wysyłam...');
            
        }.bind(this));
        this.modal.init();
    }
});

/**
 * Klasa do newslettera
 * le: 10:42 2008-08-29
 * @parm sNewsletterPriceSpliter - string - niewymagany - standardowo 'spacja'
 * dziala przy dominatorze 2.3*
 */
var Newsletter = new Class({
    initialize: function(sNewsletterPriceSpliter) {
    	this.sNewsletterPriceSpliter = sNewsletterPriceSpliter || ' ';
        this.aLinks = [];
    },
    
    init: function() {
        var links = $$('a[newsletter]');
        if (links.length == 0) return;
        
        if (window.opener && window.opener.addNewsletterOffer)  {
            links.each(function(link, i) {
            	link.setStyle('display', 'inline');
                link.addEvent('click', function(e) {
                    e.preventDefault();
                	var s = link.getProperty('newsletter');
                    this._sendToNewsletter(s);
                }.bind(this));
            }, this);
        } else {
            links.each(function(link, i) {
            	link.setStyle('display', 'none');
            }, this);
        }
    },
    
    _sendToNewsletter: function(sValue) {
        var aPricePosition = [5,13];
        for (var i=0; i<aPricePosition.length ; i++) {
            var iPrice = sValue.split('||_')[aPricePosition[i]].toString();
            if (iPrice.match(/^\s*[0-9]+\s*$/)) {
                var sNewPrice = '';
                for (var j=1; j<=iPrice.length; j++) {
                    sNewPrice = iPrice.charAt(iPrice.length-j) + sNewPrice;
                    if (j % 3 == 0 && j < iPrice.length)
                        sNewPrice = this.sNewsletterPriceSpliter + sNewPrice;
                }
                sValue = sValue.replace(iPrice, sNewPrice);
            }
        }

        var bReturn = window.opener.addNewsletterOffer(sValue);
        if ( bReturn == -1) {
            if (confirm('Podobna oferta już została dodana, mimo to kontynuować? ?')) {
                bReturn = window.opener.addNewsletterOffer(sValue, true);
            } else {
                return false;
            }
        } else if (bReturn == 1) {
            alert('Oferta została dodana do biuletynu.');
            return false;        
        } else {
            alert('Wystąpił błąd podczas dodawania oferty.');
            return true;
        }        
    }
});


/**
 * Klasa do szczegolow terminu na step4 / zastepuje funkcje activateDetailView
 * 14:02 2008-11-21  
 */

var DetailView = new Class({
    Implements: Options,
    
    options: {
        sLinkClassName: 'detail',
        sTrId: 'detail_',
        sTrHideClassName: 'hide',
        regex: /(\d+)$/
    },
    
    initialize: function(sObszarId, options) {
    	this.setOptions(options);
        this.or = $(sObszarId);
        if (!this.or) throw new Error('Detail View - nie ma na stronie elementu o id = '+sObszarId);
    },
    
    init: function() {
        this.or.addEvent('click', function(e) {
        	var el = $(e.target);
            if (!el.hasClass(this.options.sLinkClassName)) return;
            
            var tr = $(this.options.sTrId + el.id.match(this.options.regex)[1]);
            if (!tr) return;
            
            if (tr.hasClass(this.options.sTrHideClassName))
                tr.removeClass(this.options.sTrHideClassName);
            else
                tr.addClass(this.options.sTrHideClassName);
        }.bind(this));
    }
});


/**
 * Klasa do tworzenia ladnego urla dla wyszukiwarki; metoda wywolujaca 'initSearch';
 * po kliknieciu szukaj zamienia wartosci pol formularzy na poprawny string url'a
 * le: 12:02 2009-01-29 by pio
 */
var FriendlyURL = new Class({
    initialize: function(formIds) {
 
        var url = (SiteConfig.urlSite) ? SiteConfig.urlSite : "http://" + window.location.hostname + "/";
              
        for (var i=0; i<formIds.length; i++) {
        	var form = $(formIds[i]);
            if (!form) continue;
            
            form.addEvent('submit', function(e) {
            	this._createSearchUrl(e, url, form);
            }.bind(this));
        }
    },
    
    _createSearchUrl: function(e, urlSite, oForm) {
        e.stop();
        var form = new Form(oForm);
        form.getAllElements();
        
        var sVars = '', sBegin, bTmp;
        for (var i=0; i<form.aElements.length; i++) {
        	if (form.aElements[i].name == 'pidName') {
                sBegin = form.aElements[i].value + '.html';
            } else {
            	sVars += ((!bTmp) ? '?' : '&') + form.aElements[i].name + '=' + form.aElements[i].value;
                bTmp = 1;
            }        	
        }
        document.location.href = urlSite + sBegin + sVars;
    }
});


/**
 * 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;
                    
    		}
    	}
    }  
    
});