/* ===========================================================
 *
 *  Name:          selectordie.js
 *  Updated:       2014-10-11
 *  Version:       0.1.8
 *  Created by:    Per V @ Vst.mn
 *  What?:         The Select or Die JS
 *
 *  Copyright (c) 2014 Per Vestman
 *  Dual licensed under the MIT and GPL licenses.
 *
 *  To much comments in the code. Please, I know.
 *
 *  Oddny | Cogs 'n Kegs
 *
 * =========================================================== */

; (function ($) {

    function loadCatalogPage( href ){

        // var href = obj.attr( 'href' );
        window.history.pushState({},'', href );
        console.log( 'refreshh kesini bang---' + href );

        // var clone = $( 'img.loading-image' ).clone().show().css( {'cssText' : 'position:absolute;top:50%;left:50%;transform:translateX(-50%) translateY(-50%);'} ).appendTo( '.as-search-results-tiles' );
        // $( '.as-search-results-tiles' ).css( 'position', 'relative' );
        $( '.as-search-results-tiles > div' ).css( 'opacity', '0.1' );

        var data = {
                    'ubs-action'    : 'silent-body',
                    };
        $.ajax( {
            url: href,
            type: 'POST',
            data: data,
            success: function( result ) {
                if(result){
                    //refresh result tiles
                    $( '.as-search-results-tiles' ).html( $( result ).find( '.as-search-results-tiles' ).html() );

                    //refresh result paging number
                    $( 'form#product_select_pagesize' ).html( $( result ).find( 'form#product_select_pagesize' ).html() );

                    //menu horizontal child
                    $( '.menu-product-horizontal' ).html( $( result ).find( '.menu-product-horizontal' ).html() )
                    $( '.menu-product-horizontal-child' ).html( $( result ).find( '.menu-product-horizontal-child' ).html() )

                    //refresh filter
                    $( '#as-search-filters' ).html( $( result ).find( '#as-search-filters' ) );

                    //refresh pagination
                    $( '.as-pagination-align' ).html( $( result ).find( '.as-pagination-align' ).html() );

                    //reload slide image
                    var trend_gallery = $('.trend-gallery');
                    trend_gallery.each(function(index){
                        $(this).slick({
                            dots:true,
                            arrows: true,
                            prevArrow:  $(this).siblings('.paddlenav').find( '.paddlenav-arrow-previous' ),
                            nextArrow:  $(this).siblings('.paddlenav').find( '.paddlenav-arrow-next' ),
                            appendDots: $(this).siblings('.dotnav'),
                            infinite:false,
                            respondTo:'slider',
                            // mobileFirst: true,
                        });    
                    });

                    refreshPromo();

                    var els = document.getElementsByClassName("ase-truncate-title");
                    for( let i = 0; i < els.length; i++ )$clamp(els[i], {clamp: 2});

                }
            },
            complete: function(result) {
                $( '.as-search-results-tiles > div' ).css( 'opacity', '1' );
            }
        })
    }

    
    $( 'body' ).on( 'change', 'input[type].checkbox-filter-catalog', function(e){
        e.preventDefault();
        var mobile = $( 'body' ).attr( 'mobile' );
        if (typeof mobile !== typeof undefined && mobile !== false) {
            console.log( 'ini mobile croottt!' );
            return;
        }
        var params = $( this ).closest( 'form' ).serialize();
        var url = link + '?' + params;
        console.log( 'filter-search:' + url );
        loadCatalogPage( url );
    } )

    $( 'body' ).on( 'change', 'input[name="min-price"], input[name="max-price"]', function(e){
        e.preventDefault();
        var mobile = $( 'body' ).attr( 'mobile' );
        if (typeof mobile !== typeof undefined && mobile !== false) {
            console.log( 'ini mobile lho!' );
            return;
        }
        var params = $( this ).closest( 'form' ).serialize();
        var url = link + '?' + params;
        console.log( 'filter-search:' + url );
        loadCatalogPage( url ); 
    } )

    // $( 'body' ).on( 'click', 'a.as-filter-option', function( e ){
    //     e.preventDefault();
    //     $( this ).find( 'input[type=radio]' ).prop( "checked", true );
    //     var href = $( this ).attr( 'href' );
    //     loadCatalogPage( href );
    // } );

    $( 'body' ).on( 'change', '#product_select_pagesize input[name="pagesize"]', function(e){
        e.preventDefault();
        $( this ).prop( "checked", true );
        var data = $( this ).closest( 'form' ).serialize();
        var uri = $( this ).closest( 'form' ).attr( 'action' )?$( this ).closest( 'form' ).attr( 'action' ):window.location.href.split('?')[0];
        console.log( uri + '?' + data );
        loadCatalogPage( uri + '?' + data );
    } );

    $('body').on('change', '#select-filter-ringsize', function(){
        var selected  = $(this).find(":selected");
        console.log( 'selected link : ' + selected.data( 'ref' ) );
        loadCatalogPage( selected.data( 'ref' ) );
    })
    $('body').on('click', '#as-sort-drawer .as-search-sort-links', function(){
        $('form.woocommerce-ordering select').val( $(this).data( 'option-value' ) ).change();
        $('.as-search-sort-selected').html( $( this ).find( 'span' ).html() );
        console.log( $(this).data( 'option-value' ) );

        var data = $('form.woocommerce-ordering').serialize();
        var uri = window.location.href.split('?')[0];
        console.log( uri + '?' + data );
        loadCatalogPage( uri + '?' + data );
    })
    
    $(window).on('scroll', function(){
        if( $(window).width() < 1005 ) return;
        $('#localnav-disclosure').prop( "checked", false ); 
    })

    $('body').on('change', 'input.main-nav-check', function(){
        $('#localnav-disclosure').prop( "checked", false ); 
        console.log('input[name=main-nav-item]'); 
    })

    $('body').on('change', '#localnav-disclosure', function(){
        if( $(window).width() > 1005 ) return;
        if( $(this).is( ':checked' ) ){
            $( '#as-localnav-tray-content' ).css( 'height', $( window ).height() ).css( {'overflow-y':'scroll', 'display':'block', 'position':'relative' });
            $( 'body' ).css( {'overflow' : 'hidden', 'height' : '100%'} );
            
        }else{
            $( 'body' ).css( {'overflow' : 'auto', 'height' : 'auto'} );
        }
    })

    $('body').on('mouseleave', '#as-sort-drawer', function(){
        $('#as-open-drawer').prop( "checked", false ); 
        console.log('#as-sort-drawer'); 
    })

    $('body').on('change', '#filter-action-button', function(){
       if( $( window ).width() <=720 ){

            $('.as-overlay.as-overlay-mobile' ).addClass( 'active' );
            $('header#header').hide();
            //$('div#main').hide();
            $('footer#ac-globalfooter').hide();

            //get the content
            var search_filter_content = $('#as-search-filters').html();
            //copy the content
            $('#as-filter-mobile .as-search-filter-container').html( search_filter_content );
            //empty the original container
            $('#as-search-filters').html(' ');
       }else{
        console.log('no hide');
       }
    })

    $('body').on('click', '.as-overlay-close.as-searchoverlay-closeicon', function(){

        $('.as-overlay.as-overlay-mobile' ).removeClass('active');
        $('header#header').show();
        //$('div#main').show();
        $('footer#ac-globalfooter').show();

        //get the content
        var search_filter_content = $('#as-filter-mobile .as-search-filter-container').html();
        //copy the content
        $('#as-search-filters').html( search_filter_content );
        //empty the original container
        $('#as-filter-mobile .as-search-filter-container').html(' ');
       
    })

    function refreshPromo(){
        console.log( 'iterate promo..tonn....' );
        $( '.as-search-results-tiles .as-producttile' ).each( function( el ){
            var promo;
            var now=Math.round(+new Date/1e3);
            now += 7*60*60;
            if( promo = $( this ).data( 'promo' ) ){ 
                var promo_start = parseInt( $(this).data("promo-start"),10 );
                var promo_expiry = parseInt( $(this).data("promo-expiry"),10 );
                console.log( 'set promo banner' );
                console.log( 'now:' + promo_start + '<' + now + '<' + promo_expiry );  
                if( now > promo_start && now < promo_expiry ){
                    console.log( 'add-product-promo' );
                    $( this ).addClass( 'show-promo-counter' );    
                    $( this ).prepend( '<span class="product-promo ' + (promo.indexOf( '%' ) == -1?'fixed-amount':'') + '">' + promo + '</span>' );   
                } 
                
            }
        });

        $(".counter-wrapper").each(function(){
            console.log( 'start counter' );
            var b=$(".wpvc-days .value",this),
            c=$(".wpvc-hours .value",this),
            d=$(".wpvc-minutes .value",this),
            e=$(".wpvc-seconds .value",this),
            f=parseInt($(this).data("until"),10),
            g=$(this).data("done"),
            h=$(this),
            i=function(){
                var i=Math.round(+new Date/1e3) + 7*60*60;if(i>=f&&""!==g)return clearInterval(j),void h.html($("<span />").addClass("wpvc-done wpvc-block").html($("<span />").addClass("value").text(g))),function(){ console.log( 'timer-done' ) }() ;var k=Math.abs(f-i);e.text(k%60),k=Math.floor(k/60),d.text(k%60),k=Math.floor(k/60),c.text(k%24),k=Math.floor(k/24),b.text(k)
            },
            j=setInterval(i,1e3)
        })   
    }

    $( document ).ready(function() {

        refreshPromo();

        var current_uri = window.location.href;
        setTimeout( function(){
            var uri = window.location.href;
            //disable
            // loadCatalogPage( uri );
        })
        //clean up
        $('#as-sort-drawer .as-search-sort-list').html('');
        //populate select search
        $('form.woocommerce-ordering select option').each( function(){
            if( $(this).is(':selected') ){
                $( '#as-sort-selected' ).text( $(this).text() );
                console.log( 'selected : ' +  $(this).val() );
            }

            console.log( 'option : ' +  $(this).val() + ' - ' + $(this).text() );

            $('#as-sort-drawer .as-search-sort-list').append('<li class="as-search-sort-listitems"> <a href="#' + $(this).val() + '" class="as-search-sort-links ' + ( $(this).is(':selected')? 'as-search-selected-option' : '' ) + '" data-option-value="' + $(this).val() + '"> <div class="title-body"> <span> ' + $(this).text() + ' </span> </div> </a> </li>');
        });
        
        $('overlay.as-overlay').bind('swipedown', function(e){
            $( '.as-overlay-close.as-searchoverlay-closeicon' ).click();
        });

    });

})(jQuery);
