$( document ).ready(
    function(){
        $.ajax({
            type: "GET",
            url: "ajax.php",
            data: "action=search_states",
            success: function( msg ){
                $( "#wojewodztwo" ).html( msg );
            }
        });

        $( "#login, #pass" ).click( function(){
            this.value = "";
        });

        $( "#sort-search-btn" ).click( function(){
            window.location = $( "#href" ).val() + "," + $( "#sortType" ).val() + "," + $( "#sortMethod" ).val() + "," + $( "#page" ).val();
        });

        $( "input#localizator" ).click( function(){
            
            if( $( "input#localizator" ).attr( "checked" )){
                $( "div#mapContainer" ).fadeIn( "slow" );
                initializaLocalizator();

            } else
                $( "div#mapContainer" ).fadeOut( "slow" );
        });

        $( "#locationSend" ).click( function(){
            var latLng = document.marker;
            var notice_id = $( "#notice_id" ).val();
        
            if( $( "input#localizator" ).attr( "checked" )){
                var lat = document.createElement( "input" );
                var lng = document.createElement( "input" );
                var form = $( "form" )[ 0 ];
                
                    lat.type = "hidden";
                    lat.name = "lat";
                    lat.value = latLng.lat();
                    
                    lng.type = "hidden";
                    lng.name = "lng";
                    lng.value = latLng.lng();
                    
                    form.appendChild( lat );
                    form.appendChild( lng );
            }
        });

        $( "input.autofill" ).keyup( function(){
            var cena = $( "input#cena" ).val();
            var powierzchnia = $( "input#powierzchnia" ).val();
        
            if( cena != "" && powierzchnia != "" ){
                cena = parseFloat( cena );
                powierzchnia = parseFloat( powierzchnia );
                $( "input#cena_za_m2" ).val( parseFloat( cena / powierzchnia ).toFixed( 2 ));
            }
        });

        $( "select.deposit_type" ).change( function(){
            var disp = $( this ).val() == "kwota" ? "block" : "none";
            
            $( "#depozyt_kwota" ).css({
                display : disp
            });
        });

        $( "select.deposit_type_search" ).change( function(){
            var disp = $( this ).val() == "kwota" ? "block" : "none";
            
            $( "#depozyt_kwota" ).css({
                display : disp
            });
        });

        $( "#ask-for-offer-btn" ).click( function(){
            var error = false;
        
            $( this ).attr( "disabled", "disabled" );
            $( ".ch-val" ).each( function(){
                
                if( $( this ).val() == "" )
                    error = true;
                });
        
                if( error ){
                    $( this ).removeAttr( "disabled" );
                    alert( "Proszę wypełnić wszystkie pola" );
                
                } else {
                    $.ajax({
                        type: "GET",
                        url: "ajax.php",
                        data: "action=ask_for_offer&" + $( "#ask-for-offer form" ).serialize(),
                        success : function( msg ){
                        
                            if( msg == "codeError" ){
                                $( this ).removeAttr( "disabled" );
                                $( "#mailerResponse" ).html( "<span style=\"color:#ff0000\">Przepisz poprawnie kod bezpieczeństwa</span>" );
                            }
                        
                            if( msg == "notSend" ){
                                $( this ).removeAttr( "disabled" );
                                $( "#mailerResponse" ).html( "<span style=\"color:#ff0000\">Error 500: Wewnętrzny błąd serwera, wiadomośc nie wysłana</span>" );
                            }
                        
                            if( msg == "mailSend" ){
                                $( "#ask-for-offer form" ).html( "<span style=\"color:#ff0000\">Wiadomość została wysłana</span>" );
                            }
                        }
                    });
                }
            
            return false;
        });

        $( "#newsletter-form .btn" ).click( function(){
            var email = document.getElementById( "n-email" ).value, filter = /^([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+$/i;
        
            if( filter.test( email )){
                $.ajax({
                    type: "GET",
                    url: "ajax.php",
                    data: "action=newsletter&" + $( "#newsletter-form" ).serialize(),
                    success: function( msg ){
                    
                        switch( msg ){
                            case "1":
                                alert( "Twój e-mail jest już w naszej bazie. Proszę podać inny adres" );
                                break;
                            
                            case "2":
                                alert( "Wystąpił błąd. Proszę spróbować ponownie" );
                                break;
                            
                            default:
                                $( "#newsletter-form div" ).html( msg );
                        }
                    }
                });
            
            } else
                alert( "Proszę wpisać poprawny adres e-mail" );
        
            return false;
        });

        $( "input[name=cena[cena_od]]" ).before( "<em>Od</em>" ).width( "37%" );
        $( "input[name=cena[cena_do]]" ).before( "<br/><em>Do</em>" ).width( "37%" );

        $( "input[name=powierzchnia_calkowita[powierzchnia_od]], input[name=powierzchnia[powierzchnia_od]]" ).before( "<em>Od</em>" ).width( "62%" );
        $( "input[name=powierzchnia_calkowita[powierzchnia_do]], input[name=powierzchnia[powierzchnia_do]]" ).before( "<br/><em>Do</em>" ).after( " m<sup>2</sup>" ).width( "62%" );

        $( "input[name=powierzchnia_dzialki], input[name=powierzchnia_calkowita], input[name=powierzchnia_uzytkowa]" ).after( " m<sup>2</sup>" ).width( "82%" );
        $( "input[name=dlugosc], input[name=szerokosc]" ).after( " m" ).width( "85%" );

        $( "div.nMenu a" ).click( function(){
            $( ".info" ).hide();
            $( "#info_" + $( this ).attr( "id" )).show();
            $( "div.nMenu a" ).removeClass( "selected" );
            $( this ).addClass( "selected" );
        });

        $( "#nMediaMenu a.switchButton:not(.disabled)" ).click( function(){
            $( "#nMediaMenu a" ).removeClass( "selected" );
            $( this ).addClass( "selected" );
            $( ".info-box" ).hide();
            $( "#box-" + $( this ).attr( "id" )).show();
        });

        $( "#mycarousel" ).jcarousel({
            visible: 5,
            buttonNextEvent: "mouseover",
            buttonPrevEvent: "mouseover",
            animation: 600
        });

        $( "#mycarousel img" ).click( function(){
            var n = $( this ).attr( "alt" ) - 1;
            var oldImg = $( "#nPhoto img.showed" );
        
            if( $( oldImg ).attr( "alt" ) != n ){
                var zIndex = Number( $( "#nPhoto img.showed" ).css( "zIndex" )) + 1;
                var newImg = $( "#nPhoto li:eq(" + n + ") img" );
                
                $( newImg ).css( "zIndex", zIndex ).fadeIn( 1000 ).addClass( "showed" );
                $( oldImg ).removeClass( "showed" ).fadeOut( 1000 );
            }
        });

        $( ".do-ulubionych a" ).click( function(){
            title = document.title;
            url = document.URL;

            if( window.sidebar ){
                window.sidebar.addPanel( title, url, null );

            } else if( window.external ){
                window.external.AddFavorite( url, title );

            } else {
                alert( "Twoja przegłądarka nie obsługuje tej możliwości" );
                return false;
            }
        });

        $( ".drukuj-ogloszenie a" ).click( function(){
            window.open( "http://" + document.domain + "/drukuj/" + this.id );
            return false;
        });

        $( ".wyslij-znajomemu a" ).click( function(){
            popup( "http://" + document.domain + "/wyslij_znajomemu/" + this.id, 600, 240 );
            return false;
        });

        $( "#miejscowosc" ).keyup( function( event ){
            var k = event.keyCode;
        
            if(( k > 64 && k < 91 ) || ( k > 96 && k < 123 ) || k == 8 ){
                $( "div.tip" ).remove();
            
                var string = $( "#miejscowosc" ).val();
                var reg = /^[a-ząćęłńóśżź ]+$/i;
            
                if( reg.test( string )){
                    $.ajax({
                        type: "GET",
                        url: "ajax.php",
                        data: "action=search_city&s=" + escape( string ),
                        success: function( msg ){
                        
                            if( msg != "0"){
                                $( "div.tip" ).remove();
                            
                                var oDiv = document.createElement( "div" );
                                
                                    oDiv.className = "tip";
                                    $( oDiv ).append( msg );
                                    $( oDiv ).insertAfter( "#miejscowosc" );
                                    $( ".tipEl" ).bind( "click", function(){
                                        
                                        var i = $( this ).attr( "name" );
                                    
                                        $( "#miejscowosc" ).val( $( "#miasto_" + i ).html());
                                        
                                        var wojewodztwo = $( "#wojewodztwo" )[ 0 ];
                                    
                                        if( wojewodztwo.tagName == "SELECT" ){
                                            for( var l = 0; l < wojewodztwo.options.length; l++ ){
                                                if( wojewodztwo.options[ l ].value == $( "#wojewodztwo_" + i ).html()){
                                                    wojewodztwo.selectedIndex = l;
                                                    break;
                                                }
                                            }
                                        
                                        } else
                                            $( "#wojewodztwo" ).val(
                                            $( "#wojewodztwo_" + i ).html());
                                    
                                        $( "#powiat" ).val(
                                        $( "#powiat_" + i ).html());
                                        $( "#gmina" ).val(
                                        $( "#gmina_" + i ).html());
                                    });
                                
                                $( ".tipEl" ).bind( "mouseenter mouseleave", function( e ){
                                    $( this ).toggleClass( "tipElSelected" );
                                });
                            }
                        }
                    });
                }
            }
        });

        $( "#gmina" ).keyup( function( event ){
            var k = event.keyCode;
        
            if(( k > 64 && k < 91 ) || ( k > 96 && k < 123 ) || k == 8 ){
                $( "div.tipG" ).remove();
            
                var string = $( "#gmina" ).val();
                var reg = /^[a-ząćęłńóśżź ]+$/i;
            
                if( reg.test( string )){
                    $.ajax({
                        type: "GET",
                        url: "ajax.php",
                        data: "action=search_commune&s=" + escape( string ),
                        success: function( msg ){
                        
                            if( msg != "0" ){
                                $( "div.tipG" ).remove();
                            
                                var oDiv = document.createElement( "div" );
                                
                                    oDiv.className = "tipG";
                                    $( oDiv ).append( msg );
                                    $( oDiv ).insertAfter( "#gmina" );
                                    $( ".tipElG" ).bind( "click", function(){
                                        
                                        var i = $( this ).attr( "name" );
                                        var wojewodztwo = $( "#wojewodztwo" )[ 0 ];
                                    
                                        if( wojewodztwo.tagName == "SELECT" ){
                                            for( var l = 0; l < wojewodztwo.options.length; l++ ){
                                                if( wojewodztwo.options[ l ].value == $( "#wojewodztwo_" + i ).html()){
                                                    wojewodztwo.selectedIndex = l;
                                                    break;
                                                }
                                            }

                                        } else
                                            $( "#wojewodztwo" ).val(
                                            $( "#wojewodztwo_" + i ).html());
                                    
                                        $( "#powiat" ).val(
                                        $( "#powiat_" + i ).html());
                                        $( "#gmina" ).val(
                                        $( "#gmina_" + i ).html());
                                    });
                                
                                $( ".tipElG" ).bind( "mouseenter mouseleave", function( e ){
                                    $( this ).toggleClass( "tipElSelectedG" );
                                });
                            }
                        }
                    });
                }
            }
        });

        $( "#powiat" ).keyup( function( event ){
            var k = event.keyCode;
        
            if(( k > 64 && k < 91 ) || ( k > 96 && k < 123 ) || k == 8 ){
                $( "div.tipP" ).remove();
            
                var string = $( "#powiat" ).val();
                var reg = /^[a-ząćęłńóśżź ]+$/i;
            
                if( reg.test( string )){
                    $.ajax({
                        type: "GET",
                        url: "ajax.php",
                        data: "action=search_county&s=" + escape( string ),
                        success: function( msg ){
                        
                            if( msg != "0" ){
                                $( "div.tipP" ).remove();

                                var oDiv = document.createElement( "div" );
                                
                                    oDiv.className = "tipP";
                                    $( oDiv ).append( msg );
                                    $( oDiv ).insertAfter( "#powiat" );
                                    $( ".tipElP" ).bind( "click", function(){
                                        
                                        var i = $( this ).attr( "name" );
                                        var wojewodztwo = $( "#wojewodztwo" )[ 0 ];
                                    
                                        if( wojewodztwo.tagName == "SELECT" ){
                                            for( var l = 0; l < wojewodztwo.options.length; l++ ){
                                                if( wojewodztwo.options[ l ].value == $( "#wojewodztwo_" + i ).html()){
                                                    wojewodztwo.selectedIndex = l;
                                                    break;
                                                }
                                            }
                                        
                                        } else
                                            $( "#wojewodztwo" ).val(
                                            $( "#wojewodztwo_" + i ).html());
                                    
                                        $( "#powiat" ).val(
                                        $( "#powiat_" + i ).html());
                                        $( "#gmina" ).val( "" );
                                    });
                                
                                $( ".tipElP" ).bind( "mouseenter mouseleave", function( e ){
                                    $( this ).toggleClass( "tipElSelectedP" );
                                });
                            }
                        }
                    });
                }
            }
        });

        $( "*" ).click( function(){
            $( "div.tip" ).remove();
            $( "div.tipW" ).remove();
            $( "div.tipP" ).remove();
            $( "div.tipG" ).remove();
        });

        $( function(){
            $( "#notice_movie" ).makeAsyncUploader({
                upload_url: "upload_movie.php",
                flash_url: "swfupload.swf",
                button_image_url : "gfx/blankButton.png",
                file_types : "*.flv",
                file_types_description : "Pliki .flv",
                file_size_limit : 26214400,
                file_upload_limit : 26214400,
                button_text : "",
                width : "81px",
                height : "26px"
            });
        });

        if( $( "#miejscowosc" ).val() == "dowolnaMiejscowosc" )
            $( "#miejscowosc" ).parents( "div.fE" ).hide();

        $( "#dowolna_miejscowosc" ).click( function(){
            if( this.checked ){
                var selected = $( "#wojewodztwo :selected" ).text();
            
                $( "#miejscowosc" ).parents( "form" )[ 0 ].reset();
                $( "#miejscowosc" ).val( "dowolna miejscowość" );
                $( "#wojewodztwo option[value='" + selected + "']" ).attr( "selected", "selected" );
                
                this.checked = true;
                
                $( "#miejscowosc" ).parents( "div.fE" ).hide();

            } else {
                $( "#miejscowosc" ).parents( "div.fE" ).show();
                $( "#miejscowosc" ).val( "" );
            }
        });

        $( "#availability_date" ).focus( function(){
            if( this.value == "RRRR-MM" ){
                this.value = "";
            }
        });

        $( "input" ).keyup( function( event ){
            if( this.value.length > 30 ){
                this.value = this.value.slice( 0, 30 );
            }
        });

        $( "textarea" ).keyup( function( event ){
            if( this.value.length > 500 ){
                this.value = this.value.slice( 0, 500 );
            }
        });

        if( $.browser.msie && $.browser.version < 8 ){
            var BASE64_DATA = /^data:.*;base64/i;

            function fixBase64( img ){
                if( BASE64_DATA.test( img.src ))
                    img.src = "captcha/ie_base64.php?" + img.src.slice( 5 );
            }

            for( var i = 0; i < document.images.length; i++ )
                fixBase64( document.images[ i ] );
        }
    });

    function updCat( type ){
        
        document.location = "szukaj," + type + "Advanced";
    }

    function popup( href, width, height ){
        var windowHeight = window.innerHeight || document.body.offsetHeight;
        var windowWidth = window.innerWidth || document.body.offsetWidth;
        var top = ( windowHeight >> 1 ) - ( height >> 1 );
        var left = ( windowWidth >> 1 ) - ( width >> 1 );
        
        window.open( href, "window", "width=" + width + ", height=" + height + ", top=" + top + ", left=" + left + ", menubar=no, status=no, locationbar=no, scrollbars=no, resizeable=no" );
    }

    function initializeMap( lat, lang ){

        if( GBrowserIsCompatible()){
            var mapa = new GMap2( document.getElementById( "map_canvas" ), {
                size: new GSize( 425, 350 ),
                mapTypes: [ G_HYBRID_MAP, G_NORMAL_MAP ]
            });
            
            var punkt = new GLatLng( lat, lang );
            var marker = new GMarker( punkt, {
                title: "tutaj"
            });
            
            mapa.setCenter( punkt, 12 );
            mapa.addControl( new GLargeMapControl());
            mapa.addControl( new GMapTypeControl());
            mapa.addOverlay( marker );
        }
    }

    function initializaLocalizator(){

        if( $( "#miejscowosc" ).val() == "" ){
            alert( "Nie wybrałeś miasta!" );
            return;
        }

        if( GBrowserIsCompatible()){
            var mapa = new GMap2( document.getElementById( "map_canvas" ), {
                size: new GSize( 572, 400 ),
                mapTypes: [ G_HYBRID_MAP, G_NORMAL_MAP ]
            });
            
            var code = new GClientGeocoder();
            var dane = $( "#miejscowosc" ).val() + " " + $( "#wojewodztwo" ).val() + " " + $( "#powiat" ).val() + " " + $( "#gmina" ).val();

            mapa.setCenter( new GLatLng( 52.23185395123989, 21.02083683013916 ), 12 );
            code.getLatLng( dane, function( punkt ){
                
                if( punkt ){
                    var marker = new GMarker( punkt, {
                        title : "tutaj"
                    });
                    
                    mapa.setCenter( punkt );
                    mapa.addControl( new GLargeMapControl());
                    mapa.addControl( new GMapTypeControl());
                    mapa.addOverlay( marker );
                    document.marker = punkt;

                } else
                    alert( dane.toUpperCase() + ", miejscowość nie znaleziona" );
            });
        }
    }

    function setavailabilitydate( selectElement ){
        var option = selectElement.options[ selectElement.selectedIndex ].value;
        
        if( option == "0" ){
            $( "#availability_date_container" ).hide();
            $( "#availability_fake_date_container" ).hide();
            $( "#availability_date" ).val( "" );
        }
        
        if( option == "do uzgodnienia" ){
            $( "#availability_date_container" ).hide();
            $( "#availability_fake_date_container" ).hide();
            $( "#availability_date" ).val( "" );
        }
        
        if( option == "natychmiast" ){
            $( "#availability_date_container" ).hide();
            $( "#availability_fake_date_container" ).show();
            $( "#availability_date" ).val(
            $( "#availability_fake_date_container .fEElement" ).html());
        }
        
        if( option == "data" ){
            $( "#availability_fake_date_container" ).hide();
            $( "#availability_date_container" ).show();
            $( "#availability_date" ).val( "RRRR-MM" );
        }
    }

    function searchByCity( district, city, state, estateCategory ){
        
        $( "#noticeListDistrict" )[ 0 ].value = district;
        $( "#noticeListEstateCategory" )[ 0 ].value = estateCategory;
        $( "#noticeListCity" )[ 0 ].value = city;
        $( "#noticeListState" )[ 0 ].value = state;
        $( "#noticeListForm" )[ 0 ].submit();
    }
