/**************************************************************
 * EvCont Javascript
 *************************************************************/

(function($) {
    "use strict";

    var myTemplate = window.myTemplate || {};

    /* Scroll to top */
    $(document).on('click', '.totop', function() {
        $('html, body').animate({scrollTop: 0}, 600, 'swing');
        return false;
    });

    /* Smooth scroll function */
    $(document).on('click', 'ul.navbar-nav a', function(e) {
        if ( $(e.target).is('a[href*="#"]:not([href="#"]') ) {
            if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
                || location.hostname == this.hostname) {

                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
                if (target.length) {
                    $('html,body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        }
    });

    
    /* Enable link hover with full menu */
    function hoverNavLinks() {
        var winWidth = $(window).width();
        if (winWidth >= 992) {
            /* Hover navbar dropdowns */
            $('.navbar [data-toggle="dropdown"]').bootstrapDropdownHover({
                // see next for specifications
            });

            // ADD SLIDEDOWN ANIMATION TO DROPDOWN //
            $('.dropdown').on('show.bs.dropdown', function(e){
                $(this).find('.dropdown-menu').first().stop(true, true).slideDown("fast");
            });

            // ADD SLIDEUP ANIMATION TO DROPDOWN //
            $('.dropdown').on('hide.bs.dropdown', function(e){
                $(this).find('.dropdown-menu').first().stop(true, true).slideUp("fast");
            });
        }
    }

    /* Google Map Section */
    function initialize() {
        var myCenter = new google.maps.LatLng(39.7645187,-104.9951951);
        var mapProp = {
            center : myCenter,
            zoom : 13,
            mapTypeId : google.maps.MapTypeId.ROADMAP,
            scrollwheel: false,
            draggable: !("ontouchend" in document),
        };
        var map = new google.maps.Map(document.getElementById("mapSection"), mapProp);
        var marker = new google.maps.Marker({
            position : myCenter,
            icon : 'img/map_marker.png'
        });
        marker.setMap(map);
    }

    $(window).load(function() {
        /* load in correct position function */
        if ($('#totop .top-holder').length ) {  
            var hash = window.location.hash;
            var headerOffset = top;
            if (hash.length) {
                $(document).scrollTop( $(hash).offset().top - $('#totop .top-holder').outerHeight() );
            }
        }
    
        /* Isotope Image Galleries */
        myTemplate.Isotope = function () {
            // 3 column layout
            var isotopeContainer2 = $('#isotope-container2');
            if( !isotopeContainer2.length || !jQuery().isotope ) return;
            isotopeContainer2.isotope({
                itemSelector: '.isotopeSelector',
                layoutMode: 'fitRows',
            });
            $('#isotope-filters2').on( 'click', 'a', function(e) {
                $('#isotope-filters2').find('.active').removeClass('active');
                $(this).parent().addClass('active');
                var filterValue = $(this).attr('data-filter');
                isotopeContainer2.isotope({ filter: filterValue });
                e.preventDefault();
            });
        };
        // Functions Initializers
        myTemplate.Isotope();

        /* Front Page Google Map */
        if($('#mapSection').length) {
            initialize();
        }
    });

    $(document).ready(function() {
        hoverNavLinks();
        $('.fancybox-media').fancybox({
            openEffect  : 'none',
            closeEffect : 'none',
            helpers : {
                media : {}
            }
        });

        myTemplate.Fancybox = function () {
            $(".fancybox-pop").fancybox({
                maxWidth    : 900,
                maxHeight   : 700,
                fitToView   : true,
                width       : '80%',
                height      : '80%',
                autoSize    : false,
                closeClick  : false,
                openEffect  : 'elastic',
                closeEffect : 'none'
            });
        };
    
        myTemplate.Fancybox();

        $('#owl-carousel-features').owlCarousel ({
            items: 1,
            animateOut: 'fadeOutLeft',
            animateIn: 'fadeInRight',
            //autoHeight: true,
            margin: 10,
            loop: true,
            smartSpeed: 450,
            mouseDrag: false,
            nav: false
        });
        var owl = $('#owl-carousel-features').owlCarousel();
        $(document).on('click', '.detail-switch.gonext', function() {
            owl.trigger('next.owl.carousel');
            return false;
        })

        $("#submit_cereoferta").on('click', function() {
            ev.cereoferta();
        })
        $("#submit_addimpresie").on('click', function() {
            ev.addimpresie();
        })
        
        $("#submit_programeazate").on('click', function() {
            ev.programeazate();
        })
        console.log(window.screen.width)
        if (window.screen.width > 991) {
            var dimUlNav = 10;
            $('.navbar-nav-v2 li').each(function() {
                dimUlNav += $(this).width();
            })
            console.log(dimUlNav);
            $('.navbar-nav-v2').css({width: dimUlNav + 'px'});
        }


        $('#searchtips-modal').on('hide.bs.modal', function (event) {
            jQuery(".prods-categs").each(function() {
                jQuery(this).removeClass('prods-categs-selected');
            })
        })
    });
//----------------------------------------------------------------------------------------------------------------------------
// FILTRE
//----------------------------------------------------------------------------------------------------------------------------
    $('.prods-categs').on('click', function() {
        if ($(this).hasClass('prods-categs-selected')) {
            $(this).removeClass('prods-categs-selected');
            $('#featurescats-' + $(this).data('filterlink')).removeClass('show').addClass('hide');
        } else {
           $('.prods-categs').each(function() {
            $(this).removeClass('prods-categs-selected');
            })
            $(this).addClass('prods-categs-selected');
            ev.chosefilter($(this)) 
        }
        
    })
    $('#features-filters').on('click', function() {
        ev.featuresfilters($(this)) 
    })

//----------------------------------------------------------------------------------------------------------------------------
// CAUTARE SIMPLA
//----------------------------------------------------------------------------------------------------------------------------
    $("#gocauta").on('click', function(e) {
        e.preventDefault();
        ev.search($(this));
    })
//----------------------------------------------------------------------------------------------------------------------------
    
//----------------------------------------------------------------------------------------------------------------------------
// CAUTARE AVANSATA - activare butoane
//----------------------------------------------------------------------------------------------------------------------------
    $(".btn-setvaldefs").on('click', function(e) {
        e.preventDefault();
        if ($(this).hasClass('btn-primary')) {$(this).removeClass('btn-primary');} else {$(this).addClass('btn-primary');}
        // $(this).parent().find(".btn-setvaldefs").each(function() {
        //     $(this).removeClass('btn-primary');
        // })
        // $(this).addClass('btn-primary');
    })
    $(".btn-search").on('click', function(e) {
        e.preventDefault();
        ev.searchAdvanced($(this));
    })
//----------------------------------------------------------------------------------------------------------------------------
    
    
})(jQuery);


var ev = {
    baseurl: baseurl,
    baseurlAjax: baseurl+'/ajax',
    cereoferta: function() {
        var parinte = jQuery("form#cereoferta");
        parinte.find('.response').removeClass('err ok');
        parinte.find('.response').html('');
        var nume    = parinte.find('#nume').val();
        var email   = parinte.find('#email').val();
        var tel     = parinte.find('#tel').val();
        var comment = parinte.find('#comment').val();
        var codcorect = parinte.find('#codcorect').val();
        var cod = parinte.find('#cod').val();
        var err = '';
        if (!nume || !email || !tel || !comment) {
            parinte.find('.response').addClass('err');
            parinte.find('.response').html('Toate campurile sunt obligatorii!');
        } else if (cod != codcorect) {
            parinte.find('.response').addClass('err');
            parinte.find('.response').html('Codul de securitate este gresit!');
        }else {
            jQuery.ajax({
                url: ev.baseurlAjax + "/cereoferta.php",
                type: "POST",
                data: {
                    "nume": nume,  "email": email, "tel": tel, "comment": comment, "pid_link" : parinte.find('#pid_link').val(), "pid_id" : parinte.find('#pid_id').val(), "pid_nume" : parinte.find('#pid_nume').val()
                },
                success: function (response) {
                    parinte.find('.response').addClass(response.class);
                    parinte.find('.response').html(response.text);
                }
            });
        }
    },
    programeazate: function() {
        var parinte = jQuery("form#programeazate");
        parinte.find('.response').removeClass('err ok');
        parinte.find('.response').html('');
        var nume    = parinte.find('#nume').val();
        var email   = parinte.find('#email').val();
        var tel     = parinte.find('#tel').val();
        var comment = parinte.find('#comment').val();
        var data    = parinte.find('#data').val();
        var codcorect = parinte.find('#codcorect').val();
        var cod = parinte.find('#cod').val();
        var err = '';
        if (!nume || !tel || !comment || !data) {
            parinte.find('.response').addClass('err');
            parinte.find('.response').html('Toate campurile sunt obligatorii!');
        } else if (cod != codcorect) {
            parinte.find('.response').addClass('err');
            parinte.find('.response').html('Codul de securitate este gresit!');
        } else {
           jQuery.ajax({
                url: ev.baseurlAjax + "/programeazate.php",
                type: "POST",
                data: {
                    "nume": nume,  "email": email, "tel": tel, "comment": comment, "data": data
                },
                success: function (response) {
                    parinte.find('.response').addClass(response.class);
                    parinte.find('.response').html(response.text);
                }
            });
        }
    },
    addimpresie: function() {
        var parinte = jQuery("form#addimpresie");
        parinte.find('.response').removeClass('err ok');
        parinte.find('.response').html('');
        var nume    = parinte.find('#nume').val();
        var email   = parinte.find('#email').val();
        var impresie = parinte.find('#comment').val();
        var codcorect = parinte.find('#codcorect').val();
        var cod = parinte.find('#cod').val();
        var err = '';
        if (!nume || !email || !impresie || !cod) {
            parinte.find('.response').addClass('err');
            parinte.find('.response').html('Toate campurile sunt obligatorii!');
        } else if (cod != codcorect) {
            parinte.find('.response').addClass('err');
            parinte.find('.response').html('Codul de securitate este gresit!');
        } else {
           jQuery.ajax({
                url: ev.baseurlAjax + "/addimpresie.php",
                type: "POST",
                data: {
                    "nume": nume,  "email": email, "impresie" : impresie, "codcorect" : codcorect, "cod" : cod
                },
                success: function (response) {
                    parinte.find('.response').addClass(response.class);
                    parinte.find('.response').html(response.text);
                }
            });
        }
    },
    getOptionsFilter: function() {
        var filters = new Object();
        jQuery('.featurescats-all').each(function() {
            var filterlink = jQuery(this).data('filterlink');
            var checkdFeatures = jQuery(this).find("input:checkbox:checked").map(function(){
                return $(this).val();
            }).get();
            filters[jQuery(this).prop('id')] = checkdFeatures;
        })
        return filters;
    },
//----------------------------------------------------------------------------------------------------------------------------
// FILTRE AMBIENT, FORMAT, FINISAJ, COLECTIE - afisare modala
//----------------------------------------------------------------------------------------------------------------------------
    chosefilter: function(dom) {
        var filterid    = dom.data('filterid');
        var filterlink  = dom.data('filterlink');
        var filters = ev.getOptionsFilter();
        var dataObj = { filterid: filterid, filterlink:  filterlink,  filters};
        console.log(dataObj);
        jQuery.ajax({
            url: ev.baseurlAjax + "/chosefilter.php",
            type: "POST",
            data: dataObj,
            success: function (response) {
                jQuery("#searchtips-body").html(response.out);
                jQuery("#searchtips-modal").modal()
                // $('.featurescats-all').each(function() {
                //     $(this).removeClass('show').addClass('hide');
                // })
                // $('#featurescats-' + filterlink).html(response.out);
                // $('#featurescats-' + filterlink).removeClass('hide').addClass('show');
                //------------------------------------------------------------------------------------------------------------
                // filter MODAL 
                //------------------------------------------------------------------------------------------------------------
                    jQuery(".col-filter").on('click', function() {
                        ev.featuresOnefilters(jQuery(this));
                    })
                //------------------------------------------------------------------------------------------------------------
            }
        });
    },
//----------------------------------------------------------------------------------------------------------------------------
// alegere mai multe filtre - se salveaza in sesiune si se redirectioneaaz catre pagina cu afisare produse filtrate
//----------------------------------------------------------------------------------------------------------------------------
    featuresfilters: function() {
        var filters = ev.getOptionsFilter();
        var dataObj = { filters};
        jQuery.ajax({
            url: ev.baseurlAjax + "/featuresfilters.php",
            type: "POST",
            data: dataObj,
            success: function (response) {
                window.location.href = ev.baseurl + '/produse-filtrate';
            }
        });
    },
//----------------------------------------------------------------------------------------------------------------------------
// alegere 1 filtru
//----------------------------------------------------------------------------------------------------------------------------
    featuresOnefilters: function(dom) {
        var filters = new Object();
        filters['featurescats-' + dom.find('img').data('name')] = dom.find('img').data('id');
        var dataObj = { filters};
        jQuery.ajax({
            url: ev.baseurlAjax + "/featuresfilters.php",
            type: "POST",
            data: dataObj,
            success: function (response) {
                window.location.href = ev.baseurl + '/produse-filtrate';
            }
        });
    },
//----------------------------------------------------------------------------------------------------------------------------
// CAUTARE SIMPLA => redirectionare catre pagina de cautqare simpla
//----------------------------------------------------------------------------------------------------------------------------
    search: function(dom) {
        var q = jQuery('input[name="q"]').val();
        window.location.href = baseurl + '/rezultate-cautare/q=' + q;
    },
//----------------------------------------------------------------------------------------------------------------------------
// CAUTARE AVANSATA => populare rezultate
//----------------------------------------------------------------------------------------------------------------------------
    searchAdvanced: function(dom) {
        var filtre = {} ;
        jQuery(".prods-filter-cat").each(function() {
            var filterid = $(this).data('filterid');
            console.log(filterid);
            filtre[filterid] = [];
            jQuery(this).find('.btn.btn-primary').each(function() {
                filtre[filterid] += '|' + jQuery(this).data('id');
            })

        })
        if ($('.btn-setvaldefs[data-tip="incalzire_pardoseala"]').hasClass('btn-primary')) {filtre['incalzire_pardoseala'] = 1}
        // console.log(filtre);
        jQuery("#search-results").html('<span class="txtitalic">Se incarca rezultatele ...</span>');
        jQuery.ajax({
            url: ev.baseurlAjax + "/searchAdvanced.php",
            type: "POST",
            dataType: 'json',
            data: filtre,
            success: function (response) {
                jQuery("#search-results").html(response.out);
            }
        });
    }
}