
_.templateSettings.variable = "rc";

var ref_body = $('body');
var autocloseTimer;
var autocloseProgressbarInterval;
var autocloseProgressbar = 0;
var waitForFinalEvent=function(){var b={};return function(c,d,a){a||(a="something");b[a]&&clearTimeout(b[a]);b[a]=setTimeout(c,d)}}();//wait function
var fullDateString = new Date();
/**
 * Number.prototype.format(n, x, s, c)
 *
 * @param integer n: length of decimal
 * @param integer x: length of whole part
 * @param mixed   s: sections delimiter
 * @param mixed   c: decimal delimiter
 */
Number.prototype.format = function(n, x, s, c) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
        num = this.toFixed(Math.max(0, ~~n));

    return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};

function isObject(val) {
    if (val === null) { return false;}
    return ( (typeof val === 'function') || (typeof val === 'object') );
}

// Add an URL parser to JQuery that returns an object
// This function is meant to be used with an URL like the window.location
// Use: $.parseParams('http://mysite.com/?var=string') or $.parseParams() to parse the window.location
// Simple variable:  ?var=abc                        returns {var: "abc"}
// Simple object:    ?var.length=2&var.scope=123     returns {var: {length: "2", scope: "123"}}
// Simple array:     ?var[]=0&var[]=9                returns {var: ["0", "9"]}
// Array with index: ?var[0]=0&var[1]=9              returns {var: ["0", "9"]}
// Nested objects:   ?my.var.is.here=5               returns {my: {var: {is: {here: "5"}}}}
// All together:     ?var=a&my.var[]=b&my.cookie=no  returns {var: "a", my: {var: ["b"], cookie: "no"}}
// You just cant have an object in an array, ?var[1].test=abc DOES NOT WORK
// Add an URL parser to JQuery that returns an object
// This function is meant to be used with an URL like the window.location
// Use: $.parseParams('http://mysite.com/?var=string') or $.parseParams() to parse the window.location
// Simple variable:  ?var=abc                        returns {var: "abc"}
// Simple object:    ?var.length=2&var.scope=123     returns {var: {length: "2", scope: "123"}}
// Simple array:     ?var[]=0&var[]=9                returns {var: ["0", "9"]}
// Array with index: ?var[0]=0&var[1]=9              returns {var: ["0", "9"]}
// Nested objects:   ?my.var.is.here=5               returns {my: {var: {is: {here: "5"}}}}
// All together:     ?var=a&my.var[]=b&my.cookie=no  returns {var: "a", my: {var: ["b"], cookie: "no"}}
// You just cant have an object in an array, ?var[1].test=abc DOES NOT WORK
(function ($) {
    var re = /([^&=]+)=?([^&]*)/g;
    var decode = function (str) {
        return decodeURIComponent(str.replace(/\+/g, ' '));
    };
    $.parseParams = function (query) {
        // recursive function to construct the result object
        function createElement(params, key, value) {
            key = key + '';
            // if the key is a property
            if (key.indexOf('.') !== -1) {
                // extract the first part with the name of the object
                var list = key.split('.');
                // the rest of the key
                var new_key = key.split(/\.(.+)?/)[1];
                // create the object if it doesnt exist
                if (!params[list[0]]) params[list[0]] = {};
                // if the key is not empty, create it in the object
                if (new_key !== '') {
                    createElement(params[list[0]], new_key, value);
                } else console.warn('parseParams :: empty property in key "' + key + '"');
            } else
            // if the key is an array
            if (key.indexOf('[') !== -1) {
                // extract the array name
                var list = key.split('[');
                key = list[0];
                // extract the index of the array
                var list = list[1].split(']');
                var index = list[0]
                // if index is empty, just push the value at the end of the array
                if (index == '') {
                    if (!params) params = {};
                    if (!params[key] || !$.isArray(params[key])) params[key] = [];
                    params[key].push(value);
                } else
                // add the value at the index (must be an integer)
                {
                    if (!params) params = {};
                    if (!params[key] || !$.isArray(params[key])) params[key] = [];
                    params[key][parseInt(index)] = value;
                }
            } else
            // just normal key
            {
                if (!params) params = {};
                params[key] = value;
            }
        }
        // be sure the query is a string
        query = query + '';
        if (query === '') query = window.location + '';
        var params = {}, e;
        if (query) {
            // remove # from end of query
            if (query.indexOf('#') !== -1) {
                query = query.substr(0, query.indexOf('#'));
            }

            // remove ? at the begining of the query
            if (query.indexOf('?') !== -1) {
                query = query.substr(query.indexOf('?') + 1, query.length);
            } else return {};
            // empty parameters
            if (query == '') return {};

            // execute a createElement on every key and value
            while (e = re.exec(query)) {
                var key = decode(e[1]);
                var value = decode(e[2]);
                createElement(params, key, value);
            }
        }
        //console.log(query);
        return params;
    };
})(jQuery);

var remodal = $('#modalQuickView');
var remodal_title = $('#remodal_title');
var remodal_content = $('#remodal_content');
var ref_body = $('body');

var getRemodalFromArray = function(messages){

    if(messages === undefined){
        messages = {};
    }
    var m = ['warning', 'info', 'success', 'error'];
    var title = 'Hinweis';
    var type = 'success';
    var text = '';
    for (var j = 0; j < m.length; ++j) {
        if( m[j] in messages ){
            //console.log( messages[m[j]]   );
            if( !jQuery.isEmptyObject( messages[m[j]] ) ){
                for (var k in messages[m[j]]) {
                    if (messages[m[j]].hasOwnProperty(k)) {
                        for( var i=0; i < messages[m[j]][k].length; i++ ){
                            text += messages[m[j]][k][i] + '<br>';
                        }
                    }
                }
                if(m[j] === 'error'){
                    title = 'Achtung';
                    type = 'success';
                }
            }
        }
    }
    if( text !== '' ){
        createRemodal( type, title, text );
    }

    //console.log(messages);
};

var createRemodal = function(type, title, text){
    remodal_title.html(title);
    remodal_content.html(text);
    remodal.modal('show');
};

/**
 * blockContent zeigt eine Fehlermeldung in einem blockierten Element an.
 * wird im Modal für das Login benutzt
 * optional wird ein timeout mitgegeben
 */

var timeoutBlock = null;
var blockContent = function(ref, message, timeout){
    ref.block({
        message: message,
        css: {
            padding:        '30px',
            margin:         0,
            width:          '100%',
            top:            '40%',
            left:           '0',
            textAlign:      'center',
            color:          '#000',
            border:         '3px solid red',
            backgroundColor:'#fff',
            cursor:         'wait'
        }
    });
    ref.on('click', '.blockOverlay, .blockMsg', function(e){
        e.preventDefault();
        console.log('unblock click');
        ref.unblock();
        ref.off('click', '.blockOverlay, .blockMsg');
        clearTimeout(timeoutBlock);
    });
    if( typeof timeout === 'number' ){
        timeoutBlock = setTimeout(function() {
            ref.unblock();
            ref.off('click', '.blockOverlay, .blockMsg');
        }, timeout);
    }
};


function makeBgImages(){

    $('.wrapper_image[datasrc]').each(function(){
        var ref = $(this);
        var src = ref.attr('datasrc');
        //console.log(src);
        ref.css('background', 'url(' + src + ')');
        if( $(this).hasClass('contain') ){
            ref.css('background-size', 'contain');
        }else{
            ref.css('background-size', 'cover');
        }
        ref.css('background-position', 'center');
        ref.css('background-repeat', 'no-repeat');
        ref.html('');
        ref.removeAttr('datasrc');
    });

    $('.wrapper_image_contain[datasrc]').each(function(){

        var ref = $(this);
        var src = ref.attr('datasrc');
        //console.log(src);
        ref.css('background', 'url(' + src + ')');
        ref.css('background-size', 'contain');
        ref.css('background-position', 'center');
        ref.css('background-repeat', 'no-repeat');
        ref.html('');
        ref.removeAttr('datasrc');
    });
}

var make_dots = function(){

    //console.log('[makeDots]');
    $(".dotdotdot").dotdotdot({
        fallbackToLetter: true,
        ellipsis: '...',
        watch: true,
        truncate: "letter"
    });


};

function isMobile(){
    $('.hide_on_mobile').addClass('hidden');
    $('.show_on_mobile').removeClass('hidden');
}
function isDesktop(){
    $('.hide_on_desktop').addClass('hidden');
    $('.show_on_desktop').removeClass('hidden');
}
function isMobileDevice(a) {
    if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))){

        isMobile();
    }else{
        isDesktop();
    }
}
(isMobileDevice)(navigator.userAgent || navigator.vendor || window.opera);





$(function() {




    // Handler for .ready() called.
    $('div#load_screen').remove();

    make_dots();

    $('.modal[autoclose]').on('show.bs.modal', function(){
        var ref = $(this);
        var progressBar = ref.find('.progress-bar');
        var timeout = time_left = 3000;
        var intervalTime = 750;
        var start = Date.now();
        var attr_timeout = parseInt( ref.attr('autoclose') );
        if( attr_timeout > 0 ){
            timeout = attr_timeout;
        }
        var end = start + timeout;
        // init progressBar
        progressBar.css('width','100%').attr('aria-valuenow', '100');

        autocloseProgressbarInterval = setInterval(function(){
            var now = Date.now();
            var delta = end - now;
            var x = 0;
            if(delta>0){
                x = Math.floor(delta / timeout * 100);
                progressBar.css('width',x+'%').attr('aria-valuenow', x);
            }else{
                progressBar.css('width',x+'%').attr('aria-valuenow', x);
                // litte delay for css animation before close
                autocloseTimer = setTimeout(function(){
                    ref.modal('hide');
                    //console.log('hide_modal')
                }, intervalTime);
            }
        },intervalTime);

    });

    $('.modal[autoclose]').on('hide.bs.modal', function(){
        clearTimeout(autocloseTimer);
        clearInterval(autocloseProgressbarInterval);
    });

    makeBgImages();

    $('#teaser_slide').on('init', function(event, slick){
        $('#teaser_slide .item.hidden').removeClass('hidden');
    });

    $('#teaser_slide').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 5000,
        dots: true,
        fade: true
    });

    $('#slide').slick({
        lazyLoad: 'ondemand',
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 50000,
        dots: true,
        fade: true
    });
    $('#blogslide').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 50000,
        dots: true,
        fade: true
    });

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * Logout
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    $('.logout').click(function(){

        var f = {};
        f.aktion = 'logout';
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '/ajax/logout',
            data: (f),
            success: function (data) {
                if (parseInt(data.status) === 1) {
                    window.location.replace(window.location.protocol + '//' + window.location.host + '/');
                }
            },
            error : function() {
            }
        });
        return false;
    });


    //beobachten von angeboten
    ref_body.on('click', '.merken', function(e) {
        //$('.message_auktion_beobachten').html('');
        e.preventDefault();
        var ref = $(this);
        ref.attr('disabled', 'disabled');
        var f = {};
        if (ref.hasClass('active')) {
            f.flag_beobachten = 0;
        } else {
            f.flag_beobachten = 1;
        }
        f.lot = ref.attr('lot');
        //console.log(f);
        $.ajax({
            type : 'POST',
            dataType : 'json',
            url : '/ajax/beobachten',
            data : (f),
            success : function(data) {
                if (data.status === 1) {

                    $('.heart-counter').attr("data-messages", data.count_watchlist);

                    if( ref.hasClass('heart-bieten') ) {
                        var btn = $('.wrapper_merken_btn').find('.btn.merken');
                        if (data.status_beobachtung === 1) {
                            ref.addClass('active');
                            ref.attr('title', 'aus Merkliste entfernen');
                            //ref.html('<i class="fas fa-heart"></i>');
                            btn.addClass('active');
                            btn.attr('title', 'aus Merkliste entfernen');
                            btn.html('aus Merkliste entfernen');
                        }else{
                            ref.removeClass('active');
                            ref.attr('title', 'zur Merkliste hinzufügen');
                            //ref.html('<i class="far fa-heart"></i>');
                            btn.removeClass('active');
                            btn.attr('title', 'zur Merkliste hinzufügen');
                            btn.html('zur Merkliste hinzufügen');
                        }

                    }else if( ref.hasClass('btn') ) {
                        var heart = $('.page_bieten .wrapper_images').find('.merken');
                        if (data.status_beobachtung === 1) {
                            heart.addClass('active');
                            heart.attr('title', 'aus Merkliste entfernen');
                            //heart.html('<i class="fas fa-heart"></i>');
                            ref.addClass('active');
                            ref.addClass('btn-primary');
                            ref.removeClass('btn-outline-primary');
                            ref.attr('title', 'aus Merkliste entfernen');
                            ref.html('Beobachten');
                        }else{
                            heart.removeClass('active');
                            heart.attr('title', 'zur Merkliste hinzufügen');
                            //heart.html('<i class="far fa-heart"></i>');
                            ref.removeClass('active');
                            ref.addClass('btn-outline-primary');
                            ref.removeClass('btn-primary');
                            ref.attr('title', 'zur Merkliste hinzufügen');
                            ref.html('Beobachten');
                        }

                    }else if( ref.hasClass('merkliste') ){

                        var box = ref.parents('.lot_merkliste:first');
                        var heart = box.find('.heart');

                        //console.log(heart);

                        if (data.status_beobachtung === 1) {
                            box.find('.shadow').hide();
                            box.find('.undo').addClass('hidden');
                            box.find('.times.active').removeClass('hidden');
                            heart.addClass('active');
                            heart.attr('title', 'aus Merkliste entfernen');
                            //heart.html('<i class="fas fa-heart"></i>');
                        } else {
                            box.find('.shadow').show();
                            box.find('.undo').removeClass('hidden');
                            box.find('.times.active').addClass('hidden');
                            heart.removeClass('active');
                            heart.attr('title', 'zur Merkliste hinzufügen');
                            //heart.html('<i class="far fa-heart"></i>');
                        }

                    }else{
                        if (data.status_beobachtung === 1) {
                            ref.addClass('active');
                            ref.attr('title', 'aus Merkliste entfernen');
                            ref.attr('data-original-title', 'aus Merkliste entfernen');
                            //ref.html('<i class="fas fa-heart"></i>');
                        } else {
                            ref.removeClass('active');
                            ref.attr('title', 'zur Merkliste hinzufügen');
                            ref.attr('data-original-title', 'zur Merkliste hinzufügen');
                            //ref.html('<i class="far fa-heart"></i>');
                        }
                    }




                } else {

                    if( parseInt(data.flag_logged_in) === 0  ){
                        $('#myModalLogin').modal('show');
                    }else{
                        getRemodalFromArray(data.messages);
                    }


                }
                $('[data-toggle="tooltip"]').tooltip('hide');
                ref.removeAttr("disabled");
            },
            error : function() {
                $('[data-toggle="tooltip"]').tooltip('hide');
                ref.removeAttr("disabled");
            }
        });
        return false;
    });

    ref_body.on('click', '.showLogin', function(e){
        e.preventDefault();
        $('form[name=loginform]').find('input[name=location]').val('');
        var href = $(this).attr('href');
        if( href !== undefined ){
            $('form[name=loginform]').find('input[name=location]').val( $(this).attr('href') );
        }
        $('#myModalLogin').modal('show');
    });


    $('#myModalLogin').on('show.bs.modal', function () {
        $('form[name=loginform]')[0].reset();
        $('form[name=loginform]').find('input[name=login]').trigger('focus');
    });

});

