
var IsHashNedded = false ;
var ActualLimitFrom = 0 ;
var ActualUrlState = window.location.href ;
var IdState = 0 ;
var NewUrl = '' ;
var NoMoreProducts = false ;

if( window.location.href.split('#!').length > 1 &&
    window.location.href.split('#!')[0].split('/s/').length > 1 &&
    window.location.href.split('#!')[0].split('/s/')[1].substring(0, 2) == 'q-'
    ){

    RunOnLoad['SearchHintsAjax'] = 'SearchHintsAjax( "wait", 1 )' ; //SearchHintsAjax( '', 1 ) ;
}

function SearchHintsRun( Phrase, ShowProd, FromPrice, ToPrice, Sorting, Promotion, Autor ){

    clearInterval( SearchInterval ) ;

    SearchPhrase = encodeURI( Phrase ) ;

    if( ShowProd == undefined ) ShowProd = 0 ;
    if( FromPrice == undefined ) FromPrice = 0 ;
    if( ToPrice == undefined ) ToPrice = 0 ;
    if( Sorting == undefined ) Sorting = 0 ;
    if( Promotion == undefined ) Promotion = 0 ;
    if( Promotion == true ) Promotion = 1 ;
    if( Promotion == false ) Promotion = 0 ;
    if( Autor == true ) Autor = "Autor-1" ;
    else Autor = "" ;

    var CatId = 0 ;
//    if( window.location.href.split('/c-')[1] ) CatId = 'c-' +window.location.href.split('/c-')[1].split('/')[0] + "/" ;

    if( ShowProd ) {
         
        try {
          var stateObj = {foo: "bar"} ;
          IsHashNedded = false ;

          if( window.location.href.split('ttps').length > 1 ) {

              window.location.href = window.location.href.split('/')[0].replace('https', 'http') + '//' + window.location.href.split('/')[2] + "/s/q-" + SearchPhrase.replace( / /g, "_" ) + "/pc-" + FromPrice + "-" + ToPrice + "/s-" + Sorting + "/prom-" + Promotion + '/'+ CatId + '/' + Autor;
          } else {

            history.pushState( stateObj, SearchPhrase, "/s/q-" + SearchPhrase.replace( / /g, "_" ) + "/pc-" + FromPrice + "-" + ToPrice + "/s-" + Sorting + "/prom-" + Promotion + '/'+ CatId + '/' + Autor );
          }
//          history.
    //                  loadPage(href);
        }catch(e) {

            NewUrl = "!/s/q-" + SearchPhrase.replace( / /g, "_" ) + "/pc-" + FromPrice + "-" + ToPrice + "/s-" + Sorting + "/prom-" + Promotion + '/' + CatId + '/' + Autor ;

            document.getElementsByTagName('div')[0].innerHTML += "<div id='" + NewUrl + "' style='display:none;'></div>" ;
            //alert(NewUrl);

            location.hash =  '#'+NewUrl ;
            IsHashNedded = true ;

            if( window.location.href.split('#!')[1] && window.location.href.split('#!')[0].split('/s') != '/' && window.location.href.split('#!')[0].split('/s/')[1] == undefined ){

                window.location.href = 'http://' + window.location.href.split('/')[2] + '/s/q-wait/#!' + window.location.href.split('#!')[1] + '/' + Autor ;
            }
        }
    }

    ActualLimitFrom = 0 ;

    SearchHintsAjax( SearchPhrase, ShowProd, undefined, Autor ) ;
}

function SearchHintsAjax( Phrase, ShowProd, InputUrl, Autor ) { 

    document.getElementsByTagName('body')[0].style.cursor = 'progress' ;
    if( document.getElementById('SearchLupa') )
        document.getElementById('SearchLupa').style.background = 'url("/gfx/search/ajax-loader.gif") no-repeat' ;
    
    if( Autor == undefined && window.location.href.split('Autor').length > 1 ) Autor = 1 ;
    
    var Url = "";
    var Data = '' ;

    if( Phrase != 'GetMore') {

        ActualLimitFrom = 0 ;
        NoMoreProducts = false ;
    }

    SearchPhrase = decodeURI(SearchPhrase) ;
        
    if( InputUrl != undefined ) {

        try {
            
          var stateObj = {foo: "bar"};
          history.pushState( stateObj, SearchPhrase, InputUrl.href );
    //                  loadPage(href);
          IsHashNedded = false ;
          Url = InputUrl.href.split("/s/")[1] ;

        } catch(e) {
            
            NewUrl = "#!/s/" + InputUrl.href.split('#!/s/')[1] ;
            document.getElementsByTagName('div')[0].innerHTML += "<div id='" + NewUrl + "' style='display:none;'></div>" ;
            window.location.hash =  NewUrl ;
            IsHashNedded = true ;
            Url = InputUrl.href.split("#!/s/")[1] ;
        }

        Url = Url.split( "/" ) ;

        for( i in Url ){

            Data += Url[i].split('-')[0] + '=' + Url[i].split('-')[1] ;
            if( Url[i].split('-')[0] == 'pc' ) Data += '-' + Url[i].split('-')[2] ;
            Data += '&' ;
        }

        if( Url[i].split('-')[0] == 'q' ){
            SearchPhrase = Url[i].split('-')[1].replace( /_/gi, " " ) ;
        }

        var AjaxData = ( ( Data != '' ) ? (Data + '&ShowProd=1') : "q=" + SearchPhrase ) + "&page=" + ( ActualLimitFrom + 1 ) ;

    }else if( ShowProd ) {
        
        if( Phrase == 'GetMore' ) 
            var AjaxData = PrepareAjaxData( Phrase ) ;
        else
            var AjaxData = PrepareAjaxData() ;

    } else {

        var AjaxData = ( ( Data != '' ) ? (Data + '&ShowProd=1') : "q=" + encodeURI( SearchPhrase ) ) + "&page=" + ( ActualLimitFrom + 1 ) ;
    }

    ActualUrlState = window.location.href ;

    ajaxLW({
        type: "POST", 
        url: "/SearchAjaxPage.php",
        data: AjaxData,
        cookie: true,
        success: function( JsonData ){

            // Podzial danych na moduly
            var ModulesData = PrepareJsonModules( JsonData ) ;
            var View = "" ;

            if( ShowProd && ActualLimitFrom == 0 ){

                var Menu ;
                document.getElementById('SearchBarInput').value = SearchPhrase.replace( /\+/gi, " " ) ;

                if( window.location.href.substr(7, 7) == 'sklep.t') {

                    View = ShowSearchColumnLeft( ModulesData['PRODUCTS_IN_CATS'] ) ;
                    View += ShowSearchProducts( ModulesData['PRODUCTS'], ModulesData['CATS'], Autor ) ;
                    document.getElementById('Content').innerHTML = View ;

                    if( ModulesData['PRODUCTS'].length < 15 && Autor == undefined ){
                        GetSuggestProducts( AjaxData, ModulesData['PRODUCTS'] ) ;
                    }
                } else {

                    ajaxLW({url: "/lw/ColumnLeft.php", success: function( ColumnLeft ){

                        Menu = ColumnLeft ;

                        View = Menu ;
        //                View = ShowSearchColumnLeft( ModulesData['PRODUCTS_IN_CATS'] ) ;
                        View += ShowSearchProducts( ModulesData['PRODUCTS'], ModulesData['CATS'], Autor ) ;
                        document.getElementById('Content').innerHTML = View ;

                        if( ModulesData['PRODUCTS'].length < 15 && !Autor ){
                            GetSuggestProducts( AjaxData, ModulesData['PRODUCTS'] ) ;
                        }

                        GetCats() ;
                    }});
                }

                AddScrollEvent() ;

            } else if( ActualLimitFrom > 0 ) {
                
                if( !NoMoreProducts ) {
                    View = ShowMoreSearchProducts( ModulesData['PRODUCTS'] ) ;
                    document.getElementById('SearchProdTab').innerHTML += View ;
                }
            } else {

                ShowHints( ModulesData['HINTS'], ShowProd ) ;
            }

            document.getElementsByTagName('body')[0].style.cursor = 'default' ;
            if( document.getElementById('SearchLupa') )
                document.getElementById('SearchLupa').style.background = 'url("/gfx/search/lupa.png") no-repeat' ;
    }});
}

function PrepareAjaxData( Phrase ) {

    CurrentHintSelected = 0 ;
    ArrowSelect = false ;

    var Data = '' ;

    if( window.location.href.split('/autor_').length > 1 && Phrase == 'GetMore'  ) {
            
            SearchPhrase = window.location.href.split('/autor_')[1].split('?')[0] + '&ShowProd=1&Autor=1' ;
            
    } else {
        if( window.location.href.split( "#!" )[1] != '' && window.location.href.split( "#!" )[1] != undefined ){

            Url = window.location.href.split( "#!" )[1].split('/s/')[1] ;
        } else {

            Url = window.location.href.split('/s/')[1] ;
        }

        if( Url ) {
            
            Url = Url.split( "/" ) ;

            for( i in Url ){

                Data += Url[i].split('-')[0] + '=' + Url[i].split('-')[1] ;
                if( Url[i].split('-')[0] == 'pc' ) Data += '-' + Url[i].split('-')[2] ;
                Data += '&' ;

                if( Url[i].split('-')[0] == 'q' ){

                    SearchPhrase = decodeURI( Url[i].split('-')[1].replace( /_/gi, " " ) ) ;
                }
            }
        }
    }

    return ( ( Data != '' ) ? (Data + '&ShowProd=1') : "q=" + SearchPhrase ) + "&page=" + ( ActualLimitFrom + 1 ) ;
}

function GetSuggestProducts( AjaxData, Products ) {

    if( AjaxData == undefined ) AjaxData = PrepareAjaxData() ;

    var IdsProds = "" ;

    if( Products ) {

        for( i in Products ) {

            IdsProds += Products[i].Id + "," ;
        }
    } else {

        IdsProds = BasicProdIds.join(",") ;
    }

    ajaxLW({
        type: "POST",
        url: "/SearchAjaxPage.php",
        data: "q=" + SearchPhrase,
        cookie: true,
        success: function( JsonData ){

            var ModulesData = PrepareJsonModules( JsonData );
            var SuggestPhrase =  ShowHints( ModulesData['HINTS'], 1, 1 ) ;
            
            if( SuggestPhrase != '' )
            ajaxLW({
                type: "POST",
                url: "/SearchAjaxPage.php",
                data: AjaxData.replace(/q=(.*)&pc/, "q=" + encodeURI( FilterPolishChars( SuggestPhrase ).replace( / /gi, "_" ) ) + "&pc") + "&IdsProds=" + IdsProds ,
                success: function( JsonData ){

                    var ModulesData = PrepareJsonModules( JsonData );
                    if( ModulesData['PRODUCTS'].length > 0) {
                    
                        var View = ShowSuggestProducts( ModulesData['PRODUCTS'], SuggestPhrase ) ;
                        document.getElementById('SearchProdTab').innerHTML += View ;
                    }
            }});
    }});
}

function PrepareJsonModules( JsonData ){

    JsonData = JsonData.split( "^^^" ) ;

    // Podzial danych na moduly
    var ModulesData = new Object(); // Hash Table
    var SplitedData ;

    for( i in JsonData){

        SplitedData = JsonData[i].split('|||') ;
        ModulesData[ SplitedData[0] ] =  eval( SplitedData[1] )  ;
    }

    return ModulesData ;
}

var SearchInterval ;
var SelectedPosition = 0 ;
var CurrentHintSelected = 0 ;
var ArrowSelect = false ;

function SearchHints( Phrase, event ) {
    clearInterval( SearchInterval ) ;

    CurrentHintSelected = parseInt(CurrentHintSelected) ;
    
    var Key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if ( Key && Key == 13 ){ // ENTER
        if( ArrowSelect ) {
 
            document.getElementById('SearchBarInput').value = Trim( document.getElementById( "Hint_" + CurrentHintSelected ).getAttribute('value') ) ;
            Phrase = document.getElementById( "Hint_" + CurrentHintSelected ).getAttribute('value') ;
        }
 
        document.getElementById('SearchHints').style.display = 'none' ;
        SearchHintsRun( Phrase, '1' ) ;
    } else if ( Key && Key == 38 ){ // UP ARROW

        var CurrHint = ( CurrentHintSelected > 0 ) ? document.getElementById( "Hint_" + ( CurrentHintSelected - 1 ) ) : undefined ;
        var PrevHint = document.getElementById( "Hint_" + CurrentHintSelected ) ;

        if( CurrHint != undefined ) {

            if( PrevHint.className == 'OverHint' ){
                CurrHint.className='OverHint' ;
                PrevHint.className='' ;
                CurrentHintSelected--;
            } else {

                PrevHint.className='OverHint' ;
            }

            ArrowSelect = true ;
        }

    } else if ( Key && Key == 40 ){ // DOWN ARROW

        var CurrHint = document.getElementById( "Hint_" + ( CurrentHintSelected + 1 ) ) ;
        var PrevHint = document.getElementById( "Hint_" + CurrentHintSelected ) ;

        if( CurrHint != undefined ) {

            if( PrevHint.className == 'OverHint' ){

                CurrHint.className='OverHint' ;
                PrevHint.className='' ;
                CurrentHintSelected++;
            } else {

                PrevHint.className='OverHint' ;
            }
            ArrowSelect = true ;
        }
    } else {

        SearchInterval = setInterval( "SearchHintsRun( '" + Phrase + "')", 500 ) ;
    }
}

function FilterPolishChars( String ) {

    String = String.replace( /^\s+|\s+$/gi, '' ) ;
    String = String.replace( /ó/gi, "o" ) ;
    String = String.replace( /Ó/gi, "o" ) ;
    String = String.replace( /³/gi, "l" ) ;
    String = String.replace( /£/gi, "l" ) ;
    String = String.replace( /ñ/gi, "n" ) ;
    String = String.replace( /Ñ/gi, "n" ) ;
    String = String.replace( /¿/gi, "z" ) ;
    String = String.replace( /¯/gi, "z" ) ;
    String = String.replace( /¼/gi, "z" ) ;
    String = String.replace( /¬/gi, "z" ) ;
    String = String.replace( /Æ/gi, "c" ) ;
    String = String.replace( /æ/gi, "c" ) ;
    String = String.replace( /ê/gi, "e" ) ;
    String = String.replace( /Ê/gi, "e" ) ;
    String = String.replace( /¦/gi, "s" ) ;
    String = String.replace( /¶/gi, "s" ) ;
    String = String.replace( /±/gi, "a" ) ;
    String = String.replace( /¡/gi, "a" ) ;
    String = String.replace( /[\.|,|\/|<|>|?|;|:|'|"|[|]|\||{|}|\\|`|~|!|@|\$|%|\^|&|\*|\(|\)]/gi, "" ) ;
    String = String.toLowerCase() ;

    return String ;
}

function ShowAllMatchedCats(){

    var List = document.getElementById('CategorySearchList').getElementsByTagName('li') ;

    for( i in List ){

        if( List[i].style != undefined ) List[i].style.display = 'block' ;
    }

    document.getElementById('ShowMoreCats').style.display = 'none' ;
}

function SetSearchFilters(){

    var FromPrice = document.getElementById('SearchFromPrice').value ;
    var ToPrice = document.getElementById('SearchToPrice').value ;
    var Sorting = document.getElementById('SearchSorting').value ;
    var Promotion = document.getElementById('SearchOnlyPromotion').checked ;
    var Promotion = document.getElementById('SearchOnlyPromotion').checked ;
    if( SearchPhrase == '' || SearchPhrase == undefined ) SearchPhrase = document.getElementById('SearchPhrase').innerHTML ;
    
    var Autor = false ;
    if( window.location.href.split('autor').length > 1 || window.location.href.split('Autor').length > 1 ) Autor = true ;

    var Errors = "";

    if(
        ( FromPrice != '' && !RegExp( /^\d*(?:\.\d{0,2})?$/ ).test(FromPrice) ) ||
        ( ToPrice != '' && !RegExp( /^\d*(?:\.\d{0,2})?$/ ).test(ToPrice) )
      )
        Errors += "<div id='SearchOptionsErrors'>*** Popraw format ceny.</span>" ;

    if( document.getElementById('SearchOptionsErrors') )
            document.getElementById('DivSearchOptions').removeChild( document.getElementById('SearchOptionsErrors') ) ;

    if( Errors ){

        document.getElementById('DivSearchOptions').innerHTML += Errors ;
    } else {

        SearchHintsRun( SearchPhrase, 1, FromPrice, ToPrice, Sorting, Promotion, Autor ) ;
    }
}

var TimeGetMoreProd = 0 ;
if(     
    window.location.href.split('/s/').length > 1 ||
    window.location.href.split('/autor_').length > 1
    ){
    
    AddScrollEvent() ;
}

function AddScrollEvent() {

    window.onscroll = function () {
    //    alert( " x: " + GetScrollXY()[1] + ", inner: "+ window.innerHeight + ", doc.height " + document.height ) ;
        var Now = Math.round( new Date().getTime() / 1000 );

        var Height = document.body.clientHeight ;
        var InnerHeight = document.body.scrollHeight ; 

        if( ( ( ( GetScrollXY()[1] + Height ) / InnerHeight ) * 100 ) > 80  && TimeGetMoreProd < ( Now - 2 ) ) {

            TimeGetMoreProd = Math.round( new Date().getTime() /1000);
            ActualLimitFrom += 1 ;
            SearchHintsAjax( 'GetMore', 1 ) ;  
        } 
    }  
}

RunOnLoad['CheckCurrentState'] = 'CheckCurrentState' ;

function CheckCurrentState() {

    setInterval( function( e ) {

        if( ActualUrlState != window.location.href && window.location.href.split('/s/')[1] != undefined ){

            SearchHintsAjax( '', 1) ;
        } else if(  ActualUrlState.split('#')[0] != window.location.href.split('#')[0] ) {

            window.location.href = window.location.href.split('#')[0]  ;
            ActualUrlState = window.location.href ;
        }

    }, 4000);
}

RunOnLoad['HideSearchPopup'] = 'HideSearchPopup' ;
function HideSearchPopup(){

    if( document.getElementsByTagName('body')[0].addEventListener ) {

        document.getElementsByTagName('body')[0].addEventListener( 'click',
            function( event ) {

                document.getElementById('SearchHints').style.display = 'none' ;
            }
            , true
        ) ;
    } else {

        document.getElementsByTagName('body')[0].attachEvent( 'click',
            function( event ) {

                document.getElementById('SearchHints').style.display = 'none' ;
            }
        );
    }

}



