     setTimeout(function () {
        $('video').each(function (i, elm) {
            if ($(elm).attr('autoplay') != undefined) {
                $(elm).get(0).play();
            }
        })
    }, 3000);

      window.isLoading = 0;
function showLoading() {
    window.isLoading = 1;
    swal.fire({
        title: 'Loading ...',
        allowEscapeKey: false,
        allowOutsideClick: false,
        timer: 20000,
        onOpen: () => {
            swal.showLoading();
        }
    })
};
function closeLoading() {
    window.isLoading = 0;
    swal.close();
};
window.tabsStatus = [];
if (typeof window.t_hours !== "function") {

    window.t_hours = function () {
        if (typeof window.website_settings.set_sunday_hours !== 'undefined') {

            var d = new Date();
            var weekday = new Array(7);
            weekday[0] = "Sunday	" + window.website_settings.set_sunday_hours;
            weekday[1] = "Monday	" + window.website_settings.set_monday_hours;
            weekday[2] = "Tuesday	" + window.website_settings.set_tuesday_hours;
            weekday[3] = "Wednesday	" + window.website_settings.set_wednesday_hours;
            weekday[4] = "Thursday	" + window.website_settings.set_thursday_hours;
            weekday[5] = "Friday	" + window.website_settings.set_friday_hours;
            weekday[6] = "Saturday	" + window.website_settings.set_saturday_hours;

            var n = weekday[d.getDay()];
            if ($('#t_hour').size()) {
                $('#t_hour').html(n);
            }

        }
        return true;
    }
}
if (typeof window.header_scroll !== "function") {

    window.header_scroll = function () {
        return true;
    }
}
if (typeof window.changeSRPLable !== "function") {

    window.changeSRPLable = function () {
        return true;
    }
}

if (typeof window.allFormsCallback !== "function") {

    window.allFormsCallback = function () {
        if (typeof parent.allFormsCallback == "function") {
            return parent.allFormsCallback();
        } else {
            console.log('allFormsCallback Not Found');
        }
    }
}
if (typeof window.static_filter_after_load_data !== "function") {

    window.static_filter_after_load_data = function () {
        return true;
    }
}

if (typeof window.stickymenu !== "function") {

    window.stickymenu = function () {
        return true;
    }
}
if (typeof window.animatedcollapse !== "function") {

    window.animatedcollapse = function () {
        return true;
    }
}
if (typeof window.animatedcollapse.addDiv !== "function") {
    window.animatedcollapse.addDiv = function () {
        return true;
    }
}
if (typeof window.animatedcollapse.init !== "function") {
    window.animatedcollapse.init = function () {
        return true;
    }
}

/*if (typeof window.header_scroll === 'undefined') {
window.header_scroll = function() {
return false;
}
}
function undefined() {
//console.log('undefined');
return false;
}
header_scroll20();*/
//console.log(window.pageName);

if (typeof $.fn.lightSlider == 'undefined') {
    $.fn.lightSlider = function () {

        return this;
    };
}
if (typeof $.fn.multislider == 'undefined') {
    $.fn.multislider = function () {

        return this;
    };
}
if (window.pageName == undefined || !window.pageName) {

    var pagename = location.pathname.split("/");

    window.pageName = pagename[1];
    if (pagename[2] != undefined && pagename[2].indexOf('adid') == -1 && pagename[2].indexOf('rand') == -1)
        window.pageName = window.pageName + '/' + pagename[2];
}
var CaptchaCallback = function () {
    $('.g-recaptcha').each(function (i, elm) {
        if (typeof grecaptcha.render == 'function' && $(elm).data('sitekey') && !$.trim($(elm).html())) {
            var widgetId = grecaptcha.render(elm, {
                'sitekey': $(elm).data('sitekey')
            });
            $(elm).data('widgetId', widgetId);
        }
    })
};
window.reset = false;
window.modalSrc = false;

window.customDetailsDisplay = '';

$(document).mouseup(function (e) {
    var isBackOrderBtn = $(e.target).hasClass('backorder-btn');
    if (isBackOrderBtn)
        return;

    var container = $(".backorder-elements");
    if (!container.is(e.target) && container.has(e.target).length === 0)
        container.hide();
});

function backOrderDropdown(btn, qty = 1) {
    $(btn).closest('div').find('.qty_needs').val(qty);
    $(btn).closest('div').children('.backorder-elements').toggle();
}

function backOrder(btn, sheetId, sheetName, obj) {
    obj = obj || {};
    obj.token = 'ekf3eqwo2384872';
    obj.sheetId = sheetId;
    obj.sheetName = sheetName;
    var url = 'https://equipmentsearch.com/admintools/google/api.php';
    obj.qty = $(btn).closest('div').children('.qty_needs').val() ?? 1;
    $(btn).closest('div').hide();
    var orderBtn = $(btn).closest('.backorder-container').find('.backorder-btn');
    orderBtn.html('Requested');
    orderBtn.attr('disabled', true);
    $.post(url, obj);
}
function genricSubmit($form) {

    var formData = $form.serializeObject();
    formData.sid = window.sid > 0 ? window.sid : formData.sid;
    formData.href = location.href;
    if ($form[0].checkValidity()) {
        Swal.showLoading();
        $.post('/helper/esc-lead-form/', formData, function (data) {

            var res;
            allFormsCallback();
            if (typeof window.gtag === 'function') {
                res = window.gtag('event', 'submit', {
                    send_to: window.send_to['GAGT'],
                    event_category: 'form',
                    event_label: formData.lead_type_ignore + ' Form'
                });

                if (window.website_settings.google_tag) {
                    res = window.gtag('event', 'conversion', {
                        'send_to': window.send_to['GT']
                    });
                }

            } else if (typeof window.ga === 'function') {
                window.ga('send', 'event', {
                    eventCategory: 'form',
                    eventAction: 'submit',
                    send_to: window.send_to['GA'],
                });
            }

            if (data.error) {
                Swal.fire({
                    icon: 'error',
                    title: data.msg,
                    timerProgressBar: true,
                    showConfirmButton: true,
                    allowOutsideClick: true,
                    timer: 1500
                })
            } else {

                Swal.fire({
                    icon: 'success',
                    title: data.msg,
                    showConfirmButton: true,
                    timer: 1500,
                    width: 400
                })
            }

        })

    } else {
        var _req_text = window.translate("all fields are required");
        Swal.fire({
            icon: 'error',
            title: _req_text,
            timerProgressBar: true,
            showConfirmButton: false,
            allowOutsideClick: false,
            timer: 2000
        })
    }
    return false;
}
function showIframeModal(src, title, width, height) {

    title = title ? title : '';
    width = width ? parseInt(width.replace('px', '')) : 750;
    height = height ? parseInt(height.replace('px', '')) : 650;

    var dialog = bootbox.dialog({
        message: '<iframe id="dialogFrame" style="width:' + width + 'px;min-height:' + height + 'px;" src="' + src + '" frameborder="0" allowfullscreen ></iframe>',
        title: title,
        callback: function () {
            dialog.find('iframe').remove();
        },
        show: true,
        backdrop: true
    }).find("div.modal-dialog").addClass('text-center').css({
        width: (width + 50) + 'px',
        height: height + 'px'
    });
    return false;
}
function showAjaxModal(src, title, width, height) {

    title = title ? title : '';
    width = width ? parseInt(width.replace('px', '')) : 750;
    height = height ? parseInt(height.replace('px', '')) : 650;

    $.get(src, function (res) {
        setTimeout(function () {
            CaptchaCallback();
        }, 1000);

        var dialog = bootbox.dialog({
            message: res,
            title: title,
            callback: function () {},
            show: true,
            backdrop: true
        }).find("div.modal-dialog").addClass('text-center').css({
            width: (width + 50) + 'px',
            height: height + 'px'
        })
            return false;

    })

}
function showNormalModal(src, title, width, height) {

    title = title ? title : '';
    width = width ? parseInt(width.replace('px', '')) + 'px' : 750;
    height = height ? parseInt(height.replace('px', '')) + 'px' : 'auto';
    window.modalSrc = src;
    bootbox.dialog({
        'message': $(src).html(),
        'title': title,
        'show': true,
        backdrop: true,
        'className': 'normalModal'
    }).find("div.modal-dialog").addClass('text-center').css({
        width: (width + 50),
        height: height
    });

    return false;
}

function launchIntoFullscreen(element) {
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    }
}

function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    }
}

function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2)
        return parts.pop().split(";").shift();
}

function setCookie(c_name, value, exhours = 24) {
    var exhours = 24;
    var exdate = new Date();
    exdate.setHours(exdate.getHours() + exhours);
    var c_value = escape(value) + ((exhours == null) ? "" : "; expires=" + exdate.toUTCString()) + "; path=/";
    document.cookie = c_name + "=" + c_value;
}

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]]; //detailsFormSubmit
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
$(function () {
    $('#searchButton, #searchReset ,.searchReset').click(function () {
        $('#searchLoading').show();
    });

    static_filter_gather_data();
});

function searchByEnterKey(e) {
    e = e || window.event;
    //console.log( e );
    return;
    if (e.keyCode == 13) {
        $('#searchButton').click();
        return false;
    }
    return true;
}
var loadReCaptcha = function () {

    if ($('#grecaptcha').length > 0) {
        var sitekey = '';

        $('#grecaptcha').each(function (i, elm) {
            if (!sitekey && $(elm).data('sitekey')) {
                var sitekey = $(elm).data('sitekey');
            }

            console.log(sitekey);
            grecaptcha.render('grecaptcha', {
                sitekey: sitekey
            });

            if (window.self !== window.top) {
                grecaptcha.reset($(elm));
            }
        })

    }

};

function htmlEncode(value) {
    if (value) {
        return $('<div/>').text(value).html();
    } else {
        return '';
    }
}

function setPageTitle(title) {
    title = title.replace('-', ' ').replace('--', '/');
    var curTitle = $.trim($('title').text());
    if (curTitle.indexOf('|') != -1) {
        if ($.trim(title))
            $('title').text(curTitle.replace(/([^\|]+)\|.+/, '$1 | ' + title));
        else
            $('title').text(curTitle.replace(/([^\|]+)\|.+/, '$1'));
    } else {
        if ($.trim(title))
            $('title').text(curTitle + ' | ' + title);
    }
}

function setPageDescription(title) {
    title = title.replace('-', ' ').replace('--', '/');
    var curTitle = $.trim($('meta[name=description]').attr("content"));
    if (curTitle.indexOf('|') != -1) {
        if ($.trim(title))
            $('meta[name=description]').attr("content", curTitle.replace(/([^\|]*)\|.+/, '$1 | ' + title));
        else
            $('meta[name=description]').attr("content", curTitle.replace(/([^\|]*)\|.+/, '$1'));
    } else {
        if ($.trim(title))
            $('meta[name=description]').attr("content", curTitle + ' | ' + title);
    }
}

function setCanonical(href) {
    href = $.trim(href);
    if (href) {
        $('link[rel=canonical]').attr("href", href);
    } else {
        var newHref = "http://" + window.location.hostname + (window.redirctPageName ? window.redirctPageName : location.pathname);
        $('link[rel=canonical]').attr("href", newHref);
    }

}
function genericLoginForm(form) {
    var data = $(form).serializeObject();
    console.log(data);
    $.post('/page/generic-login',
        data, function (res) {
        if (res.error == 1) {
            Swal.fire({
                icon: 'error',
                title: res.msg,
                showConfirmButton: false,
                timer: 3500,
                width: 400
            })
            $(form)[0].reset();
        } else if (res.error == 0) {
            Swal.fire({
                icon: 'success',
                title: res.msg,
                showConfirmButton: false,
                timer: 3500,
                width: 400
            })
            setTimeout(function () {
                location.href = '/';
            }, 2000);

        }
    }, 'json');

    return false;
}

function saveTabsStatus() {

    $('#filters .collapse').each(function (i, elm) {
        if ($(elm).attr('id')) {
            window.tabsStatus[$(elm).attr('id')] = $(elm).hasClass('in') ? 1 : 0;
        }

    })
}

function restoreTabsStatus() {
    for (var key in window.tabsStatus) {
        var value = window.tabsStatus[key];

        if ($('#' + key).length) {
            if (value > 0) {
                $('#' + key).addClass("in");
            } else {
                $('#' + key).removeClass("in");
            }
        }

    }

}
function parseQuery(queryString) {
    var query = {};
    var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');
        pair[1] = decodeURIComponent(pair[1] || '');
        //pair[1] = pair[1].replace('[','').replace(']','').split(',');
        query[decodeURIComponent(pair[0])] = pair[1];
    }
    // console.log(query);
    return query;
}
function modernFilters(formData, div) {
    if (window.isLoading == 1) {
        return;
    }
    showLoading();
    saveTabsStatus();

    formData = parseQuery(formData.replace(/[^\?]*\?/, ''));
    //console.log(formData);
    $('html,body').css({
        'cursor': 'wait'
    });

    $('#ESCAdsResponse' + div).css('min-height', "");
    $('#ESCAdsResponse' + div).css("overflow", "visible");
    $.post('/helper/apply-filters/?sid=0&pcompid=' + $('#ESCAdsResponse' + div).attr('rel'), formData, function (data) {

        var jsFile = $(data).find('inject').html();
        if ($.trim(jsFile)) {
            $.getScript($.trim(jsFile), function () {
                console.log('JS-LOADED');
                closeLoading();
            });
        }

        $('#ESCAdsResponse' + div).find('#products').html($(data).find('#products').html());
        $('#ESCAdsResponse' + div).find('#filters').html($(data).find('#filters').html());

        $.fn.matchHeight._update();

        setTimeout(function () {
            onAdsListLoad();
        }, 2000)
        $('html,body').css({
            'cursor': 'default'
        });
        $('#ESCAdsResponse' + div).removeAttr("style");

        restoreTabsStatus();

    });
}

function modernFilterEvent_Static_DetectChanges(sender, isSlider = false, input = null) {
    var isChanged = true;

    if (isSlider) {
        var a1 = $(input).slider("option", "values").join('-');
        var a2 = $('.staticFilterContainer').data($(input).attr('id').replaceAll('-', '_'))?.val;
        isChanged = a1 != a2;
        //console.log('ttttttttttt', $(input).attr('id').replaceAll('-', '_'), a1, a2, isChanged);
    } else {
        isChanged = $('.staticFilterContainer').data($(input).attr('id'))?.status != $(input).is(':checked');
        //$('.staticFilterContainer').data($(input).attr('id'), {status: $(input).is(':checked'), val: $(input).val()});

        $.each($('.staticFilterContainer').data(), (e, i) => {
            //console.log(e, i);
        });
    }

    isChanged = true; // TODO::
    modernFilterEvent_Static(sender);
    //$('.apply_btn_' + sender).css({visibility: isChanged ? 'visible':'hidden'});

}

function modernFilterEvent_Static(sender, isSlider = false, input = null) {
    $('.apply_btn_' + sender).css({
        visibility: 'hidden'
    });
    static_filter_gather_data();
    modernFilterEvent(sender, isSlider, true);
}

function static_filter_gather_data() {
    setTimeout(() => {
        $('.staticFilterContainer').removeData();
        $('[class*="static_filter_gather_data"] input').each((i, e) => {
            $('.staticFilterContainer').data($(e).attr('id'), {
                status: $(e).is(':checked'),
                val: $(e).val()
            });
        });

        $('[id*="slider-range-"]').each((i, e) => {
            //console.log($(e).attr('id').replaceAll('-', '_'), $(e).slider( "option", "values" ));
            //$('.staticFilterContainer').data($(e).attr('id').replaceAll('-', '_'), {status: 'slider', val: $(e).slider( "option", "values").join('-')});
        });
        //console.log($('.staticFilterContainer').data());
    }, 500);
}

function static_filter_after_load_data($keywords = '') {
    fill_active_filters($keywords);
}

function activeFilterRemove(elem, cat, itemId, type, id) {
    // console.log([elem, cat, itemId, type,id]);
    var id = id ? id : itemId;
    if (id) {
        $(elem).closest('.static-filter-active-item').hide();
    } else {
        $(elem).closest('.static-filter-active-container').find('.static-filter-active-item').hide();
    }

    const $cat = $(elem).closest('.static-filter-active-container').find('.static-filter-active-item:visible');

    if ($cat.length <= 0)
        $(elem).closest('.static-filter-active-container').hide();

    const $parent = $(`.filter-collapse-container.${cat}`);
    var $items = null;

    if (type == 'checkbox') {
        //$items = id ? $(`#${id}`) : $parent.find(`input:checked`);
        $items = id ? $("#" + $.escapeSelector(id)) : $parent.find(`input:checked`);
        $items.prop("checked", false);
    } else if (type == 'slider') {
        if (id) {
            // Sender = Item
            elem = $(`#${id}`);
            const min = $(elem).slider("option", "min");
            const max = $(elem).slider("option", "max");
            $(elem).slider("values", [min, max]);
        } else {
            // Sender = Category
            elem = $(elem).closest('.static-filter-active-container').find('.static-filter-active-item span.icon').click();
        }
    } else if (type == 'keywords') {
        $('#search').val('');
    }

    // $('#'+id).prop('checked',false);//.trigger('change');
    modernFilterEvent("");
    //modernFilterEvent_Static('bodyStyle')
}

function fill_active_filters($keywords = "") {
    var activeFilters = {};

    // Keywords filter
    if ($keywords) {
        const label = 'keywords';
        if (!activeFilters[label]) {
            activeFilters[label] = [];
        }
        activeFilters[label].push({
            label: $keywords.trim(),
            id: 'search',
            type: label
        });
    }

    // Checkbox filters
    $.each($('.modernFilterCheckBox'), (index, elem) => {
        const label = $(elem).closest('.filter-collapse-container')?.find('a')?.text()?.trim();
        $.each($('input:checked', elem), (i, e) => {
            const item = $(e).parent('label');
            //console.log(item);
            if (item?.length) {
                if (!activeFilters[label]) {
                    activeFilters[label] = [];
                }
                activeFilters[label].push({
                    label: item.text()?.trim(),
                    id: item.find('input').attr('id'),
                    type: 'checkbox'
                });
            }
        });
    });

    // Sliders filters
    $('[id*="slider-range-"]').each((i, elem) => {
        const label = $(elem).attr('name')?.trim();
        const min = $(elem).slider("option", "min");
        const max = $(elem).slider("option", "max");
        const selected_min = $(elem).slider("values", 0);
        const selected_max = $(elem).slider("values", 1);
        // console.log(selected_min, selected_max, min, max);

        if (min != selected_min || max != selected_max) {
            if (!activeFilters[label]) {
                activeFilters[label] = [];
            }

            activeFilters[label].push({
                //${SellableItems.paymentsCurrency}
                label: `${selected_min} - ${selected_max}`,
                id: $(elem).attr('id'),
                type: 'slider'
            });
        }
    });

    //console.log(activeFilters);
    $('.static-filter-active-main').empty();

    if ($.isEmptyObject(activeFilters)) {
        $('.active-filter-container').hide();
    } else {
        $('.active-filter-container').show();
        var tmp = '';
        var childCount = 0;

        $.each(activeFilters, (_index, _elem) => {
            tmp += `
				<div class="row static-filter-active-container">
                    <div class="static-filter-active-grp">
                      <span class="static-filter-active-title">${_index}</span>
                      <span class="pull-right active-filter-category">
						  <i class="fal fa-times-circle" title="Remove" onclick="activeFilterRemove(this, '${_index}', false, '${_elem[0].type}', '${_elem[0].id}')"></i>
					  </span>
					</div>
				`;

            $.each(_elem, (_index2, _filter) => {
                childCount += 1;
                tmp += `
                    <div class="static-filter-active-item">
                      <div class="icon">
						  <span class="glyphicon glyphicon-remove icon" title="Remove" onclick="activeFilterRemove(this, '${_index}', '${_filter.id}', '${_filter.type}', '${_filter.id}')"></span>
					  </div>
					  <div class="col-xs-10">${_filter.label}</div>
                    </div>
					`;
            });

            tmp += `
					</div>
				`;
        });

        $("#static-filter-count").text(childCount);
        $(".static-filter-active-main").append(tmp);
    }
}

function modernFilterEvent(sender = '', isSlider = false, isStaticFilter = false) {

    window.reset = false;
    if (window?.customFilter?.search != undefined && window?.customFilter?.search == 'all') {
        window.customFilter.search = '';
        window.reset = true;
        window.filtersOrder = [];
        var div = $('.ESCAdsResponse').attr('id').replace('ESCAdsResponse', '');
        modernFilters('/' + window.pageName + '/', div);

    } else {
        //console.log(filterParams);
        var filterParams = [];
        //console.log(filterParams);
        if (sender != '' && window?.customFilter?.page && window?.customFilter?.page > 1) {
            window.customFilter.page = 1;
        }
        //console.log(window.customFilter);
        //console.log(filterParams);
        $('.modernFilter').each((index, elem) => {
            var selected = $(elem).find('input:checked').toArray();
            if (selected.length) {
                filterParams.push('filters[' + $(elem).attr('name') + ']=' + selected.map(item => {
                        return encodeURI($(item).val().replaceAll(',', '%7C'))
                    }).join(",").replaceAll('&', '%26') + '');
            }
        });
        //console.log(filterParams);
        $('.modernFilterSelect').each((index, elem) => {
            // var selected = $(elem).val();
            filterParams.push('filters[' + $(elem).attr('name') + ']=' + $(elem).val() + '');
        });
        //console.log(filterParams);
        $.each(window.fitmentItems, (index, elem) => {
            filterParams.push('filters[fitment][' + index + ']=' + elem);
        });
        //console.log(filterParams);
        $.each(window?.customFilter, (index, elem) => {
            filterParams.push('filters[' + index + ']=' + elem);
        });
        //console.log(filterParams);
        $('[id*="slider-range-"]').each((index, elem) => {
            const min = $(elem).slider("option", "min");
            const max = $(elem).slider("option", "max");
            const selected_min = $(elem).slider("values", 0);
            const selected_max = $(elem).slider("values", 1);
            // console.log(selected_min, selected_max, min, max);

            if (min != selected_min || max != selected_max) {
                filterParams.push('filters[' + $(elem).attr('name') + ']=' + encodeURI(selected_min + ',' + selected_max));
            }
        });
        //console.log(filterParams);
        $('.modernFilterText').each((index, elem) => {
            //console.log($(elem).val(),$(elem));
            $(elem).val() && filterParams.push('filters[' + $(elem).attr('name') + ']=' + encodeURI($(elem).val()));
        });

        //console.log(filterParams);
        var url = filterParams.length ? '/' + window.pageName + '/?filters[lastFilter]=' + sender + '&modernFilter=true&isStaticFilter=' + isStaticFilter + '&' + filterParams.join('&') : '/' + window.pageName + '/';
        //console.log(url);
        callLoadContent(url);
    }
}

function loadContent(locHash) {

    if (locHash.indexOf('?') !== -1) {

        var div = $('.ESCAdsResponse').attr('id').replace('ESCAdsResponse', '');
        //console.log(locHash);
        modernFilters(locHash, div);
    } else {
        tlocHash = locHash.split("/");

        if (window.escComps == "escComp" && isNumeric(locHash.replace("#", ""))) {

            if (locHash.length > 1) {

                if (locHash.search("RANDOM") >= 0) {
                    adId = locHash.replace("#RANDOM", "");
                    getRandomAdDetails(adId, window.detailsStyle);
                } else if (locHash.search("POS") >= 0) {
                    adId = locHash.replace("#", "");
                    location.hash = "";
                    //alert(adId);
                    $("." + adId).click();
                } else {
                    adId = locHash.replace("#", "");
                    getAdDetails(adId, window.detailsStyle, window.quantityShow, window.odometerShow);
                }
            }
        } else if (locHash.indexOf('subname') != -1) {
            locHash = locHash.split("/");
            if (isNumeric(locHash[1])) {
                setPageTitle(locHash[3] + " for Sale");
                setPageDescription(locHash[3] + " for Sale");
                var subid = locHash[1];
                var div = $('#sub_' + subid).size() > 0 ? $('#sub_' + subid).attr('rel') : $('.ESCAdsResponse').attr('id').replace('ESCAdsResponse', '');
                //console.log(div);
                filterAds("subcategoryId", subid, div);
            }

        } else if (locHash.indexOf('search') != -1) {

            locHash = locHash.split("/");
            //alert(locHash[1]);
            if (locHash[1]) {
                $('.adsSearchKeywords').val(decodeURIComponent(locHash[1]));
                searchAds('', locHash[1]);
                return;
            }

        } else if (locHash.indexOf('categoryId') != -1) {
            locHash = locHash.split("/");
            if (isNumeric(locHash[1])) {
                var div = $('.ESCAdsResponse').attr('id').replace('ESCAdsResponse', '');
                var catid = locHash[1];
                if (catid == 0) {
                    filterAds("categoryId", 0, div);
                    setPageTitle('');
                    setPageDescription('');
                } else {
                    setPageTitle(locHash[3]);
                    setPageDescription(locHash[3]);
                    //console.log(div);
                    filterAds("categoryId", catid, div);
                }
            }

        } else if (locHash.indexOf('page') != -1) {
            locHash = locHash.split("/");
            //console.log(locHash);
            if (isNumeric(locHash[1])) {
                var pagenum = locHash[1];
                setPageTitle('Page :' + pagenum);
                filterAds("page", pagenum, window.responseDiv);
            }
        } else if (locHash.indexOf('adid') != -1) {
            locHashAr = locHash.split("/");

            var adId = locHashAr[1];
            getAdDetails(adId, window.detailsStyle, window.quantityShow, window.odometerShow);

        } else if (locHash.indexOf('randad') != -1) {
            locHashAr = locHash.split("/");

            var adId = locHashAr[1];
            getRandomAdDetails(adId, window.detailsStyle);

        } else if (tlocHash[0] != undefined && tlocHash[1] != undefined && tlocHash[3] != undefined) {
            locHash = locHash.split("/");
            var div = $('.ESCAdsResponse').attr('id').replace('ESCAdsResponse', '');
            var catid = locHash[1];
            setPageTitle(locHash[3]);
            setPageDescription(locHash[3]);
            //console.log(div);
            filterAds(locHash[0], locHash[1], div);

        } else if ((locHash == '/' || locHash == "" || window.reset == true) && $('.ESCAdsResponse').size() > 0) {
            var div = $('.ESCAdsResponse').attr('id').replace('ESCAdsResponse', '');
            filterAds("search", 'all', div);
            setPageTitle('');
            setPageDescription('');
            $('select').removeClass('selectBorder');
        }
    }
}

function onAdsListLoad() {
    if ($('.single_row').size() > 0)
        return;
    var new_container_height = 0;
    $('.thumbnail').each(function (i, elm) {
        if ($(elm).outerHeight() > new_container_height)
            new_container_height = $(elm).height();

    })
    if (new_container_height > 0)
        $('.thumbnail').css('height', (new_container_height + 25) + "px");

    //alert(new_container_height);
    //console.log( new_container_height );
    modernFilterHideUlItemsFun();
}

function postSize(height) {
    var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);

    if (document.body && typeof target != undefined && document.body.scrollHeight) {
        target.postMessage(height, "*");
    }
}
if (window.self !== window.top) {
    setInterval(function () {
        //$('html, body', window.parent.document).animate({scrollTop:0}, 'slow');
        var contentHeight = $("#CenterDiv").height() + 100;
        //console.log(contentHeight);
        postSize(contentHeight);
    }, 500);

}

window.addEventListener('hashchange', function () {
    var locHash = location.hash.replace("#", "");
    loadContent(locHash);

});

function callLoadContent(href) {
    //console.log(href);

    var newHref = href.split('/');
    newHref.splice(0, 1);
    newHref.splice(0, 1);
    if (window.redirctPageName) {
        newHref.splice(0, 1);
    }
    newHref = newHref.join('/');
    ///console.log(newHref);
    if (window.reset == true && location.href.indexOf('fitment') !== -1) {
        location.href = location.href.replace(/\?.*/, '');
    } else {
        //console.log(newHref);
        //console.log(href);
        loadContent(newHref);
        // HISTORY.PUSHSTATE
        history.pushState(null, href, href);
    }

}
$(window).on('load', function () {

    setTimeout(function () {
        $('iframe').each(function (i, elm) {
            if ($(elm).data('src') != undefined && !$(elm).hasClass("skip")) {
                $(elm).attr('src', $(elm).data('src'));
            }
        })
    }, 1500);

    $('iframe.skip').each(function (i, elm) {
        if ($(elm).data('src') != undefined) {
            $(elm).attr('src', $(elm).data('src'));
        }
    });

    setTimeout(function () {
        // THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
        window.onpopstate = function (event) {
            //console.log( "pathname: " + location.pathname );
                         var newHref = location.pathname;
            newHref = newHref.split('/');
            newHref.splice(0, 1);
            newHref.splice(0, 1);
            if (window.redirctPageName) {
                newHref.splice(0, 1);
            }
            newHref = newHref.join('/');
            //console.log( "newHref: " + newHref );
            if (!newHref)
                location.reload();
            else
                loadContent(newHref);
        };

    }, 2000);
});

function modernFilterHideUlItemsFun() {
    $('ul.modernFilterHideUlItems').each(function () {
        if ($(this).children('li').length > 5 && !$('.loadMore', this).length) {
            $(this).children('li:lt(5)').css({
                display: 'flex'
            });
            $(this).append('<button class="loadMore">Load More</button>');
        }
    });
    $('ul.modernFilterHideUlItems').on("click", '.loadMore', function () {
        $(this).parent('.modernFilterHideUlItems').children('li:gt(4)').css({
            display : 'flex'
        }); // use gt instead of lt
        $(this).removeClass('loadMore').addClass('loadLess').text('Load Less');
    });
    $('ul.modernFilterHideUlItems').on("click", '.loadLess', function () {
        $(this).parent('.modernFilterHideUlItems').children('li:gt(4)').css({
            display : 'none'
        }); // use gt instead of lt
        $(this).removeClass('loadLess').addClass('loadMore').text('Load More');
    });
}

$(function () {
    if ($('#t_hour').size() > 0) {
        t_hours();
    }
    $(document).on('hidden.bs.modal', function (e) {
        if (window.modalSrc) {
            $(window.modalSrc).html($(e.target).find('.bootbox-body').html());
            window.modalSrc = false;
        }
    });

    $(document).on('click', '.pushstate', function (e) {

        e.preventDefault();
        if ($(this).parents('.pagination').size() && window.paramUrl.indexOf('legacy') == -1) {
            var pageNum = $(this).attr('href').replace(/.+\/page\/(\d+).*/, '$1');
            window.customFilter['page'] = pageNum;
            return modernFilterEvent();
        } else {
            if ($('.ESCAdsResponse').size() && $(this).parents('.pagination.dark').size()) {
                $('html,body').animate({
                    scrollTop: $('.ESCAdsResponse').offset().top
                }, 1000);
            }

            var href = $(this).attr("href");
            if (href.indexOf('/adid/') !== -1) {
                location.href = href;
            } else {
                callLoadContent(href);
            }
            return false;
        }

    });

    /*window.addEventListener('popstate', function(event) {


    //console.log( "pathname: " + location.pathname,event );
        var newHref = location.pathname;
    newHref = newHref.split( '/' );
    newHref.splice( 0, 1 );
    newHref.splice( 0, 1 );
    if ( window.redirctPageName ) {
    newHref.splice( 0, 1 );
    }
    newHref = newHref.join( '/' );
    //console.log( "newHref: " + newHref );
    if ( !newHref )
    location.reload();
    else
    loadContent( newHref );
        }, false);*/
    if ($('#LeftDiv,#RightDiv,#CenterDiv').length) {
        $('#LeftDiv,#RightDiv,#CenterDiv').matchHeight();
    }

    // Basem
    $('#topPanel textarea').css({
        'color' : '#000'
    });

    $.ajaxSetup({
        cache : false
    });
         //window.ADDOC = new Array();
    $("img[src$='.pdf'],img[src$='.pptx']").each(function (i, elm) {

        var href = $(elm).attr('src');
        $(elm).attr('src', 'https://equipmentsearch.com/images/downloads3.png');
        /*     adId = $(elm).parent().attr('rel').replace("RANDOM","");
        window.ADDOC[adId]=href;*/
    })

    $(".youtube").click(function () {
        var $this = $(this);
        if ($this.attr('vwidth')) {
            var width = $this.attr('vwidth');
        } else {
            var width = 680;
        }
        if ($this.attr('vheight')) {
            var height = $this.attr('vheight');
        } else {
            height = 495;
        }
        $.fancybox({
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'title': this.title,
            'width': width,
            'height': height,
            'href': $this.attr('href').replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type': 'swf',
            'swf': {
                'wmode': 'transparent',
                'allowfullscreen': 'true'
            }
        });

        return false;
    });

    $(document).on('click', '.lightboxs', function () {
        var src = $(this).attr('href');
        var title = $(this).attr('title');
        var popuptype = $(this).data('popuptype');
        var width = '850';
        var height = '800';
        console.log(popuptype);
        if (popuptype == "ajax") {
            showAjaxModal(src, title, width, height);
        } else {
            showIframeModal(src, title, width, height);
        }

        return false;
    });

    $(document).on('click', '.lightbox', function () {
        var src = $(this).attr('href');
        var title = $(this).attr('title') ? $(this).attr('title') : $(this)[0].innerText;
        var width = '1500';
        var height = '800';
        var popuptype = $(this).data('popuptype');
        console.log(popuptype);
        if (popuptype == "ajax") {
            showAjaxModal(src, title, width, height);
        } else {
            showIframeModal(src, title, width, height);
        }
        //console.log([src, title, width, height]);
        return false;
    });

    /*var border = RUZEE.ShadedBorder.create({ corner:8, shadow:16,  border:2 });
    border.render('siteMenu');*/

    $('ul.mainMenu').css('background-color', $('.mainMenu > li:first').css('background-color'));

    //$(".curved").corner();
    //$("ul.sf-menu > li:last").corner("round 15px tr br");


    window.sid =  0 ;
    window.pageId =  49761 ;

    $('.insertedcss').css('width', 'auto');
    // $('.curved').cornerz();
    if (!$.browser.msie) {
        $('object').append('<param name="wmode" value="transparent">').find('embed').attr('wmode', 'transparent')
    } else {

        if ($('iframe').size() > 0) {
            $('iframe').each(function (i, elm) {

                var src = $(elm).attr('src');
                var add = src.indexOf('?') == -1 ? src + '?wmode=transparent' : src + '&wmode=transparent';
                $(elm).attr('src', add);

            })
        }
    }

    if ($('#theForm').size() > 0) {
        $('input,select,textarea,radio').each(function (i, elm) {

            //$(this).attr('class','');
            var meta = $(elm).clone().metadata({
                type: 'attr',
                name: 'json'
            })

                $(this).attr('name', $(this).parent().parent('tr').find('th').find('label').html());
            if ($(this).attr('name')) {
                if (meta.required !== '0') {

                    $(this).addClass('required');
                }
                if (meta.rule !== '0') {

                    $(this).addClass(meta.rule);

                }
                if (meta.rule == 'numberic') {

                    $(this).addClass('number');
                }
                if (meta.err_msg) {

                    $(this).attr('title', meta.err_msg)
                }
                if (meta.init_val) {

                    $(this).val(meta.init_val)
                }
            }

        });

        var formMeta = $("#theForm").clone().metadata({
            type: 'attr',
            name: 'json'
        })

            if (formMeta.font_color) {
                //  alert(formMeta.font_color);
                $("#theForm").css('color', formMeta.font_color);
            }
            if (formMeta.back_color) {

                $("#theForm").css('background-color', formMeta.back_color);

            }
            $("#theForm").validate({
                submitHandler: function () {
                    var g_recaptcha_response = '';
                    if ($("[data-size='invisible']").length > 0 ) {
                        grecaptcha.execute();
                    }
                    setTimeout(function () {
                        $.each($('.g-recaptcha-response'), function (i, elm) {
                            if ($(elm).val()) {
                                g_recaptcha_response = $(elm).val();
                            }
                        })
                    

                    if (!g_recaptcha_response && $('#theForm').find('#grecaptcha').size() > 0) {
//this
                        Swal.fire({
                            icon: 'error',
                            title: "You must verfiy the CAPTCHA",
                            timerProgressBar: true,
                            showConfirmButton: true,
                            allowOutsideClick: true,
                            timer: 1500
                        })
                        return false;
                    }

                    $('#theForm').ajaxSubmit({
                        type: 'POST',
                        url: '/helper/mailformtraget',
                        success: function (data) {
                            allFormsCallback();
                            alert("Your message has been sent");
                        },
                        iframe: true,
                        data: {
                            subject: formMeta.email_subject,
                            email_from: formMeta.email_from,
                            email_to: formMeta.email_to,
                            g_recaptcha_response: g_recaptcha_response
                        }
                    });

                }, 500)
				
				}
            })

            $('#form1Submit').removeAttr('onclick');

    }

    if ($('.mailForm').size() > 0 && $('.mailForm').attr('json')) {
        $form = $(".mailForm");
        $form.validate({
            submitHandler: function () {
                var formMeta = $form.clone().metadata({
                    type: 'attr',
                    name: 'json'
                })
                    $form.ajaxSubmit({
                        type: 'POST',
                        url: '/helper/mailformtraget',

                        success: function (data) {
                            allFormsCallback();
                            Swal.fire({
                                icon: 'success',
                                title: 'Sent Successfully',
                                timerProgressBar: true,
                                showConfirmButton: false,
                                allowOutsideClick: false,
                                timer: 2000
                            })
                        },
                        iframe: false,
                        data: {
                            subject: formMeta.email_subject,
                            email_from: formMeta.email_from,
                            email_to: formMeta.email_to
                        }
                    });
                return false;
            }
        })

    }

    if ($('.mailForm').size() > 0 && $('.mailForm').attr('json')) {
        $form = $(".mailForm");
        $form.validate({
            submitHandler: function () {
                var formMeta = $form.clone().metadata({
                    type: 'attr',
                    name: 'json'
                })
                    $form.ajaxSubmit({
                        type: 'POST',
                        url: '/helper/mailformtraget',

                        success: function (data) {
                            allFormsCallback();
                            Swal.fire({
                                icon: 'success',
                                title: 'Sent Successfully',
                                timerProgressBar: true,
                                showConfirmButton: false,
                                allowOutsideClick: false,
                                timer: 2000
                            })
                        },
                        iframe: false,
                        data: {
                            subject: formMeta.email_subject,
                            email_from: formMeta.email_from,
                            email_to: formMeta.email_to
                        }
                    });
                return false;
            }
        })

    }

    if ($("#TrilliumForm").size() > 0) {

        $("#TrilliumForm").validate();
        $("#CalcLoan").click(function () {

            if ($("#TrilliumForm").valid()) {
                $.post("/cgi-bin/newcalc.cgi", $("#TrilliumForm").serialize(), function (data) {
                    $(".loanCalcResult").html(data);

                })
            } else {
                return false;
            }

        })
    }
})

/*Rollover by Dapina*/

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function imageholderclass() {
    this.over = new Array();
    this.down = new Array();
    this.src = new Array();
    this.store = store;

    function store(src, down, over) {
        var AL = this.src.length;
        this.src[AL] = new Image();

        this.src[AL].src = src;
        this.over[AL] = new Image();
        this.over[AL].src = over;
        this.down[AL] = new Image();
        this.down[AL].src = down;
    }
}

var ih = new imageholderclass();
var mouseisdown = 0;

function preloader(t) {
    for (i = 0; i < t.length; i++) {
        if (t[i].getAttribute('srcover') || t[i].getAttribute('srcdown')) {

            storeimages(t[i]);
            var checker = '';
            checker = (t[i].getAttribute('srcover')) ? checker + 'A' : checker + '';
            checker = (t[i].getAttribute('srcdown')) ? checker + 'B' : checker + '';

            switch (checker) {
            case 'A':
                mouseover(t[i]);
                mouseout(t[i]);
                break;
            case 'B':
                mousedown(t[i]);
                mouseup2(t[i]);
                break;
            case 'AB':
                mouseover(t[i]);
                mouseout(t[i]);
                mousedown(t[i]);
                mouseup(t[i]);
                break;
            default:
                return;
            }

            if (t[i].src) {
                t[i].setAttribute("oldsrc", t[i].src);
            }
        }
    }
}

function mouseup(t) {
    var newmouseup;
    if (t.onmouseup) {
        t.oldmouseup = t.onmouseup;
        newmouseup = function () {
            mouseisdown = 0;
            this.src = this.getAttribute("srcover");
            this.oldmouseup();
        }

    } else {
        newmouseup = function () {
            mouseisdown = 0;
            this.src = this.getAttribute("srcover");
        }
    }
    t.onmouseup = newmouseup;
}

function mouseup2(t) {
    var newmouseup;
    if (t.onmouseup) {
        t.oldmouseup = t.onmouseup;
        newmouseup = function () {
            mouseisdown = 0;
            this.src = this.getAttribute("oldsrc");
            this.oldmouseup();
        }
    } else {
        newmouseup = function () {
            mouseisdown = 0;
            this.src = this.getAttribute("oldsrc");
        }
    }
    t.onmouseup = newmouseup;
}

function mousedown(t) {
    var newmousedown;
    if (t.onmousedown) {
        t.oldmousedown = t.onmousedown;
        newmousedown = function () {
            if (mouseisdown == 0) {
                this.src = this.getAttribute("srcdown");
                this.oldmousedown();
            }
        }
    } else {
        newmousedown = function () {
            if (mouseisdown == 0) {
                this.src = this.getAttribute("srcdown");
            }
        }
    }
    t.onmousedown = newmousedown;
}

function mouseover(t) {
    var newmouseover;
    if (t.onmouseover) {
        t.oldmouseover = t.onmouseover;
        newmouseover = function () {
            this.src = this.getAttribute("srcover");
            this.oldmouseover();
        }
    } else {
        newmouseover = function () {
            this.src = this.getAttribute("srcover");
        }
    }
    t.onmouseover = newmouseover;
}

function mouseout(t) {
    var newmouseout;
    if (t.onmouseout) {
        t.oldmouseout = t.onmouseout;
        newmouseout = function () {
            this.src = this.getAttribute("oldsrc");
            this.oldmouseout();
        }
    } else {
        newmouseout = function () {
            this.src = this.getAttribute("oldsrc");
        }
    }
    t.onmouseout = newmouseout;
}

function storeimages(t) {
    var s = (t.getAttribute('src')) ? t.getAttribute('src') : '';
    var d = (t.getAttribute('srcdown')) ? t.getAttribute('srcdown') : '';
    var o = (t.getAttribute('srcover')) ? t.getAttribute('srcover') : '';
    ih.store(s, d, o);
}

function preloadimgsrc() {
    if (!document.getElementById)
        return;
    var it = document.getElementsByTagName('IMG');
    var it2 = document.getElementsByTagName('INPUT');
    preloader(it);
    preloader(it2);
}

if (window.addEventListener) {
    window.addEventListener("load", preloadimgsrc, false);
} else {
    if (window.attachEvent) {
        window.attachEvent("onload", preloadimgsrc);
    } else {
        if (document.getElementById) {
            window.onload = preloadimgsrc;
        }
    }
}

function compareSelected(id) {
    $('.compareButtonDiv').show();
    window.compare = String(id);
    window.compareItems = 1;
    $('.adsCompareDiv').each(function (i) {
        if ($(this).attr('AdId') != id) {
            $(this).html('<input type="button" value="Add" onClick="addCompare(' + $(this).attr('AdId') + ')" />');
        } else {
            $(this).html('<input type="button" value="Remove" onClick="removeCompare(' + id + ')" />');
        }
    });
}

function addCompare(id) {
    var compare = window.compare;
    compare += "-" + id;
    window.compare = compare;
    window.compareItems++;
    $('.adsCompareDiv').each(function (i) {
        if ($(this).attr('AdId') == id) {
            $(this).html('<input type="button" value="Remove" onClick="removeCompare(' + id + ')" />');
        }
    });
}

function removeCompare(id) {
    var compare = window.compare;
    compare = compare.replace("-" + id, "");
    window.compare = compare;
    window.compareItems--;
    //alert(window.compareItems);
    if (window.compareItems == 0) {
        $('.compareButtonDiv').hide();
        window.compare = "";
        $('.adsCompareDiv').each(function (i) {
            $(this).html('<input type="checkbox" style="border:0px" value="' + $(this).attr('AdId') + '" name="compare[]" class="adsSelectCheckbox" onChange="compareSelected(' + $(this).attr('AdId') + ')"/>');
        });
    } else {
        $('.adsCompareDiv').each(function (i) {
            if ($(this).attr('AdId') == id) {
                $(this).html('<input type="button" value="Add" onClick="addCompare(' + $(this).attr('AdId') + ')" />');
            }
        });
    }

}

function doCompare() {
    //return;
    var compare = window.compare;
    //alert(compare);
    var pos = compare.search("-");
    if (pos >= 0) {
        window.compare = "";
        location.href = location.href + "#" + compare;
        getAdDetails(compare, window.detailsStyle);
    } else {
        alert('You Have to Select 2 Ads or more');
    }

}

function pickCompareAd(id) {
    //return;
    location.href = window.hRef + "#" + id;
    getAdDetails(id, window.detailsStyle);
}

function changeBack(div, color) {
    //alert(color);
    $("." + div + "Back").css('background-color', color);
}

function goToPage(x, div) {
    //alert('#ESCAdsResponse'+div);
    $('#ESCAdsResponse' + div).css('min-height', "");
    $('#ESCAdsResponse' + div).css("overflow", "visible");

    $('#ESCAdsResponse' + div).load('/helper/escadspaging/page/' + x)
}

function searchAds(div, value) {
    //alert(div);
    div = div || $('.ESCAdsResponse').attr('id').replace('ESCAdsResponse', '');

    value = $('.adsSearchKeywords').size() > 0 ? encodeURIComponent(htmlEncode($.trim($('.adsSearchKeywords').val()))) : encodeURIComponent(htmlEncode($.trim(value)));
    if (!$.trim(value))
        return;

    if (window.sid == 1000709 && window.pageName.toLowerCase().indexOf('equipment') == -1 && window.pageName.toLowerCase().indexOf('all-used-items') == -1) {
        location.href = '/All-Used-Items/search/' + value + '/';
        return;
    } else if (window.sid == 1000754 && window.pageName.toLowerCase().indexOf('all-used-items') == -1) {
        location.href = '/all-used-items/search/' + value + '/';
        return;
    }
    var href = '/' + window.pageName + '/search/' + value + '/';
    //callLoadContent(href);
    history.pushState(null, href, href);

    var locHash = href; //.replace(window.pageName,'');
    locHash = locHash.split("/");
    //console.log( locHash );

    if ($.trim(value)) {
        setPageTitle("Search Result for :" + value);
        setPageDescription("Search Result for :" + value);
        var query = locHash[1];
        if (value && $('.adsSearchKeywords').val() != 'Enter search terms separated by comma') {
            var formData = $('#ESCAdsResponse' + div).find('select').serializeObject();
            window.searchValue = htmlEncode(decodeURIComponent(value));
            filterAds("search", value, div, formData);
        } else {
            window.searchValue = '';
            filterAds("search", "all", div);
        }

    }

}

function cLoan(randDivId) {
    var $target = $('#' + randDivId);
    var $form = $target.find('form');
    var formData = $form.serializeObject();
    if (formData.amount > 100) {
        $.post('/helper/loan-Schedule-Comp', formData, function (res) {
            $target.find('.response').html(res);
        })
    }

}

function filterAds(filter, value, div, formData) {
    if (window.paramUrl.indexOf('legacy') === -1) {
        window.customFilter[filter] = value;
        // console.log([filter, value, div, window.customFilter]);
        modernFilterEvent();
        return;
    } else {
        window.hRefHash = location.hash;
        formData = formData || $('#ESCAdsResponse' + div).find('select').serializeObject();
        if (jQuery.trim(value) != "" && jQuery.trim(value) != undefined && value != "Entersearchtermsseparatedbycomma") {
            $('html,body').css({
                'cursor': 'wait'
            });
            var order = $('#order').val() == undefined ? '' : $('#order').val();
            if (window.reset == true) {
                filter = 'reset';
                value = 1;
                window.reset = false;
                formData = {};
                window.searchValue = '';
            }
            value = String(value);
            //var url = '/helper/escadsfilter/?' + filter + '=' + value.replace( /\./g, '%2E' ) + '&filters[order]=' + order + '&pcompid=' + $( '#ESCAdsResponse' + div ).attr( 'rel' ) + ( window.searchValue ? '&search=' + window.searchValue : '&search=' );
            var url = '/helper/escadsfilter/?' + filter + '=' + value.replace(/\./g, '%2E') + '&order=' + order + '&pcompid=' + $('#ESCAdsResponse' + div).attr('rel') + (window.searchValue ? '&search=' + window.searchValue : '&search=');
            $('#ESCAdsResponse' + div).css('min-height', "");
            $('#ESCAdsResponse' + div).css("overflow", "visible");
            $.post(url, formData, function (data) {

                $('#ESCAdsResponse' + div).parents('.contentComp').html(data);

                $.fn.matchHeight._update();

                setTimeout(function () {
                    onAdsListLoad();
                }, 2000)
                $('html,body').css({
                    'cursor': 'default'
                });
                $('#ESCAdsResponse' + div).removeAttr("style");
                if (filter == "search") {
                    window.filterType = "Search";
                    if (value == "all") {
                        window.searchValue = "";
                    }
                } else {
                    window.filterType = "";
                }

                $('.adsSearchKeywords').val(window.searchValue);
                $("select[name='" + filter + "']").addClass('selectBorder');

            });
        } else {
            alert("Please enter at least 1 word in the search field.");
        }
        //console.log('URL From font_end.js.php', url);
    }
}

function highlightValues(value, div) {
    // $('#ESCAdsResponse'+div).text($('#ESCAdsResponse'+div).text().replace((new RegExp(value, 'gi')),'adsSearchResults'+value));
    $('#ESCAdsResponse' + div).html($('#ESCAdsResponse' + div).html().replace((new RegExp(value, 'gi')), '<span class="adsSearchResults">' + value + '</span>'));
}

function unloadEscAds() {
    return;
    $('.unload').load("/helper/unloadescitems");
}

function ScrollToElement(theElement) {

    var selectedPosX = 0;
    var selectedPosY = 0;

    while (theElement != null) {
        selectedPosX += theElement.offsetLeft;
        selectedPosY += theElement.offsetTop;
        theElement = theElement.offsetParent;
    }

    window.scrollTo(selectedPosX, selectedPosY);

}

function backTo(url) {
    history.back();
    return;
    var newHref = location.pathname;
    //console.log( location.pathname, history.length );
    //console.log( newHref, newHref.split( '/' ) );
    //setPageTitle('');
    //setPageDescription('');

    if (newHref.indexOf('adid') != -1) {
        var newHref = location.pathname;
        newHref = newHref.split('/');
        newHref = '/' + newHref[1] + '/';

        location.href = newHref;
    } else if (history.length > 1 && newHref.indexOf('randad') == -1) {

        history.back();
    } else {
        var newHref = location.pathname;
        newHref = newHref.split('/');
        newHref = '/' + newHref[1] + '/';

        location.href = newHref;
    }
    return;
    if (location.href != window.hRef && window.hRef != undefined)
        location.href = window.hRef;
    else
        location.hash = window.hRefHash != undefined ? window.hRefHash : '';
    return;
    /*history.back();
    return;*/
    var pageType = window.pageType;
    url = encode64(url);
    url = "/helper/backtoprev/url/" + url + "/pageType/" + pageType;
    document.title = window.pageTitle;
    $(window).unbind('hashchange');
    location.hash = '';

    var responseDiv = window.responseDiv;
    if (responseDiv === undefined) {
        responseDiv = "CenterDiv";
    } else {
        responseDiv = "ESCAdsResponse" + responseDiv;
    }

    $('#' + responseDiv).load(url, function () {
        if (window.hashPos != '' || window.hashPos != undefined) {
            //ScrollToElement(document.getElementById(window.hashPos));
            window.scrollTo(0, window.divTop);
            //window.hashPos = '';
        }

    });

}

function clearMeCheck(theClass, value) {
    if ($("." + theClass).val() == value) {
        $("." + theClass).val("");
    }
}

function emptyCheck(theClass, value) {
    //return;
    if ($("." + theClass).val() == "") {
        $("." + theClass).attr('placeholder', value);
    }
}

function emptyCheck2(e, value) {
    return;
    if (e.val() == "") {
        e.attr('placeholder', value);
    }
}

$(document).on('click', ".adsSearchKeywords", function () {
    if ($(".adsSearchKeywords").val() == "Enter search terms separated by comma") {
        $(".adsSearchKeywords").val("");
    }
});

$(document).on('focusout', ".adsSearchKeywords", function () {
    //if($(".adsSearchKeywords").val() == ""){
    //emptyCheck('adsSearchKeywords','Enter search terms separated by comma');
    //}
    var e = $(this);
    if (e.val() == "") {
        emptyCheck2(e, 'Enter search terms separated by comma')
    }
});

$(document).on('focusout', ".firstName", function () {
    //if($(".firstName").val() == ""){
    //emptyCheck('firstName','First Name*')
    //}
    var e = $(this);
    if (e.val() == "") {
        emptyCheck2(e, 'First Name*')
    }
});
$(document).on('focusout', ".lastName", function () {
    //if($(".lastName").val() == ""){
    //emptyCheck('lastName','Last Name*')
    //}
    var e = $(this);
    if (e.val() == "") {
        emptyCheck2(e, 'Last Name*')
    }
});
$(document).on('focusout', ".phone", function () {
    //if($(".phone").val() == ""){
    //emptyCheck('phone','Telephone*')
    //}
    var e = $(this);
    if (e.val() == "") {
        emptyCheck2(e, 'Telephone*')
    }
});
$(document).on('focusout', ".email", function () {
    var e = $(this);
    if (e.val() == "") {
        emptyCheck2(e, 'Email*')
    }
});
$(document).on('focusout', ".comment", function () {
    //if($(".comment").val() == ""){
    //emptyCheck('comment','Comments*')
    //}
    var e = $(this);
    if (e.val() == "") {
        emptyCheck2(e, 'Comments*')
    }
});

function changeView(view, div) {
    //$('#ESCAdsFiltering').remove();
    var url = '/helper/changeview/view/' + view;
    //alert(url);

    $('#ESCAdsResponse' + div).load(url, function (data) {

        $('#ESCAdsResponse' + div).removeAttr("style");

    });
}

function refreshCaptcha(div) {
    var url = '/helper/createnewcaptcha';
    //alert(url);

    $('.captcha' + div).load(url);
}

function getAdDetails(id, style, quantityShow, odometerShow) {
    $('#' + responseDiv).css('height', "").css("overflow", "visible")
    .css('min-height', "").css("overflow", "visible");

    //$('.parentDiv').css("height","");
    //$('.parentDiv').css('min-height',"");
    var taxesDisplay = window.taxesDisplay;
    var newWindow = window.newWindow;
    var responseDiv = window.responseDiv;
    //console.log('ddd333334444', responseDiv);
    if (responseDiv === undefined) {
        responseDiv = "CenterDiv";
    } else {
        responseDiv = "ESCAdsResponse" + responseDiv;
    }

    var price_d = $('#price_d').val();
    var show_msrp_details = $('#show_msrp_details').val();

    var categoryName = window.categoryName;
    var subCatName = window.subCatName;
    if (categoryName === undefined) {
        categoryName = "Previous";
    }
    if (id.search("-") >= 0) {
        $('#' + responseDiv).load('/helper/addetails/', {
            compare: id,
            style: style,
            quantityShow: quantityShow,
            odometerShow: odometerShow,
            categoryName: categoryName,
            subCatName: subCatName,
            paramDetailsHeader: window.paramDetailsHeader,
            dealerId: window.ESCADSdealerId,
            logo: window.logo,
            taxesDisplay: taxesDisplay,
            price_d: price_d,
            pageName: window.pageName,
            show_msrp_details: show_msrp_details
        }, function () {

            CaptchaCallback();
            $.fn.matchHeight._update();

            /*				$( ".lightbox" ).fancybox( {
            'overlayShow': false,
            'width': 570,
            'height': 600,
            'autoScale': false,
            'autoDimensions': true,
            'centerOnScroll': false
            } );*/
            $(".lightbox2").fancybox({
                'overlayShow': false,
                'width': 650,
                'height': 600,
                'autoScale': false,
                'autoDimensions': true,
                'centerOnScroll': false
            });

            window.scrollTo(0, 0);
            FixImagesHeightDetailsView();

        });
    } else {
        //alert(window.logo);
        if (window.escComps == 'escComp' && window.escCompsResponsive && window.escCompsResponsive == 'responsive1') {
            //window.detailsDisplay = 'responsive1_vertical';
            window.detailsDisplay = 'responsive1_vertical_escComp';
        }
        //console.log('object before sending', window.detailsDisplay, window.escComps);

        $('#' + responseDiv).load('/helper/addetails/', {
            adId: id,
            style: style,
            quantityShow: quantityShow,
            odometerShow: odometerShow,
            categoryName: categoryName,
            subCatName: subCatName,
            view: window.view,
            detailsDisplay: window.customDetailsDisplay ? window.customDetailsDisplay : window.detailsDisplay,
            paramDetailsHeader: window.paramDetailsHeader,
            dealerId: window.ESCADSdealerId,
            logo: window.logo,
            taxesDisplay: taxesDisplay,
            price_d: price_d,
            pageName: window.pageName,
            show_msrp_details: show_msrp_details
        }, function (res) {
            //console.log(res);
            if ($('.breadcrumbParent').size()) {
                var $last = $('.breadcrumbParent').find('li').last();
                $last.removeClass('active').html('<a href="' + $last.data('url') + '">' + $last.text() + '</a>');
                $('.breadcrumbParent ol.breadcrumb').append('<li class="breadcrumb-item active" aria-current="page" >' + $('title').html().split('|')[1] + '</li>');

            }
            if ($('.ShowReadMore').length) {

                var oldHeight = 0;
                $('.ShowReadMore').readmore({
                    speed: 250,
                    heightMargin: 20,
                    collapsedHeight: CalcRightHeights(),
                    moreLink: '<a href="#" style="margin-top: 15px;">Read more ...</a>',
                    lessLink: '<a href="#" style="margin-top: 15px;" >Read less</a>',
                    beforeToggle: function () {
                        $.fn.matchHeight._update();
                    },
                    afterToggle: function () {
                        $.fn.matchHeight._update();
                    }
                });
            }
            window.scrollTo(0, 0);
            /*if ( $( ".lightbox" ).size() ) {
            $( ".lightbox" ).fancybox( {
            'overlayShow': false,
            'width': 570,
            'height': 600,
            'autoScale': false,
            'autoDimensions': true,
            'centerOnScroll': false
            } );
            }*/
            if ($(".lightbox2").size()) {
                $(".lightbox2").fancybox({
                    'overlayShow': false,
                    'width': 650,
                    'height': 600,
                    'autoScale': false,
                    'autoDimensions': true,
                    'centerOnScroll': false
                });
            }
            if ($(".lightbox3").size()) {
                $(".lightbox3").fancybox({
                    'overlayShow': false,
                    'width': 550,
                    'height': 420,
                    'autoScale': false,
                    'autoDimensions': true,
                    'centerOnScroll': false
                });
            }
            FixImagesHeightDetailsView();
            CaptchaCallback();
            $.fn.matchHeight._update();

            $("img[onmouseover*='.pdf'],img[onmouseover*='.pptx']").each(function (i, elm) {

                var plink = $(elm).attr('onmouseover').match(/'([^']+)',/);
                var FileName = plink[1].split('/');
                //console.log( plink, FileName );
                FileName = FileName[FileName.length - 1];
                //var ShortFileName = FileName.length > 10 ? FileName.substr(0, 10) + '' : FileName;
                var ShortFileName = $(elm).attr('title') ? $(elm).attr('title') : FileName.replace('.pdf', '').replace('.pptx', '').replace('-', ' ').replace('_', ' ');
                if (plink[1].indexOf('equipmentsearch.com') == -1) {

                    plink[1] = "https://equipmentsearch.com" + plink[1];
                    var Icon = 'https://equipmentsearch.com/images/downloads3.png';
                }
                if (plink[1].indexOf('.pdf') != -1) {

                    //plink[ 1 ] = "/helper/viewpdf/tar/" + btoa( plink[ 1 ] );
                    var Icon = '/images/pdf-icon2.png';
                }

                $(elm).remove();
                var _html = '<div class="col-lg-4 col-md-3 text-left"><a href="' + plink[1] + '" target="_blank" title="' + FileName + '"><img src="' + Icon + '" width="72" alt="' + FileName + '" class="img-thumbnail" style="margin:10px" /><br />' + ShortFileName + '</a></div>';
                if ($('#DocumentsDiv').size() == 0) {
                    $("div:contains('Click on photo for gallery')").parent('td').append('<div id="DocumentsDiv" style="padding:5px;margin:5px"><b>Documents : </b><br /> <a href="' + plink[1] + '" target="_blank" style="text-align:center;float:left;over-flow:hidden;margin:5px" title="' + FileName + '"><img src="' + Icon + '" width="72" alt="' + FileName + '" /><br />' + ShortFileName + '</a></div>');
                    if (isResponsiveMode) {
                        $("#DocumentsDiv_responsive").append('<div id="DocumentsDiv" class="col-lg-12" style="margin-top: 15px;"><strong>Documents :</strong></div>');
                        $('#DocumentsDiv').append('<div class="row">' + _html + '</div>');
                    }
                } else {
                    if (isResponsiveMode) {
                        $('#DocumentsDiv .row').append(_html);
                    } else {
                        $('#DocumentsDiv .row').append('<a href="' + plink[1] + '" target="_blank" style="text-align:center;float:left;over-flow:hidden;margin:5px" title="' + FileName + '"><img src="' + Icon + '" width="64" alt="' + FileName + '" class="img-thumbnail"/><br />' + ShortFileName + '</a>');
                    }
                }

            })
        });
    }

}

function getRandomAdDetails(id, style) {
    var menuPos = $("#siteMenu").attr("pos"); //$('#CenterDiv').height(500);
    //console.log("menu pos is : ", menuPos);
    $('#CenterDiv').css('height', "");
    $('#CenterDiv').css("overflow", "visible");
    if (menuPos == 2) {
        //$('#CenterDiv').width($('#CenterDiv').width()+$('#LeftDiv').width()-10);
        var leftWidth = $('#LeftDiv').width();
        var centerWidth = $('#CenterDiv').width();
        centerWidth += leftWidth - 4;
        $('#LeftDiv').hide();
        $('#LeftDiv').width('0');
        $('#CenterDiv').width(centerWidth);
    } else if (menuPos == 4) {
        //$('#CenterDiv').width($('#CenterDiv').width()+$('#RightDiv').width()-$('#LeftDiv').width());
        var rightWidth = $('#RightDiv').width();
        var centerWidth = $('#CenterDiv').width();
        centerWidth += rightWidth - 2;
        $('#RightDiv').hide();
        $('#RightDiv').width('0');
        $('#CenterDiv').width(centerWidth);
    } else {

        $('#LeftDiv').width('0');
        $('#RightDiv').width('0');
        $('#LeftDiv').hide();
        $('#RightDiv').hide();
        $('#CenterDiv').width('100%');
    }
    //Basem
    if ($('#CenterDiv').width() > $('#parent').width()) {
        $('#CenterDiv').width($('#parent').width());
    }
    var details_width_style = $('#details_width_style').val();
    //console.log('details_width_style is :', details_width_style);
    //console.log('CenterDiv width is :', $('#CenterDiv').width());
    $('#CenterDiv').load('/helper/addetails/', {
        adId : id,
        style : style,
        categoryName : 'Previous',
        view : window.view,
        detailsDisplay: window.detailsDisplay,
        paramDetailsHeader: window.paramDetailsHeader,
        dealerId: window.ESCADSdealerId,
        taxesDisplay: taxesDisplay,
        pageName: window.pageName,
        details_width_style: details_width_style
    }, function () {

        /*$( ".lightbox" ).fancybox( {
        'overlayShow': false,
        'width': 570,
        'height': 600,
        'autoScale': false,
        'autoDimensions': true,
        'centerOnScroll': false
        } );*/
        $(".lightbox2").fancybox({
            'overlayShow': false,
            'width': 650,
            'height': 600,
            'autoScale': false,
            'autoDimensions': true,
            'centerOnScroll': false
        });
        $(".lightbox3").fancybox({
            'overlayShow': false,
            'width': 550,
            'height': 420,
            'autoScale': false,
            'autoDimensions': true,
            'centerOnScroll': false
        });

        FixImagesHeightDetailsView();
        window.scrollTo(0, 0);
        CaptchaCallback();
        $.fn.matchHeight._update();

    });

}

function encode64(input) {
    var keyStr = "ABCDEFGHIJKLMNOP" +
        "QRSTUVWXYZabcdef" +
        "ghijklmnopqrstuv" +
        "wxyz0123456789+/" +
        "=";
    input = escape(input);
    var output = "";
    var chr1,
    chr2,
    chr3 = "";
    var enc1,
    enc2,
    enc3,
    enc4 = "";
    var i = 0;

    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
            keyStr.charAt(enc1) +
            keyStr.charAt(enc2) +
            keyStr.charAt(enc3) +
            keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);

    return output;
}

function FixImagesHeightDetailsView() {
    /*console.log("After Loading .......", new Date());
    window._max_height_thumbnail = 0;
    $('[class*="hidden_img_"]').each(function(i, e){

    if(window._max_height_thumbnail < $(e).height()){
    window._max_height_thumbnail = $(e).height();
    }
    });
    var _new_height = $('#imgWidth').closest('.img-parent').height();

    width = 1024;
    height = 768;

    ratio_orig = width_orig/height_orig;

    if (width/height > ratio_orig) {
    width = height*ratio_orig;
    } else {
    height = width/ratio_orig;
    }
     */

    var _new_height = 0;
    var _new_width = 0;

    $('.img-thumbnail').each(function (i, elm) {
        if (_new_height < parseInt($(elm).attr('oheight')))
            _new_height = parseInt($(elm).attr('oheight'));

        if (_new_width < parseInt($(elm).attr('owidth')))
            _new_width = parseInt($(elm).attr('owidth'));

    })
    var ratio_orig = _new_width / _new_height;

    /*if(window._max_height_thumbnail < _new_height){
    window._max_width_thumbnail = $('#imgWidth').closest('.img-parent').width();
    //console.log($('#imgWidth').closest('.img-parent').width());
    window._max_height_thumbnail = _new_height;
    }*/
    window._max_width_thumbnail = $('#imgWidth').closest('.img-parent').width();

    //console.log(ratio_orig,window._max_width_thumbnail/ratio_orig);


    $('[class*="hidden_img_"]').css({
        'height': '75px',
        'visibility': 'visible'
    });
    $('#bigImageDiv img').css({
        'visibility': 'visible'
    });
    if (_new_height > 0) {
        window._max_height_thumbnail = (window._max_width_thumbnail / ratio_orig);
        window._max_height_thumbnail = window._max_height_thumbnail > _new_height ? _new_height : window._max_height_thumbnail;
        //console.log(_new_height,_max_height_thumbnail);
        $('#bigImageDiv').css({
            'height': _max_height_thumbnail + 'px'
        });

        $('.img-parent').css({
            'min-height': _max_height_thumbnail + 'px'
        });
    }
}

function loadPhoto(url, div) {
    url = url.replace("t_", "_");
    url = url.replace("t.", ".");
    div = div == 'bigImageDiv' ? '.bigImageDiv' : '#' + div;

    if (window.detailsDisplay == "vertical" || window.detailsDisplay == "vertical2") {
        $(div).html('<img src="http://www.equipmentsearch.com/resize.php?image=' + url + '" width="580" style="max-height:450px" class="thumb" border="0" alt="Listing image" />');
    } else if (window.detailsDisplay == "new1" || window.detailsDisplay == "Sideways2") {
        $(div).html('<img src="http://www.equipmentsearch.com/resize.php?image=' + url + '" width="344" style="max-height:300px" class="thumb" border="0" alt="Listing image" /><br />');
    } else if (window.detailsDisplay == "responsive1_normal" || window.detailsDisplay == "responsive1_vertical") {
        var _max_width = window._max_width_thumbnail;
        var _max_height = window._max_height_thumbnail;
        $(div).html('<img src="http://www.equipmentsearch.com/resize.php?image=' + url + '" style="max-height:' + _max_height + 'px; max-width:' + _max_width + 'px" class="thumb" border="0" alt="Listing image" /><br />');

    } else {
        $(div).html('<img src="http://www.equipmentsearch.com/resize.php?image=' + url + '" width="400" style="max-height:350px" class="thumb" border="0" alt="Listing image" />');
    }
}

$(document).ready(function () {
    if ($('.ShowReadMore').length) {

        var oldHeight = 0;
        $('.ShowReadMore').readmore({
            speed: 250,
            heightMargin: 20,
            collapsedHeight: 400,
            moreLink: '<a href="#" style="margin-top: 15px;">Read more ...</a>',
            lessLink: '<a href="#" style="margin-top: 15px;" >Read less</a>',
            beforeToggle: function () {
                $.fn.matchHeight._update();
            },
            afterToggle: function () {
                $.fn.matchHeight._update();
            }
        });
    }
    //alert($('#FooterDiv').height());
    //$('#LeftDiv,#RightDiv,#CenterDiv').addClass('parentDiv');

    if ($('.encrypted').size() > 0) {

        //document.addEventListener('contextmenu', event => event.preventDefault());
        $('.encrypted').each(function (i, elm) {
            $(elm).html(window.atob($(elm).html())).show();
        })
    }

    $('.adsSearchKeywords').val(window.searchValue);

    var locHash = location.hash;
    if ($.trim(locHash) && locHash.indexOf('#') != -1) {
        /*var newHref = locHash.split( '/' );
        newHref.splice( 0, 1 );
        newHref = newHref.join( '/' );
        loadContent( newHref ); */
    } else {
        if (location.hash.indexOf('modernFilter') !== -1) {
            loadContent(location.hash);
        }
        var newHref = location.pathname;
        newHref = newHref.split('/');
        newHref.splice(0, 1);
        newHref.splice(0, 1);
        if (window.redirctPageName) {
            newHref.splice(0, 1);
        }
        /*if ( newHref.length > 1 ) {
        newHref = newHref.join( '/' );
        if( location.pathname.indexOf('adid/') == -1 ){
        loadContent( newHref );
        }

        }*/
    }
    var counter = 1;
    $(document).on("click", '.loanCalc', function () {
        var prin = $("input[name='prin']").val();
        var theInt = $("input[name='theInt']").val();
        var years = $("select[name='years']").val();
        var howoften = $("select[name='howoften']").val();
        var show_amort = $("input:radio[name='show_amort']:checked").val();
        //alert(url);
        if ($("input[name='counter']").val() == "first") {
            //alert(counter);
            var menuPos = $("#siteMenu").attr("pos");
            //alert(menuPos);
            if (menuPos == 2) {
                //$('#CenterDiv').width($('#CenterDiv').width()+$('#LeftDiv').width()-10);
                $('#LeftDiv').hide();
            } else if (menuPos == 4) {
                //$('#CenterDiv').width($('#CenterDiv').width()+$('#RightDiv').width()-$('#LeftDiv').width());
                $('#RightDiv').hide();
            } else {
                $('#LeftDiv').hide();
                $('#RightDiv').hide();
                $('#CenterDiv').width($('#CenterDiv').width() + $('#RightDiv').width() + $('#LeftDiv').width());
            }
        }
        var url = '/cgi-bin/calculator.cgi?prin=' + prin + '&theInt=' + theInt + '&years=' + years + '&howoften=' + howoften + '&show_amort=' + show_amort + '&width=' + $('#CenterDiv').width();

        //$('.loanCalcContainerDiv').width($('#CenterDiv').width()-10);
        $('.loanCalcResponse').load("/helper/calc", {
            url: url
        }, function (responseText, textStatus, XMLHttpRequest) {
            //alert($("input:radio[name='show_amort']").val());
            $("select[name='years']").val(years).select();
            $("select[name='howoften']").val(howoften).select();
            //$("input:radio").val(show_amort).attr("checked", "checked");
            $("input:radio[name='show_amort']").each(function () {
                //alert($(this).val());
                if ($(this).val() == show_amort) {

                    $(this).attr("checked", "checked");
                }
            });
        });

    });

    $(document).on("click", "a[href^='tel']", function () {

        window.gtag('event', 'PhoneLinkClick', {
            'send_to': window.send_to['GT']
        });
    })
    $(document).on("click", 'td.adDetails,div.adDetails', function () {
        if ($(this).parents('a').size() > 0) {
            return;
        } else {
            var href = $(this).attr('rel');
            if (!href)
                return false;
            else {
                callLoadContent(href);
                return;
            }

            divTop = $("#floatdiv").offset();
            window.divTop = parseInt(divTop.top);
            var newWindow = window.newWindow;
            if (newWindow !== 'show') {
                location.hash = adId;
                //getAdDetails(adId, window.detailsStyle, window.quantityShow, window.odometerShow);
            } else {
                //alert(newWindow);
                var categoryName = window.categoryName;
                var pos = location.hash + "POS";
                pos = pos.replace("#", "");
                if (categoryName === undefined) {
                    categoryName = "Previous";
                }
                if (window.detailsDisplay == "vertical2") {
                    window.detailsDisplay = "vertical";
                }
                if (window.detailsDisplay == "normal2") {
                    window.detailsDisplay = "normal";
                }
                window.detailsUrl = '/helper/newaddetails/adId/' + adId + '/style/' + window.detailsStyle + '/quantityShow/' + window.quantityShow + '/odometerShow/' + window.odometerShow + '/categoryName/' + categoryName + '/view/' + window.view + '/detailsDisplay/' + window.detailsDisplay + '/paramDetailsHeader/' + window.paramDetailsHeader + '/dealerId/' + window.ESCADSdealerId + '/taxesDisplay/' + window.taxesDisplay;
                //var sData = "";
                OpenWindow = window.open('/helper/newwindowdetails/adId/' + adId, 'AdDetails', 'width=1000,height=800,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no');
                //OpenWindow.document.write(sData);
                location.hash = "";

            }
        }
    });

    /* $(document).on("click", '.randomAdDetails', function() {
    var adId = $(this).attr('rel');

    adId = adId.replace("RANDOM", "");
    location.hash = adId;
    //getRandomAdDetails(adId, window.detailsStyle);
    });*/

    $(document).on("click", "a[href^='tel']", function () {
        window.gtag('event', 'PhoneLinkClick', {
            'send_to': window.send_to['GT']
        });
    })
    $(document).on("click", '.detailsFormSubmit', function () {
        var id = 1;
        var recaptcha_challenge_field = '',
        recaptcha_response_field = '';
        var $form = $(this).parents('form');
        //Basem
        isResponsiveMode = true;
        recaptcha_challenge_field = $form.find('#recaptcha_challenge_field').val();
        recaptcha_response_field = $form.find('#recaptcha_response_field').val();
        var captchaVal = 'true';
        //alert(captchaVal);

        if ($form.validate().form()) {
            if (((typeof($form.find('#captchaWrapper').find('.captchaSuccess').val()) != 'undefined' || $form.find('.adCaptcha').size() == 0) && isResponsiveMode == false) || isResponsiveMode == true) {

                var AdId = $form.find('.detailsFormAdId' + id).val() ? $form.find('.detailsFormAdId' + id).val() : location.hash.replace('#', '');
                AdId = AdId > 0 ? AdId : window.adId;

                var g_recaptcha_response = '';
                if ($("[data-size='invisible']").length > 0 ) {
                    grecaptcha.execute();
                }
                setTimeout(function () {
                    $.each($form.find('.g-recaptcha-response'), function (i, elm) {
                        if ($(elm).val()) {
                            g_recaptcha_response = $(elm).val();
                        }
                    })

                    if (reCaptchaVersion == 2) {
                        //console.log(g_recaptcha_response, $form.find('#grecaptcha').size());
                        if (!g_recaptcha_response && $form.find('#grecaptcha').size() > 0) {

                            //alert('You must verfiy the CAPTCHA first');

                            Swal.fire({
                                icon: 'error', //this
                                title: "You must verfiy the CAPTCHA first",
                                timerProgressBar: true,
                                showConfirmButton: true,
                                allowOutsideClick: true,
                                timer: 1500
                            })
                            return;
                        }
                    }
                    $form.find('#detailsFormResponseDiv' + id).html("<img src='/images/loader.gif' />");

                    var postData = $form.serializeObject();
                    postData.adId = AdId;
                    postData.PreferredStartDate = $form.find('[name=PreferredStartDate]').val() ? $form.find('[name=PreferredStartDate]').val().toString().replace('/', '-').replace('/', '-') : '';
                    postData.lead_type_ignore = 'lead';
                    postData.g_recaptcha_response = window.g_recaptcha_response;
                    postData.pageName = window.pageName;
                    postData.isResponsiveMode = window.isResponsiveMode;
                    postData.reCaptchaVersion = reCaptchaVersion;
                    postData.captcha = captchaVal;
                    postData.recaptcha_challenge_field = recaptcha_challenge_field;
                    postData.recaptcha_response_field = recaptcha_response_field;
                    postData.pathname = location.pathname;
                    postData.href = location.href;

                    postData.sid = window.sid;

                    if (typeof window.gtag === 'function') {

                        window.gtag('event', 'submit', {
                            send_to: window.send_to['GAGT'],
                            event_category: 'form',
                            event_label: 'Item Enquiry form'
                        });

                        if (window.website_settings.google_tag) {
                            window.gtag('event', 'conversion', {
                                'send_to': window.send_to['GT']
                            });
                        }
                    } else {
                        if (typeof window.ga === 'function') {
                            window.ga('send', 'event', {
                                eventCategory: 'form',
                                eventAction: 'submit',
                                send_to: window.send_to['GA']
                            });
                        }
                    }
                    $.post('/helper/escadscaptcha/', postData, function (data) {
                        $form.trigger("reset"); //console.log(postData);
                        allFormsCallback();
                        if ($form.find('#detailsFormResponseDiv' + id).size() > 0) {
                            $form.find('#detailsFormResponseDiv' + id).text(data);

                        } else {
							Swal.fire({
								icon: 'info',
								title: data,
								showConfirmButton: true
							})
                        }

                        if (reCaptchaVersion == 1 && Recaptcha != undefined) {
                            Recaptcha.reload();
                        } else if (reCaptchaVersion == 2) {

                            grecaptcha.reset($form.find('.g-recaptcha').data('widgetId'));
                        }
                    });
                }, 500)
            } else {
                $form.find('#detailsFormResponseDiv' + id).text("The Captcha is incorrect"); //alert("");
            }

        }
    });

    $(document).on("click", '.financialSubmit', function () {
        var id = $(this).parent("td").attr("id");
        var captchaVal = $(".captcha" + id).find("input").val();
        //alert(captchaVal);
        if ($('.financeFirstName').val() != "" && $('.financeLastName').val() != "" && $('.financePhone').val() != "" && $('.financeEmail').val() != "" && $('.financeComment').val() != "" && captchaVal != "") {
            var AdId = $('.financeAdId').val() ? $('.financeAdId').val() : location.hash.replace('#', '');

            $('#financeResponseDiv' + id).html("<img src='/images/loader.gif' />");
            // url = url.split(' ').join('%20');
            // alert(url);
            $.post('/helper/escadscaptcha/', {
                captcha: captchaVal,
                firstName: $('.financeFirstName').val(),
                lastName: $('.financeLastName').val(),
                phone: $('.financePhone').val(),
                email: $('.financeEmail').val(),
                comment: $('.financeComment').val(),
                adId: AdId
            }, function (data) {
                allFormsCallback();
                $('#financeResponseDiv' + id).html(data);
            })
            $('.captcha').load("/helper/createnewcaptcha/");

            // history.go(0);

        } else {
            $('#financeResponseDiv' + id).text("all fields are required"); //alert("");
        }

    });

    $(document).on("click", '.emailSubmit', function () {
        var id = $(this).parent("td").attr("id") ? $(this).parent("td").attr("id") : $("#formType").val();
        var captchaVal = $(".captcha" + id).find("input").val();
        var emailLinkVal = $(".emailLink").val();
        var lang = $('#lang').val();

        if ($('.emailName').val() != "" && $('.emailEmail').val() != "" && captchaVal != "") {
            var AdId = $('.emailAdId').val() ? $('.emailAdId').val() : location.hash.replace('#', '');

            $('#emailResponseDiv' + id).html("<img src='/images/loader.gif' />");

            $.post('/helper/escadscaptcha/', {
                captcha: captchaVal,
                'g-recaptcha-response': g_recaptcha_response,
                firstName: $('.emailName').val(),
                email: $('.emailEmail').val(),
                emailLink: emailLinkVal,
                adId: AdId,
                lang: lang,
                type: 'email'
            }, function (data) {
                allFormsCallback();
                $('#emailResponseDiv' + id).show().html(data);
            })


        } else {
            var _req_text = window.translate("all fields are required");
            $('#emailResponseDiv' + id).show().text(_req_text); //alert("");
        }

    });

    $(document).on("click", 'button.genricSubmit,a.genricSubmit', function () {
        //console.log(typeof  window.gtag);
        var $form = $(this).parents('form');
        return genricSubmit($form);
    });
    $(document).on("submit", 'form.genricSubmit', function () {
        //console.log(typeof  window.gtag);
        var $form = $(this);
        return genricSubmit($form);
    });

             if (window.WebsiteModal != false && window.WebsiteModal != undefined) {
            var popup = getCookie('popup_' + window.sid);
            //alert(popup);
            if (popup != 1) {
                window.WebsiteModal.modal('show');
            } else if (window.PageModal != false && window.PageModal != undefined) {
                var popup = getCookie('popup_' + window.pageId);
                if (popup != 1) {
                    window.PageModal.modal('show');
                }
            }
        } else if (window.PageModal != false && window.PageModal != undefined) {
            var popup = getCookie('popup_' + window.pageId);
            if (popup != 1) {

                window.PageModal.modal('show');
            }
        }
        if (window.WebsiteModal != false && window.WebsiteModal != undefined) {
            window.WebsiteModal.on('hidden.bs.modal', function () {
                //alert('1');
                setCookie('popup_' + window.sid, 1);
                var popup = getCookie('popup_' + window.pageId);
                if (popup != 1 && window.PageModal != false) {
                    window.PageModal.modal('show');
                }
            })
        }
        if (window.PageModal != false && window.PageModal != undefined) {
            window.PageModal.on('hidden.bs.modal', function () {
                //alert('2');
                setCookie('popup_' + window.pageId, 1);
            })
        }

         });
var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
