$(document).observe('dom:loaded', function()
{
    // chowanie i pokazywanie pola na kod pocztowy
    if($('zipCodeFields')){
        if($('fRegion').getValue().substr(0,3)!='rad'){
            $('zipCodeFields').hide();
        }
        $('fRegion').observe('change', function(){
            if(this.getValue().substr(0,3)=='rad' && !$('zipCodeFields').visible()){
                $('zipCodeFields').show();
                $('fZipCode').focus();
            } else if(this.getValue().substr(0,3)!='rad' && $('zipCodeFields').visible()) {
                $('zipCodeFields').hide();
            }
        })
    }
    
    // zmiana action formularza gdy szukamy w calym serwisie
    if($('fInCategory') || $('fInUserOffers')){
        ($('fInCategory') || $('fInUserOffers')).observe('change', function(){
            if(this.getValue()==0 && $('searchForm').action!=link_search){
                Categories.oldAction = $('searchForm').action;
                $('searchForm').action = link_search;
            } else if(this.getValue()==1 && $('searchForm').action.endsWith(link_search)){
                $('searchForm').action = Categories.oldAction;
            }
        })
    }
    
    // validacja formularza szukania
    $('searchForm').observe('submit', function(event){
        if($('fRegion').getValue().substr(0,3)=='rad'){
            if($F('fZipCode').blank()){
                event.stop();
                new jsWindowManager.Window(Categories.noZipCodeTitle, Categories.noZipCodeMessage, {type:'error'});
            } else if(!$F('fZipCode').match(/[0-9]{2}-[0-9]{3}/)){
                event.stop();
                new jsWindowManager.Window(Categories.wrongZipCodeTitle, Categories.wrongZipCodeMessage, {type:'error'});
            }
        }
    })
    
    // ukrywanie zbyt wielu checkboxow z grupy (przy filtrach)
    if($$('span.hiddenFields')){
        var divs = $$('div.hiddenFields');
        divs.each(function(div){
            var id = div.id.substr(0, div.id.indexOf('_'));
            div.hide();
            $(id+'_button').observe('click', function(event){
                event.stop();
                var id = this.id.substr(0, this.id.indexOf('_'));
                if($(id+'_fields').visible()){
                    new Effect.BlindUp($(id+'_fields'), {duration:0.3});
                } else {
                    new Effect.BlindDown($(id+'_fields'), {duration:0.3});
                }
            });
        });
    }
});
