/* Minification failed. Returning unminified contents.
(2582,25-26): run-time error JS1195: Expected expression: )
(2582,28-29): run-time error JS1195: Expected expression: >
(2590,1-2): run-time error JS1002: Syntax error: }
(2592,24-25): run-time error JS1004: Expected ';': {
 */
!function (t, e) { "function" == typeof define && define.amd ? define(e) : "object" == typeof exports ? module.exports = e() : t.Blazy = e() }(this, function () { "use strict"; var t, e, o, n, s = "src", i = "srcset"; return function (s) { if (!document.querySelectorAll) { var i = document.createStyleSheet(); document.querySelectorAll = function (t, e, o, n, s) { for (s = document.all, e = [], o = (t = t.replace(/\[for\b/gi, "[htmlFor").split(",")).length; o--;) { for (i.addRule(t[o], "k:v"), n = s.length; n--;) s[n].currentStyle.k && e.push(s[n]); i.removeRule(0) } return e } } var c = this, l = c._util = {}; l.elements = [], l.destroyed = !0, c.options = s || {}, c.options.error = c.options.error || !1, c.options.offset = c.options.offset || 100, c.options.root = c.options.root || document, c.options.success = c.options.success || !1, c.options.selector = c.options.selector || ".b-lazy", c.options.separator = c.options.separator || "|", c.options.containerClass = c.options.container, c.options.container = !!c.options.containerClass && document.querySelectorAll(c.options.containerClass), c.options.errorClass = c.options.errorClass || "b-error", c.options.breakpoints = c.options.breakpoints || !1, c.options.loadInvisible = c.options.loadInvisible || !1, c.options.successClass = c.options.successClass || "b-loaded", c.options.validateDelay = c.options.validateDelay || 25, c.options.saveViewportOffsetDelay = c.options.saveViewportOffsetDelay || 50, c.options.srcset = c.options.srcset || "data-srcset", c.options.src = t = c.options.src || "data-src", n = Element.prototype.closest, o = window.devicePixelRatio > 1, (e = {}).top = 0 - c.options.offset, e.left = 0 - c.options.offset, c.revalidate = function () { r(c) }, c.load = function (t, e) { var o = this.options; t && void 0 === t.length ? f(t, e, o) : E(t, function (t) { f(t, e, o) }) }, c.destroy = function () { var t = c._util; c.options.container && E(c.options.container, function (e) { C(e, "scroll", t.validateT) }), C(window, "scroll", t.validateT), C(window, "resize", t.validateT), C(window, "resize", t.saveViewportOffsetT), t.count = 0, t.elements.length = 0, t.destroyed = !0 }, l.validateT = T(function () { a(c) }, c.options.validateDelay, c), l.saveViewportOffsetT = T(function () { y(c.options.offset) }, c.options.saveViewportOffsetDelay, c), y(c.options.offset), E(c.options.breakpoints, function (e) { if (e.width >= window.screen.width) return t = e.src, !1 }), setTimeout(function () { r(c) }) }; function r(t) { var e = t._util; e.elements = function (t) { for (var e = [], o = t.root.querySelectorAll(t.selector), n = o.length; n--; e.unshift(o[n])); return e }(t.options), e.count = e.elements.length, e.destroyed && (e.destroyed = !1, t.options.container && E(t.options.container, function (t) { b(t, "scroll", e.validateT) }), b(window, "resize", e.saveViewportOffsetT), b(window, "resize", e.validateT), b(window, "scroll", e.validateT)), a(t) } function a(t) { for (var e = t._util, o = 0; o < e.count; o++) { var n = e.elements[o]; (c(n, t.options) || g(n, t.options.successClass)) && (t.load(n), e.elements.splice(o, 1), e.count--, o--) } 0 === e.count && t.destroy() } function c(t, o) { var s = t.getBoundingClientRect(); if (o.container && n) { var i = t.closest(o.containerClass); if (i) { var r = i.getBoundingClientRect(); if (l(r, e)) { var a = r.top - o.offset, c = r.right + o.offset, f = r.bottom + o.offset, u = r.left - o.offset; return l(s, { top: a > e.top ? a : e.top, right: c < e.right ? c : e.right, bottom: f < e.bottom ? f : e.bottom, left: u > e.left ? u : e.left }) } return !1 } } return l(s, e) } function l(t, e) { return t.right >= e.left && t.bottom >= e.top && t.left <= e.right && t.top <= e.bottom } function f(e, n, r) { if (!g(e, r.successClass) && (n || r.loadInvisible || e.offsetWidth > 0 && e.offsetHeight > 0)) { var a = m(e, t) || m(e, r.src); if (a) { var c = a.split(r.separator), l = c[o && c.length > 1 ? 1 : 0], f = m(e, r.srcset), v = h(e, "img"), y = e.parentNode, T = y && h(y, "picture"); if (v || void 0 === e.src) { var A = new Image, D = function () { r.error && r.error(e, "invalid"), w(e, r.errorClass), C(A, "error", D), C(A, "load", O) }, O = function () { v ? T || d(e, l, f) : e.style.backgroundImage = 'url("' + l + '")', u(e, r), C(A, "load", O), C(A, "error", D) }; T && (A = e, E(y.getElementsByTagName("source"), function (t) { p(t, i, r.srcset) })), b(A, "error", D), b(A, "load", O), d(A, l, f) } else e.src = l, u(e, r) } else h(e, "video") ? (E(e.getElementsByTagName("source"), function (t) { p(t, s, r.src) }), e.load(), u(e, r)) : (r.error && r.error(e, "missing"), w(e, r.errorClass)) } } function u(t, e) { w(t, e.successClass), e.success && e.success(t) } function p(t, e, o) { var n = m(t, o); n && (v(t, e, n), function (t, e) { t.removeAttribute(e) }(t, o)) } function d(t, e, o) { o && v(t, i, o), t.src = e } function v(t, e, o) { t.setAttribute(e, o) } function m(t, e) { return t.getAttribute(e) } function h(t, e) { return t.nodeName.toLowerCase() === e } function g(t, e) { return -1 !== (" " + t.className + " ").indexOf(" " + e + " ") } function w(t, e) { g(t, e) || (t.className += " " + e) } function y(t) { e.bottom = (window.innerHeight || document.documentElement.clientHeight) + t, e.right = (window.innerWidth || document.documentElement.clientWidth) + t } function b(t, e, o) { t.attachEvent ? t.attachEvent && t.attachEvent("on" + e, o) : t.addEventListener(e, o, { capture: !1, passive: !0 }) } function C(t, e, o) { t.detachEvent ? t.detachEvent && t.detachEvent("on" + e, o) : t.removeEventListener(e, o, { capture: !1, passive: !0 }) } function E(t, e) { if (t && e) for (var o = t.length, n = 0; n < o && !1 !== e(t[n], n) ; n++); } function T(t, e, o) { var n = 0; return function () { var s = +new Date; s - n < e || (n = s, t.apply(o, arguments)) } } });;
/*! lightgallery - v1.2.19 - 2016-05-17
* http://sachinchoolur.github.io/lightGallery/
* Copyright (c) 2016 Sachin N; Licensed Apache 2.0 */
(function($, window, document, undefined) {

    'use strict';

    var defaults = {

        mode: 'lg-slide',

        // Ex : 'ease'
        cssEasing: 'ease',

        //'for jquery animation'
        easing: 'linear',
        speed: 400,
        height: '',
        width: '',
        addClass: '',
        startClass: '',
        backdropDuration: 150,
        hideBarsDelay: 6000,

        useLeft: false,

        closable: true,
        loop: true,
        escKey: true,
        keyPress: true,
        controls: true,
        slideEndAnimatoin: false,
        hideControlOnEnd: true,
        mousewheel: true,

        getCaptionFromTitleOrAlt: true,

        // .lg-item || '.lg-sub-html'
        appendSubHtmlTo: '.lg-sub-html',

        /**
         * @desc number of preload slides
         * will exicute only after the current slide is fully loaded.
         *
         * @ex you clicked on 4th image and if preload = 1 then 3rd slide and 5th
         * slide will be loaded in the background after the 4th slide is fully loaded..
         * if preload is 2 then 2nd 3rd 5th 6th slides will be preloaded.. ... ...
         *
         */
        preload: 1,
        showAfterLoad: true,
        selector: '',
        selectWithin: '',
        nextHtml: '',
        prevHtml: '',

        // 0, 1
        index: false,

        iframeMaxWidth: '100%',

        download: false,
        counter: true,
        appendCounterTo: '.lg-toolbar',

        swipeThreshold: 50,
        enableSwipe: true,
        enableDrag: true,

        dynamic: false,
        dynamicEl: [],
        galleryId: 1
    };

    function Plugin(element, options) {

        // Current lightGallery element
        this.el = element;

        // Current jquery element
        this.$el = $(element);

        // lightGallery settings
        this.s = $.extend({}, defaults, options);

        // When using dynamic mode, ensure dynamicEl is an array
        if (this.s.dynamic && this.s.dynamicEl !== 'undefined' && this.s.dynamicEl.constructor === Array && !this.s.dynamicEl.length) {
            throw ('When using dynamic mode, you must also define dynamicEl as an Array.');
        }

        // lightGallery modules
        this.modules = {};

        // false when lightgallery complete first slide;
        this.lGalleryOn = false;

        this.lgBusy = false;

        // Timeout function for hiding controls;
        this.hideBartimeout = false;

        // To determine browser supports for touch events;
        this.isTouch = ('ontouchstart' in document.documentElement);

        // Disable hideControlOnEnd if sildeEndAnimation is true
        if (this.s.slideEndAnimatoin) {
            this.s.hideControlOnEnd = false;
        }

        // Gallery items
        if (this.s.dynamic) {
            this.$items = this.s.dynamicEl;
        } else {
            if (this.s.selector === 'this') {
                this.$items = this.$el;
            } else if (this.s.selector !== '') {
                if (this.s.selectWithin) {
                    this.$items = $(this.s.selectWithin).find(this.s.selector);
                } else {
                    this.$items = this.$el.find($(this.s.selector));
                }
            } else {
                this.$items = this.$el.children();
            }
        }

        // .lg-item
        this.$slide = '';

        // .lg-outer
        this.$outer = '';

        this.init();

        return this;
    }

    Plugin.prototype.init = function() {

        var _this = this;

        // s.preload should not be more than $item.length
        if (_this.s.preload > _this.$items.length) {
            _this.s.preload = _this.$items.length;
        }

        // if dynamic option is enabled execute immediately
        var _hash = window.location.hash;
        if (_hash.indexOf('lg=' + this.s.galleryId) > 0) {

            _this.index = parseInt(_hash.split('&slide=')[1], 10);

            $('body').addClass('lg-from-hash');
            if (!$('body').hasClass('lg-on')) {
                setTimeout(function() {
                    _this.build(_this.index);
                    $('body').addClass('lg-on');
                });
            }
        }

        if (_this.s.dynamic) {

            _this.$el.trigger('onBeforeOpen.lg');

            _this.index = _this.s.index || 0;

            // prevent accidental double execution
            if (!$('body').hasClass('lg-on')) {
                setTimeout(function() {
                    _this.build(_this.index);
                    $('body').addClass('lg-on');
                });
            }
        } else {

            // Using different namespace for click because click event should not unbind if selector is same object('this')
            _this.$items.on('click.lgcustom', function(event) {

                // For IE8
                try {
                    event.preventDefault();
                    event.preventDefault();
                } catch (er) {
                    event.returnValue = false;
                }

                _this.$el.trigger('onBeforeOpen.lg');

                _this.index = _this.s.index || _this.$items.index(this);

                // prevent accidental double execution
                if (!$('body').hasClass('lg-on')) {
                    _this.build(_this.index);
                    $('body').addClass('lg-on');
                }
            });
        }

    };

    Plugin.prototype.build = function(index) {

        var _this = this;

        _this.structure();

        // module constructor
        $.each($.fn.lightGallery.modules, function(key) {
            _this.modules[key] = new $.fn.lightGallery.modules[key](_this.el);
        });

        // initiate slide function
        _this.slide(index, false, false);

        if (_this.s.keyPress) {
            _this.keyPress();
        }

        if (_this.$items.length > 1) {

            _this.arrow();

            setTimeout(function() {
                _this.enableDrag();
                _this.enableSwipe();
            }, 50);

            if (_this.s.mousewheel) {
                _this.mousewheel();
            }
        }

        _this.counter();

        _this.closeGallery();

        _this.$el.trigger('onAfterOpen.lg');

        // Hide controllers if mouse doesn't move for some period
        _this.$outer.on('mousemove.lg click.lg touchstart.lg', function() {

            _this.$outer.removeClass('lg-hide-items');

            clearTimeout(_this.hideBartimeout);

            // Timeout will be cleared on each slide movement also
            _this.hideBartimeout = setTimeout(function() {
                _this.$outer.addClass('lg-hide-items');
            }, _this.s.hideBarsDelay);

        });

    };

    Plugin.prototype.structure = function() {
        var list = '';
        var controls = '';
        var i = 0;
        var subHtmlCont = '';
        var template;
        var _this = this;

        $('body').append('<div class="lg-backdrop"></div>');
        $('.lg-backdrop').css('transition-duration', this.s.backdropDuration + 'ms');

        // Create gallery items
        for (i = 0; i < this.$items.length; i++) {
            list += '<div class="lg-item"></div>';
        }

        // Create controlls
        if (this.s.controls && this.$items.length > 1) {
            controls = '<div class="lg-actions">' +
                '<div class="icon-previous">' + this.s.prevHtml + '</div>' +
                '<div class="icon-next">' + this.s.nextHtml + '</div>' +
                '</div>';
        }

        if (this.s.appendSubHtmlTo === '.lg-sub-html') {
            subHtmlCont = ' ';
        }

        template = '<div class="container">'+'<div class="lg-outer ' + this.s.addClass + ' ' + this.s.startClass + '">' +
            '<div class="lg-toolbar group">' +
            '<span class="icon-close"></span>' +
            '</div>' +
            controls +
            '<div class="lg" style="width:' + this.s.width + '; height:' + this.s.height + '">' +
            '<div class="lg-inner">' + list + '</div>' +
            subHtmlCont +
            '</div>' +
            '</div>'
            '</div>';

        $('body').append(template);
        this.$outer = $('.lg-outer');
        this.$slide = this.$outer.find('.lg-item');

        if (this.s.useLeft) {
            this.$outer.addClass('lg-use-left');

            // Set mode lg-slide if use left is true;
            this.s.mode = 'lg-slide';
        } else {
            this.$outer.addClass('lg-use-css3');
        }

        // For fixed height gallery
        _this.setTop();
        $(window).on('resize.lg orientationchange.lg', function() {
            setTimeout(function() {
                _this.setTop();
            }, 100);
        });

        // add class lg-current to remove initial transition
        this.$slide.eq(this.index).addClass('lg-current');

        // add Class for css support and transition mode
        if (this.doCss()) {
            this.$outer.addClass('lg-css3');
        } else {
            this.$outer.addClass('lg-css');

            // Set speed 0 because no animation will happen if browser doesn't support css3
            this.s.speed = 0;
        }

        this.$outer.addClass(this.s.mode);

        if (this.s.enableDrag && this.$items.length > 1) {
            this.$outer.addClass('lg-grab');
        }

        if (this.s.showAfterLoad) {
            this.$outer.addClass('lg-show-after-load');
        }

        if (this.doCss()) {
            var $inner = this.$outer.find('.lg-inner');
            $inner.css('transition-timing-function', this.s.cssEasing);
            $inner.css('transition-duration', this.s.speed + 'ms');
        }

        $('.lg-backdrop').addClass('in');

        setTimeout(function() {
            _this.$outer.addClass('lg-visible');
        }, this.s.backdropDuration);

        

        // Store the current scroll top value to scroll back after closing the gallery..
        this.prevScrollTop = $(window).scrollTop();

    };

    // For fixed height gallery
    Plugin.prototype.setTop = function() {
        if (this.s.height !== '100%') {
            var wH = $(window).height();
            var top = (wH - parseInt(this.s.height, 10)) / 2;
            var $lGallery = this.$outer.find('.lg');
            if (wH >= parseInt(this.s.height, 10)) {
                $lGallery.css('top', top + 'px');
            } else {
                $lGallery.css('top', '0px');
            }
        }
    };

    // Find css3 support
    Plugin.prototype.doCss = function() {
        // check for css animation support
        var support = function() {
            var transition = ['transition', 'MozTransition', 'WebkitTransition', 'OTransition', 'msTransition', 'KhtmlTransition'];
            var root = document.documentElement;
            var i = 0;
            for (i = 0; i < transition.length; i++) {
                if (transition[i] in root.style) {
                    return true;
                }
            }
        };

        if (support()) {
            return true;
        }

        return false;
    };

    /**
     *  @desc Check the given src is video
     *  @param {String} src
     *  @return {Object} video type
     *  Ex:{ youtube  :  ["//www.youtube.com/watch?v=c0asJgSyxcY", "c0asJgSyxcY"] }
     */
    Plugin.prototype.isVideo = function(src, index) {

        var html;
        if (this.s.dynamic) {
            html = this.s.dynamicEl[index].html;
        } else {
            html = this.$items.eq(index).attr('data-html');
        }

        if (!src && html) {
            return {
                html5: true
            };
        }

        var youtube = src.match(/\/\/(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=|embed\/)?([a-z0-9\-\_\%]+)/i);
        var vimeo = src.match(/\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+)/i);
        var dailymotion = src.match(/\/\/(?:www\.)?dai.ly\/([0-9a-z\-_]+)/i);
        var vk = src.match(/\/\/(?:www\.)?(?:vk\.com|vkontakte\.ru)\/(?:video_ext\.php\?)(.*)/i);

        if (youtube) {
            return {
                youtube: youtube
            };
        } else if (vimeo) {
            return {
                vimeo: vimeo
            };
        } else if (dailymotion) {
            return {
                dailymotion: dailymotion
            };
        } else if (vk) {
            return {
                vk: vk
            };
        }
    };

    /**
     *  @desc Create image counter
     *  Ex: 1/10
     */
    Plugin.prototype.counter = function() {
        if (this.s.counter) {
            $(this.s.appendCounterTo).append('<div id="lg-counter"><span id="lg-counter-current">' + (parseInt(this.index, 10) + 1) + '</span> / <span id="lg-counter-all">' + this.$items.length + '</span></div>');
        }
    };

    /**
     *  @desc add sub-html into the slide
     *  @param {Number} index - index of the slide
     */
    Plugin.prototype.addHtml = function(index) {
        var subHtml = null;
        var subHtmlUrl;
        if (this.s.dynamic) {
            if (this.s.dynamicEl[index].subHtmlUrl) {
                subHtmlUrl = this.s.dynamicEl[index].subHtmlUrl;
            } else {
                subHtml = this.s.dynamicEl[index].subHtml;
            }
        } else {
            if (this.$items.eq(index).attr('data-sub-html-url')) {
                subHtmlUrl = this.$items.eq(index).attr('data-sub-html-url');
            } else {

                subHtml = this.$items.eq(index).attr('data-sub-html');
                if (this.s.getCaptionFromTitleOrAlt && !subHtml) {
                    subHtml = this.$items.eq(index).attr('title') || this.$items.eq(index).find('img').first().attr('alt');
                }
            }
        }

        if (!subHtmlUrl) {
            if (typeof subHtml !== 'undefined' && subHtml !== null) {

                // get first letter of subhtml
                // if first letter starts with . or # get the html form the jQuery object
                var fL = subHtml.substring(0, 1);
                if (fL === '.' || fL === '#') {
                    subHtml = $(subHtml).html();
                }
            } else {
                subHtml = '';
            }
        }

        if (this.s.appendSubHtmlTo === '.lg-sub-html') {

            if (subHtmlUrl) {
                this.$outer.find(this.s.appendSubHtmlTo).load(subHtmlUrl);
            } else {
                this.$outer.find(this.s.appendSubHtmlTo).html(subHtml);
            }

        } else {

            if (subHtmlUrl) {
                this.$slide.eq(index).load(subHtmlUrl);
            } else {
                this.$slide.eq(index).append(subHtml);
            }
        }

        // Add lg-empty-html class if title doesn't exist
        if (typeof subHtml !== 'undefined' && subHtml !== null) {
            if (subHtml === '') {
                this.$outer.find(this.s.appendSubHtmlTo).addClass('lg-empty-html');
            } else {
                this.$outer.find(this.s.appendSubHtmlTo).removeClass('lg-empty-html');
            }
        }

        this.$el.trigger('onAfterAppendSubHtml.lg', [index]);
    };

    /**
     *  @desc Preload slides
     *  @param {Number} index - index of the slide
     */
    Plugin.prototype.preload = function(index) {
        var i = 1;
        var j = 1;
        for (i = 1; i <= this.s.preload; i++) {
            if (i >= this.$items.length - index) {
                break;
            }

            this.loadContent(index + i, false, 0);
        }

        for (j = 1; j <= this.s.preload; j++) {
            if (index - j < 0) {
                break;
            }

            this.loadContent(index - j, false, 0);
        }
    };

    /**
     *  @desc Load slide content into slide.
     *  @param {Number} index - index of the slide.
     *  @param {Boolean} rec - if true call loadcontent() function again.
     *  @param {Boolean} delay - delay for adding complete class. it is 0 except first time.
     */
    Plugin.prototype.loadContent = function(index, rec, delay) {

        var _this = this;
        var _hasPoster = false;
        var _$img;
        var _src;
        var _poster;
        var _srcset;
        var _sizes;
        var _html;
        var getResponsiveSrc = function(srcItms) {
            var rsWidth = [];
            var rsSrc = [];
            for (var i = 0; i < srcItms.length; i++) {
                var __src = srcItms[i].split(' ');

                // Manage empty space
                if (__src[0] === '') {
                    __src.splice(0, 1);
                }

                rsSrc.push(__src[0]);
                rsWidth.push(__src[1]);
            }

            var wWidth = $(window).width();
            for (var j = 0; j < rsWidth.length; j++) {
                if (parseInt(rsWidth[j], 10) > wWidth) {
                    _src = rsSrc[j];
                    break;
                }
            }
        };

        if (_this.s.dynamic) {

            if (_this.s.dynamicEl[index].poster) {
                _hasPoster = true;
                _poster = _this.s.dynamicEl[index].poster;
            }

            _html = _this.s.dynamicEl[index].html;
            _src = _this.s.dynamicEl[index].src;

            if (_this.s.dynamicEl[index].responsive) {
                var srcDyItms = _this.s.dynamicEl[index].responsive.split(',');
                getResponsiveSrc(srcDyItms);
            }

            _srcset = _this.s.dynamicEl[index].srcset;
            _sizes = _this.s.dynamicEl[index].sizes;

        } else {

            if (_this.$items.eq(index).attr('data-poster')) {
                _hasPoster = true;
                _poster = _this.$items.eq(index).attr('data-poster');
            }

            _html = _this.$items.eq(index).attr('data-html');
            _src = _this.$items.eq(index).attr('href') || _this.$items.eq(index).attr('data-src');

            if (_this.$items.eq(index).attr('data-responsive')) {
                var srcItms = _this.$items.eq(index).attr('data-responsive').split(',');
                getResponsiveSrc(srcItms);
            }

            _srcset = _this.$items.eq(index).attr('data-srcset');
            _sizes = _this.$items.eq(index).attr('data-sizes');

        }

        //if (_src || _srcset || _sizes || _poster) {

        var iframe = false;
        if (_this.s.dynamic) {
            if (_this.s.dynamicEl[index].iframe) {
                iframe = true;
            }
        } else {
            if (_this.$items.eq(index).attr('data-iframe') === 'true') {
                iframe = true;
            }
        }

        var _isVideo = _this.isVideo(_src, index);
        if (!_this.$slide.eq(index).hasClass('lg-loaded')) {
            if (iframe) {
                _this.$slide.eq(index).prepend('<div class="lg-video-cont" style="max-width:' + _this.s.iframeMaxWidth + '"><div class="lg-video"><iframe class="lg-object" frameborder="0" src="' + _src + '"  allowfullscreen="true"></iframe></div></div>');
            } else if (_hasPoster) {
                var videoClass = '';
                if (_isVideo && _isVideo.youtube) {
                    videoClass = 'lg-has-youtube';
                } else if (_isVideo && _isVideo.vimeo) {
                    videoClass = 'lg-has-vimeo';
                } else {
                    videoClass = 'lg-has-html5';
                }

                _this.$slide.eq(index).prepend('<div class="lg-video-cont ' + videoClass + ' "><div class="lg-video"><span class="lg-video-play"></span><img class="lg-object lg-has-poster" src="' + _poster + '" /></div></div>');

            } else if (_isVideo) {
                _this.$slide.eq(index).prepend('<div class="lg-video-cont "><div class="lg-video"></div></div>');
                _this.$el.trigger('hasVideo.lg', [index, _src, _html]);
            } else {
                _this.$slide.eq(index).prepend('<div class="lg-img-wrap"><img class="lg-object lg-image" src="' + _src + '" /><div class="lg-sub-html"></div></div>');
            }

            _this.$el.trigger('onAferAppendSlide.lg', [index]);

            _$img = _this.$slide.eq(index).find('.lg-object');
            if (_sizes) {
                _$img.attr('sizes', _sizes);
            }

            if (_srcset) {
                _$img.attr('srcset', _srcset);
                try {
                    picturefill({
                        elements: [_$img[0]]
                    });
                } catch (e) {
                    console.error('Make sure you have included Picturefill version 2');
                }
            }

            if (this.s.appendSubHtmlTo !== '.lg-sub-html') {
                _this.addHtml(index);
            }

            _this.$slide.eq(index).addClass('lg-loaded');
        }

        _this.$slide.eq(index).find('.lg-object').on('load.lg error.lg', function() {

            // For first time add some delay for displaying the start animation.
            var _speed = 0;

            // Do not change the delay value because it is required for zoom plugin.
            // If gallery opened from direct url (hash) speed value should be 0
            if (delay && !$('body').hasClass('lg-from-hash')) {
                _speed = delay;
            }

            setTimeout(function() {
                _this.$slide.eq(index).addClass('lg-complete');
                _this.$el.trigger('onSlideItemLoad.lg', [index, delay || 0]);
            }, _speed);

        });

        // @todo check load state for html5 videos
        if (_isVideo && _isVideo.html5 && !_hasPoster) {
            _this.$slide.eq(index).addClass('lg-complete');
        }

        if (rec === true) {
            if (!_this.$slide.eq(index).hasClass('lg-complete')) {
                _this.$slide.eq(index).find('.lg-object').on('load.lg error.lg', function() {
                    _this.preload(index);
                });
            } else {
                _this.preload(index);
            }
        }

        //}
    };

    /**
    *   @desc slide function for lightgallery
        ** Slide() gets call on start
        ** ** Set lg.on true once slide() function gets called.
        ** Call loadContent() on slide() function inside setTimeout
        ** ** On first slide we do not want any animation like slide of fade
        ** ** So on first slide( if lg.on if false that is first slide) loadContent() should start loading immediately
        ** ** Else loadContent() should wait for the transition to complete.
        ** ** So set timeout s.speed + 50
    <=> ** loadContent() will load slide content in to the particular slide
        ** ** It has recursion (rec) parameter. if rec === true loadContent() will call preload() function.
        ** ** preload will execute only when the previous slide is fully loaded (images iframe)
        ** ** avoid simultaneous image load
    <=> ** Preload() will check for s.preload value and call loadContent() again accoring to preload value
        ** loadContent()  <====> Preload();

    *   @param {Number} index - index of the slide
    *   @param {Boolean} fromTouch - true if slide function called via touch event or mouse drag
    *   @param {Boolean} fromThumb - true if slide function called via thumbnail click
    */
    Plugin.prototype.slide = function(index, fromTouch, fromThumb) {

        var _prevIndex = this.$outer.find('.lg-current').index();
        var _this = this;

        // Prevent if multiple call
        // Required for hsh plugin
        if (_this.lGalleryOn && (_prevIndex === index)) {
            return;
        }

        var _length = this.$slide.length;
        var _time = _this.lGalleryOn ? this.s.speed : 0;
        var _next = false;
        var _prev = false;

        if (!_this.lgBusy) {

            if (this.s.download) {
                var _src;
                if (_this.s.dynamic) {
                    _src = _this.s.dynamicEl[index].downloadUrl !== false && (_this.s.dynamicEl[index].downloadUrl || _this.s.dynamicEl[index].src);
                } else {
                    _src = _this.$items.eq(index).attr('data-download-url') !== 'false' && (_this.$items.eq(index).attr('data-download-url') || _this.$items.eq(index).attr('href') || _this.$items.eq(index).attr('data-src'));

                }

                if (_src) {
                    $('#lg-download').attr('href', _src);
                    _this.$outer.removeClass('lg-hide-download');
                } else {
                    _this.$outer.addClass('lg-hide-download');
                }
            }

            this.$el.trigger('onBeforeSlide.lg', [_prevIndex, index, fromTouch, fromThumb]);

            _this.lgBusy = true;

            clearTimeout(_this.hideBartimeout);

            // Add title if this.s.appendSubHtmlTo === lg-sub-html
            if (this.s.appendSubHtmlTo === '.lg-sub-html') {

                // wait for slide animation to complete
                setTimeout(function() {
                    _this.addHtml(index);
                }, _time);
            }

            this.arrowDisable(index);

            if (!fromTouch) {

                // remove all transitions
                _this.$outer.addClass('lg-no-trans');

                this.$slide.removeClass('lg-prev-slide lg-next-slide');

                if (index < _prevIndex) {
                    _prev = true;
                    if ((index === 0) && (_prevIndex === _length - 1) && !fromThumb) {
                        _prev = false;
                        _next = true;
                    }
                } else if (index > _prevIndex) {
                    _next = true;
                    if ((index === _length - 1) && (_prevIndex === 0) && !fromThumb) {
                        _prev = true;
                        _next = false;
                    }
                }

                if (_prev) {

                    //prevslide
                    this.$slide.eq(index).addClass('lg-prev-slide');
                    this.$slide.eq(_prevIndex).addClass('lg-next-slide');
                } else if (_next) {

                    // next slide
                    this.$slide.eq(index).addClass('lg-next-slide');
                    this.$slide.eq(_prevIndex).addClass('lg-prev-slide');
                }

                // give 50 ms for browser to add/remove class
                setTimeout(function() {
                    _this.$slide.removeClass('lg-current');

                    //_this.$slide.eq(_prevIndex).removeClass('lg-current');
                    _this.$slide.eq(index).addClass('lg-current');

                    // reset all transitions
                    _this.$outer.removeClass('lg-no-trans');
                }, 50);
            } else {

                var touchPrev = index - 1;
                var touchNext = index + 1;

                if ((index === 0) && (_prevIndex === _length - 1)) {

                    // next slide
                    touchNext = 0;
                    touchPrev = _length - 1;
                } else if ((index === _length - 1) && (_prevIndex === 0)) {

                    // prev slide
                    touchNext = 0;
                    touchPrev = _length - 1;
                }

                this.$slide.removeClass('lg-prev-slide lg-current lg-next-slide');
                _this.$slide.eq(touchPrev).addClass('lg-prev-slide');
                _this.$slide.eq(touchNext).addClass('lg-next-slide');
                _this.$slide.eq(index).addClass('lg-current');
            }

            if (_this.lGalleryOn) {
                setTimeout(function() {
                    _this.loadContent(index, true, 0);
                }, this.s.speed + 50);

                setTimeout(function() {
                    _this.lgBusy = false;
                    _this.$el.trigger('onAfterSlide.lg', [_prevIndex, index, fromTouch, fromThumb]);
                }, this.s.speed);

            } else {
                _this.loadContent(index, true, _this.s.backdropDuration);

                _this.lgBusy = false;
                _this.$el.trigger('onAfterSlide.lg', [_prevIndex, index, fromTouch, fromThumb]);
            }

            _this.lGalleryOn = true;

            if (this.s.counter) {
                $('#lg-counter-current').text(index + 1);
            }

        }

    };

    /**
     *  @desc Go to next slide
     *  @param {Boolean} fromTouch - true if slide function called via touch event
     */
    Plugin.prototype.goToNextSlide = function(fromTouch) {
        var _this = this;
        if (!_this.lgBusy) {
            if ((_this.index + 1) < _this.$slide.length) {
                _this.index++;
                _this.$el.trigger('onBeforeNextSlide.lg', [_this.index]);
                _this.slide(_this.index, fromTouch, false);
            } else {
                if (_this.s.loop) {
                    _this.index = 0;
                    _this.$el.trigger('onBeforeNextSlide.lg', [_this.index]);
                    _this.slide(_this.index, fromTouch, false);
                } else if (_this.s.slideEndAnimatoin) {
                    _this.$outer.addClass('lg-right-end');
                    setTimeout(function() {
                        _this.$outer.removeClass('lg-right-end');
                    }, 400);
                }
            }
        }
    };

    /**
     *  @desc Go to previous slide
     *  @param {Boolean} fromTouch - true if slide function called via touch event
     */
    Plugin.prototype.goToPrevSlide = function(fromTouch) {
        var _this = this;
        if (!_this.lgBusy) {
            if (_this.index > 0) {
                _this.index--;
                _this.$el.trigger('onBeforePrevSlide.lg', [_this.index, fromTouch]);
                _this.slide(_this.index, fromTouch, false);
            } else {
                if (_this.s.loop) {
                    _this.index = _this.$items.length - 1;
                    _this.$el.trigger('onBeforePrevSlide.lg', [_this.index, fromTouch]);
                    _this.slide(_this.index, fromTouch, false);
                } else if (_this.s.slideEndAnimatoin) {
                    _this.$outer.addClass('lg-left-end');
                    setTimeout(function() {
                        _this.$outer.removeClass('lg-left-end');
                    }, 400);
                }
            }
        }
    };

    Plugin.prototype.keyPress = function() {
        var _this = this;
        if (this.$items.length > 1) {
            $(window).on('keyup.lg', function(e) {
                if (_this.$items.length > 1) {
                    if (e.keyCode === 37) {
                        e.preventDefault();
                        _this.goToPrevSlide();
                    }

                    if (e.keyCode === 39) {
                        e.preventDefault();
                        _this.goToNextSlide();
                    }
                }
            });
        }

        $(window).on('keydown.lg', function(e) {
            if (_this.s.escKey === true && e.keyCode === 27) {
                e.preventDefault();
                if (!_this.$outer.hasClass('lg-thumb-open')) {
                    _this.destroy();
                } else {
                    _this.$outer.removeClass('lg-thumb-open');
                }
            }
        });
    };

    Plugin.prototype.arrow = function() {
        var _this = this;
        this.$outer.find('.icon-previous').on('click.lg', function() {
            _this.goToPrevSlide();
        });

        this.$outer.find('.icon-next').on('click.lg', function() {
            _this.goToNextSlide();
        });
    };

    Plugin.prototype.arrowDisable = function(index) {

        // Disable arrows if s.hideControlOnEnd is true
        if (!this.s.loop && this.s.hideControlOnEnd) {
            if ((index + 1) < this.$slide.length) {
                this.$outer.find('.lg-next').removeAttr('disabled').removeClass('disabled');
            } else {
                this.$outer.find('.lg-next').attr('disabled', 'disabled').addClass('disabled');
            }

            if (index > 0) {
                this.$outer.find('.lg-prev').removeAttr('disabled').removeClass('disabled');
            } else {
                this.$outer.find('.lg-prev').attr('disabled', 'disabled').addClass('disabled');
            }
        }
    };

    Plugin.prototype.setTranslate = function($el, xValue, yValue) {
        // jQuery supports Automatic CSS prefixing since jQuery 1.8.0
        if (this.s.useLeft) {
            $el.css('left', xValue);
        } else {
            $el.css({
                transform: 'translate3d(' + (xValue) + 'px, ' + yValue + 'px, 0px)'
            });
        }
    };

    Plugin.prototype.touchMove = function(startCoords, endCoords) {

        var distance = endCoords - startCoords;

        if (Math.abs(distance) > 15) {
            // reset opacity and transition duration
            this.$outer.addClass('lg-dragging');

            // move current slide
            this.setTranslate(this.$slide.eq(this.index), distance, 0);

            // move next and prev slide with current slide
            this.setTranslate($('.lg-prev-slide'), -this.$slide.eq(this.index).width() + distance, 0);
            this.setTranslate($('.lg-next-slide'), this.$slide.eq(this.index).width() + distance, 0);
        }
    };

    Plugin.prototype.touchEnd = function(distance) {
        var _this = this;

        // keep slide animation for any mode while dragg/swipe
        if (_this.s.mode !== 'lg-slide') {
            _this.$outer.addClass('lg-slide');
        }

        this.$slide.not('.lg-current, .lg-prev-slide, .lg-next-slide').css('opacity', '0');

        // set transition duration
        setTimeout(function() {
            _this.$outer.removeClass('lg-dragging');
            if ((distance < 0) && (Math.abs(distance) > _this.s.swipeThreshold)) {
                _this.goToNextSlide(true);
            } else if ((distance > 0) && (Math.abs(distance) > _this.s.swipeThreshold)) {
                _this.goToPrevSlide(true);
            } else if (Math.abs(distance) < 5) {

                // Trigger click if distance is less than 5 pix
                _this.$el.trigger('onSlideClick.lg');
            }

            _this.$slide.removeAttr('style');
        });

        // remove slide class once drag/swipe is completed if mode is not slide
        setTimeout(function() {
            if (!_this.$outer.hasClass('lg-dragging') && _this.s.mode !== 'lg-slide') {
                _this.$outer.removeClass('lg-slide');
            }
        }, _this.s.speed + 100);

    };

    Plugin.prototype.enableSwipe = function() {
        var _this = this;
        var startCoords = 0;
        var endCoords = 0;
        var isMoved = false;

        if (_this.s.enableSwipe && _this.isTouch && _this.doCss()) {

            _this.$slide.on('touchstart.lg', function(e) {
                if (!_this.$outer.hasClass('lg-zoomed') && !_this.lgBusy) {
                    e.preventDefault();
                    _this.manageSwipeClass();
                    startCoords = e.originalEvent.targetTouches[0].pageX;
                }
            });

            _this.$slide.on('touchmove.lg', function(e) {
                if (!_this.$outer.hasClass('lg-zoomed')) {
                    e.preventDefault();
                    endCoords = e.originalEvent.targetTouches[0].pageX;
                    _this.touchMove(startCoords, endCoords);
                    isMoved = true;
                }
            });

            _this.$slide.on('touchend.lg', function() {
                if (!_this.$outer.hasClass('lg-zoomed')) {
                    if (isMoved) {
                        isMoved = false;
                        _this.touchEnd(endCoords - startCoords);
                    } else {
                        _this.$el.trigger('onSlideClick.lg');
                    }
                }
            });
        }

    };

    Plugin.prototype.enableDrag = function() {
        var _this = this;
        var startCoords = 0;
        var endCoords = 0;
        var isDraging = false;
        var isMoved = false;
        if (_this.s.enableDrag && !_this.isTouch && _this.doCss()) {
            _this.$slide.on('mousedown.lg', function(e) {
                // execute only on .lg-object
                if (!_this.$outer.hasClass('lg-zoomed')) {
                    if ($(e.target).hasClass('lg-object') || $(e.target).hasClass('lg-video-play')) {
                        e.preventDefault();

                        if (!_this.lgBusy) {
                            _this.manageSwipeClass();
                            startCoords = e.pageX;
                            isDraging = true;

                            // ** Fix for webkit cursor issue https://code.google.com/p/chromium/issues/detail?id=26723
                            _this.$outer.scrollLeft += 1;
                            _this.$outer.scrollLeft -= 1;

                            // *

                            _this.$outer.removeClass('lg-grab').addClass('lg-grabbing');

                            _this.$el.trigger('onDragstart.lg');
                        }

                    }
                }
            });

            $(window).on('mousemove.lg', function(e) {
                if (isDraging) {
                    isMoved = true;
                    endCoords = e.pageX;
                    _this.touchMove(startCoords, endCoords);
                    _this.$el.trigger('onDragmove.lg');
                }
            });

            $(window).on('mouseup.lg', function(e) {
                if (isMoved) {
                    isMoved = false;
                    _this.touchEnd(endCoords - startCoords);
                    _this.$el.trigger('onDragend.lg');
                } else if ($(e.target).hasClass('lg-object') || $(e.target).hasClass('lg-video-play')) {
                    _this.$el.trigger('onSlideClick.lg');
                }

                // Prevent execution on click
                if (isDraging) {
                    isDraging = false;
                    _this.$outer.removeClass('lg-grabbing').addClass('lg-grab');
                }
            });

        }
    };

    Plugin.prototype.manageSwipeClass = function() {
        var touchNext = this.index + 1;
        var touchPrev = this.index - 1;
        var length = this.$slide.length;
        if (this.s.loop) {
            if (this.index === 0) {
                touchPrev = length - 1;
            } else if (this.index === length - 1) {
                touchNext = 0;
            }
        }

        this.$slide.removeClass('lg-next-slide lg-prev-slide');
        if (touchPrev > -1) {
            this.$slide.eq(touchPrev).addClass('lg-prev-slide');
        }

        this.$slide.eq(touchNext).addClass('lg-next-slide');
    };

    Plugin.prototype.mousewheel = function() {
        var _this = this;
        _this.$outer.on('mousewheel.lg', function(e) {

            if (!e.deltaY) {
                return;
            }

            if (e.deltaY > 0) {
                _this.goToPrevSlide();
            } else {
                _this.goToNextSlide();
            }

            e.preventDefault();
        });

    };

    Plugin.prototype.closeGallery = function() {

        var _this = this;
        var mousedown = false;
        this.$outer.find('.icon-close').on('click.lg', function() {
            _this.destroy();
        });

        if (_this.s.closable) {

            // If you drag the slide and release outside gallery gets close on chrome
            // for preventing this check mousedown and mouseup happened on .lg-item or lg-outer
            _this.$outer.on('mousedown.lg', function(e) {

                if ($(e.target).is('.lg-outer') || $(e.target).is('.lg-item ') || $(e.target).is('.lg-img-wrap')) {
                    mousedown = true;
                } else {
                    mousedown = false;
                }

            });

            _this.$outer.on('mouseup.lg', function(e) {

                if ($(e.target).is('.lg-outer') || $(e.target).is('.lg-item ') || $(e.target).is('.lg-img-wrap') && mousedown) {
                    if (!_this.$outer.hasClass('lg-dragging')) {
                        _this.destroy();
                    }
                }

            });

        }

    };

    Plugin.prototype.destroy = function(d) {

        var _this = this;

        if (!d) {
            _this.$el.trigger('onBeforeClose.lg');
        }

        $(window).scrollTop(_this.prevScrollTop);

        /**
         * if d is false or undefined destroy will only close the gallery
         * plugins instance remains with the element
         *
         * if d is true destroy will completely remove the plugin
         */

        if (d) {
            if (!_this.s.dynamic) {
                // only when not using dynamic mode is $items a jquery collection
                this.$items.off('click.lg click.lgcustom');
            }

            $.removeData(_this.el, 'lightGallery');
        }

        // Unbind all events added by lightGallery
        this.$el.off('.lg.tm');

        // Distroy all lightGallery modules
        $.each($.fn.lightGallery.modules, function(key) {
            if (_this.modules[key]) {
                _this.modules[key].destroy();
            }
        });

        this.lGalleryOn = false;

        clearTimeout(_this.hideBartimeout);
        this.hideBartimeout = false;
        $(window).off('.lg');
        $('body').removeClass('lg-on lg-from-hash');

        if (_this.$outer) {
            _this.$outer.removeClass('lg-visible');
        }

        $('.lg-backdrop').removeClass('in');

        setTimeout(function() {
            if (_this.$outer) {
                _this.$outer.remove();
            }

            $('.lg-backdrop').remove();

            if (!d) {
                _this.$el.trigger('onCloseAfter.lg');
            }

        }, _this.s.backdropDuration + 50);
    };

    $.fn.lightGallery = function(options) {
        return this.each(function() {
            if (!$.data(this, 'lightGallery')) {
                $.data(this, 'lightGallery', new Plugin(this, options));
            } else {
                try {
                    $(this).data('lightGallery').init();
                } catch (err) {
                    console.error('lightGallery has not initiated properly');
                }
            }
        });
    };

    $.fn.lightGallery.modules = {};

})(jQuery, window, document);

$(document).ready(function () {
    
});
;
/*! lightgallery - v1.2.19 - 2016-05-17
* http://sachinchoolur.github.io/lightGallery/
* Copyright (c) 2016 Sachin N; Licensed Apache 2.0 */
(function($, window, document, undefined) {

    'use strict';

    var defaults = {
        thumbnail: true,

        animateThumb: true,
        currentPagerPosition: 'middle',

        thumbWidth: 120,
        thumbContHeight: 100,
        thumbMargin: 5,

        exThumbImage: false,
        showThumbByDefault: true,
        toogleThumb: true,
        pullCaptionUp: true,

        enableThumbDrag: true,
        enableThumbSwipe: true,
        swipeThreshold: 50,

        loadYoutubeThumbnail: true,
        youtubeThumbSize: 1,

        loadVimeoThumbnail: true,
        vimeoThumbSize: 'thumbnail_small',

        loadDailymotionThumbnail: true
    };
    
    var Thumbnail = function(element) {
        // get lightGallery core plugin data
        this.core = $(element).data('lightGallery');

        // extend module default settings with lightGallery core settings
        this.core.s = $.extend({}, defaults, this.core.s);

        this.$el = $(element);
        this.$thumbOuter = null;
        this.thumbOuterWidth = 0;
        this.thumbTotalWidth = (this.core.$items.length * (this.core.s.thumbWidth + this.core.s.thumbMargin));
        this.thumbIndex = this.core.index;

        // Thumbnail animation value
        this.left = 0;

        this.init();

        return this;
    };

    Thumbnail.prototype.init = function() {
        var _this = this;
        if (this.core.s.thumbnail && this.core.$items.length > 1) {
            if (this.core.s.showThumbByDefault) {
                setTimeout(function(){
                    _this.core.$outer.addClass('lg-thumb-open');
                }, 700);
            }

            if (this.core.s.pullCaptionUp) {
                this.core.$outer.addClass('lg-pull-caption-up');
            }

            this.build();
            if (this.core.s.animateThumb) {
                if (this.core.s.enableThumbDrag && !this.core.isTouch && this.core.doCss()) {
                    this.enableThumbDrag();
                }

                if (this.core.s.enableThumbSwipe && this.core.isTouch && this.core.doCss()) {
                    this.enableThumbSwipe();
                }

                this.thumbClickable = false;
            } else {
                this.thumbClickable = true;
            }

            this.toogle();
            this.thumbkeyPress();
        }
        $('.lg-outer .lg-inner,.icon-previous,.icon-next').on({
            mouseover: function () {
                $('.lg-outer .lg-thumb-outer').fadeOut('fast');
            },
            mouseleave: function () {
                $('.lg-outer .lg-thumb-outer').fadeIn('fast');
            }
        });
    };

    Thumbnail.prototype.build = function() {
        var _this = this;
        var thumbList = '';
        var vimeoErrorThumbSize = '';
        var $thumb;
        var html = '<div class="lg-thumb-outer">' +
            '<div class="lg-thumb group">' +
            '</div>' +
            '</div>';

        switch (this.core.s.vimeoThumbSize) {
            case 'thumbnail_large':
                vimeoErrorThumbSize = '640';
                break;
            case 'thumbnail_medium':
                vimeoErrorThumbSize = '200x150';
                break;
            case 'thumbnail_small':
                vimeoErrorThumbSize = '100x75';
        }

        _this.core.$outer.addClass('lg-has-thumb');

        _this.core.$outer.append(html);

        _this.$thumbOuter = _this.core.$outer.find('.lg-thumb-outer');
        _this.thumbOuterWidth = _this.$thumbOuter.width();

        if (_this.core.s.animateThumb) {
            _this.core.$outer.find('.lg-thumb').css({
                width: _this.thumbTotalWidth + 'px',
                position: 'relative'
            });
        }

        if (this.core.s.animateThumb) {
            _this.$thumbOuter.css('height', _this.core.s.thumbContHeight + 'px');
        }

        function getThumb(src, thumb, index) {
            var isVideo = _this.core.isVideo(src, index) || {};
            var thumbImg;
            var vimeoId = '';

            if (isVideo.youtube || isVideo.vimeo || isVideo.dailymotion) {
                if (isVideo.youtube) {
                    if (_this.core.s.loadYoutubeThumbnail) {
                        thumbImg = '//img.youtube.com/vi/' + isVideo.youtube[1] + '/' + _this.core.s.youtubeThumbSize + '.jpg';
                    } else {
                        thumbImg = thumb;
                    }
                } else if (isVideo.vimeo) {
                    if (_this.core.s.loadVimeoThumbnail) {
                        thumbImg = '//i.vimeocdn.com/video/error_' + vimeoErrorThumbSize + '.jpg';
                        vimeoId = isVideo.vimeo[1];
                    } else {
                        thumbImg = thumb;
                    }
                } else if (isVideo.dailymotion) {
                    if (_this.core.s.loadDailymotionThumbnail) {
                        thumbImg = '//www.dailymotion.com/thumbnail/video/' + isVideo.dailymotion[1];
                    } else {
                        thumbImg = thumb;
                    }
                }
            } else {
                thumbImg = thumb;
            }

            thumbList += '<div data-vimeo-id="' + vimeoId + '" class="lg-thumb-item" style="width:' + _this.core.s.thumbWidth + 'px; margin-right: ' + _this.core.s.thumbMargin + 'px"><img src="' + thumbImg + '" /></div>';
            vimeoId = '';
        }

        if (_this.core.s.dynamic) {
            for (var i = 0; i < _this.core.s.dynamicEl.length; i++) {
                getThumb(_this.core.s.dynamicEl[i].src, _this.core.s.dynamicEl[i].thumb, i);
            }
        } else {
            _this.core.$items.each(function(i) {

                if (!_this.core.s.exThumbImage) {
                    getThumb($(this).attr('href') || $(this).attr('data-src'), $(this).find('img').attr('data-src'), i);
                } else {
                    getThumb($(this).attr('href') || $(this).attr('data-src'), $(this).attr(_this.core.s.exThumbImage), i);
                }

            });
        }

        _this.core.$outer.find('.lg-thumb').html(thumbList);

        $thumb = _this.core.$outer.find('.lg-thumb-item');

        // Load vimeo thumbnails
        $thumb.each(function() {
            var $this = $(this);
            var vimeoVideoId = $this.attr('data-vimeo-id');

            if (vimeoVideoId) {
                $.getJSON('//www.vimeo.com/api/v2/video/' + vimeoVideoId + '.json?callback=?', {
                    format: 'json'
                }, function(data) {
                    $this.find('img').attr('src', data[0][_this.core.s.vimeoThumbSize]);
                });
            }
        });

        // manage active class for thumbnail
        $thumb.eq(_this.core.index).addClass('active');
        _this.core.$el.on('onBeforeSlide.lg.tm', function() {
            $thumb.removeClass('active');
            $thumb.eq(_this.core.index).addClass('active');
        });

        $thumb.on('click.lg touchend.lg', function() {
            var _$this = $(this);
            setTimeout(function() {

                // In IE9 and bellow touch does not support
                // Go to slide if browser does not support css transitions
                if ((_this.thumbClickable && !_this.core.lgBusy) || !_this.core.doCss()) {
                    _this.core.index = _$this.index();
                    _this.core.slide(_this.core.index, false, true);
                }
            }, 50);
        });

        _this.core.$el.on('onBeforeSlide.lg.tm', function() {
            _this.animateThumb(_this.core.index);
        });

        $(window).on('resize.lg.thumb orientationchange.lg.thumb', function() {
            setTimeout(function() {
                _this.animateThumb(_this.core.index);
                _this.thumbOuterWidth = _this.$thumbOuter.width();
            }, 200);
        });

    };

    Thumbnail.prototype.setTranslate = function(value) {
        // jQuery supports Automatic CSS prefixing since jQuery 1.8.0
        this.core.$outer.find('.lg-thumb').css({
            transform: 'translate3d(-' + (value) + 'px, 0px, 0px)'
        });
    };

    Thumbnail.prototype.animateThumb = function(index) {
        var $thumb = this.core.$outer.find('.lg-thumb');
        if (this.core.s.animateThumb) {
            var position;
            switch (this.core.s.currentPagerPosition) {
                case 'left':
                    position = 0;
                    break;
                case 'middle':
                    position = (this.thumbOuterWidth / 2) - (this.core.s.thumbWidth / 2);
                    break;
                case 'right':
                    position = this.thumbOuterWidth - this.core.s.thumbWidth;
            }
            this.left = ((this.core.s.thumbWidth + this.core.s.thumbMargin) * index - 1) - position;
            if (this.left > (this.thumbTotalWidth - this.thumbOuterWidth)) {
                this.left = this.thumbTotalWidth - this.thumbOuterWidth;
            }

            if (this.left < 0) {
                this.left = 0;
            }

            if (this.core.lGalleryOn) {
                if (!$thumb.hasClass('on')) {
                    this.core.$outer.find('.lg-thumb').css('transition-duration', this.core.s.speed + 'ms');
                }

                if (!this.core.doCss()) {
                    $thumb.animate({
                        left: -this.left + 'px'
                    }, this.core.s.speed);
                }
            } else {
                if (!this.core.doCss()) {
                    $thumb.css('left', -this.left + 'px');
                }
            }

            this.setTranslate(this.left);

        }
    };

    // Enable thumbnail dragging and swiping
    Thumbnail.prototype.enableThumbDrag = function() {

        var _this = this;
        var startCoords = 0;
        var endCoords = 0;
        var isDraging = false;
        var isMoved = false;
        var tempLeft = 0;

        _this.$thumbOuter.addClass('lg-grab');

        _this.core.$outer.find('.lg-thumb').on('mousedown.lg.thumb', function(e) {
            if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
                // execute only on .lg-object
                e.preventDefault();
                startCoords = e.pageX;
                isDraging = true;

                // ** Fix for webkit cursor issue https://code.google.com/p/chromium/issues/detail?id=26723
                _this.core.$outer.scrollLeft += 1;
                _this.core.$outer.scrollLeft -= 1;

                // *
                _this.thumbClickable = false;
                _this.$thumbOuter.removeClass('lg-grab').addClass('lg-grabbing');
            }
        });

        $(window).on('mousemove.lg.thumb', function(e) {
            if (isDraging) {
                tempLeft = _this.left;
                isMoved = true;
                endCoords = e.pageX;

                _this.$thumbOuter.addClass('lg-dragging');

                tempLeft = tempLeft - (endCoords - startCoords);

                if (tempLeft > (_this.thumbTotalWidth - _this.thumbOuterWidth)) {
                    tempLeft = _this.thumbTotalWidth - _this.thumbOuterWidth;
                }

                if (tempLeft < 0) {
                    tempLeft = 0;
                }

                // move current slide
                _this.setTranslate(tempLeft);

            }
        });

        $(window).on('mouseup.lg.thumb', function() {
            if (isMoved) {
                isMoved = false;
                _this.$thumbOuter.removeClass('lg-dragging');

                _this.left = tempLeft;

                if (Math.abs(endCoords - startCoords) < _this.core.s.swipeThreshold) {
                    _this.thumbClickable = true;
                }

            } else {
                _this.thumbClickable = true;
            }

            if (isDraging) {
                isDraging = false;
                _this.$thumbOuter.removeClass('lg-grabbing').addClass('lg-grab');
            }
        });

    };

    Thumbnail.prototype.enableThumbSwipe = function() {
        var _this = this;
        var startCoords = 0;
        var endCoords = 0;
        var isMoved = false;
        var tempLeft = 0;

        _this.core.$outer.find('.lg-thumb').on('touchstart.lg', function(e) {
            if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
                e.preventDefault();
                startCoords = e.originalEvent.targetTouches[0].pageX;
                _this.thumbClickable = false;
            }
        });

        _this.core.$outer.find('.lg-thumb').on('touchmove.lg', function(e) {
            if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
                e.preventDefault();
                endCoords = e.originalEvent.targetTouches[0].pageX;
                isMoved = true;

                _this.$thumbOuter.addClass('lg-dragging');

                tempLeft = _this.left;

                tempLeft = tempLeft - (endCoords - startCoords);

                if (tempLeft > (_this.thumbTotalWidth - _this.thumbOuterWidth)) {
                    tempLeft = _this.thumbTotalWidth - _this.thumbOuterWidth;
                }

                if (tempLeft < 0) {
                    tempLeft = 0;
                }

                // move current slide
                _this.setTranslate(tempLeft);

            }
        });

        _this.core.$outer.find('.lg-thumb').on('touchend.lg', function() {
            if (_this.thumbTotalWidth > _this.thumbOuterWidth) {

                if (isMoved) {
                    isMoved = false;
                    _this.$thumbOuter.removeClass('lg-dragging');
                    if (Math.abs(endCoords - startCoords) < _this.core.s.swipeThreshold) {
                        _this.thumbClickable = true;
                    }

                    _this.left = tempLeft;
                } else {
                    _this.thumbClickable = true;
                }
            } else {
                _this.thumbClickable = true;
            }
        });

    };

    Thumbnail.prototype.toogle = function() {
        var _this = this;
        if (_this.core.s.toogleThumb) {
            _this.core.$outer.addClass('lg-can-toggle');
            // _this.$thumbOuter.append('<span class="lg-toogle-thumb lg-icon"></span>');
            // _this.core.$outer.find('.lg-toogle-thumb').on('click.lg', function() {
            //     _this.core.$outer.toggleClass('lg-thumb-open');
            // });
        }
    };

    Thumbnail.prototype.thumbkeyPress = function() {
        var _this = this;
        $(window).on('keydown.lg.thumb', function(e) {
            if (e.keyCode === 38) {
                e.preventDefault();
                _this.core.$outer.addClass('lg-thumb-open');
            } else if (e.keyCode === 40) {
                e.preventDefault();
                _this.core.$outer.removeClass('lg-thumb-open');
            }
        });
    };

    Thumbnail.prototype.destroy = function() {
        if (this.core.s.thumbnail && this.core.$items.length > 1) {
            $(window).off('resize.lg.thumb orientationchange.lg.thumb keydown.lg.thumb');
            this.$thumbOuter.remove();
            this.core.$outer.removeClass('lg-has-thumb');
        }
    };

    $.fn.lightGallery.modules.Thumbnail = Thumbnail;

})(jQuery, window, document);
;
//$(document).ready(function () {
//    showimages_catphoto(CatId);
//});

document.addEventListener("DOMContentLoaded", function (event) {
    setTimeout(function () {
        showimages_catphoto(CatId);
    }, 500);

})

function showimages_catphoto(cat_id) {

    $.ajax({
        url: "/review/CorporateResponse.ashx",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "text",
        data: { type: 'catphoto', catid: cat_id, corp: false },
        responseType: "text/html",
        success: function (data) {

            if (data != '') {
                var arrimagedata = data.split('^');
                $('#divphotos_catphoto').html(arrimagedata[0]);
                $('#divphotos_catphoto').lightGallery();
            }
            else {
                $('#divphotos_catphoto').hide();
            }
        },
        error: function (data, status, jqXHR) { }
    });
}


function initialize() {

    if ($('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_customheader_imgproduct').attr('src').indexOf('map.jpg') > -1) {
        if (lt2 == '0' || lt2 == '') {
            $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_customheader_imgproduct').attr('src', $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_customheader_imgproduct').attr('data-src'));
        }
        else {

            var myLatlng2 = new google.maps.LatLng(lt2, lng2);
            var mapProp2 = {
                center: myLatlng2,
                zoom: 17,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scaleControl: true,
                zoomControl: true,
                zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE }
            };
            var map2 = new google.maps.Map(document.getElementById("dealmap"), mapProp2);

            map2.setTilt(45);
            var marker2 = new google.maps.Marker({
                position: myLatlng2,
                map: map2,
                draggable: false
            });
            marker2.setMap(map2);
            var infowindow1 = new google.maps.InfoWindow({
                content: '<p>Marker Location:' + marker2.getPosition() + '</p>'
            });

            google.maps.event.addListener(marker2, 'click', function () {
                infowindow.open(map2, marker2);
            });

            $('#divdealmap').show();
            $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_customheader_imgproduct').hide();
            $('.product-images').removeClass('product-images');
        }
    }


}

function UrlEncode(str) {
    str = str.replace(/\+/g, "%2b")
    str = escape(str)
    return str
}
function redirectvarients(objdrop) {

    var url_hit = objdrop.options[objdrop.selectedIndex].value
    window.location.href = url_hit

}

function analyseYearChanged() {
    var ddlYrs = $('#analyse_dropdown option:selected').val();
    var lblval = $('#analyse_dropdown option:selected').text();

    $('#analyse_dropdown').val('-1');
    displayLastRatings(ddlYrs, lblval, mergedprods);

}

function displayLastRatings(ddlYrs, lblval, mergedprods) {
    $('#dvAnalyseRating').empty();
    var txt = lblval

    openModal('.analyse-rating');
    var html = $('#wait_icon').html();
    $('#dvAnalyseRating').append(html);

    if (ddlYrs >= 0) {
        var clsAjax = new CreateRequest()
        clsAjax.ajaxObject.onreadystatechange = function () {
            if (clsAjax.ajaxObject.readyState == 4) {
                document.getElementById('dvAnalyseRating').innerHTML = clsAjax.ajaxObject.responseText;
                $(element).append('<span class="icon-close"></span>');
            }
        }
        clsAjax.ajaxObject.open("GET", "/review/reviewratings_ajax.aspx?pid=" + pid + "&year=" + lblval + "&range=" + ddlYrs + "&rndIe=" + ReturnRndIe() + "&mergedprods=" + mergedprods + "&ismerge_new=" + ismerge_new + "&check_corp=" + check_corp, true)
        clsAjax.ajaxObject.send(null)
    }
}




function clsRR() {
    document.getElementById("link_hide2").style.display = "none";
}

function showspecsdiv(dvhide) {
    dvhide.style.display = "none";
    var elems = document.getElementsByClassName("spec");
    for (i = 0; i < elems.length; i++) {
        elems[i].style.display = 'block';

    }

}
function hidespecsdiv(dvhide) {
    document.getElementById('dvshowspecs').style.display = "block";

    var elems = document.getElementsByClassName("specsdiv");
    for (i = 0; i < elems.length; i++) {
        elems[i].style.display = 'none';

    }
    window.scrollTo(0, 400);

}
function assignimg(path) {
    if (path.indexOf('/' + CatId) > -1) {
        path = imgPathForLayer;
    }
    var dtObj = new Date();
    var timee = dtObj.getTime();
    path = path + '?p=' + timee;
    $('img#ph1').attr('src', path)
              .load(function () {
                  document.getElementById("ph1").height = getImgSize(path);
                  document.getElementById("ph1").style.maxWidth = "800px";
                  document.getElementById("ph1").style.maxHeight = "460px";
                  document.getElementById("photolarge").style.display = "";
                  document.getElementById("photolarge").style.visibility = "visible";
                  document.getElementById("photolarge").focus();
                  showcentre('photolarge');
              });

}
function changebtnreviewlink(revcatid) {
    cidOfuserreview = revcatid;
}
function submit_corporate() {
    alert('This feature is not available for Brand Pulse');
    return false;
}


function submit_review_verified() {
    alert(vdrmsg);
    return false;
}
function writereview_disabled() {
    alert(drmsg);
    return false;
}
function writereview_discont() {
    alert("Write Review is currently disabled for the Discontinued products.");
    return false;
}
function writereview_closed() {
    alert("Write Review is currently disabled for the Closed products.");
    return false;
}

function editreview_disabled() {
    alert('Editing is disabled for FAKE review, kindly contact support@mouthshut.com for any further query!');
    return false;
}

function validateEmail(str) {
    var filter = /^[a-zA-Z0-9.][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/i
    if (filter.test(str))
        return true
    else
        return false
}

function verified_pepperfry(txtemail) {
    var email_ver = "";
    var catid_ver = 0;
    catid_ver = CatId;

    var pepperfry_redirect = mshostver;
    if (txtemail.value == "")
    { alert("Please enter email address"); return false; }
    else
    {
        if (!validateEmail(txtemail.value)) { alert("Invalid email address");; return false; }
    }
    email_ver = txtemail.value;
    var clsAjax = new CreateRequest()
    clsAjax.ajaxObject.onreadystatechange = function () {
        if (clsAjax.ajaxObject.readyState == 4) {
            if (clsAjax.ajaxObject.responseText == "redirect") {

                pepperfry_redirect = mshostver;
                window.location.href = mshostver + red_ver_url + "/" + email_ver;
            }
            else if (clsAjax.ajaxObject.responseText == "login") {

                pepperfry_redirect = mshostver;
                $('#modal-bckpep').hide();
               
                var pepperfry_redirect = mshostver + red_ver_url + "/" + email_ver;
                if (strSession == 0)
                    ajaxLogin(pepperfry_redirect);
                else
                    window.location.href = mshostver + red_ver_url + "/" + email_ver;
                return false;
            }
            else {

                pepperfry_redirect = mshostver;
                $('#modal-bckpep').hide();
                
                var pepperfry_redirect = mshostver + red_ver_url + '#writerev';
                if (strSession == 0)
                    ajaxLogin(pepperfry_redirect);
                else
                    window.location.href = mshostver + red_ver_url;

                return false;
            }
        }
    }
    clsAjax.ajaxObject.open("GET", "/review/new_verified.aspx?email_ver=" + email_ver + "&catid_ver=" + catid_ver + "", true)
    clsAjax.ajaxObject.send(null)

}

function redirect_pepperfry(url) {
    window.location.href = url
}

function AdditionalhighlightsDetails() {
    $("#dvpopLayer").empty();
    $("#pptitle").html("Additional details");
    $("#popuplayer1").width(625);
    $("#dvpopLayer").html(document.getElementById("dvhighlights").innerHTML);
    showcentre('popuplayer1');
}
function showexpresssuccess() {
    $("#dvpopLayer").empty();
    $("#dvRating").attr('class', 'confirmationbox');
    $("#dvRating").html('<span>Thank you for rating this Product</span>');
    $("#pptitle").html("&nbsp;");
    $("#popuplayer1").width(347);
    $("#popuplayer5").hide();
    showcentre('popuplayer1');
    closepptimeout('popuplayer1', 3000);
    var f = document.getElementById('ifrmReview');
    f.src = f.src;
}


function redirecttowrite() {

    if (window.onload) {
        var querystring = "cid=" + cidOfuserreview;

        if ($("#expressrev").html() == '') {
            document.getElementById('writereviewpanel2').innerHTML = "<iframe allowtransparency scrolling='no' frameborder='0' id='ifrmReview'  style='width: 650px; border:0;' src='/review/expressreview.aspx?" + querystring + "'></iframe>"
            var ref = $("#writereviewpanel2").html();
            $("#popuplayer1").hide();
            $("#expressrev").empty();
            $("#expressrev").append(ref);
        }

        $("#popuplayer5").show();
        $("#writereviewpanel2").empty();
        showcentrepop('popuplayer5');

    }

}

function editrestdetails(str) {
    $("#pptitle").html("Edit this listing");
    $("#dvpopLayer").empty();
    $("#popuplayer1").width(400);
    $("#dvpopLayer").append($("#restodetails").html());
    showcentre('popuplayer1');
}


function WriteReview() {
    if (cidOfuserreview1 != cidOfuserreview) { cidOfuserreview = cidOfuserreview1; }
    if (orderid == '')
        window.location.href = '/review/writereview_readall.aspx?cid=' + cidOfuserreview;
    else
        window.location.href = '/review/writereview_readall.aspx?cid=' + cidOfuserreview + '&oid=' + orderid + '&verrevid=' + ver_rev_id;
}

function setHeight(height) {
    document.getElementById('ifrmReview').style.height = height + 30 + "px";
}
function scrollOnTop(val) {
    if (val == 2) {
        var eTop = $('#writereviewpanel2').offset().top; window.scroll(eTop, eTop);
    }
    else {
        var eTop = $('#writereviewpanel').offset().top; window.scroll(eTop, eTop);
    }
}


function setHeight2(height) {
    document.getElementById('ifrmReview2').style.height = height + 30 + "px";
}



function callcustom(catid, maincat, subcat) {

    var dvSpecification = document.getElementById('specification');
    var spec_table = document.getElementById('idspec');
    if (dvSpecification.style.display == 'none' && dvSpecification.innerHTML != "")
        dvSpecification.style.display = '';

    else if ((type == 0 || type == 2) && (dvSpecification.style.display == 'block' || dvSpecification.style.display == '')) {
        dvSpecification.style.display = 'none';
        window.scrollTo(0, 0);
    }

    var parameter = "";
    if (isbot == '0') {
        parameter = "PType=spec" + "&id=" + catid + "&CatName=" + CatName + "&maincat=" + maincat + "&subcat=" + subcat;
        if (dvSpecification.innerHTML == "") {

            var xmlhttp = new CreateRequest()
            xmlhttp.ajaxObject.onreadystatechange = function ajaxResponse() {
                if (xmlhttp.ajaxObject.readyState == 4) {
                    if (xmlhttp.ajaxObject.responseText.indexOf("confirmationbox") > -1) {
                        dvSpecification.style.display = 'none';
                        var lispecs = document.getElementById('ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_customheader_tabs1_tdSpec');
                        if (lispecs != null) {
                            lispecs.removeAttribute("class");
                        }
                    }
                    else {
                        if (xmlhttp.ajaxObject.responseText == '') {
                            lispecs.removeAttribute("class"); dvSpecification.style.display = 'none';
                        }
                        else {
                            var arr = xmlhttp.ajaxObject.responseText.split('|');
                            dvSpecification.innerHTML = arr[0];
                            spec_table.innerHTML = arr[1];

                            var lispecs = document.getElementById('ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_customheader_tabs1_tdSpec');
                            if (lispecs != null) {
                                lispecs.setAttribute("class", "on");
                            }
                            dvSpecification.style.display = 'block';
                            dvSpecification.style.marginTop = '10px';
                        }
                    }
                }
            }
            xmlhttp.ajaxObject.open("GET", '/Comparison/compareproducts.php?' + parameter, true);
            xmlhttp.ajaxObject.send(null)
        }

    }


}
function customSpecification(catid, maincat, subcat) {
    var dvSpecification = document.getElementById('specification');
    var spec_table = $('.spec');
    var spec_title = $('.spec_title');
    if ($('#specification').css('display') == 'none' && dvSpecification.innerHTML != "") {
        dvSpecification.style.display = 'block';
    }
    else if ((type == 0 || type == 2) && (dvSpecification.style.display == 'block' || dvSpecification.style.display == '')) {
        dvSpecification.style.display = 'none';
        window.scrollTo(0, 0);
    }
    else if ((dvSpecification.innerHTML != "") && (dvSpecification.style.display == 'block')) {
        dvSpecification.style.display = 'none';
    }
    var parameter = "";
    if (isbot == '0') {
        parameter = "PType=spec" + "&id=" + catid + "&CatName=" + CatName + "&maincat=" + maincat + "&subcat=" + subcat;
        if (dvSpecification.innerHTML == "") {

            var xmlhttp = new CreateRequest()
            xmlhttp.ajaxObject.onreadystatechange = function ajaxResponse() {
                if (xmlhttp.ajaxObject.readyState == 4) {
                    dvSpecification.style.display = 'block';
                    var eTop = $('#specificationa').offset().top - 120;
                    window.scrollTo(eTop, eTop);
                    dvSpecification.style.marginTop = '10px';
                    var arr = xmlhttp.ajaxObject.responseText.split('|');
                    dvSpecification.innerHTML = arr[0];
                    spec_table.innerHTML = arr[1];

                }
            }
            xmlhttp.ajaxObject.open("GET", '/Comparison/compareproducts.php?' + parameter, true);
            xmlhttp.ajaxObject.send(null)
        }

    }

}

function Specification(type, parent) {
    var dvSpecification = document.getElementById('specification');
    var iscars = ""
    if (parent == "101") {
        if (CatId == merge_parent)
            iscars = "&ov=1&mpar=1";
        else
            iscars = "&ov=1";


    }
    if (CatId == merge_parent)
        iscars = "&ov=1&mpar=1";

    if ($('#specification').css('display') == 'none') {

        dvSpecification.style.display = 'block';
        dvSpecification.style.marginTop = '10px';
        var eTop = $('#specificationa').offset().top - 120;
        window.scrollTo(eTop, eTop);

    }
    else if ((type == 0 || type == 2) && (dvSpecification.style.display == 'block' || dvSpecification.style.display == '')) {

        dvSpecification.style.display = 'none';
        window.scrollTo(0, 0);
    }

    var parameter = "";
    if (isbot == '0') {
        if (type == 1) {
            $("#specification").html('');
            parameter = "PType=spec" + "&id=" + parent + "&CatName=" + CatName;
        }
        else if (type == 2) {
            parameter = "PType=info" + "&id=" + CatId + "&CatName=" + CatName.replace("&", "**");
        }
        else {
            parameter = "PType=spec" + iscars + "&id=" + parent + "|1|" + CatId + "&CatName=" + CatName;

        }
        if (dvSpecification.innerHTML == '') {

            var xmlhttp = new CreateRequest()
            xmlhttp.ajaxObject.onreadystatechange = function ajaxResponse() {
                if (xmlhttp.ajaxObject.readyState == 4) {
                    dvSpecification.innerHTML = xmlhttp.ajaxObject.responseText
                }
            }
            xmlhttp.ajaxObject.open("GET", '/Comparison/compareproducts.php?' + parameter, true);
            xmlhttp.ajaxObject.send(null)
        }
    }
    else {
        if (type == 1) {
            $("#specification").html('');
        }
    }

}



function headover(n) {
    try {
        for (i = 1; i <= 2 ; i++) {
            if (i == n) {
                show('link_hide' + i);
            } else {
                hide('link_hide' + i);
            }
        }
    } catch (e) { }
}

function headout(e, no) {
    try {
        var p = drop_div(e);
        if (p.id != 'link_hide' + no) {
            hide('link_hide' + no);
        }
    } catch (e) { }
}
function show(divnm) {
    try { d_g_id(divnm).style.display = "block"; } catch (e) { }
}

function hide(divnm) {
    try { d_g_id(divnm).style.display = "none"; } catch (e) { }
}
function d_g_id(elem) {
    try {
        return document.getElementById(elem);
    } catch (e) { }
}

function toggle(divnm) {
    if (d_g_id(divnm).style.display == "none" || d_g_id(divnm).style.display == "" || d_g_id(divnm).style.display == null || d_g_id(divnm).style.display == undefined) {
        show(divnm);
    } else {
        hide(divnm);
    }
}
function drop_div(e) {
    if (!e) var e = window.event;
    var relTarg = e.relatedTarget || e.toElement;
    return relTarg;
}
function showDiscreation(rid, postedby) {
    if (strSession > 0) {
        if(postedby == user_id){
            if (strUsrName == $('[id$=linkrevname]').text()) {
            if ($('[id$=hidDiscretionExist]').val() != "0") {
                document.getElementById('dvthankModal').innerHTML = "<span>We have already taken your feedback. Be patient while our Support Team processes your request.</span>"
                $('#dvthankModal').show();
                $('#dvfakeModal').hide();
                $('.upload-file-selected').html('');
                openModal('.fakeModal');

            }
            else {
                document.getElementById('hidReviewId').value = rid;
                document.getElementById('btnSubmitDisc').style.display = '';

                $('#dvthankModal').hide();
                $('#dvfakeModal').show();
                $('#txtDAreaComm').val("");
                $('.upload-file-selected').html('');
                openModal('.fakeModal');
            }
        
        }
        else if ($('[id$=linkrevname]').text() == 'Anonymous' && strUsrName == postedby) {
            if ($('[id$=hidDiscretionExist]').val() != "0") {
                document.getElementById('dvthankModal').innerHTML = "<span>We have already taken your feedback. Be patient while our Support Team processes your request.</span>"
                $('#dvthankModal').show();
                $('#dvfakeModal').hide();
                $('.upload-file-selected').html('');
                openModal('.fakeModal');
            }
            else {
                document.getElementById('hidReviewId').value = rid;
                document.getElementById('btnSubmitDisc').style.display = '';

                $('#dvthankModal').hide();
                $('#dvfakeModal').show();
                $('#txtDAreaComm').val("");
                $('.upload-file-selected').html('');
                openModal('.fakeModal');
            }
        }
        }
    }
    else {
        ajaxLogin('');
    }
}

function setFocus() {
    document.getElementById('txtDAreaComm').focus();
}
function validateQuoteForm() {
    var loaderdiv = $("#loader").html();
    $("#lnkviewmore").hide();
    $('#getQuote').append(loaderdiv);
    $('.ajaxloader').show();



    if (nameGetRoadPrice.value == "" || emailGetRoadPrice.value == "" || teleGetRoadPrice.value == "") {
        document.getElementById(dvqerror).style.display = "block";
        document.getElementById(dvqerror).innerText = "Fields marked with * are mandatory. ";
        $("#getQuote .ajaxloader").remove();
        return false;
    }
    else if (validateEmail(emailGetRoadPrice.value) == false) {
        document.getElementById(dvqerror).style.display = "block";
        document.getElementById(dvqerror).innerText = "Invalid Email ID. ";
        $("#getQuote .ajaxloader").remove();
        return false;
    }
    else if (teleGetRoadPrice.value.length < 10) {
        document.getElementById(dvqerror).style.display = "block";
        document.getElementById(dvqerror).innerText = "Invalid Mobile Number ";
        $("#getQuote .ajaxloader").remove();
        return false;
    }
    else {


        $.ajax({
            type: 'POST',
            url: '/web/WebService3.asmx/SaveOnRoadPrice',
            data: "{Name:'" + $("#txtName").val() + "',ProdName:'" + $("#txtModel").val() + "',Email:'" + $("#txtMail").val() + "',MobileNo:'" + $("#txtMob").val() + "',City:'" + $("#txtCity").val() + "',PinCode:'" + $("[id$=txtPinCode]").val() + "',CatId:'" + CatId + "',CatName:'" + CatName + "',Parent2:'" + parent2 + "',Level1:'" + Level1 + "',userId:'" + userId + "',Productlaunch:'" + $("#hdnproductlaunch").val() + "'}",
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            processData: false,
            success: function (result) {
                var res = (result.d).split('|')
                if (res[0].toLowerCase().trim() == "error") {
                    openModal('#getQuote');
                    $("#dvQuoteError").css('display', 'block');
                    $("#dvQuoteError").html(res[1]);
                }
                else {
                    openThankYouModal()
                }
            },
            error: function (err) {
                $("#dvQuoteError").html(err);
            }
        });
    }
}

function openPriceModal() {
    $("#getQuote .ajaxloader").remove();
    openModal('#getQuote');
}

function validateQuoteForm12() {
    $("#getQuote1").css('display', 'block');
    $("#dvQuoteError1").css('display', 'block');
    $("#dvQuoteError1").html("Fields marked with * are mandatory. ");
    return false;
}
function validateQuoteForm1() {
    if ($("#txtName").val() == "" || $("#txtMail").val() == "") {
        $("#getQuote1").css('display', 'block');
        $("#dvQuoteError1").css('display', 'block');
        $("#dvQuoteError1").html("Fields marked with * are mandatory. ");
        return false;
    }
    else if (validateEmail($("#txtMail").val()) == false) {
        $("#dvQuoteError1").css('display', 'block');
        $("#dvQuoteError1").html("Invalid Email ID. ");
        $("#getQuote1").css('display', 'block');
        return false;
    }
    else if ($("#txtMob").val().length < 10) {
        $("#dvQuoteError1").css('display', 'block');
        $("#dvQuoteError1").html("Invalid Mobile Number ");
        $("#getQuote1").css('display', 'block');
        return false;
    }
    else {


        $.ajax({
            type: 'POST',
            url: '/web/WebService3.asmx/SaveOnRoadPrice',
            data: "{Name:'" + $("#txtName").val() + "',ProdName:'" + $("#txtModel").val() + "',Email:'" + $("#txtMail").val() + "',MobileNo:'" + $("#txtMob").val() + "',City:'" + $("#txtCity").val() + "',PinCode:'" + $("[id$=txtPinCode]").val() + "',CatId:'" + CatId + "',CatName:'" + CatName + "',Parent2:'" + parent2 + "',Level1:'" + Level1 + "',userId:'" + userId + "',Productlaunch:'" + $("#hdnproductlaunch").val() + "'}",
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            processData: false,
            success: function (result) {
                var res = (result.d).split('|')
                if (res[0].toLowerCase().trim() == "error") {
                    $("#dvQuoteError1").css('display', 'block');
                    $("#dvQuoteError1").html(res[1]);
                }
                else {
                    openThankYouModal()
                    $("#dvQuoteError1").css('display', 'none');
                }
            },
            error: function (err) {
                $("#dvQuoteError1").html(err);
            }
        });
    }
}
function openLeadModal1(catId, AdditionalField) {

    $.ajax({
        type: 'POST',
        url: '/web/WebService3.asmx/GetTextDrop',
        data: "{CatId:'" + catId + "',AdditionalField:'" + AdditionalField + "'}",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        processData: false,
        success: function (result) {
            $("#dvLead1").html(result.d);
        },
        error: function (err) {

        }
    });
}

function validateLeadForm() {
    var data = {
        Name: $("#txtName1").val(),
        ProdName: $("#prodName").val(),
        Email: $("#txtMail1").val(),
        MobileNo: $("#txtMob1").val(),
        City: $("#txtCity1").val(),
        PinCode: $("[id$=txtPinCode1]").val(),
        Values: []
    };
    $("#dvLead .form-control").each(function (key, val) {
        data.Values.push($(val).val());
    });
    $.ajax({
        type: 'POST',
        url: '/web/WebService3.asmx/SaveLeadGeneration',
        data: "{Name:'" + data.Name + "',ProdName:'" + data.ProdName + "',Email:'" + data.Email + "',MobileNo:'" + data.MobileNo + "',City:'" + data.City + "',PinCode:'" + data.PinCode + "',values:" + JSON.stringify(data.Values) + ",CatId:'" + CatId + "',CatName:'" + CatName + "',Parent2:'" + parent2 + "',Level1:'" + Level1 + "',mshost:'" + mshost + "',Ip:'" + Ip + "',userId:'" + userId + "'}",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        processData: false,
        success: function (result) {
            var res = (result.d).split('|')
            if (res[0].toLowerCase().trim() == "error") {
                openModal('#getLead');
                $("#dvLeadError").css('display', 'block');
                $("#dvLeadError").html(res[1]);
            }
            else {
                openLeadThankYouModal()
            }
        },
        error: function (err) {
            $("#dvLeadError").html(err);
        }
    });
}


function validateLeadForm1() {
    var data = {
        Name: $("#txtName1").val(),
        ProdName: $("#prodName").val(),
        Email: $("#txtMail1").val(),
        MobileNo: $("#txtMob1").val(),
        City: $("#txtCity1").val(),
        PinCode: $("[id$=txtPinCode1]").val(),
        Values: []
    };
    $("#dvLead1 .field-outline").each(function (key, val) {
        data.Values.push($(val).val());
    });
    $.ajax({
        type: 'POST',
        url: '/web/WebService3.asmx/SaveLeadGeneration',
        data: "{Name:'" + data.Name + "',ProdName:'" + data.ProdName + "',Email:'" + data.Email + "',MobileNo:'" + data.MobileNo + "',City:'" + data.City + "',PinCode:'" + data.PinCode + "',values:" + JSON.stringify(data.Values) + ",CatId:'" + CatId + "',CatName:'" + CatName + "',Parent2:'" + parent2 + "',Level1:'" + Level1 + "',mshost:'" + mshost + "',Ip:'" + Ip + "',userId:'" + userId + "'}",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        processData: false,
        success: function (result) {
         
            var res = (result.d).split('|')
            if (res[0].toLowerCase().trim() == "error") {
                $('#getLead').css('display', 'block');
                $("#dvLeadError1").css('display', 'block');
                $("#dvLeadError1").html(res[1]);
            }
            else {
                openLeadThankYouModal()
                $('#getLead').css('display', 'block');
                $("#dvLeadError1").css('display', 'none');
                resetLeadsForm();
            }
        },
        error: function (err) {
            $("#dvLeadError1").html(err);
        }
    });
}

const resetLeadsForm = () => {
    $("#txtName1").val('');
    $("#txtMail1").val('');
    $("#txtMob1").val('');
    $("#txtCity1").val('');
    $("[id$=txtPinCode1]").val('');
    $('[id^="ddlVal"] option[value="0"]').prop('selected', true);
    $('[id^="txtVal"]').val('');
}

function setddlStyle() {
    const ddlSelect = document.querySelectorAll('[id ^="ddlVal"]');
    for (const element of ddlSelect) {
        if (element.value != "0") {
            element.style.color = "#242c42";
            element.style.fontWeight = "400";
        } else {
            element.style.color = "gray";
        }
    }
}


function openThankYouModal() {
    $('.black-layer').css('visibility', 'hidden');
    openModal('#dvThankQuote');
}

function openLeadThankYouModal() {
    $('.black-layer').css('visibility', 'hidden');
    openModal('#dvLeadThankQuote');
}


function validateEmail(str) {
    var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    var emailid = str.split("@");
    var array = emailid[0].split(".");
    var length = array.length;

    if (filter.test(str) && length > 2 && (emailid[1] == "gmail.com" || emailid[1] == "yahoo.com"))
        return false
    else if (filter.test(str))
        return true
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; }
    return true;
}

function isNumberKey1(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; }
    if (document.getElementById('txtMob1').value.length>=10) {
        return false;
    }
    return true;
}
function validate() {

    var comm = document.getElementById("txtDAreaComm").value.trim();
    var gfval;
    var err = "";
    var emailerr = "";
    if (document.getElementById('roundedOne').checked != true && document.getElementById('roundedTwo').checked != true) {
        err = err + "Please select any one option " + '\n';
    }
    else {
        if (document.getElementById('roundedOne').checked == true) {
            gfval = 0;
        }
        else {
            gfval = 1;
        }
    }
    if (emai == "") {
        err = err + "Email cannot be blank " + '\n';
    }
    else {
        if (validateEmail(emai) == false) {
            emailerr = emailerr + "Invalid E-mail ID" + '\n';
        }
    }
    if (comm == "") {
        err = err + "Your Comments cannot be blank " + '\n';
    }
    if (err == "" && emailerr == "") {
        SendEmail(name, msid, emai, comm, document.getElementById('hidReviewId').value, gfval);
    }
    else if (emailerr != "") {
    }
    else {
        alert(err);
    }
}
function SendEmail(name, msid, emai, comm, rid, gfval) {

    var formData = new FormData();
    var files = $("#fileJustifyPhoto").get(0).files;
    if (files.length != 0) {

        formData.append(files[0].name, files[0]);
        formData.append('name', name);
        formData.append('msid', msid);
        formData.append('email', emai);
        formData.append('comment', comm);
        formData.append('rid', rid);
        formData.append('gfval', gfval);

        var extension = $("#fileJustifyPhoto").val().split('.').pop().toLowerCase();
        if ($.inArray(extension, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
            alert('Invalid file extension. Only files with png, jpg, jpeg and gif extensions are allowed.')
            return;
        }

        $.ajax({
            url: "/review/DescritionAjax.aspx",
            type: "POST",
            contentType: false,
            processData: false,
            data: formData,
            success: function (result) {
                document.getElementById('btnSubmitDisc').style.display = 'none';
                $('#dvfakeModal').hide();
                $('#dvthankModal').show();
                document.getElementById('dvthankModal').innerHTML = "<span>Thank you for writing to us. Our Support Team shall look into this and get back to you soon.</span>"
                setTimeout(function () {
                    $('.black-layer').css('visibility', 'hidden');
                    $('body').css('overflow-y', 'auto');
                    $('#optionpopup').hide().removeClass('modal');

                    let currentUrl = window.location.href;
                    if (currentUrl.length > 5) {
                        let last = currentUrl.substr(currentUrl.length - 5, 5);
                        if (last == "-fake") {
                            window.location = currentUrl.substr(0, currentUrl.length - 5);
                        }
                        else {
                            window.location.reload();
                        }

                    }

                }, 2500);
            },
            error: function (err) {
                alert('Something error occurred');
            }
        });
    }
    else {
        alert('At least one proof is mandatory. Please upload a purchase proof');
    }
}

function changeJustifyPhoto() {
    if ($('#fileJustifyPhoto').val()) {
        let array = $('#fileJustifyPhoto').val().split('\\');
        $('.upload-file-selected').text(array[array.length - 1]);
    }
};
$(document).ready(function () {
    try {
        Naviagtion(cid);
        try { Naviagtion(actualCid); }
        catch (e) { }
        Naviagtion(ActualParent2);
        ReplaceBreaks();
        Rebind();
        maincategorydivresize();

        (function () {
            var bLazy = new Blazy();
        })();


    }
    catch (e) { }
});
var scrollsAds = false;
$(window).scroll(function () {
    try {
        if (IsGoogleBot == "0" && scrollsAds== false) {
            try {
                $('.adsBoxRpt').html('<iframe class="w-100 border-0 b-lazy" src="' + mshost + 'DisplayAd.aspx?cid=' + actualCid + '&size=728-15&type=listing" data-src="' + mshost + 'DisplayAd.aspx?cid=' + actualCid + '&size=728-15&type=listing" style="" scrolling="no"></iframe>')
                $('#divLnkAd').html('<iframe class="w-100 border-0 b-lazy" src="' + mshost + 'DisplayAd.aspx?cid=' + actualCid + '&size=300-250&type=matched-listing" data-src="' + mshost + 'DisplayAd.aspx?cid=' + actualCid + '&size=300-250&type=matched-listing"  scrolling="no"></iframe>');
                $('#divAds').html('<iframe class="w-100 border-0 b-lazy" src="' + mshost + 'DisplayAd.aspx?cid=' + actualCid + '&size=300-250&type=listing" data-src="' + mshost + 'DisplayAd.aspx?cid=' + actualCid + '&size=300-250&type=listing" scrolling="no"></iframe>');
            } catch (e) { console.error("error in adsBoxRpt" + e); }
            scrollsAds = true;
        }
    }
    catch (e) { }

});
function Showgridview() {
    $('.nav-opt').hide();
    try {
        $("#reviewjs").remove();
    }
    catch (e) { }
    $('.travel-head').show();

    try {
        if (Pagetype == "1") {
            $('#maincontainer').removeClass('box-module');
            $('.mainCategoryproductlist').addClass('listing-section');
            $('#categorierightpanel').removeClass('right-panel');
            var catid = $('.dropdown-item > a').attr('value');
            $('.src-fltr').attr('value', catid);
            $('.nav-opt').show();
        }
        else {
            $('.src-fltr').remove();

            try {
                $('.category-list>h1').each(function () {
                    $(this).replaceWith("<h2>" + $(this).html() + "</h2>");
                });

            } catch (e) { }
            try {
                $('.filter.prod-listing').removeClass('right-module');
                $('.filter.prod-listing').removeClass('toggle');
                $('.filter.prod-listing').addClass('container');
                $('.filter.prod-listing').addClass('box-module');
                $('.search-prod').hide();
                $('.toggle-content').toggleClass('toggle-content list-all-brands');
                $('.pull-right.icon-drop-down').hide();
                $('.filter.prod-listing').removeClass('prod-listing');
                $('.filter').removeClass('filter');
                $('.container.box-module>h5').each(function () {
                    $(this).replaceWith("<h2>" + $(this).html() + "</h2>");
                });

            }
            catch (e) { }
        }
    }
    catch (e) { }
    try {
        var Imageurl = ImageServerVirtualPath + 'Offline/Common/Images/' + cid + '.jpg';
        $('.travel-head').css('background-image', 'url(' + Imageurl + ')');
        ReplaceBreaks();

    }
    catch (e) { }

    $('.dropdown-item').click(function () {
        var selText = $(this).text();
        $('.src-fltr .opt').text(selText);
        var catid = $(this).attr('value');
        $('.src-fltr').attr('value', catid);
        $('.search-filter').hide();
        try { document.getElementById('txtproductSearch').value = ''; } catch (e) { }
    });

    $('.ReadMore').click(function () {
        var selText = $(this).text().toLowerCase();
        if (selText.indexOf("more") > -1) {
            $('#GuideInformation').removeClass('content-truncate');
            $(this).text('Read less')
        }
        else {
            $('#GuideInformation').addClass('content-truncate');
            $(this).text('Read more');
        }
    });

    if (Pagetype == "1") {
        try {
            var elements = $(".mainCategoryproductlist").each(function (index, element) {
                var id = this.id;
                $("#" + id + " img").load(function () {
                    var maxHeight = 0;
                    var heights = $("#" + id + " .row.list .col-3 div.rtitle").map(function () {
                        return $(this).height();
                    }).get(),
                    maxHeight = Math.max.apply(null, heights);
                    if (maxHeight > 0) {
                        $("#" + id + " .row.list .col-3 div.rtitle").css({
                            'height': maxHeight + 'px'
                        });
                    }
                });
            });
        }
        catch (e) { }

        try {
            var elements = $(".mainCategoryproductlist").each(function (index, element) {
                var id = this.id;
                $("#" + id + " img").load(function () {

                    var maxHeight = 0;
                    var heights = $("#" + id + " .row.list .col-3").map(function () {
                        return $(this).height();
                    }).get(),

                    maxHeight = Math.max.apply(null, heights);
                    if (maxHeight > 0) {
                        $("#" + id + " .row.list .col-3 .box").css({
                            'height': (maxHeight - 30) + 'px'

                        });
                    }
                });

            });
        }
        catch (e) { }
    }
    else {
        try {

            var heights = $(".row.list .col-3 div.rtitle").map(function () {
                return $(this).height();
            }).get(),

            maxHeight = Math.max.apply(null, heights);

            if (maxHeight > 0) {
                $(".row.list .col-3 .gridl div.rtitle").css({
                    'height': maxHeight + 'px'

                });
            }
        }
        catch (e) { }


        try {
            var maxHeight = 0;
            var heights = $(".row.list .col-3").map(function () {
                return $(this).height();
            }).get(),

            maxHeight = Math.max.apply(null, heights);
            if (Pagetype == "1") { maxHeight = maxHeight + 32 } else { maxHeight = maxHeight - 30 }
            if (maxHeight > 0) {
                $(".row.list .col-3 .gridl").css({
                    'height': maxHeight + 'px'

                });
            }

        }
        catch (e) { }
    }
}


function HideMaincategory() {
    $(".wrapper .col-12").removeClass('col-12');
    $('.grid-view > span').addClass('unrated-star');
    $('.travel-head').remove();
    $('.nav-opt').remove();
    $("#traveljs").remove();
    $("#travelcss").remove();
}
var maincategorydivresizeLoded = 0;
function maincategorydivresize() {

    $('.pull-left.listview').show();
    $('.pull-left.listview div').show();
    $('.pull-left.gridview').hide();
    if (Pagetype == "1" || Pagetype == "4") {
        try {
            $('.pull-left.gridviews').attr("style", "display: block !important");
            $('.pull-left.gridviews  div').attr("style", "display: block !important");
            var elements = $(".mainCategoryproductlist").each(function (index, element) {
                var id = this.id;
                $("#" + id + " img").load(function () {

                    var maxHeight = 0;
                    var heights = $("#" + id + " .row.list .col-3 div.rtitle").map(function () {
                        return $(this).height();
                    }).get(),

                    maxHeight = Math.max.apply(null, heights);

                    if (maxHeight > 0) {
                        $("#" + id + " .row.list .col-3 div.rtitle").css({
                            'height': maxHeight + 'px'

                        });
                    }
                });
            });
        }
        catch (e) { }

        try {
            var elements = $(".mainCategoryproductlist").each(function (index, element) {
                var id = this.id;
                $("#" + id + " img").load(function () {

                    var maxHeight = 0;
                    var heights = $("#" + id + " .row.list .col-3").map(function () {
                        return $(this).height();
                    }).get(),

            maxHeight = Math.max.apply(null, heights);

                    if (maxHeight > 0) {
                        $("#" + id + " .row.list .col-3 .box").css({
                            'height': (maxHeight - 30) + 'px'

                        });
                    }
                });

            });
        }
        catch (e) { }

    }

}


var navigationloded = 0, navigationloded1 = 0;
function Naviagtion(id) {

    var n;
    if (Pagetype == "1" || Pagetype == "4") {
        $(".catlist-left").attr('style', 'margin-top: 38px !important');
    }
    if (navigationloded == 0) {
        try {
            if (cid == ActualParent2) {
                $("#Navigation_" + id).addClass("active");

            }
            else if (id == ActualParent2 && n < 1) {
                var nextid = $("#Navigation_" + ActualParent2).next().find("#TipCollapse_" + ActualParent2);

                if ($("#Navigation_" + ActualParent2)[0].childNodes.length > 1) {
                    $("#TipCollapseimg_" + ActualParent2).prop("src", "../../APP_THEMES/images/category/collapse.svg");
                    $("#TipCollapse_" + ActualParent2).addClass('show');
                    $("#TipCollapse_" + ActualParent2).addClass('active');
                } else {
                    $("#Navigation_" + ActualParent2).addClass("active");
                }
            }
            else {
                n = 1;
                var nextid = $("#Navigation_" + cid).next().find("#TipCollapse_" + cid);
                if (nextid.prevObject.length > 0) {
                    $("#TipCollapseimg_" + cid).prop("src", "../../APP_THEMES/images/category/collapse.svg");
                    $("#TipCollapse_" + cid).addClass('show');
                    $("#Navigation_" + cid).addClass("active");
                } else if (nextid.prevObject.length < 1 && nextid.prevObject.prevObject.length > 0) {
                    $("#TipCollapseimg_" + cid).prop("src", "../../APP_THEMES/images/category/collapse.svg");
                    $("#TipCollapse_" + cid).addClass('show');
                    $("#Navigation_" + cid).addClass("active");
                }


                else {
                    $("#Navigation_" + ActualParent2).addClass("active");
                }

            }

            var id = $("#Navigation_" + id).parent().parent().attr('id');
            var n = id.split('_').pop();

            if (id) {

                $('#' + id).addClass('show');
                $('#TipCollapseimg_' + n).prop("src", "../../APP_THEMES/images/category/collapse.svg");
            }

            var parentid = $("#Navigation_" + n).parent().parent().attr('id');
            var pn = parentid.split('_').pop();

            if (parentid) {
                $('#' + parentid).addClass('show');
                $('#TipCollapseimg_' + pn).prop("src", "../../APP_THEMES/images/category/collapse.svg");
            }

        } catch (e) { }
    }
}

function changeimg(id) {
    var navigationid = id.dataset.target;
    var n = navigationid.split('_').pop();
    var div1Class = $('#TipCollapse_' + n).attr('class');
    if (div1Class == "collapse show") {
        $('#TipCollapseimg_' + n).prop("src", "../../APP_THEMES/images/category/expland.svg");
    }
    else {
        $('#TipCollapseimg_' + n).prop("src", "../../APP_THEMES/images/category/collapse.svg");

    }

}
function Naviagtion1(id) {
    if (Pagetype == "1" || Pagetype == "4") {
        $(".catlist-left").attr('style', 'margin-top: 38px !important');
    }
    if (navigationloded1 == 0) {
        try { $("#Navigation_" + id + " > a").addClass("act-link") } catch (e) { }
        var getid = $('#Navigation_' + id).parents('li');
        for (i = 0; i <= getid.length; i++) {
            try {
                var control = $(getid[i]).find('> span');

                var ids = $(control).attr('id');
                if (ids.indexOf('Navigation') >= 0) {
                    try {
                        document.getElementById(ids).click();
                        navigationloded1 = 1;
                    } catch (e) { }

                }

            }
            catch (e) { }
        }
    }
}

function BindImages() {
    if (IsGoogleBot == '1' || ((Pagetype == "1" || Pagetype == "4") && IsGoogleBot == '0')) {
        var imgDefer = document.getElementsByTagName('img'); for (var i = 0; i < imgDefer.length; i++) { try { if (imgDefer[i].getAttribute('data-src')) { imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src')); } } catch (e) { } }

    }
}
setTimeout("BindImages()", 0);

if (IsGoogleBot == '1') { BindImages() }

if (window.addEventListener) window.addEventListener("load", BindImages, false);
else if (window.attachEvent) window.attachEvent("onload", BindImages);
else window.onload = BindImages;

function Rebind() {
    $('[data-toggle=radio]').each(function () {
        var clientId = $(this).attr('id');

        $(this).find('input').each(function () {
            $(this).attr('data-parent', clientId);
            $(this).click(function (e) {
                if (!e) e = window.event;
                var sender = e.target || e.srcElement;
                if (sender.nodeName != 'INPUT') return;
                var id = $(this).attr('id');
                var parent = $(this).attr('data-parent');
                $('input[data-parent=' + parent + ']').not('#' + id).prop('checked', false);
            });
        });
    });

    $('.clFilterTextOtherBrands').keyup(function () {
        $('#less').css('display', 'block');
        $('#show').css('display', 'none');
        $('.filterOtherBrands').css("height", "150px");
        $('.filterOtherBrands').css("overflow-y", "scroll");
        var valThis = $(this).val().toLowerCase().replace(/[_\W]+/g, "-");
        var ulid = $(this).parents('div:eq(1)').find('ul').attr("id");
        if (valThis != '') {
            var cnt = 0;
            $(this).parents('div:eq(1)').find('ul >li').each(function () {
                var text = $(this).find('a').html().toLowerCase().replace(/[_\W]+/g, "-");

                if (text.indexOf(valThis) < 0) {
                    $(this).hide();

                }
                else {
                    $(this).show()
                }
            });
            if (cnt < 5) {
                $('#less').css('display', 'none');
                $('.filterOtherBrands').css("height", "auto");
                $('.filterOtherBrands').css("overflow-y", "hidden");
            }
        }
        else {
            $('.pl-0 li:gt(4)').hide();
            $('.pl-0 li:lt(5)').css('display', 'block');
            $('#less').css('display', 'none');
            $('#show').css('display', 'block');
            $('.filterOtherBrands').css("height", "auto");
            $('.filterOtherBrands').css("overflow-y", "hidden");
        }

    });

    $('.clFilterTextOtherBrands0').keyup(function () {
        $('#less0').css('display', 'block');
        $('#show0').css('display', 'none');
        $('.filterOtherBrands0').css("height", "150px");
        $('.filterOtherBrands0').css("overflow-y", "scroll");

        var valThis = $(this).val().toLowerCase().replace(/[_\W]+/g, "-");
        var ulid = $(this).parents('div:eq(1)').find('ul').attr("id");
        if (valThis != '') {
            var cnt = 0;
            $(this).parents('div:eq(1)').find('ul >li').each(function () {
                var text = $(this).find('a').html().toLowerCase().replace(/[_\W]+/g, "-");

                if (text.indexOf(valThis) < 0) {
                    $(this).hide();

                }
                else {
                    cnt++;
                    $(this).show()
                }
            });
            if (cnt < 5) {
                $('#less0').css('display', 'none');
                $('.filterOtherBrands0').css("height", "auto");
                $('.filterOtherBrands0').css("overflow-y", "hidden");
            }

        }
        else {
            $('#0 li:gt(3)').hide();
            $('#0 li:lt(4)').css('display', 'block');
            $('#less0').css('display', 'none');
            $('#show0').css('display', 'block');
            $('.filterOtherBrands0').css("height", "auto");
            $('.filterOtherBrands0').css("overflow-y", "hidden");
        }

    });

    $('.clFilterTextOtherBrands1').keyup(function () {
        $('#less1').css('display', 'block');
        $('#show1').css('display', 'none');
        $('.filterOtherBrands1').css("height", "150px");
        $('.filterOtherBrands1').css("overflow-y", "scroll");
        var valThis = $(this).val().toLowerCase().replace(/[_\W]+/g, "-");
        var ulid = $(this).parents('div:eq(1)').find('ul').attr("id");
        if (valThis != '') {
            var cnt = 0;
            $(this).parents('div:eq(1)').find('ul >li').each(function () {
                var text = $(this).find('a').html().toLowerCase().replace(/[_\W]+/g, "-");

                if (text.indexOf(valThis) < 0) {
                    $(this).hide();
                }
                else {
                    cnt++;
                    $(this).show()
                }
            });

            if (cnt < 5) {
                $('#less1').css('display', 'none');
                $('.filterOtherBrands1').css("height", "auto");
                $('.filterOtherBrands1').css("overflow-y", "hidden");
            }
        }
        else {
            $('#1 li:gt(3)').hide();
            $('#1 li:lt(4)').css('display', 'block');
            $('#less1').css('display', 'none');
            $('#show1').css('display', 'block');
            $('.filterOtherBrands1').css("height", "auto");
            $('.filterOtherBrands1').css("overflow-y", "hidden");
        }

    });

    $('.clFilterTextOtherBrands2').keyup(function () {
        $('#less2').css('display', 'block');
        $('#show2').css('display', 'none');
        $('.filterOtherBrands2').css("height", "150px");
        $('.filterOtherBrands2').css("overflow-y", "scroll");
        var valThis = $(this).val().toLowerCase().replace(/[_\W]+/g, "-");
        var ulid = $(this).parents('div:eq(1)').find('ul').attr("id");
        if (valThis != '') {
            var cnt = 0;
            $(this).parents('div:eq(1)').find('ul >li').each(function () {
                var text = $(this).find('a').html().toLowerCase().replace(/[_\W]+/g, "-");

                if (text.indexOf(valThis) < 0) {
                    $(this).hide();
                }
                else {
                    cnt++;
                    $(this).show()
                }
            });
            if (cnt < 5) {
                $('#less2').css('display', 'none');
                $('.filterOtherBrands2').css("height", "auto");
                $('.filterOtherBrands2').css("overflow-y", "hidden");
            }
        }
        else {
            $('#2 li:gt(3)').hide();
            $('#2 li:lt(4)').css('display', 'block');
            $('#less2').css('display', 'none');
            $('#show2').css('display', 'block');
            $('.filterOtherBrands2').css("height", "auto");
            $('.filterOtherBrands2').css("overflow-y", "hidden");
        }

    });

    $('.clFilterTextOtherBrands3').keyup(function () {

        $('#less3').css('display', 'block');
        $('#show3').css('display', 'none');
        $('.filterOtherBrands3').css("height", "150px");
        $('.filterOtherBrands3').css("overflow-y", "scroll");
        var valThis = $(this).val().toLowerCase().replace(/[_\W]+/g, "-");
        var ulid = $(this).parents('div:eq(1)').find('ul').attr("id");
        if (valThis != '') {
            var cnt = 0;
            $(this).parents('div:eq(1)').find('ul >li').each(function () {
                var text = $(this).find('a').html().toLowerCase().replace(/[_\W]+/g, "-");

                if (text.indexOf(valThis) < 0) {
                    $(this).hide();
                }
                else {
                    cnt++;
                    $(this).show()
                }
            });

            if (cnt < 5) {
                $('#less3').css('display', 'none');
                $('.filterOtherBrands3').css("height", "auto");
                $('.filterOtherBrands3').css("overflow-y", "hidden");
            }
        }
        else {

            $('#3 li:gt(3)').hide();
            $('#3 li:lt(4)').css('display', 'block');
            $('#less3').css('display', 'none');
            $('#show3').css('display', 'block');
            $('.filterOtherBrands3').css("height", "auto");
            $('.filterOtherBrands3').css("overflow-y", "hidden");
        }

    });

    $('.clFilterTextOtherBrands4').keyup(function () {

        $('#less4').css('display', 'block');
        $('#show4').css('display', 'none');
        $('.filterOtherBrands4').css("height", "150px");
        $('.filterOtherBrands4').css("overflow-y", "scroll");
        var valThis = $(this).val().toLowerCase().replace(/[_\W]+/g, "-");
        var ulid = $(this).parents('div:eq(1)').find('ul').attr("id");
        if (valThis != '') {
            var cnt = 0;
            $(this).parents('div:eq(1)').find('ul >li').each(function () {
                var text = $(this).find('a').html().toLowerCase().replace(/[_\W]+/g, "-");

                if (text.indexOf(valThis) < 0) {
                    $(this).hide();
                }
                else {
                    cnt++;
                    $(this).show()
                }
            });

            if (cnt < 5) {
                $('#less4').css('display', 'none');
                $('.filterOtherBrands4').css("height", "auto");
                $('.filterOtherBrands4').css("overflow-y", "hidden");
            }
        }
        else {
            $('#4 li:gt(3)').hide();
            $('#4 li:lt(4)').css('display', 'block');
            $('#less4').css('display', 'none');
            $('#show4').css('display', 'block');
            $('.filterOtherBrands4').css("height", "auto");
            $('.filterOtherBrands4').css("overflow-y", "hidden");
        }

    });
    $('.clFilterTextOtherBrands').on("input", function () {
        var valThis = $(this).val().toLowerCase().replace(/[_\W]+/g, "-");
        var ulid = $(this).parents('div:eq(1)').find('ul').attr("id");
        $(this).parents('div:eq(1)').find('ul >li').each(function () {
            var text = $(this).find('a').html().toLowerCase().replace(/[_\W]+/g, "-");

            if (text.indexOf(valThis) < 0)
            { $(this).hide(); }
            else {
                $(this).show()
            }
        });
    });

    $('.add-product.mb-4').click(function () {
        if (loginstatus == '1') {
            window.location = mshost + 'product/suggestproduct.php';
            return false;
        }
        else {
            var url = "/product/suggestproduct.php";
            ajaxLogin(url);
        }
    });


}

function getProd1(r, t) {
    $(this).parent().parent().find(".custom-dropdown-btn").text(r);
    if (actualCid != cid && r != "" && "Upcoming" != r && "Latest" != r) {
        cid = actualCid;
        actualUrl = mshost + "product/categories.php";
    }

    var c = "",
	a = "",
	i = "",
	b = "";
    try {
        "" != redirecturl && (i = redirecturl)
    } catch (o) { }
    "Upcoming" == sort && (sort = ""),
    "Latest" == sort && (sort = ""),
    "" != sort && (c = "&sort=" + sort.toLowerCase()),
	"" != r && (c = "&sort=" + r.toLowerCase()),
    "" != Advice && (b = "&adv=1"),
    "Upcoming" == r && (i = ""),
    "Latest" == r && (i = ""),
	a = navigator.userAgent.indexOf("3.6.28") > 1 ? actualUrl + "?cid=" + cid + b + i + sort : "" != pageno ? actualUrl + "?cid=" + cid + b + i + c : actualUrl + "?cid=" + cid + b + i + c,
	"" != a && (window.location.href = a)
}



function ReplaceBreaks() {
    $('.box.product .details .prod-sp .table >p').each(function () {
        var html = $(this).html();
        html = html.replace("(<br */>)|(\[br */\]|<br*>)", " ").replace("<br>", " ");
        html = html.replace(/<br\s*\/?>/mg, " ")
        $(this).html(html);
    });

    $('.col-3 .details .prod-sp .table >p').each(function () {
        var html = $(this).html();
        html = html.replace("(<br */>)|(\[br */\]|<br*>)", " ").replace("<br>", " ");
        html = html.replace(/<br\s*\/?>/mg, " ")
        $(this).html(html);
    });
}

function getSelected(chkId, parametername) {
    var selectedvalues = "";
    try {
        $("#" + chkId + " input[type=checkbox]:checked").each(function () {
            var currentValue = $(this).parent().attr('FilterValue');
            if (currentValue != '') { if (selectedvalues != '') { selectedvalues = selectedvalues + "," + currentValue; } else { selectedvalues = currentValue; } }
        });
        if (selectedvalues != '') { selectedvalues = parametername + selectedvalues; }
    }
    catch (e)
    { }
    return selectedvalues;
}

function getSelected(chkId, parametername, bindFilter) {
    var selectedvalues = "";
    try {
        try {
            if (bindFilter != undefined) {
                if ($("#" + bindFilter + " input[type=checkbox]:checked").length > 0) {
                    $("#" + chkId + " input[type=checkbox]:checked").each(function () {
                        var currentValue = $(this).parent().attr('FilterValue');
                        if (currentValue != '') { if (selectedvalues != '') { selectedvalues = selectedvalues + "," + currentValue; } else { selectedvalues = currentValue; } }
                    });
                }
            }
            else {
                $("#" + chkId + " input[type=checkbox]:checked").each(function () {
                    var currentValue = $(this).parent().attr('FilterValue');
                    if (currentValue != '') { if (selectedvalues != '') { selectedvalues = selectedvalues + "," + currentValue; } else { selectedvalues = currentValue; } }
                });
            }
        }
        catch (e) {
            $("#" + chkId + " input[type=checkbox]:checked").each(function () {
                var currentValue = $(this).parent().attr('FilterValue');
                if (currentValue != '') { if (selectedvalues != '') { selectedvalues = selectedvalues + "," + currentValue; } else { selectedvalues = currentValue; } }
            });

        }
        if (selectedvalues != '') { selectedvalues = parametername + selectedvalues; }
    }
    catch (e)
    { }
    return selectedvalues;
}

function KeyUp(txtboxID, chklistboxID) {
    if ($(txtboxID).val() != "") {
        $("table" + chklistboxID + " > tbody > tr").show();
        var n = chklistboxID.lastIndexOf('_');
        var result = chklistboxID.substring(n + 1);
        $('#less' + result).css('display', 'block');
        $('#show' + result).css('display', 'none');
        $('#' + result).css("height", "150px");
        $('#' + result).css("overflow-y", "scroll");

        $(chklistboxID).children('tbody').children('tr').each(function () {
            $(this).show();
        });

        var match = '0';
        $(chklistboxID).children('tbody').children('tr').each(function () {

            $(this).children('td').children('label').each(function () {

                if ($(this).text().toUpperCase().indexOf($(txtboxID).val().toUpperCase()) > -1)
                { match = '1'; }

            });

            if ($(this).text().toUpperCase().indexOf($(txtboxID).val().toUpperCase()) > -1) {
                match = '1';
                $(this).show();
            }
            else {
                $(this).hide();

            }
        });
    }
    else {
        var n = chklistboxID.lastIndexOf('_');
        var result = chklistboxID.substring(n + 1);
        $('#less' + result).css('display', 'none');
        $('#show' + result).css('display', 'block');
        $('#' + result).css("height", "auto");
        $('#' + result).css("overflow-y", "hidden");
        $("table" + chklistboxID + " > tbody > tr").hide().slice(0, 4).show();
    }
    if (match == '0') {
        var n = chklistboxID.lastIndexOf('_');
        var result = chklistboxID.substring(n + 1);
        $('#less' + result).css('display', 'none');
        $('#show' + result).css('display', 'none');
        $('#' + result).css("height", "auto");
        $('#' + result).css("overflow-y", "hidden");
    }

}

function createCookie(name, value, min) {
    if (min) {
        var date = new Date();
        date.setTime(date.getTime() + (min * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}


function AddProductListingProducts(Catid, CatName, Image) {
    var read = readCookie('CookieCompare' + CompareParent2);
    if (read !== 'undefined' && read != null) {
        var compare = $.parseJSON(read);
        for (var i = 0; i <= compare.length - 1; i++) {
            var compareData = compare[i];
            if (compareData.Catid == Catid) {
                alert('You Have Already Added This Product To Compare');
                try {
                    $('#txtcompareproduct').focus()
                } catch (e) { }
                try {
                    $('.search-box').focus()
                } catch (e) { }
                return false;
            }
        }

        if (compare.length >= 4) {
            alert('You Have Already Added 4 Products To Compare');
            try {
                $('#txtcompareproduct').focus()
            } catch (e) { }
            try {
                $('.search-box').focus()
            } catch (e) { }
            return false;
        }
        if (compare.indexOf(Catid, 1) == -1 && compare.length - 1 < 4) {
            compare.push(
                { 'Catid': Catid, 'CatName': CatName, 'Image': Image, 'Parent': CompareParent, 'Parent2': CompareParent2 }
            );
            createCookie('CookieCompare' + CompareParent2, JSON.stringify(compare), 10);
        }
        else {
            Alert('You Have Already Added This Product To Compare');
            try {
                $('#txtcompareproduct').focus()
            } catch (e) { }
            try {
                $('.search-box').focus()
            } catch (e) { }
            return false;
        }
    }
    else {
        var compare = [
          { 'Catid': Catid, 'CatName': CatName, 'Image': Image, 'Parent': CompareParent, 'Parent2': CompareParent2 }
        ];
        createCookie('CookieCompare' + CompareParent2, JSON.stringify(compare), 10);
    }

    $('#addProduct').modal("hide");
    document.getElementById("txtcompareproduct").value = "";
    return true;
}

function RemoveCompareProducts(Catid, CatName, Image) {
    var read = readCookie('CookieCompare' + CompareParent2);
    if (read !== 'undefined' && read != null) {
        var Newcompare;
        var compare = $.parseJSON(read);
        for (var i = 0; i <= compare.length - 1; i++) {
            var compareData = compare[i];
            if (compareData.Catid != Catid) {
                if (Newcompare == null) {
                    Newcompare = [
                    { 'Catid': compareData.Catid, 'CatName': compareData.CatName, 'Image': compareData.Image, 'Parent': CompareParent, 'Parent2': CompareParent2 }
                    ];
                }
                else {
                    Newcompare.push(
                  { 'Catid': compareData.Catid, 'CatName': compareData.CatName, 'Image': compareData.Image, 'Parent': CompareParent, 'Parent2': CompareParent2 }
                   );
                }
            }
        }
        createCookie('CookieCompare' + CompareParent2, JSON.stringify(Newcompare), 10);
    }
}
function RemoveCompare() {
    try {
        createCookie('CookieCompare' + CompareParent2, 'undefined', -1);
        CompareProductsDiv();
        CompareProductListingProducts();
        CompareProductsCheckBox();
    }
    catch (e) {
    }
}

function AddProductListingProductsDiv(Catid, CatName, Image) {
    var currentLocation = window.location.pathname;
    try {

        $.ajax({
            url: "/Account/Handler.ashx",
            contentType: "application/json; charset=utf-8",
            dataType: "text",
            async: false,
            data: { type: 'checkcustomproduct', catID: Catid },
            responseType: "text/html",
            success: function (data) {
                if (data == "discontinue") {
                    var CompareDiv = '<div class="compare-now-cell"><div class="compare-now-close"><span><img src="../../APP_THEMES/images/category/Close - Dark.svg" onclick="CompareProducts(false,\'' + Catid + '\',\'' + CatName + '\',\'' + Image + '\',\'' + CompareParent + '\',\'' + CompareParent2 + '\')"></span></div><div class="d-flex align-items-center h-100"><div class="compare-now-img"><img class="image-object-fit-contain" src="' + Image + '" alt="' + CatName + ' Image"><img class="discontnue" src="https://image3.mouthshut.com/images/imagesp/discontinued.png"></div><div class="compare-now-title">' + CatName + '</div></div></div>'
                } else if (data == "closed") {
                    var CompareDiv = '<div class="compare-now-cell"><div class="compare-now-close"><span><img src="../../APP_THEMES/images/category/Close - Dark.svg" onclick="CompareProducts(false,\'' + Catid + '\',\'' + CatName + '\',\'' + Image + '\',\'' + CompareParent + '\',\'' + CompareParent2 + '\')"></span></div><div class="d-flex align-items-center h-100"><div class="compare-now-img"><img class="image-object-fit-contain" src="' + Image + '" alt="' + CatName + ' Image"><img class="discontnue" src="https://image3.mouthshut.com/images/imagesp/closed.png"></div><div class="compare-now-title">' + CatName + '</div></div></div>'
                } else {
                    var CompareDiv = '<div class="compare-now-cell"><div class="compare-now-close"><span><img src="../../APP_THEMES/images/category/Close - Dark.svg" onclick="CompareProducts(false,\'' + Catid + '\',\'' + CatName + '\',\'' + Image + '\',\'' + CompareParent + '\',\'' + CompareParent2 + '\')"></span></div><div class="d-flex align-items-center h-100"><div class="compare-now-img"><img class="image-object-fit-contain" src="' + Image + '" alt="' + CatName + ' Image"></div><div class="compare-now-title">' + CatName + '</div></div></div>'
                }
                $('.compare-prod').append(CompareDiv);
            }
        });

    }
    catch (e) {
    }

}
function MoreAddProductListingProductsDiv() {
    try {
        var CompareDiv = $('<div class="compare-now-cell" ><div class="add-another-prod text-black-50" data-target="#addProduct" data-toggle="modal">Add Another Product</div></div>');
        $('.compare-prod').append(CompareDiv)
    }
    catch (e) {
    }
}

function CompareProductListingProducts() {
    $('.compare-prod').html('');
    $('.compare-now-section').hide();
    $('.comp-cont').hide();
    try {
        var read = readCookie('CookieCompare' + CompareParent2);
        if (read == null) {

            $('.compare-now-section').hide();
            $('.comp-cont').hide();
        }
        else if (read !== 'undefined' && read != null && read.length > 0) {
            var compare = $.parseJSON(read);

            for (var i = 0; i <= 3; i++) {
                var compareData = compare[i]
                if (compareData != null) {
                    var productname;
                    if (compareData.CatName.length > 25) {
                        productname = compareData.CatName.substring(0, 25) + " ..."
                    }
                    else {
                        productname = compareData.CatName;
                    }
                    AddProductListingProductsDiv(compareData.Catid, productname, compareData.Image);
                }
                else {
                    MoreAddProductListingProductsDiv();
                }
            }
            $('.compare-now-section').show();
            $('.comp-cont').show();

        }
    }
    catch (e) {
    }

    $('.comp-cont .icon-drop-down').unbind('click');
    $('.comp-cont .icon-drop-down').click(function () {
        $(this).toggleClass('icon-next')
        .closest('.comp-cont').toggleClass('minimize');
    });

}

function CompareProductsDiv() {
    $('.compare-prod').html('');
    $('.page-header.compare').hide();
    $('.comp-cont').hide();
    try {
        var read = readCookie('CookieCompare' + CompareParent2);
        if (read == null) {

            $('.page-header.compare').hide();
            $('.comp-cont').hide();
        }
        else if (read !== 'undefined' && read != null && read.length > 0) {
            var compare = $.parseJSON(read);

            for (var i = 0; i <= 3; i++) {
                var compareData = compare[i]
                if (compareData != null) {
                    AddCompareProductsDiv(compareData.Catid, compareData.CatName, compareData.Image);
                }
                else {
                    MoreAddCompareProductsDiv();
                }
            }
            $('.page-header.compare').show();
            $('.comp-cont').show();

        }

    }
    catch (e) {
    }
    $('.comp-cont .icon-drop-down').unbind('click');
    $('.comp-cont .icon-drop-down').click(function () {
        $(this).toggleClass('icon-next')
        .closest('.comp-cont').toggleClass('minimize');
    });


}


function AddCompareProducts(Catid, CatName, Image) {
    var read = readCookie('CookieCompare' + CompareParent2);
    if (read !== 'undefined' && read != null) {
        var compare = $.parseJSON(read);
        for (var i = 0; i <= compare.length - 1; i++) {
            var compareData = compare[i];
            if (compareData.Catid == Catid) {
                alert('You Have Already Added This Product To Compare');
                try {
                    $('#txtcompareproduct').focus()
                } catch (e) { }
                try {
                    $('.search-box').focus()
                } catch (e) { }
                return false;
            }
        }

        if (compare.length >= 4) {
            alert('You Have Already Added 4 Products To Compare');
            try {
                $('#txtcompareproduct').focus()
            } catch (e) { }
            try {
                $('.search-box').focus()
            } catch (e) { }
            return false;
        }
        if (compare.indexOf(Catid, 1) == -1 && compare.length - 1 < 4) {
            compare.push(
                { 'Catid': Catid, 'CatName': CatName, 'Image': Image, 'Parent': CompareParent, 'Parent2': CompareParent2 }
            );
            createCookie('CookieCompare' + CompareParent2, JSON.stringify(compare), 10);
        }
        else {
            Alert('You Have Already Added This Product To Compare');
            try {
                $('#txtcompareproduct').focus()
            } catch (e) { }
            try {
                $('.search-box').focus()
            } catch (e) { }
            return false;
        }
    }
    else {
        var compare = [
          { 'Catid': Catid, 'CatName': CatName, 'Image': Image, 'Parent': CompareParent, 'Parent2': CompareParent2 }
        ];
        createCookie('CookieCompare' + CompareParent2, JSON.stringify(compare), 10);
    }
    return true;
}

function AddCompareProductsDiv(Catid, CatName, Image) {
    try {
        var CompareDiv = '<div class="compare-col"><img src="' + Image + '" class="col-6"><p class="col-6">' + CatName + '</p><span class="icon-close" onclick="CompareProducts(false,\'' + Catid + '\',\'' + CatName + '\',\'' + Image + '\',\'' + CompareParent + '\',\'' + CompareParent2 + '\')"></span> </div>';
        $('.compare-prod').append(CompareDiv);

    }
    catch (e) {
    }
}
function MoreAddCompareProductsDiv() {
    try {
        var CompareDiv = $('<div class="compare-col add-product" onclick="opencompareproducts()"><div class="text-center"><p>Add Another Product</p></div></div>');
        $('.compare-prod').append(CompareDiv)
    }
    catch (e) {
    }
}

function CompareProducts(CheckedStatus, Catid, CatName, Image) {
    var status = false;
    CatName = CatName.replace("'", "");
    if (CheckedStatus) {
        if (pageName == "RAR") {
            var read = readCookie('CookieCompare' + CompareParent2);
            if (read !== 'undefined' && read != null) { }
            else {
                status = AddCompareProducts(cat_id, cat_name, cat_imgSrc);
            }
            status = AddCompareProducts(Catid, CatName, Image);
            CompareProductsDiv();
        } else if (pageName == "ProductListing") {
            status = AddProductListingProducts(Catid, CatName, Image);
            CompareProductListingProducts();
        }

    } else if (!CheckedStatus && pageName == "ProductListing") {
        RemoveCompareProducts(Catid, CatName, Image);
        CompareProductListingProducts();
        status = true;
    } else {
        RemoveCompareProducts(Catid, CatName, Image);
        CompareProductsDiv();
        status = true;
    }
    CompareProductsCheckBox();
    return status;
}
function CompareProductsCheckBox() {
    try {
        $('.chkcompare').each(function () {
            var chkcompareid = $(this).attr('id');
            chkcompareid = chkcompareid.replace('chkcompare', '');
            if (CheckCompareProductsCheckBox(chkcompareid)) {
                $(this).prop('checked', true);
            }
            else {
                $(this).prop('checked', false);
            }
        });
    }

    catch (e) {
    }

}
function CheckCompareProductsCheckBox(chkcompareid) {
    try {
        var read = readCookie('CookieCompare' + CompareParent2);
        if (read !== 'undefined' && read != null) {
            var compare = $.parseJSON(read);
            for (var i = 0; i <= compare.length - 1; i++) {
                var compareData = compare[i];
                if (compareData.Catid == chkcompareid) {
                    return true;
                }
            }
        }

    }
    catch (e) {
        return false;
    }
    return false;
}

function CompareProductsReset() {
    try {
        var read = readCookie('CookieCompare' + CompareParent2);
        if (read !== 'undefined' && read != null) {
            var compare = $.parseJSON(read);
            createCookie('CookieCompare' + CompareParent2, JSON.stringify(compare), 10);
        }

    }
    catch (e) {

    }
}
$(document).ready(function () {
    CompareProductsDiv();
    CompareProductListingProducts();
    CompareProductsCheckBox();
    CompareProductsReset();
});

function GetCompareAutoCompleteID(source, eventArgs) {

    var HdnKey = eventArgs.get_value();
    var value = eventArgs.get_value();
    if (value.indexOf("No Results Found") > -1) {
        try { document.getElementById('txtcompareproduct').value = ''; } catch (e) { }
    }
    var comapreAutovalue = HdnKey.split('|');

    if (comapreAutovalue.length > 0) {
        if (comapreAutovalue[1] != "0") {
            if (CompareProducts(true, comapreAutovalue[1], comapreAutovalue[0], comapreAutovalue[2])) {
                $('.addProduct').hide().removeClass('modal');
                $('.black-layer').css('visibility', 'hidden');
                $('body').css('overflow-y', 'auto');
            }
        }
    }
}

function GetCompareAutoCompleteIDRAR(source, eventArgs) {
    var HdnKey = eventArgs.get_value();
    var value = eventArgs.get_value();
    if (value.indexOf("No Results Found") > -1) {
        try { document.getElementById('txtcompareproduct').value = ''; } catch (e) { }
    }
    var comapreAutovalue = HdnKey.split('|');

    if (comapreAutovalue.length > 0) {
        if (comapreAutovalue[1] != "0") {
            if (CompareProducts(true, comapreAutovalue[1], comapreAutovalue[0], comapreAutovalue[2])) {
                $('.addProduct').hide().removeClass('modal');
                $('.black-layer').css('visibility', 'hidden');
                $('body').css('overflow-y', 'auto');
            }
        }
    }
    document.getElementById('txtCompProd').value = "";
}

function ProductComparecatid(CompareListcatid) {
    try {
        createCookie('CookieCompare' + CompareParent2, 'undefined', -1);
    } catch (e) { }
}

function setContextKey() {
    $find('AutoCompleteCompare').set_contextKey(CompareParent + "|" + CompareParent2);
}

function setContextKeyRHS() {
    $find('accRAR_RHS').set_contextKey(CompareParent + "|" + CompareParent2);
}

$("#txtproductSearch").keydown(function (e) {
    //Enter key
    if (e.which == 13) {
        e.preventDefault();
    }
});
function SearchProductRedirectPageUrl(source, eventArgs) {
    var HdnKey = eventArgs.get_value();
    var value = eventArgs.get_value();
    if (value.indexOf("No Results Found") > -1) {
        try { document.getElementById('txtproductSearch').value = ''; } catch (e) { }
    }
    else {
        var comapreAutovalue = HdnKey.split('|');

        if (comapreAutovalue.length > 3) {
            try {
                window.location.href = comapreAutovalue[3];
            }
            catch (err) { alert("Error: " + err); }

        }
        else {
            var url = mshost + "product-reviews/" + comapreAutovalue[0].replace(/[^A-Z0-9]/ig, "-") + "-reviews-" + comapreAutovalue[1];
            window.location.href = url;
        }
    }
}

function setContextKeyproductSearch() {

    if (Pagetype == "1") {
        var searchcatid = $('.src-fltr').attr('value');
        if (searchcatid == "") {
            searchcatid = "0";
        }
        $find('AutoCompleteproductSearch').set_contextKey("0" + "|" + searchcatid + "|0");
    }
    else {

        $find('AutoCompleteproductSearch').set_contextKey("0" + "|" + cid + "|0");
    }
}

function opencompareproducts() {
    document.cookie = "chkdiff=;";
    document.cookie = "chksim=;";
    openModal('.addProduct');
    try { document.getElementById('txtcompareproduct').value = ''; $('#txtcompareproduct').focus() } catch (e) { }
    try { $('.search-box').val(''); $('.search-box').focus() } catch (e) { }
}

function Redirectcompare() {
    var url = mshost + "comparison/compareproducts.php?catid=";
    try {
        var read = readCookie('CookieCompare' + CompareParent2);
        if (read !== 'undefined' && read != null) {
            var compare = $.parseJSON(read);
            for (var i = 0; i <= compare.length - 1; i++) {
                var compareData = compare[i];
                if (i == compare.length - 1) {
                    url = url + compareData.Catid + '|' + CompareParent;
                }
                else {
                    url = url + compareData.Catid + '|' + CompareParent + ',';
                }
            }
        }
        window.location.href = url;
        return false;
    }
    catch (e) {
        return false;
    }

}
var scrollFilter = false;

$(window).scroll(function () {
    if (scrollFilter == false) {
        if (ShowAsyn == "False") {

            if ($('.listing-filter-tag').find("span").length <= 0 && GetFilters != '') {
                GetFilters = '1';
            }
            else if (GetFilters == '1') {
                GetFilters = '1';
            }
            else {
                GetFilters = '0';
            }

            $.ajax({
                url: mainurl,
                async: true,
                type: 'POST',
                dataType: 'text',
                headers: {
                    'ShowAsyn': '1',
                    'GetFilters': GetFilters
                },
                contentType: 'application/x-www-form-urlencoded',
                data: $(this).serialize(),
                success: function (data, textStatus, jQxhr) {

                    if (data.split("~").length > 1) {
                        var data1 = data.split("~")[0];
                        var data2 = data.split('~')[1].replace("class=\"module filters\"", "");
                        var data3 = data.split('~')[2];
                        $('#divReviewsAdvice').html(data1);
                        $('.module.filters').html(data2);
                        $('.listing-filter-tag').html(data3);
                        Rebind();
                    }
                    else if (data.indexOf("Reviews") > -1) {
                        $('#divReviewsAdvice').html(data);
                        Rebind();
                    }
                    else if (data.indexOf("sidebar") > -1) {
                        $('.module.filters').html(data);
                        Rebind();
                    }
                    else if (data.indexOf("badge - list") > -1) {
                        $('.listing-filter-tag').html(data);
                        Rebind();
                    }
                    displayOnlyFourFilters();
                    (function () {
                        var bLazy = new Blazy();
                    })();
                },
                error: function (jqXhr, textStatus, errorThrown) {
                    console.log(errorThrown);
                }
            });

            ShowAsyn = "True";

        }
    scrollFilter=true;
}
});

try {

    if (sel >= 11) {
        var mod = sel % 10;
        if (mod == 0) {
            var intMorePage = sel - mod + 1;
            var intLessPage = sel - mod - 9;
        }
        else {
            var intMorePage = sel - mod + 11;
            var intLessPage = sel - mod + 1;
        }
        var tabThisPage = 10;
    }
    else {
        var intMorePage = 11;
        var intLessPage = 1;
        var tabThisPage = 10;
    }
}
catch (e) { }
function showMorePages(maxPg, sel) {
    var spnPaging = document.getElementById("spnPaging");
    var strPaging = "";

    strMore = "";
    var strPaging = "<li class='page-item'>  <a class='page-link' href= '" + mshost.slice(0, mshost.lastIndexOf("/")) + Actual.replace("&page=", "").replace("?page=", "") + "'\>" + 1 + "</a></li>" + "<li class='page-item'> <span class='page-link' onClick=\"return showLessPages(" + maxPg + ", " + sel + ");\"><b>...</b></span> </li>";

    if (intMorePage + 9 < maxPg) {
        loopPages = 9;
        tabThisPage = 10;
        strMore = "<li class='page-item'> <span class='page-link' onClick=\"return showMorePages(" + maxPg + ", " + sel + ");\"><b>...</b></span></li>";
        strMore = strMore + "<li class='page-item'>  <a class='page-link' href= '" + mshost.slice(0, mshost.lastIndexOf("/")) + Actual + maxPg + "'\>" + maxPg + "</a></li>";
    } else {
        loopPages = maxPg - intMorePage;
        tabThisPage = loopPages;
    }

    for (i = intMorePage; i <= loopPages + intMorePage; i++) {
        if (i == sel)
            strPaging = strPaging + "<li class='page-item active'>  <span  class='page-link active'>" + i + "</span> </li>";
        else
            strPaging = strPaging + "<li class='page-item'>  <a class='page-link' href= '" + mshost.slice(0, mshost.lastIndexOf("/")) + Actual + i + "'\>" + i + "</a></li>";
    }   // END OF FOR

    intMorePage = intMorePage + tabThisPage;
    intLessPage = intLessPage + 10;
    spnPaging.innerHTML = strPaging + strMore;
} // END OF FUNCTION showMorePages


function showLessPages(maxPg, sel) {

    var spnPaging = document.getElementById("spnPaging");
    var strPaging = "";
    var strLess = "";

    if (intLessPage > 11) {
        strLess = "<li class='page-item'>  <a class='page-link' href= '" + mshost.slice(0, mshost.lastIndexOf("/")) + Actual.replace("&page=", "").replace("?page=", "") + "'\>" + 1 + "</a></li>" + "<li class='page-item'> <span class='page-link' onClick=\"return showLessPages(" + maxPg + ", " + sel + ");\"><b>...</b></span></li>";
    }

    for (i = intLessPage - 1; i >= intLessPage - 10; i--) {
        if (i == sel)
            strPaging = "<li class='page-item active'>  <span  class='page-link active'>" + i + "</span> " + strPaging;
        else if (i == 1) {
            strPaging = " <li class='page-item'> <a class='page-link'  href= '" + mshost.slice(0, mshost.lastIndexOf("/")) + Actual.replace("&page=", "").replace("?page=", "") + "'\>" + i + "</a></li>" + strPaging;
        }
        else
            strPaging = " <li class='page-item'> <a class='page-link'  href= '" + mshost.slice(0, mshost.lastIndexOf("/")) + Actual + i + "'\>" + i + "</a></li>" + strPaging;
    }   // END OF FOR
    strMore = "<li> <span class='page-link' onClick=\"return showMorePages(" + maxPg + ", " + sel + ");\"><b>...</b></span></li>";
    strMore = strMore + "<li class='page-item'>  <a class='page-link' href= '" + mshost.slice(0, mshost.lastIndexOf("/")) + Actual + maxPg + "'\>" + maxPg + "</a></li>";

    intLessPage = intLessPage - 10;
    spnPaging.innerHTML = strLess + strPaging + strMore;
    if (intMorePage > 11)
        intMorePage = intMorePage - tabThisPage;
    tabThisPage = 10;	  ///  -- shifted

}


function displayOnlyFourFilters() {
    var filters = [];
    var $filtersArrayOfId = [];
    var $filtersArrayOfClass = [];
    filters = $("ul.pl-0.mb-0").parent();

    filters.each(function () {
        var hasid = $(this).attr('id');
        if (hasid !== undefined) {
            $("table#ctl00_ContentPlaceHolderBody_ChkboxLstFilter_" + hasid + " > tbody > tr").hide().slice(0, 4).show();
        }
    });

}

$(document).ready(function () {
    document.getElementById("txtproduct").value = "";
    if (Pagetype == "1" || Pagetype == "4" || $('body').find('.travel-head').length > 0) {
        Pagetext = 'Tours';
        $(".listing-prod-card").removeClass("list-view");
        $(".listing-prod-card").addClass("gride-view");
        $(".list-view-comapre").hide();
        $(".listviewads").hide();

    }
    else {
       // $(".listing-prod-card").addClass("list-view");
      //  $('#listview').prop("src", "../../APP_THEMES/images/category/list.svg");
       // $('#gridview').prop("src", "../../APP_THEMES/images/category/grid.svg");
        $(".grid-view-comapre").show();
        $(".list-view-comapre").hide();

    }
   

    if (Pagetype == "2" && $('body').find('.travel-head').length > 0) {
        $(".listing-prod-card").removeClass("list-view");
        $(".listing-prod-card").addClass("gride-view");
        $(".list-view-comapre").hide();


    }
    $(".big-ads").hide();
    document.getElementById("txtcompareproduct").value = "";

    $(".list-view-img").click(function () {
        $(".listing-prod-card").addClass("list-view");
        $('#listview').prop("src", "../../APP_THEMES/images/category/list.svg");
        $('#gridview').prop("src", "../../APP_THEMES/images/category/grid.svg");
        $(".grid-view-comapre").hide();
        $(".list-view-comapre").show();
       $(".listing-prod-card").addClass("list-view");
        $(".listviewads").show();
        $(".dot-seperator").show();
        $(".comp").show();
        $(".listingVerify").removeClass("twwverify");

    })
    $(".grid-view-img").click(function () {
        $(".listing-prod-card").removeClass("list-view");
        $('#gridview').prop("src", "../../APP_THEMES/images/category/grid-high.svg");
        $('#listview').prop("src", "../../APP_THEMES/images/category/list-nonhigh.svg");
        $(".list-view-comapre").hide();
        $(".grid-view-comapre").show();
        $(".listviewads").hide();
        $(".dot-seperator").hide();
        $(".listingVerify").addClass("twwverify");

    })

    //onload show only 3 records
    var list = $('#0 li:gt(3)');
    list.hide();

    var list1 = $('#1 li:gt(3)');
    list1.hide();

    var list2 = $('#2 li:gt(3)');
    list2.hide();

    var list3 = $('#3 li:gt(3)');
    list3.hide();

    var list4 = $('#4 li:gt(3)');
    list4.hide();

})

function closed() {
    var searchtext = document.getElementById("txtcompareproduct").value = "";

}

$(".top-listing-btn").click(function () {
    $(window).scrollTop(0);
})
$(window).scroll(function () {
    if ($(this).scrollTop() < 100) {
        $('.to-top').hide();
    } else {
        $('.to-top').show();
    }
});


//To show selected sorted value in dropdown
if (document.getElementById("sortBy") != null) {
    if (window.location.search.includes("sort=") == true) {
        if (window.location.search.includes("popular") == true) {
            document.getElementById("sortBy").innerHTML = "Popular";
        }
        if (window.location.search.includes("pricelow") == true) {
            document.getElementById("sortBy").innerHTML = "Price-Low";
        }
        if (window.location.search.includes("pricehigh") == true) {
            document.getElementById("sortBy").innerHTML = "Price-High";
        }
        if (window.location.search.includes("rating") == true) {
            document.getElementById("sortBy").innerHTML = "Product Rating";
        }
        if (window.location.search.includes("reviewcnt") == true) {
            document.getElementById("sortBy").innerHTML = "Most Reviewed";
        }
        if (window.location.search.includes("upcoming") == true) {
            document.getElementById("sortBy").innerHTML = "Upcoming";
        }
        if (window.location.search.includes("latest") == true) {
            document.getElementById("sortBy").innerHTML = "Latest";
        }
    }
    else {
        if (window.location.search.includes("srchKeyword") == false && window.location.search.includes("srchcatid") == false && sortBy.classList.contains("src-fltr")) {
            document.getElementById("sortBy").innerHTML = "All";
        }
        else {
            document.getElementById("sortBy").innerHTML = "Popular";
        }
    }
}

//End

//Fixed menu on tour page

let travelLinks = document.querySelector(".travel-links");
if (travelLinks) {
    var offset = 167;

    $('.travel-links a').click(function (event) {
        event.preventDefault();
        $($(this).attr('href'))[0].scrollIntoView();
        scrollBy(0, -offset);
    });


    let travelLinksPos = travelLinks.offsetTop;

    window.addEventListener("scroll", function (e) {

        if (window.scrollY >= travelLinksPos) {
            travelLinks.classList.add("fixed-top");
        }
        else {
            travelLinks.classList.remove("fixed-top");
        }
    })

}


//show more and less
function showmore() {
    var list = $('.pl-0 li');
    $('li').slideDown();
    //list.show();
    $('#less').css('display', 'block');
    $('#show').css('display', 'none');
    $('.filterOtherBrands').css("height", "150px");
    $('.filterOtherBrands').css("overflow-y", "scroll");
}

function less() {
    var list = $('.pl-0 li:gt(4)');
    list.slideUp();
    $('#less').css('display', 'none');
    $('#show').css('display', 'block');
    $('.filterOtherBrands').css("height", "auto");
    $('.filterOtherBrands').css("overflow-y", "none");
}

function showmore(i) {
    var id = '#' + i + ' li';
    console.log("'" + id + "'");
    var list = $(id);
    list.slideDown();
    $('#less' + i).css('display', 'block');
    $('#show' + i).css('display', 'none');
    $('.filterOtherBrands' + i).css("height", "150px");
    $('.filterOtherBrands' + i).css("overflow-y", "scroll");
}

function less(i) {
    var id = '#' + i + ' li:gt(3)';
    var list = $(id);
    list.hide();
    $('#less' + i).css('display', 'none');
    $('#show' + i).css('display', 'block');
    $('.filterOtherBrands' + i).css("height", "auto");
    $('.filterOtherBrands' + i).css("overflow-y", "none");
}

//End



function showfilters(filterid) {
    var filtertext = filterid;
    $("table#ctl00_ContentPlaceHolderBody_ChkboxLstFilter_" + filtertext + " > tbody > tr").show();
    $('#less' + filterid).css('display', 'block');
    $('#show' + filterid).css('display', 'none');
    $('#' + filterid).css("height", "150px");
    $('#' + filterid).css("overflow-y", "scroll");
}

function hidefilters(filterid) {
    var id = '#' + i + ' li:gt(3)';
    var filtertext = filterid;
    $("table#ctl00_ContentPlaceHolderBody_ChkboxLstFilter_" + filtertext + " > tbody > tr").hide().slice(0, 4).show();
    $('#less' + filterid).css('display', 'none');
    $('#show' + filterid).css('display', 'block');
    $('#' + filterid).css("height", "auto");
    $('#' + filterid).css("overflow", "hidden");
}
$('.tooltip1').on({
    mouseenter: function () {
        var tipContent = $(this).find('.tooltip-content');
        var posObj, posClass = $(this).attr('class').split(' ');
        for (var i = 0; i < posClass.length; i++) {
            switch (posClass[i]) {
                case "left":
                    tipContent.css({ 'margin-left': -($(tipContent).width() + 15) + 'px', 'margin-top': -$(this).height() + 'px' });
                    break;

                case "right":
                    tipContent.css({ 'margin-left': $(this).width() + 5 + 'px', 'margin-top': -$(this).height() + 'px' });
                    break;

                case "top":
                    tipContent.css('margin-top', -($(this).height() + $(tipContent).height() + 5) + 'px');
                    break;
            }
            $(this).find('.tooltip-content').css('display', 'block');
        };
    },
    mouseleave: function () {
        $('.tooltip-content').hide();
    }
});;
var divMoreReviews, linkMoreProdRev, linkMoreMemRev, linkEditorsPick, MoreMemRevUrl, MoreProdRevUrl, OverallRatUrl, TrustRatUrl
var tabMoreProdRev, tabMoreMemRev, tabEditorsPick
var divComments, divCorpComments, spancomcount, diverror, txtComment, btnSubmit, btnEdit, hidCommentId, loadhead, divTotcnt, hidviewmore, corp_btnEdit, corp_btnSubmit
var Rate_Comment = false
var FocusOnComments = false
var Add_Comment = false
var FocusOnAddComments = false
var Height1;
var Height2;
var width1;
var width2;
var selEdit
var urlredirect, indesof, urlredirectTo;
var editabletr;
var firstvisit = 1;
var canPostComntonResponse1;

try {
    canPostComntonResponse1 = canPostComntOnResponse;
} catch (e) {

}

$(document).ready(function () {
    btnSubmit = document.getElementById("btnSubmit");
    divCorpComments = document.getElementById("corp_divComments");
    linkpostcomment = document.getElementById("linkpostcomment");
    btnEdit = document.getElementById("btnEdit");
    txtComment = document.getElementById("txtComment");
    corp_txtComment = document.getElementById("corp_txtComment");
    hidCommentId = document.getElementById("hidCommentId");
    corp_btnSubmit = document.getElementById("corp_btnSubmit");
    corp_btnEdit = document.getElementById("corp_btnEdit");
    //$('#lightgallery1').lightGallery();
    
});

function textCommentCounterrr(errcommentid, btnsubmitid, btneditid, textid, commentType) {
    //console.log($('#' + textid).val().length);
    //alert(user_id);
    //if (user_id == "0") {
    //    ChkLoginComment("login", "");
    //}
    
    if (CountWordsrr($('#' + textid).val()) < 3) {

        if ($('#' + textid).val().length > 50) {
            $(".comment-box").css('height', '152px');
            if (commentType == "corp") {
                $("#" + errcommentid).html("<span class='icon-tool-tip'></span> &nbsp; Minimum 3 words and Maximum 2000 characters").css('color', 'red').show();
                $("#" + textid).css('height', '152px');
            }
            else {
                $("#" + errcommentid).html("<span class='icon-tool-tip'></span> &nbsp; Minimum 3 words and Maximum 2000 characters").css('color', 'red').show();
            }
            
        }

        $("#" + btnsubmitid).prop('disabled', true);
        $("#" + btneditid).prop('disabled', true);
        
    }
    else {
        if ($('#' + textid).val().length > 2000) {
            if (commentType == "corp") {
                $("#" + errcommentid).html("<span class='icon-tool-tip'></span> &nbsp; Minimum 3 words and Maximum 2000 characters").css('color', 'red').show();
                $("#" + textid).css('height', '152px');
            }
            else {
                $("#" + errcommentid).html("<span class='icon-tool-tip'></span> &nbsp; Minimum 3 words and Maximum 2000 characters").css('color', 'red').show();
            }

            $("#" + btnsubmitid).prop('disabled', true);
            $("#" + btneditid).prop('disabled', true);
            
        }
        else {
            $("#" + errcommentid).html("").hide();
            $("#" + btnsubmitid).prop('disabled', false);
            $("#" + btneditid).prop('disabled', false);
            
            //this.style.height = 'auto';
            //this.style.height =(this.scrollHeight) + 'px';
            
        }

        if ($('#' + textid).val().length > 100) {
            $("#" + textid).css('height', '152px');
        }

        
       
    }
}

function ChkLoginComment(str, RedirectPage, params) {
    if (str == 'login') {
        
        if (typeof pgurl == 'undefined') {
            pgurl = uri
        }
        else if (pgurl.includes("sort")) {
            pgurl = pgurl
        }
        else {
            pgurl = mainurl
        }
        urlredirect = encodeURI(pgurl) + encodeURI(RedirectPage) + (params == undefined ? "" : params);
        indesof = urlredirect.indexOf("/review/");
        urlredirectTo = urlredirect.substr(urlredirect);
        ajaxLogin(urlredirectTo);
    }
}


function Ajaxrr(funcname, querystring, divid, linkpostid, commentcntid, hidskipid, hidskipidval) {

    var clsAjax = new CreateRequest()
    clsAjax.ajaxObject.onreadystatechange = function () {
        if (clsAjax.ajaxObject.readyState == 4) {
            funcname(clsAjax.ajaxObject.responseText, divid, linkpostid, commentcntid, hidskipid, hidskipidval)
        }
    }
    clsAjax.ajaxObject.open("GET", "/review/reviewajax.php?" + querystring, true)
    clsAjax.ajaxObject.send(null)
}
function AjaxByHashrr(funcname, querystring, divid, linkpostid, commentcntid, hidskipid, rate, cmts) {
    var clsAjax = new CreateRequest()
    clsAjax.ajaxObject.onreadystatechange = function () {
        if (clsAjax.ajaxObject.readyState == 4) {
            if (clsAjax.ajaxObject.responseText == 'no records') {
                $('#' + divid).parent().find('h5').hide();
                $('#' + divid).parent().find('.text-center').hide();
            }
            funcname(clsAjax.ajaxObject.responseText, divid, linkpostid, commentcntid, hidskipid, rate, cmts)
        }
    }
    clsAjax.ajaxObject.open("GET", "/review/reviewajax.php?" + querystring, false)
    clsAjax.ajaxObject.send(null)
}
function AjaxByHashCorprr(funcname, querystring, divcorpid, corp_txtCommentid, corp_errCommentid, corp_btnSubmitid, corp_btnEditid) {
    var clsAjax = new CreateRequest()
    clsAjax.ajaxObject.onreadystatechange = function () {
        if (clsAjax.ajaxObject.readyState == 4) {
            funcname(clsAjax.ajaxObject.responseText, divcorpid, corp_txtCommentid, corp_errCommentid, corp_btnSubmitid, corp_btnEditid)
        }
    }
    clsAjax.ajaxObject.open("GET", "/review/reviewajax.php?" + querystring, false)
    clsAjax.ajaxObject.send(null)
}
function AjaxresAllrr(funcname, querystring, arateid, reviewid, rand, skipid, mergeparent, parent, divcommentid, lnkpostcommid, hidcmtcnt, hidskipid, txtcommentid, errorid, acorp) {

    var clsAjax = new CreateRequest()
    clsAjax.ajaxObject.onreadystatechange = function () {
        if (clsAjax.ajaxObject.readyState == 4) {
            funcname(clsAjax.ajaxObject.responseText, arateid, reviewid, rand, skipid, mergeparent, parent, divcommentid, lnkpostcommid, hidcmtcnt, hidskipid, txtcommentid, errorid, acorp)
        }
    }
    clsAjax.ajaxObject.open("GET", "/review/reviewratingrestaurant.aspx?" + querystring, true)
    clsAjax.ajaxObject.send(null)
}

function AjaxPostrr(funcname, parameters, divid, errid, txtcommentid, btnaddid, btnupdateid, aid, commentcntid, linkpostid, hidskipid, hidskipidval, divlike) {
    var clsAjax = new CreateRequest()
    clsAjax.ajaxObject.onreadystatechange = function () {
        if (clsAjax.ajaxObject.readyState == 4) {
            if (parameters.includes("AddCorpComment=1")) {
                $("#ltCommentCount").text(parseInt($("#ltCommentCount").text()) + 1);
            }
            funcname(clsAjax.ajaxObject.responseText, divid, errid, txtcommentid, btnaddid, btnupdateid, aid, commentcntid, linkpostid, hidskipid, hidskipidval);
        }
    }
    clsAjax.ajaxObject.open("POST", "/review/reviewajax.php", true)
    clsAjax.ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
    clsAjax.ajaxObject.setRequestHeader("Content-length", parameters.length)
    clsAjax.ajaxObject.setRequestHeader("Connection", "close")
    clsAjax.ajaxObject.send(parameters)
}
function ChkLoginrr(str, RedirectPage, params) {
    if (str == 'login') {
        if (typeof pgurl == 'undefined') {
            pgurl = uri
        }
        else if (pgurl.includes("sort")) {
            pgurl = pgurl
        }
        else {
            pgurl = mainurl
        }
        urlredirect = encodeURI(pgurl) + encodeURI(RedirectPage) + (params == undefined ? "" : params);
        indesof = urlredirect.indexOf("/review/");
        urlredirectTo = urlredirect.substr(urlredirect);
        ajaxLogin(urlredirectTo);
    }
}
function ChkLogin_Raterr(str, RedirectPage, Rid, params) {
    if (str == '0') {
        urlredirect = "/signup/login/login_now.php?add=" + encodeURI("/review/" + CatName + "-review-" + Rid + "") + encodeURI(RedirectPage) + (params == undefined ? "" : params);
        indesof = urlredirect.indexOf("/review/");
        urlredirectTo = urlredirect.substr(indesof);
        ajaxLogin(urlredirectTo);
        return 'false';
    }
    else return 'true';
}
function OverallRatingrr(responsText, arateid, divlikeid, reviewid) {
    ShowGraph1(responsText, arateid, divlikeid, reviewid)
}
function ajaxTooltip() {

    $('.tooltip').on({
        mouseenter: function () {
            var tipContent = $(this).find('.tooltip-content');
            var posObj, posClass = $(this).attr('class').split(' ');
            for (var i = 0; i < posClass.length; i++) {
                switch (posClass[i]) {
                    case "left":
                        tipContent.css({ 'margin-left': -($(tipContent).width() + 15) + 'px', 'margin-top': -$(this).height() + 'px' });
                        break;

                    case "right":
                        tipContent.css({ 'margin-left': $(this).width() + 5 + 'px', 'margin-top': -$(this).height() + 'px' });
                        break;

                    case "top":
                        tipContent.css('margin-top', -($(this).height() + $(tipContent).height() + 5) + 'px');
                        break;
                }
                $(this).find('.tooltip-content').css('display', 'block');
            };
        },
        mouseleave: function () {
            $('.tooltip-content').hide();
        }
    });
}
function ajaxTooltip1(liName) {
    $('#iconLI' + liName + ' .tooltip').on({
        mouseenter: function () {
            var tipContent = $(this).find('.tooltip-content');
            var posObj, posClass = $(this).attr('class').split(' ');
            for (var i = 0; i < posClass.length; i++) {

                switch (posClass[i]) {
                    case "left":
                        tipContent.css({ 'margin-left': -($(tipContent).width() + 15) + 'px', 'margin-top': -$(this).height() + 'px' });
                        break;

                    case "right":
                        tipContent.css({ 'margin-left': $(this).width() + 5 + 'px', 'margin-top': -$(this).height() + 'px' });
                        break;

                    case "top":
                        tipContent.css('margin-top', -($(this).height() + $(tipContent).height() + 5) + 'px');
                        break;
                }
                $(this).find('.tooltip-content').css('display', 'block');
            };
        },
        mouseleave: function () {
            $('#iconLI' + liName + ' .tooltip-content').hide();
        }
    });
}
function MoreMemberReviews(responseText) {
    if (responseText == "no records") {
        divMoreReviews.innerHTML = "<span class='font'>No records found.</span>"
    }
    else {
        divMoreReviews.innerHTML = responseText
    }
    tabMoreMemRev.className = "tabs_blue"
    tabEditorsPick.className = "tabs_grey"
    linkMoreMemRev.removeAttribute("href")
    linkEditorsPick.setAttribute("href", "javascript:Ajax(EditorsPick,'EditorsPick=1&Random=" + Math.random() + "')")
}
function EditorsPick(responseText) {
    if (responseText == "no records") {
        divMoreReviews.innerHTML = "<span class='font'>No records found.</span>"
    }
    else {
        divMoreReviews.innerHTML = responseText
    }
    tabMoreMemRev.className = "tabs_grey"
    tabEditorsPick.className = "tabs_blue"
    linkEditorsPick.removeAttribute("href")
    linkMoreMemRev.setAttribute("href", "javascript:Ajax(MoreMemberReviews,'" + MoreMemRevUrl + Math.random() + "')")
}
function ShowCommentsRatingrr(responseText, divcommentid, linkpostid, commentcntid, hidskipid, rate, cmts) {
    divComments = document.getElementById(divcommentid);
    if (responseText != "no records") {
        responseText = responseText.replace('&lt;br/&gt;', '\r\n');
        Rate_Comment = rate
        $(divComments).find('#hidCmmtCnt').remove();

        divComments.innerHTML = responseText;
        $(divComments).parent().slideDown();
        var revCmtTotCnt = $('#' + commentcntid).val();
        if (cmts == 'show') {
            $('#' + linkpostid).hide();
        }
        else {

            if (submitclick && parseInt(revCmtTotCnt) > 3) {
                $('#' + linkpostid).html("View " + (parseInt(revCmtTotCnt) - 3) + " more comment").show();
                $('#' + linkpostid).parent().show();
                submitclick = false;
                $('#' + hidskipid).val(13);

            }
            else {
                if (($('#' + hidskipid).val() - 10) < parseInt(revCmtTotCnt)) {
                    $('#' + linkpostid).show();
                    var remCount = parseInt(revCmtTotCnt) - ($('#' + hidskipid).val() - 10);
                    if (remCount > 1) {
                        $('#' + linkpostid).html("View " + remCount + " more comments").show();
                        $('#' + divcommentid).parent().find('.text-center').show();
                    }
                    else if (remCount == 1) {
                        $('#' + linkpostid).html("View " + remCount + " more comment").show();
                        $('#' + divcommentid).parent().find('.text-center').show();
                    }
                    else {
                        $('#' + linkpostid).hide();
                    }
                }
                else {
                    $('#' + linkpostid).hide();
                }
            }

        }

        if (FocusOnComments == true) {
            window.location.hash = "#comments"
        }
        divComments.style.display = "block";

    }
    else {
        if (responseText == 'no records' && $(divComments).parent().is(':visible'))
            $(divComments).parent().slideUp();
        else
            $(divComments).parent().slideDown();
        divComments.style.display = "none";
        $('#' + linkpostid).hide();
    }
}
function ShowCorpCommentsrr(responseText, divcorpid, corp_txtCommentid, corp_errCommentid, corp_btnSubmitid, corp_btnEditid) {

    if (responseText != "no records") {
        responseText = responseText.replace('&lt;br/&gt;', '\r\n');
        buttonclicked = FindButtonClickedrr(corp_btnEditid)
        if (buttonclicked == "edit") {
            var edittop = $(editabletr).offset().top;
        }

        $('#' + divcorpid).html(responseText);

        if (buttonclicked == "edit") {
            $('html,body').animate({
                scrollTop: parseInt(edittop) - 180
            }, 'slow');
            $("#" + corp_errCommentid).text('Comment updated successfully.').css('color', '#3c763d').show();
        }
        else {
            $("#" + corp_errCommentid).html("");
        }
        $('#' + corp_txtCommentid).val("");

        $("#" + corp_btnSubmitid).show();
        $("#" + corp_btnEditid).hide();
        DisableButtonrr(false, corp_btnSubmitid, corp_btnEditid);
    }
    else {
        $('#' + divcorpid).hide();
    }
}
function ShowMoreCommentsrr(responseText, divid, linkpostid, commentcntid, hidskipid, hidskipval) {
    var revCmtTotCnt = $('#' + commentcntid).val();
    divComments = document.getElementById(divid);
    if (responseText != "no records") {

        var incCount = parseInt(hidskipval)
        if (revCmtTotCnt > incCount) {

            var remCount = parseInt(revCmtTotCnt) - parseInt(hidskipval);
            if (remCount > 1) {
                $('#' + linkpostid).html("View " + remCount + " more comments");
            }
            else {
                $('#' + linkpostid).html("View " + remCount + " more comment");
            }

        } else {
            $('#' + linkpostid).hide();
        }
        incCount = parseInt(hidskipval) + 10
        $('#' + hidskipid).val(incCount);

        divComments.innerHTML = responseText;
        revCmtTotCnt.value = document.getElementById("hidCmmtCnt").value;

        if (FocusOnComments == true)
        { window.location.hash = "#comments" }
        if (FocusOnAddComments == true) {
            if (document.getElementById("hidAddCommentId").value != "") {
                ViewmoreFocus();
            }
        }
        divComments.style.display = "block";
    }
}
function EditCommentrr(btnedit, CommId, ObjName, editanchor, tr) {
    var comment = $(btnedit).parent().siblings(0).html();// document.getElementById(ObjName).innerHTML;
    editabletr = $(btnedit).closest('.corp-response');
    selEdit = editanchor;
    comment = comment.replace('...', '').replace('READ MORE', '').replace('Read More', '');
    comment = comment.replace(/<(?!br\s*\/?)[^>]+>/g, '');
    comment = comment.replace("(<(/)*p>)", "<br/>");
    comment = comment.replace("(\n)", "<br/>");
    comment = comment.replace("((\s)*<(/)*br(/)*>(\s)*){2,}", "<br/><br/>");
    comment = comment.replace("(<(/)*br(/)*>)", "\n");
    comment = comment.replace(/<br>/g, "\n")
    comment = comment.replace(/<BR>/g, "\n")
    comment = comment.replace(/&nbsp;/g, " ")
    comment = comment.replace(/&amp;/g, "&")
    comment = comment.replace(/&lt;/g, "<")
    comment = comment.replace(/&gt;/g, ">")
    comment = comment.replace(/<a target.*?>/g, "")
    comment = comment.replace(/<\/a>/g, "")
    comment = comment.replace(/<(|\n)*?>/g, "")
    comment = comment.trim();
    hidCommentId.value = CommId
    $(btnedit).closest('.divcomment').siblings(0).find('.comment-box').val(comment);
    $(btnedit).closest('.divcomment').siblings(0).find('.pull-right').children('.addcomment').hide();
    $(btnedit).closest('.divcomment').siblings(0).find('.pull-right').children('.updatecomment').show();
    $('html,body').animate({
        scrollTop: $(btnedit).closest('.divcomment').siblings(0).find('.comment-box').offset().top - 180
    },
    'slow');
    $(btnedit).closest('.divcomment').siblings(0).find('.comment-box').focus();

}
function EditCorpCommentrr(btnedit, CommId, ObjName, editanchor, tr) {
    var comment = $(btnedit).parent().siblings(0).html();// document.getElementById(ObjName).innerHTML;
    editabletr = $(btnedit).closest('.corp-response');
    selEdit = editanchor;
    comment = comment.replace('...', '').replace('READ MORE', '').replace('Read More', '');
    comment = comment.replace(/<(?!br\s*\/?)[^>]+>/g, '');
    comment = comment.replace("(<(/)*p>)", "<br/>");
    comment = comment.replace("(\n)", "<br/>");
    comment = comment.replace("((\s)*<(/)*br(/)*>(\s)*){2,}", "<br/><br/>");
    comment = comment.replace("(<(/)*br(/)*>)", "\n");
    comment = comment.replace(/<br>/g, "\n")
    comment = comment.replace(/<BR>/g, "\n")
    comment = comment.replace(/&nbsp;/g, " ")
    comment = comment.replace(/&amp;/g, "&")
    comment = comment.replace(/&lt;/g, "<")
    comment = comment.replace(/&gt;/g, ">")
    comment = comment.replace(/<a target.*?>/g, "")
    comment = comment.replace(/<\/a>/g, "")
    comment = comment.replace(/<(|\n)*?>/g, "")
    $(btnedit).closest('.divcorpcomment').siblings(1).find('textarea').val(comment)
    hidCorpCommentId.value = CommId
    $(btnedit).closest('.divcorpcomment').siblings(1).find('.pull-right').children('.addcorpcomment').hide();
    $(btnedit).closest('.divcorpcomment').siblings(1).find('.pull-right').children('.updatecorpcomment').show();
    $('html,body').animate({
        scrollTop: $(btnedit).closest('.divcorpcomment').siblings(1).find('textarea').offset().top - 180
    },
   'slow');
    $(btnedit).closest('.divcorpcomment').siblings(1).find('textarea').focus();

}
function AjaxPostcorprr(funcname, parameters, divcommentid, txtcommentid, errdivid, btnaddid, btnupdateid) {
    var clsAjax = new CreateRequest()
    clsAjax.ajaxObject.onreadystatechange = function () {
        if (clsAjax.ajaxObject.readyState == 4) {
            funcname(clsAjax.ajaxObject.responseText, divcommentid, txtcommentid, errdivid, btnaddid, btnupdateid);
            if (parameters.includes("AddCorpComment=1")) {
                $('#' + divcommentid).parent().siblings(1).find('.pull-right').find('.pull-right > span > span').html(parseInt($('#' + divcommentid).parent().siblings(1).find('.pull-right').find('.pull-right > span > span').html()) + 1);
                $("#" + errdivid).text('Comment added successfully.').css('color', '#3c763d').show();
            }

        }
    }
    clsAjax.ajaxObject.open("POST", "/review/reviewajax.php", true)
    clsAjax.ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
    clsAjax.ajaxObject.setRequestHeader("Content-length", parameters.length)
    clsAjax.ajaxObject.setRequestHeader("Connection", "close")
    clsAjax.ajaxObject.send(parameters)
}
function corp_AddCommentrr(login_id, divcommentid, txtcommentid, errdivid, btnaddid, btnupdateid, corpPostId, reviewid) {
    if (ValidateCorpCommentrr($('#' + txtcommentid).val(), errdivid) == true) {
        if (login_id != 0) {
            DisableButtonrr(true, btnaddid, btnupdateid);
            AjaxPostcorprr(ShowCorpCommentsrr, 'AddCorpComment=1&PostId=' + corpPostId + '&Rid=' + reviewid + '&Comment=' + UrlEncode($('#' + txtcommentid).val()) + "&loadhead=1&rar=1",
                divcommentid, txtcommentid, errdivid, btnaddid, btnupdateid)
        }
        else {
            ajaxLogin("/review/ReviewAjax.php?AddCorpComment=1&PostId=" + corpPostId + "&Rid=" + reviewid + "&Comment=" + UrlEncode($('#' + txtcommentid).val()) + "&redirectToRAR=1&cat_name=" + CatName + "&loadhead=1&what=1")
            createCookie('fbLoginRedirection1', "/review/ReviewAjax.php?AddCorpComment=1&PostId=" + corpPostId + "&Rid=" + reviewid + "&Comment=" + UrlEncode($('#' + txtcommentid).val()) + "&redirectToRAR=1&cat_name=" + CatName + "&loadhead=1&what=1", 30)
        }
    }
}
function corp_AddComment_other(login_id, divcommentid, txtcommentid, errdivid, btnaddid, btnupdateid, corpPostId, reviewid) {
    if (ValidateCorpCommentrr($('#' + txtcommentid).val(), errdivid) == true) {
        if (login_id != 0) {
            DisableButtonrr(true, btnaddid, btnupdateid);
            AjaxPostcorprr(ShowCorpCommentsrr, 'AddCorpComment=1&PostId=' + corpPostId + '&Rid=' + reviewid + '&Comment=' + UrlEncode($('#' + txtcommentid).val()) + "&loadhead=1&rar=1",
                divcommentid, txtcommentid, errdivid, btnaddid, btnupdateid)



        }
        else {
            ajaxLogin("/review/ReviewAjax.php?AddCorpComment=1&PostId=" + corpPostId + "&Rid=" + reviewid + "&Comment=" + UrlEncode($('#' + txtcommentid).val()) + "&redirectToRAR_other=1&cat_name=" + CatName + "&loadhead=1&what=1")
        }
    }
}
function corp_UpdateCommentrr(divcommentid, txtcommentid, errdivid, btnaddid, btnupdateid, corpPostId, reviewid) {
    if (ValidateCorpCommentrr($('#' + txtcommentid).val(), errdivid) == true) {
        DisableButtonrr(true, btnaddid, btnupdateid);
        var CommId = hidCorpCommentId.value;
        AjaxPostcorprr(ShowCorpCommentsrr, 'UpdateCorpComment=1&CommentId=' + CommId + '&PostId=' + corpPostId + '&Rid=' + reviewid + '&Comment=' + UrlEncode($('#' + txtcommentid).val()) + "&loadhead=1&rar=1",
                divcommentid, txtcommentid, errdivid, btnaddid, btnupdateid)
    }
}
function AddOnlyCommentrr(responseText, divid, errid, txtcommentid, btnaddid, btnupdateid, commentcntid, linkpostid, hidskipid, hidskipval) {
    ChkLoginrr(responseText, "", "")
    if (responseText != "login") {
        if (responseText.substring(0, 11).toLowerCase() == "bad word(s)") {
            $("#" + errid).html("<span class='icon-tool-tip'></span> &nbsp; " + responseText + ".").css('color', 'red').show();
        }
        else {

            var startpos, endpos, totalcomments, buttonclicked
            buttonclicked = FindButtonClickedrr(btnupdateid)
            if (buttonclicked == "edit") {
                var Comm_Id = hidCommentId.value
                var edittrtop = $(editabletr).offset().top;
                $("#" + errid).text('Comment updated successfully.').css('color', '#3c763d').show();
                ShowCommentsRatingrr(responseText, divid, linkpostid, commentcntid, hidskipid, false);
                var revCmtTotCnt = $('#' + commentcntid).val();

                $('html,body').animate({
                    scrollTop: parseInt(edittrtop) - 180
                }, 'slow');
                hidCommentId.value = ""
            } else {
                Add_Comment = true
                $("#" + errid).text('Comment posted successfully.').css('color', '#3c763d').show();
                $('#' + commentcntid).val(parseInt($('#' + commentcntid).val()) + 1);
                $('#' + txtcommentid).closest('.comment.hide').siblings('.count-section').find('.comment-clk').find('span:nth-child(2)').text('Comments ' + $('#' + commentcntid).val() + '')
                ShowCommentsRatingrr(responseText, divid, linkpostid, commentcntid, hidskipid, false);
            }
            $('#' + txtcommentid).val("");
            $('#' + btnaddid).show();
            $('#' + btnupdateid).hide();
        }
    }
    DisableButtonrr(false, btnaddid, btnupdateid)
}
function RateNU_Commentrr(responseText, divid, errid, txtcommentid, btnaddid, btnupdateid, aid, commentcntid, divlike) {
    ChkLoginrr(responseText, "", "")
    if (responseText != "login") {
        if (responseText.substring(0, 11).toLowerCase() == "bad word(s)") {
            $("#" + errid).html("<span class='icon-tool-tip'></span> &nbsp; " + responseText + ".").css('color', 'red').show();
        } else {
            if (responseText == "reload comment") {
                window.location.href = "/comment/readcomment.php?rid=" + Rid
            } else if (responseText == "reload") {
                window.location.reload()
            } else {
                Add_Comment = true
                var strarr = responseText.split('||');
                $('#' + commentcntid).val(parseInt($('#' + commentcntid).val()) + 1);
                $('#' + divid).html(strarr[0]);
                if (!$('#' + divid).is(":visible"))
                    $('#' + divid).slideToggle();
                $('#' + divlike).html('<a>&nbsp;' + strarr[1] + '</a>' + strarr[2])
                $("#" + errid).html("");
                $('#' + txtcommentid).val("");
                hidCommentId.value = ""
                $('#' + aid).html("<img src='/Images/like-icon.svg' class='like-image-new'/><span class='nu-color'>Not Useful</span>");
                $('#' + txtcommentid).closest('.comment.hide').siblings('.count-section').find('.comment-clk').find('span:nth-child(2)').text('Comments ' + $('#' + commentcntid).val() + '')
                Rate_Comment = false;
            }
        }
    }
    DisableButtonrr(false, btnaddid, btnupdateid)
}
function ValidateCorpCommentrr(Comment, errid) {
    let dvCustomer = $('#' + errid).closest('.response').find('[id$=customer]');
    if (dvCustomer.css('display') == 'block') {
        $('#' + errid).html('<span class="icon-tool-tip"></span> &nbsp;Please click "YES" or "NO" to justify your comments!');
        $('#' + errid).css('display', "block");
        $('.corp-box').siblings('.comment').slideDown();
        return false;
    }

    if (Comment.trim() == "") {
        $("#" + errid).html("<span class='icon-tool-tip'></span> &nbsp; This information is required.").css('color', 'red').show();
        return false
    }
    else if (canPostComntonResponse1 == 'False') {
        $("#" + errid).html("<span class='icon-tool-tip'></span> &nbsp; Access Not Granted.").css('color', 'red').show();
        return false
    }
    else if (CountWordsrr(Comment) < 3) {
        if (Comment.length < 2000) {
            $("#" + errid).html("<span class='icon-tool-tip'></span> &nbsp; Minimum 3 words and Maximum 2000 characters.").css('color', 'red').show();
            return false
        }
        if (Comment.length >= 2000) {
            $("#" + errid).html("").hide();
            return true
        }
    }
    else
        return true
}
function ValidateCommentrr(Comment, errid, rev_id) {
    if (Comment.trim() == "") {
        $("#" + errid).html("<span class='icon-tool-tip'></span> &nbsp; This information is required.").css('color', 'red').show();
        return false
    }
    else if (canPostComntOnReview == 'False') {
        $("#" + errid).html("<span class='icon-tool-tip'></span> &nbsp; Access Not Granted.").css('color', 'red').show();
        return false
    }
    else if (CountWordsrr(Comment) < 3) {
        if (Comment.length <= 2000) {
            $("#" + errid).html("<span class='icon-tool-tip'></span> &nbsp; Minimum 3 words and Maximum 2000 characters.").css('color', 'red').show();
            return false
        }
        if (Comment.length > 2000) {
            $("#" + errid).html("").hide();
            return true
        }
    }
    else if (!checkCommentCount(rev_id)) {
        window.parent.$('#commentpopimg').attr("src", "../Images/comment_popup_desktop.png");
        window.parent.$('#commentpopimg').attr("width","400px")
        window.parent.$('.to-top').css("display", "none");
        window.parent.$('.imgPastePrevent1,#commentpopimg').css("display", "block");
        window.parent.$('.black-layer').css("visibility", "visible");
        window.parent.$('.black-layer').css("display", "block");
        window.parent.$('#mainBody').css("overflow-y", "hidden");
        return false;
    }
    else
        return true
}
function checkCommentCount(review_id) {
    var status = false;
    var mergprod;
    mergprod = CatId;

    $.ajax({
        url: "/review/CorporateResponse.ashx",
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        async: false,
        data: { type: 'commentcount', corp: false, cat_id: mergprod, login_id: loginid, reviewid: review_id, corp_name: corporateName, corp_product: iscorp },
        responseType: "text/html",
        success: function (data) { if (data == 'success') status = true; }

    });
    return status;
}
function checkRatingCount(review_id) {
    var status = false;
    var mergprod;
    mergprod = CatId;

    $.ajax({
        url: "/review/CorporateResponse.ashx",
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        async: false,
        data: { type: 'ratecount', corp: false, cat_id: mergprod, login_id: loginid, reviewid: review_id, corp_name: corporateName, corp_product: iscorp },
        responseType: "text/html",
        success: function (data) { if (data == 'success') status = true; }

    });
    return status;
}
function FindButtonClickedrr(btneditid) {
    var buttonclicked
    if ($('#' + btneditid).is(":visible") == false) {
        buttonclicked = "add"
    }
    else {
        buttonclicked = "edit"
    }
    return buttonclicked
}
function CountWordsrr(val) {
    var removenbsp = /&nbsp;/gi; val = val.replace(removenbsp, "")
    var fullStr = val.trim();
    var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
    var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
    var non_alphanumerics_rExp = rExp = "" //  /[^A-Za-z0-9]+/gi; 
    var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
    var splitString = cleanedStr.split(" ");
    var word_count = 0;
    if (splitString.length - 1 <= 5000) {
        var splitString = cleanedStr.split("\n");
        var splitString_new
        var i = 0;

        if (splitString.length >= 1) {
            for (i = 0; i < splitString.length; i++) {
                splitString_new = splitString[i].split(" ");
                for (var j = 0; j < splitString_new.length; j++) {
                    if (splitString_new[j].trim() != "")
                        word_count = word_count + 1;
                }
            }
        }
        else {
            for (var j = 0; j < splitString.length; j++) {
                if (splitString[j].trim() != "")
                    word_count = word_count + 1;
            }
        }
    }
    else {
        for (var j = 0; j < splitString.length; j++) {
            if (splitString[j].trim() != "")
                word_count = word_count + 1;
        }
    }

    if (fullStr.length < 2) { word_count = 0; }
    return word_count;
}



function Ratingrr(Button, reviewid, lhead, catname, aid, sessionid, errorid, acorp, rand, skipid, mergeparent, parent, divcommentid, lnkpostcommid, hidcmtcnt, hidskipid, txtcommentid) {
    if (Button == "btnAjxVU") {

        if (!checkRatingCount(reviewid)) {
            window.parent.$('#ratepopimg').attr("src", "../Images/rate_popup_web.png");
            window.parent.$('#ratepopimg').attr("width", "400px");
            window.parent.$('.to-top').css("display", "none");
            window.parent.$('.imgPastePrevent2,#ratepopimg').css("display", "block");
            window.parent.$('.black-layer').css("visibility", "visible");
            window.parent.$('.black-layer').css("display", "block");
            window.parent.$('#mainBody').css("overflow-y", "hidden");
            return false;
        }
        else {
            Ajaxresrr(VUrr, "rid=" + reviewid + "&rating=4" + "&catname=&loadhead=" + lhead + '&arateid=' + aid, aid, reviewid, errorid, acorp)
        }
    }
    else if (Button == "btnAjxU") {
        if (!checkRatingCount(reviewid)) {
            window.parent.$('#ratepopimg').attr("src", "../Images/rate_popup_web.png");
            window.parent.$('#ratepopimg').attr("width", "400px");
            window.parent.$('.to-top').css("display", "none");
            window.parent.$('.imgPastePrevent2,#ratepopimg').css("display", "block");
            window.parent.$('.black-layer').css("visibility", "visible");
            window.parent.$('.black-layer').css("display", "block");
            window.parent.$('#mainBody').css("overflow-y", "hidden");
            return false;
        }
        else {
            Ajaxresrr(Urr, "rid=" + reviewid + "&rating=2" + "&catname=&loadhead=" + lhead + '&arateid=' + aid, aid, reviewid, errorid, acorp)
        }
    }
    else if (Button == "btnAjxNU") {
        if (!checkRatingCount(reviewid)) {
            window.parent.$('#ratepopimg').attr("src", "../Images/rate_popup_web.png");
            window.parent.$('#ratepopimg').attr("width", "400px");
            window.parent.$('.to-top').css("display", "none");
            window.parent.$('.imgPastePrevent2,#ratepopimg').css("display", "block");
            window.parent.$('.black-layer').css("visibility", "visible");
            window.parent.$('.black-layer').css("display", "block");
            window.parent.$('#mainBody').css("overflow-y", "hidden");
            return false;
        }
        else {
            AjaxresAllrr(NUrr, "rid=" + reviewid + "&rating=-4" + "&catname=&loadhead=" + lhead + '&arateid=' +
               aid, aid, reviewid, rand, skipid, mergeparent, parent, divcommentid, lnkpostcommid, hidcmtcnt, hidskipid, txtcommentid, errorid, acorp)
        }
    }
}
function Ajaxresrr(funcname, querystring, arateid, divlikeid, reviewid, acorp, txtcommentid, errorid) {
    $('#' + arateid).parent().siblings("img").show();
    $('#' + arateid).parent().hide();
    $('#' + arateid).parent().siblings('.like-count').hide();

    var clsAjax = new CreateRequest()
    clsAjax.ajaxObject.onreadystatechange = function () {
        if (clsAjax.ajaxObject.readyState == 4) {

            funcname(clsAjax.ajaxObject.responseText, arateid, divlikeid, reviewid, acorp, txtcommentid, errorid)
        }
    }
    clsAjax.ajaxObject.open("GET", "/review/reviewratingrestaurant.aspx?" + querystring, true)
    clsAjax.ajaxObject.send(null)
}
function VUrr(responseText, arateid, rid, errorid, acorp) {

    ChkLoginrr(responseText, "");

    if (responseText != '' && responseText != 'login') {
        $("#" + errorid).html('').hide();
        var arr = responseText.split('|')
        if (responseText.toLowerCase() == "corporate cannot rate reviews.") {
            $('#' + acorp).show();
            $('#' + acorp).html(arr[0]);
            $('#' + arateid).parent().hide();
        }
        else {
            $('#' + acorp).hide();
            $('#' + arateid).html(arr[0]);
            $('#' + arateid).parent().show();
        }
        $('#' + arateid).parent().siblings(0).html(arr[1]);
        $('#' + arateid).parent().siblings(0).attr("onclick", "ratingMore_Ajax123('" + rid + "');");
    }
    Rate_Comment = false;
    $('#' + arateid).parent().siblings("img").hide();

    if (responseText.toString().toLowerCase().indexOf('cannot rate') == -1) {
        $('#' + arateid).parent().siblings('.like-count').show();
        $('#' + arateid).parent().show();
    }
}
function Urr(responseText, arateid, rid, errorid, acorp) {
    ChkLoginrr(responseText, "");
    $("#" + errorid).html('').hide();
    if (responseText != '' && responseText != 'login') {
        var arr = responseText.split('|')
        if (responseText.toLowerCase() == "corporate cannot rate reviews.") {
            $('#' + acorp).show();
            $('#' + acorp).html(arr[0]);
            $('#' + arateid).parent().hide();
        }
        else {
            $('#' + acorp).hide();
            $('#' + arateid).html(arr[0]);
            $('#' + arateid).parent().show();
        }
        $('#' + arateid).parent().siblings(0).html(arr[1]);
        $('#' + arateid).parent().siblings(0).attr("onclick", "ratingMore_Ajax123('" + rid + "');");
    }
    Rate_Comment = false;
    $('#' + arateid).parent().siblings("img").hide();
    if (responseText.toString().toLowerCase().indexOf('cannot rate') == -1) {
        $('#' + arateid).parent().siblings('.like-count').show();
        $('#' + arateid).parent().show();
    }
}
function NUrr(responseText, arateid, reviewid, rand, skipid, mergeparent, parent, divcommentid, lnkpostcommid, hidcmtcnt, hidskipid, txtcommentid, errorid, acorp) {
    ChkLoginrr(responseText, "");
    if (responseText != "login") {
        if (responseText == "write comment") {
            $("#" + errorid).html("<span class='icon-tool-tip'></span> &nbsp; Please fill in a comment to justify your rating for this review.").css('color', 'red').show();
            Rate_Comment = true
            FocusOnComments = true
            AjaxByHashrr(ShowCommentsRatingrr, "ShowComments=" + reviewid + "&Random=" + rand + "&skip=" + skipid + "mergeparent=" + mergeparent + "&parent" + parent, divcommentid, lnkpostcommid, hidcmtcnt, hidskipid, true);
        }
        else {

            if (responseText != '' && responseText != 'login') {
                var arr = responseText.split('|')
                if (responseText.toLowerCase() == "corporate cannot rate reviews.") {
                    $('#' + acorp).show();
                    $('#' + acorp).html(arr[0]);
                    $('#' + arateid).parent().hide();
                    $('#' + arateid).parent().siblings('.like-count').hide();
                }
                else {
                    $('#' + acorp).hide();
                    $('#' + arateid).html(arr[0]);
                    $('#' + arateid).parent().show();
                }
                // $('#' + acorp).html(arr[0]);
                $('#' + arateid).parent().siblings(0).html(arr[1]);
                $('#' + arateid).parent().siblings(0).attr("onclick", "ratingMore_Ajax123('" + reviewid + "');");
                //$('#' + arateid).html(responseText);
            }
        }

    }
    $('#' + arateid).parent().siblings("img").hide();
    if (responseText.toString().toLowerCase().indexOf('cannot rate') == -1) {
        $('#' + arateid).parent().siblings('.like-count').show();
        $('#' + arateid).parent().show();
    }
}
function DisableButtonrr(Disable, addid, updateid) {
    if (Disable == true) {
        $('#' + addid).attr('disabled', 'disabled');
        $('#' + updateid).attr('disabled', 'disabled');
    }
    else {
        $('#' + addid).removeAttr('disabled');
        $('#' + updateid).removeAttr('disabled');
    }
}
function UrlEncode(str) {
    str = str.replace(/\+/g, "%2b")
    str = encodeURIComponent(str)
    return str
}
$(".AjxLayrClose").click(function (evt) {
    $("#popuplayer1").hide();
    if (urlredirectTo != undefined && urlredirectTo.indexOf('ratereview') != -1) {
        urlredirectTo = urlredirectTo.replace('-ratereview', '').replace('&ratereview=1', '');
    }
});
function htmlEncode(value) {
    return $('<div/>').text(value).html();
}
function ratingMore_Ajax123(e) {
    $("#dvpopupbox .dvpopupbox").load("/review/rating-list_ajax.aspx?rid=" + e);
    openModal("#dvpopupbox");
}
function showMore(a, event) {
    event.preventDefault();
    $(a).hide();
    $(a).siblings('.moreellipses').hide();
    $(a).siblings('.morecontent').show();
    $(a).closest('.more').siblings('.share').removeClass("hide");
}
function setheight() {
    try {

        var maxHeight = 0;
        var heights = $("#variants .row.list > .col-3").map(function () {
            return $(this).height();
        }).get(),

        maxHeight = Math.max.apply(null, heights);
        maxHeight = maxHeight
        if (maxHeight > 0) {
            $("#variants .row.list > .col-3 .gridl").css({
                'height': maxHeight - 15 + 'px'

            });
        }

    }
    catch (e) { }
}

function addcomments(ReviewId, divid, linkpostid, commentcntid, hidskipid, hidskipidval, errid, txtcommentid, btnaddid, btnupdateid, aid, divlike) {

    if (ValidateCommentrr($('#' + txtcommentid).val(), errid, ReviewId) == true) {
        DisableButtonrr(true, btnaddid, btnupdateid)
        if (Rate_Comment == false) {
            AjaxPostrr(AddOnlyCommentrr, 'Rid=' + ReviewId + '&AddComment=' + UrlEncode($('#' + txtcommentid).val()) + "&loadhead=1&rar=1", divid, errid, txtcommentid, btnaddid, btnupdateid, commentcntid, linkpostid, hidskipid, $('#' + divid).next().val())
        } else {
            AjaxPostrr(RateNU_Commentrr, 'Rid=' + ReviewId + '&RateComment=' + UrlEncode($('#' + txtcommentid).val()) + "&catname=" + CatName + "&loadhead=1&rar=1&arateid=" + aid, divid, errid, txtcommentid, btnaddid, btnupdateid, aid, commentcntid, divlike)
        }
    }
}
function showcomments(id, reviewid, random, skip, mergeparent, parent, divcommenid, postcommentid, cmntcntid, skipid, strshowhide) {

    if ($('#' + divcommenid).html() == '') {
        AjaxByHashrr(ShowCommentsRatingrr, "ShowComments=" + reviewid + "&Random=" + random + "&skip=" + skip + "&mergeparent=" + mergeparent + "&rar=1&parent=" + parent,
           divcommenid, postcommentid, cmntcntid, skipid, false, strshowhide);
        if ($(id).closest('.count-section').siblings('.response').is(':visible'))
            $(id).closest('.count-section').siblings('.response').slideUp();
        //$(id).closest('.count-section').siblings('.response').css('height', '49px');
    }
    else {
        if ($(id).closest('.count-section').siblings('.response').is(':visible') && !$(id).closest('.count-section').siblings('.comment').is(':visible'))
            $(id).closest('.count-section').siblings('.response').slideUp();
        $('#' + divcommenid).parent().slideToggle();
    }


}
function updatecomments(ReviewId, divid, linkpostid, commentcntid, hidskipid, hidskipidval, errid, txtcommentid, btnaddid, btnupdateid) {

    if (ValidateCommentrr($('#' + txtcommentid).val(), errid, ReviewId) == true) {
        DisableButtonrr(true, btnaddid, btnupdateid)
        var CommId = hidCommentId.value
        AjaxPostrr(AddOnlyCommentrr, 'Rid=' + ReviewId + '&EditCommentId=' + CommId + '&Comment=' + UrlEncode($('#' + txtcommentid).val()) + '&rar=1&count=' + $('#' + hidskipid).val(), divid, errid, txtcommentid, btnaddid, btnupdateid, commentcntid, linkpostid, hidskipid, $('#' + divid).next().val())
    }
}



function showSection(e) {
    $("#dvAll,#dvVU,#dvU,#dvNU").hide();
    $("#liAll,#liVU,#liU,#liNU").removeClass('active');
    switch (e) {
        case 'all':
            $("#dvAll").show();
            $("#liAll").addClass("active");
            break;
        case 'vu':
            $("#dvVU").show();
            $("#liVU").addClass("active");
            break;
        case 'u':
            $("#dvU").show();
            $("#liU").addClass("active");
            break;
        case 'nu':
            $("#dvNU").show();
            $("#liNU").addClass("active");
            break;
        default:
            $("#dvAll").show();
            $("#liAll").addClass("active");
            break;
    }
}
function setCookie(cname, cvalue) {
    if (checklogin()) {

        var d = new Date();
        d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        var path = "path=/";
        document.cookie = cname + "=" + cvalue + "; " + expires + "; " + path;
        return true;

    }
    else return false;
}
function setCookiesrch(cname, cvalue) {
        var d = new Date();
        d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        var path = "path=/";
        document.cookie = cname + "=" + cvalue + "; " + expires + "; " + path;

}
function setCookieCorp(cname, cvalue) {
    if (checkloginCorp()) {
        var d = new Date();
        d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        var path = "path=/";
        document.cookie = cname + "=" + cvalue + "; " + expires + "; " + path;
        return true;

    }
    else return false;

}



function hideBlackLayer() {
    $('.black-layer').hide();
}
function setFocusToHeaderSrch() {
    document.getElementById("txtproduct").focus();

}

$(document).ready(function () {
    var src = $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_customheader_btnwritereview').attr("onclick")
    $("#btnWritereview_scroll").attr("onclick", src);
    $("#imgWriteReview").attr("onclick", src);
    $(".your-rating-star").attr("onclick", src);

    var d = new Date();
    d.setTime(d.getTime());
    var expires = "expires=" + d.toUTCString();
    document.cookie = "brandReply=0" + "; " + expires;

    var showChar = 300;  // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Read More...";
    var lesstext = "Show less";
    ajaxTooltip();
    $('.like-image-new').each(function () {

        var reviewid = $(this).parent().attr("reviewid");
        var userid = $(this).parent().attr("userid");
        var aid = $(this).parent().attr('id');
        var divlikeid = $(this).parent().attr("divlikeid")
        var divcorpid = $(this).parent().attr("divcorpid")
        var is_rate = $(this).parent().attr("is_rate")
        var href_arr = $(this).parent().attr("href_arr")
        
        
        if ( is_rate != -6 || iscorp != "" || ((iscorp == corporateName && iscorp != "")))
        {

            $.ajax({
                url: "/review/CorporateResponse.ashx",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                data: { type: 'like', OverallGraph: reviewid, u: userid, Random: Math.random(), arateid: aid, corp: false, Session: strSession, corpname: corporateName, catid: cid, catname: prod, sessionname: strUsrName, divcorprespid: divcorpid },
                responseType: "text/html",
                success: function (data) { ShowGraph1(data, aid, divlikeid, reviewid) }

            });
        }
        else
        {

            //var data_str = "<img src='/Images/like-icon.svg' class='like-image-new'/><span>Like</span>|<a style='margin-left: 3px;'>0</a>|<a id='areply' onclick=~CheckIfCookie('"+ href_arr +"')~ style='cursor:pointer'><span class='icon-reply' style='font-size: 17px; color: rgba(36,44,66,.5);'></span><span id='resplink'>Reply as Brand</span></a>"
            ajaxTooltip();
           
            document.getElementById(aid).innerHTML = "<img src='/Images/like-icon.svg' class='like-image-new'/><span>Like</span>";
            document.getElementById(divlikeid).innerHTML = "<a style='margin-left: 3px;'>0</a>";
            if (userId != "0")
            {
                $('#' + aid.replace("arate", "dvResponse")).html('');
            }
            else
            {
                var data_str = "<a id='areply' onclick=~CheckIfCookie('" + href_arr + "')~ style='cursor:pointer'><span class='icon-reply' style='font-size: 17px; color: rgba(36,44,66,.5);'></span><span id='resplink'>Reply as Brand</span></a>"
                $('#' + aid.replace("arate", "dvResponse")).html(data_str.replace('~', '"').replace('~', '"'));
            }
            
            $('#' + divlikeid).attr("onclick", "ratingMore_Ajax123('" + reviewid + "');");
        }
               
    });


    if (editreview == 1) {
        $('.advice-section').hide();
        $('#starsep').hide();
        $('.rar-section-divider').hide();
    }
});

function CheckIfCookie(href_1)
{
    if(setCookieCorp('brandReply','1')) {window.location.href=href_1}
}

function ShowGraph1(responseText, arateid, divlikeid, reviewid) {
    
    if (responseText != '') {
        ajaxTooltip();
        var arr = responseText.split('|')

        document.getElementById(arateid).innerHTML = arr[0];
        document.getElementById(divlikeid).innerHTML = arr[1];
        $('#' + arateid.replace("arate", "dvResponse")).html(arr[2]);
        $('#' + divlikeid).attr("onclick", "ratingMore_Ajax123('" + reviewid + "');");
    }
}

function getCorpResponse(acorp) {
    //debugger;
    var reviewid = $(acorp).attr("reviewid");
    var userid = $(acorp).attr("userid");
    var aid = $(acorp).attr('id');
    var divcorpid = $(acorp).attr("divcorpid");
   
    $.ajax({
        url: "/review/CorporateResponse.ashx",
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        data: { type: 'corpresp', review_id: reviewid, Random: Math.random(), corp: false, Session: strSession, corpname: corporateName, catid: cid, catname: prod, sessionname: strUsrName },
        responseType: "text/html",
        success: function (data) {
            
            $('#' + divcorpid).html(data);
            
            let onFullComm = $('#lnkFullComm').attr('onclick');
            if (onFullComm) {
                eval(onFullComm);
            }
          
            $('.row .gallery-thumbnails').lightGallery({
                selector: '.g-imgbox'
            });
        }

    });
    if ($(acorp).find('span:eq(1)').text() == 'Brand Response') {
        $(acorp).closest('.count-section').siblings('.response').slideToggle();
    }
    Rebindcorp();

}
function bindreviewcontent(review_id, id, is_video, fb_message, cat_id, prod_Img, twitter_msg, twitter_lnk, cat_name, ratingstr, review_key) {

    $.ajax({
        url: "/review/CorporateResponse.ashx",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "text",
        async: false,
        data: { type: 'review', reviewid: review_id, corp: false, isvideo: is_video, fbmessage: fb_message, catid: cat_id, prodimg: prod_Img, twittermsg: twitter_msg, twitterlnk: twitter_lnk, catname: cat_name, rating_str: ratingstr, usession: parseInt(usessions) },
        responseType: "text/html",
        success: function (data) {
            $(id).closest('.reviewdata').html(data);
            ajaxTooltip1(review_key);
        },
        error: function (data, status, jqXHR) { window.location.href = "/error.php" }
    });

}

function bindShareAll(review_id, id, is_video, fb_message, cat_id, prod_Img, twitter_msg, twitter_lnk, cat_name, ratingstr, review_key, brandname) {


    if ($(id).children(".sharedivdata").html().trim() == "") {
        $.ajax({
            url: "/review/CorporateResponse.ashx",
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            dataType: "text",
            async: false,
            data: { type: 'share_rar', reviewid: review_id, corp: false, isvideo: is_video, fbmessage: fb_message, catid: cat_id, prodimg: prod_Img, twittermsg: twitter_msg, twitterlnk: twitter_lnk, catname: cat_name, rating_str: ratingstr, usession: parseInt(usessions), brandname: brandname },
            responseType: "text/html",
            success: function (data) {
                $(id).children(".sharedivdata").html(data)
                $(id).children(".sharedivdata").show()
            },
            error: function (data, status, jqXHR) { window.location.href = "/error.php" }
        });
    }
    else {
        $(id).children(".sharedivdata").show()
    }



}

$(document).mouseup(function (e) {
    var container = $(".sharedivdata");
    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.hide();
    }
});



function bindblogcontent(blog_id, id, canonical_URL, tweet_Title, user_name) {

    $.ajax({
        url: "/review/CorporateResponse.ashx",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "text",
        data: { type: 'blog', blogid: blog_id, corp: false, canonicalURL: canonical_URL, tweetTitle: tweet_Title, username: user_name },
        responseType: "text/html",
        success: function (data) { $(id).closest('.reviewdata').html(data); },
        error: function (data, status, jqXHR) { window.location.href = "/error.php" }
    });

}

function createurlforpaging() {
    var e;
    var t = $("#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_ddlSorting");
    var n = sortorder;
    if (n == "") n = "d";
    else n = n.charAt(0);
    if (t.value == 0) {
        e = pgurl + "-sort-msdate" + "-order-" + n
    }
    if (t.value == 1) {
        e = pgurl + "-sort-rating" + "-order-" + n
    }
    if (t.value == 2) {
        e = pgurl + "-sort-avgrating" + "-order-" + n
    }
    if (t.value == 3) {
        e = pgurl + "-sort-trustedcircle" + "-order-" + n
    }
    if (t.value == 4)
    { e = pgurl + "-sort-read" + "-order-" + n } return e
}



function dissCounter(id) {
    var totalchar = id.value.replace(/\s+/g, " ").length;
    var p = id.parentNode;
    if (totalchar < 5 || totalchar > 500) {
        p.parentElement.children[3].style.color = '#FD3A02';
        if (totalchar < 5) {
            p.parentElement.children[3].innerHTML = (500 - totalchar);
        } else {
            p.parentElement.children[3].innerHTML = '-' + (totalchar - 500);
        }

        p.parentElement.children[2].setAttribute('disabled', '');

    }
    if (totalchar >= 5 && totalchar < 500 || totalchar == 0) {
        p.parentElement.children[3].style.color = '#76A44E';
        p.parentElement.children[3].innerHTML = (500 - totalchar);
        p.parentElement.children[2].removeAttribute('disabled');

    }
}

function askQuestion(id, pagVal) {
    document.getElementById('askquestion').disabled = true;
    var txtVal = $('#txtQueArea').val();
    var cid = CatId;
    if (txtVal.replace(/\s+/g, " ").replace(/(<([^>]+)>)/ig, "") == '') {
        $("#errCommentrr").html("<span class='icon-tool-tip'></span> &nbsp; This information is required.").show();
        return false;
    }
    $.get('/product/product_discussion_ajax.aspx?cid=' + cid + '&valid=1&ques=' + UrlEncode1(txtVal).replace(/\s+/g, " ").replace("#", "hhash") + '&ask=1&timestamp=' + new Date().getTime(), function (data) {
        if (data.indexOf("Bad word(s)") > -1) {
            document.getElementById('errCommentrr').style.display = "block"
            document.getElementById('errCommentrr').innerHTML = "<span>" + data + "</span>"
            document.getElementById('askquestion').disabled = false;
            return false;

        }

        if (data.indexOf("success") > -1) {
            $(id).parent().siblings('#emptytext').hide();
            document.getElementById('errCommentrr').style.display = "none";
            document.getElementById('errCommentrr').innerHTML = "";
            var queId = data.substring(data.indexOf("|") + 1);
            $('#txtQueArea').val("");
            document.getElementById('askquestion').disabled = false;
            var html = '';
            if ($(id).parent().parent().children('ul').length > 0) {
                html = '';
            }
            else {
                html = html + '';
            }
            html = html + '<div class="answer"><div class="row table"><div class="qnauserpic" > <a href="/' + strUsrName + '"><div class="profile-img"><img src="' + strUsrIcon + '" /></div></a></div>';
            html = html + '<div class="ans-content"><div class="row qatitle" onclick="javascript:userAnswerNew(event,this);"><p>' + txtVal + '</p>'
            html = html + '<p class="notify">few seconds ago</p>';
            html = html + '<p class="notify">By: <a id="hypUser" href="/' + strUsrName + '/timeline">' + strUsrName + '</a></p>';
            html = html + '<p class="notify numbers"><span class="icon-comment"></span>Answers: <span id="spn' + queId + '">0</span></p></div>';
            html = html + '<div class="answer-field" style="overflow: hidden; display: none;">' +
                                '<p class="warning hide" id="errCommentans"></p><span><textarea placeholder="Write your answer..." onkeyup="dissCounter(this);"></textarea></span>' +
                                '<button class="btn btn-secondary" onclick="javascript:answerQuestion(this,' + queId + ');return false;">Submit</button><span class="pull-right text-right">500</span></div></div>';
            html = html + '<div class="text-right"><a class="btn btn-link btn-light"  onclick="javascript:answerQuesNew(event,this);">Answer</a></div></div></div>'

            $('#quesdata').after(html);
            $(id).siblings('.pull-right').html("500");
            $(".answer .btn-link").click(function (event) {
                $(this).parent().parent().siblings(".answer-field").slideToggle(500);
                event.stopPropagation();
            });

            $('.h2val1').html('500');

        }
    });
}
function answerQuestion(id, quesId) {
    document.getElementById('answer').disabled = true;
    var txtVal = $(id).parent().children(2).children('textarea').val();
    var cid = CatId;
    var p = id.parentNode;

    if (txtVal.replace(/\s+/g, " ").replace(/(<([^>]+)>)/ig, "") == '') {
        $(id).parent().children('p').html("<span class='icon-tool-tip'></span> &nbsp; This information is required.").show();
        document.getElementById('answer').disabled = false;
        return false;
    }
    else { $(id).parent().children('p').html(""); }
    $.get('/product/product_discussion_ajax.aspx?cid=' + cid + '&valid=1&anstxt=' + UrlEncode1(txtVal).replace(/\s+/g, " ").replace("#", "hhash") + '&quesId=' + quesId + '&ans=1&timestamp=' + new Date().getTime(), function (data) {

        if (data != "") {
            if (data.indexOf("Bad word(s)") > -1) {
                document.getElementById('diverror_discussion').style.display = "block"
                document.getElementById('diverror_discussion').innerHTML = "<span>" + data + "</span>"
                document.getElementById('answer').disabled = false;
                return false;

            }
            document.getElementById('diverror_discussion').style.display = "none";
            document.getElementById('diverror_discussion').innerHTML = "";
            $(id).parent().children(2).children('textarea').val("");
            document.getElementById('answer').disabled = false;
            var html = '';
            var arr = data.split('|');
            html = html + '<div class="user-answer">';
            html = html + '<div>';
            html = html + '<p class="br-none lh20">' + arr[0] + '</p>'
            html = html + '<p class="notify">few seconds ago</p>'
            html = html + '<p class="notify">'
            html = html + 'By: <a id="hypUsrAns" href="/' + strUsrName + '/timeline">' + strUsrName + '</a> ';
            html = html + '</p>';
            html = html + '</div>';
            html = html + '</div>';
            if ($(id).parent().siblings('.user-answers').html() != null) {
                html = html + $(id).parent().siblings('.user-answers').html();
                $(id).parent().siblings('.user-answers').html(html);
                $(id).siblings('.pull-right').html("500");
            }
            else {
                $(id).parent().parent().append('<div class="row user-answers display" id="dvanswer">' + html + '</div>');
                $(id).siblings('.pull-right').html("500");
            }

            var spnVal = parseInt($('#spn' + quesId).html());
            $('#spn' + quesId).html(spnVal + 1);
            $('.h2val').html('500');
            $(id).parent().siblings(".user-answers").slideDown({
                easing: "easeInQuad"
            });
        }
    });
}


function showMorePagesrr(e, t, n, r) {

    var s = $("#spnPaging");
    var o = "";
    var strMore = "";
    var o = "<li>  <a class='btn btn-link' href= '" + pgurl.replace('-page-', '') + "'>" + 1 + "</a></li>" + "<li><span style='cursor:pointer' onClick=\"return showLessPagesrr(" + e + ", " + t + ", '" + n + "', " + r + ');"><b>...</b></span></li> ';
    if (intMorePage + 9 < e) {
        loopPages = 9; tabThisPage = 10;
        strMore = "<li> <span style='cursor:pointer' onClick=\"return showMorePagesrr(" + e + ", " + t + ", '" + n + "', " + r + ');"><b>...</b></span></li>'
        strMore = strMore + "<li>  <a class='btn btn-link' href= '" + pgurl + "" + e + "'>" + e + "</a></li>";
    }
    else {
        loopPages = e - intMorePage; tabThisPage = loopPages
    }
    for (i = intMorePage; i <= loopPages + intMorePage; i++) {
        if (i == t)
            o = o + " <li> <a class='btn btn-link active'>" + i + "</a> </li>";
        else
            o = o + " <li> <a class='btn btn-link' href='" + pgurl + "" + i + "'>" + i + "</a></li>";
    }
    intMorePage = intMorePage + tabThisPage;
    intLessPage = intLessPage + 10;
    s.html(o + strMore);
}
function showLessPagesrr(e, t, n, r) {
    var s = $("#spnPaging");
    var o = "";
    var u = "";


    if (intLessPage > 11) {
        u = "<li>  <a class='btn btn-link' href= '" + pgurl.replace('-page-', '') + "'>" + 1 + "</a></li>" + "<li><span style='cursor:pointer' onClick=\"return showLessPagesrr(" + e + ", " + t + ", '" + n + "', " + r + ");\"><b>...</b></span></li>";

    }
    for (i = intLessPage - 1; i >= intLessPage - 10; i--) {
        if (i == t) o = "<li> <a class='btn btn-link active'>" + i + "</a></li> " + o;
        else o = "<li> <a class='btn btn-link' href='" + pgurl + "" + i + "'>" + i + "</a></li> " + o;
    }

    strMore = "<li><span style='cursor:pointer' onClick=\"return showMorePagesrr(" + e + ", " + t + ", '" + n + "', " + r + ");\"><b>...</b></span></li>";

    s.html(u + o + strMore + "<li><a class='btn btn-link' href='" + pgurl + "" + e + "'><b>" + e + "</b></a></li>");
    intLessPage = intLessPage - 10;
    if (intMorePage > 11)
        intMorePage = intMorePage - tabThisPage; tabThisPage = 10

}

var intMorePage = 11; var intLessPage = 1; var tabThisPage = 10

function UrlEncode1(str) {

    if (encodeURIComponent) str = encodeURIComponent(str);
    else if (encodeURI) str = encodeURI(str);
    else str = encodeURI(str);
    str = str.replace(/\+/g, '%2B'); // Force the replacement of "+"
    return str;

}
try {

    if (sel >= 11) {
        var mod = sel % 10;
        if (mod == 0) {
            var intMorePage = sel - mod + 1;
            var intLessPage = sel - mod - 9;
        }
        else {
            var intMorePage = sel - mod + 11;
            var intLessPage = sel - mod + 1;
        }
        var tabThisPage = 10;
    }
    else {
        var intMorePage = 11;
        var intLessPage = 1;
        var tabThisPage = 10;
    }
}
catch (e) { }

function chkCommentToClose(rid) {
    var clsAjax2 = new CreateRequest();
    clsAjax2.ajaxObject.onreadystatechange = function ajaxResponse() {
        if (clsAjax2.ajaxObject.readyState == 4) {
            emailflag = clsAjax2.ajaxObject.responseText;

            if (emailflag == "success") {
                document.location.href = document.getElementById(custnolink).value;
            }
            else {

                document.getElementById("customer").style.display = 'none';


                document.getElementById('corp_errComment_' + rid).innerHTML = "<span>Please fill in a comment for this response</span>";
                document.getElementById('corp_errComment_' + rid).style.display = "block";
                $('.corp-box').siblings('.comment').slideDown();
                $('#lnkFullComm').hide();
            }
        }
    }
    clsAjax2.ajaxObject.open('GET', '/withoutlogin.aspx?postid=' + $('#hdnResponseID').val() + '&resp=no', true);
    clsAjax2.ajaxObject.send(null);
}




$(function () {

$(document).ready(function () {

    currLatLong = 0;
    var latlongCookie = getCookie("currLatLong");
    if (latlongCookie == "" || latlongCookie == "0") {
        getLocationsrch();
    } else {
        currLatLong = latlongCookie;
    }

});
function getLocationsrch() {
    if (navigator.geolocation) {
        try {
            navigator.geolocation.getCurrentPosition(foundLocationsrch, locationIp, { timeout: 10000 });
        } catch (e) {
            locationIp();
        }
    }
    else {
        locationIp();
    }
}
function foundLocationsrch(position) {
    geo_loc = processGeolocationResult(position);
    currLatLong = geo_loc.split(",");
    setCookiesrch("currLatLong", currLatLong);
}
function locationIp() {
    currLatLong = 0;
    try {
        $.get("https://ipapi.co/json", function (response) {
            if (response != null && response != '') {

                try {
                    html5Lat = response.latitude;
                    html5Lon = response.longitude;
                    currLatLong = (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
                    currLatLong = currLatLong.split(",");
                    setCookiesrch("currLatLong", currLatLong);
                } catch (e) {
                    setCookiesrch("currLatLong", currLatLong);
                }
            }
        }, "json");
    } catch (e) {
        currLatLong = 0;
    }
}
function processGeolocationResult(position) {

    html5Lat = position.coords.latitude;
    html5Lon = position.coords.longitude;

    return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
 
    $("#txtRarTabSearch").autocomplete({
        source: function (request, response) {

            var tempTxt = 0;
            var txt = request.term;
            txt = stripHTML(txt);
            request.term = txt;
            if (txt.replace(/[^\w\s]/gi, '') == "") {
                tempTxt = 1;
            }

            var key;
            srctype = srctype1;
            key = srchcat;
            txtId = "txtRarTabSearch";
            if (txt == "Search Product, Reviews and Ratings") { txt = "" };
            var parameters = "{contextKey:'" + key + "|0||',count:10,prefixText:'" + txt + "',type:'" + srctype1 + "'}"

            if (txt.trim().length >= 2 && tempTxt == 0) {

                if (prevparameters == parameters) dupreq = true;
                prevparameters = parameters;
                if (dupreq == true && prevmsgd != undefined) {
                    var msgd = prevmsgd;
                    msgdlength = msgd.length;
                    response($.map(msgd, function (item) {
                        if (item != null) {
                            var ele = item.split("|")
                            var lblstr;

                            if (ele[1] == 0) {
                                return {
                                    label: '<b style="padding-left: 7px;">' + ele[0].replace("repme", stripHTML($('#txtRarTabSearch').val())) + '</b>' + '  ',
                                    value: ele[1],
                                    catid: ele[1],
                                    parent2: ele[6]
                                }
                            }
                            else if (ele[1] == 111111) {
                                return {
                                    label: '<span ><span style="color: #6d6d6d;">' + ele[0] + '</span>',
                                    value: 111111,
                                    catid: ele[1],
                                    parent2: ele[6],
                                    url: ele[9]
                                }
                            }
                            else {
                                lblstr = '<span ><span style="color: #6d6d6d;">' + ele[0] + '</span>' + ele[10] + ele[3];
                                if (ele[2] > 0) {
                                    lblstr = lblstr + ' <span  style="font-size:11px;color:#44a512;">(' + ele[2] + ' Variants)</span>';
                                }
                                lblstr = lblstr + '</span>';
                                lblstr = lblstr + '<div class="clear"></div>'
                                lblstr = lblstr + ' <span style="font-size:11px;color:#44a512;">' + ele[5] + '</span>';

                                return {
                                    label: lblstr,
                                    value: ele[0] + '-' + ele[1],
                                    catid: ele[1],
                                    parent2: ele[6],
                                    level1: ele[7],
                                    ptype: ele[8],
                                    valueUrl: ele[9],
                                    isCorp: ele[10]
                                }
                            }
                        }
                    }));
                    dupreq = false;
                }
                else {
                    if (xhr1 && xhr1.readyState != 4) {
                        xhr1.abort();
                    }
                    xhr1 = $.ajax({
                        type: "GET",
                        url: "/web/search.asmx/GetAutoCompleteProductSearch",
                        data: { contextKey: "'" + key + "|0||'", strProductSrh: "'" + txt.replace("'", "\\'") + "'", currLatLong: "'" + currLatLong + "'", isPreWrite: '0' },
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) {

                            if ($("#txtRarTabSearch").val() == txt) {
                                prevmsg = msg;
                                var msgd;
                                var lblstr;
                                if (msg.d) {
                                    msgd = msg.d;
                                }
                                else {
                                    msgd = msg
                                }
                                msgdlength = msgd.length;
                                prevmsgd = msgd;

                                response($.map(msgd, function (item) {
                                    if (item != null) {
                                        var ele = item.split("|")
                                        if (ele[1] == 0) {
                                            if (msgd.length == 1) {
                                                insertSearch(document.getElementById("txtRarTabSearch").value, "No Action", btoa(window.location.href), '');

                                            }
                                            return {
                                                label: '<b style="padding-left: 7px;">' + ele[0].replace("repme", stripHTML($('#txtRarTabSearch').val())) + '</b>' + '  ',
                                                value: ele[1],
                                                catid: ele[1],
                                                parent2: ele[6]
                                            }
                                        }
                                        else if (ele[1] == 111111) {
                                            return {
                                                label: '<span ><span style="color: #6d6d6d;">' + ele[0] + '</span>',
                                                value: 111111,
                                                catid: ele[1],
                                                parent2: ele[6],
                                                url: ele[9]
                                            }
                                        }
                                        else {
                                            lblstr = '<span><span style="color: #6d6d6d;">' + ele[0] + '</span>' + ele[10] + ele[3];
                                            if (ele[2] > 0) {
                                                lblstr = lblstr + ' <span  style="font-size:11px;color:#44a512;">(' + ele[2] + ' Variants)</span>';
                                            }
                                            lblstr = lblstr + '</span>';
                                            lblstr = lblstr + '<div class="clear"></div>'
                                            lblstr = lblstr + ' <span style="font-size:11px;color:#44a512;">' + ele[5] + '</span>';

                                            return {
                                                label: lblstr,
                                                value: ele[0] + '-' + ele[1],
                                                catid: ele[1],
                                                parent2: ele[6],
                                                level1: ele[7],
                                                ptype: ele[8],
                                                valueUrl: ele[9],
                                                isCorp: ele[10]
                                            }
                                        }
                                    }
                                }
                                ));
                                srctype = srctype1;
                            }
                        },
                        error: function (e) {

                        }
                    });
                }
            }
            else {
                //FOR FIXED SEARCH
                if (prevparameters == parameters) dupreq = true;
                prevparameters = parameters;
                if (dupreq == true && prevmsgd != undefined) {
                    //for 2nd time
                    var msgd;
                    var lblstr;
                    var ele;
                    var innEle;
                    var aa;
                    msgd = prevmsgd;
                    msgdlength = msgd.length;

                    response($.map(msgd, function (item) {
                        if (item != null) {
                            ele = item.split("|");

                            if (ele[1] == 0) {
                                //for header and link of pages
                                if (ele[2] != "" && ele[3] == "") {
                                    innEle = ele[2].split("~");

                                    if (innEle[1]) {
                                        lblstr = '<span ><span class="search-span-headAnchor" style="color: #6d6d6d;"><b>' + innEle[0] + '</b></span></span>';
                                        aa = innEle[1];
                                    }
                                    else {
                                        lblstr = '<span ><span class="search-span-head" style="color: #6d6d6d;"><b>' + innEle[0] + '</b></span></span>';
                                        aa = "";
                                    }

                                }
                                else {
                                    //for header and link of pages
                                    lblstr = '<span ><span style="color: #6d6d6d;">' + ele[2] + '</span></span>';
                                }

                                return {
                                    label: lblstr,
                                    value: "Redirecting",
                                    catid: ele[1],
                                    parent2: ele[6],
                                    innValueUrl: aa,
                                    valueUrl: ele[3]
                                }
                            }
                            else {
                                //for rar(product pages)
                                lblstr = '<span ><span style="color: #6d6d6d;">' + ele[0] + '</span>' + ele[12];
                                if (ele[4] > 0) {
                                    lblstr = lblstr + ' <span  style="font-size:11px;color:#44a512;padding-top: 3px;">(' + ele[4] + ' Variants)</span>';
                                }
                                lblstr = lblstr + '</span>';
                                lblstr = lblstr + '<div class="clear"></div>'
                                lblstr = lblstr + ' <span style="font-size:11px;color:#44a512;padding-top: 3px;">' + ele[7] + '</span>';

                                return {
                                    label: lblstr,
                                    value: ele[0] + '-' + ele[1],
                                    catid: ele[1],
                                    parent2: ele[6],
                                    level1: ele[8],
                                    ptype: ele[9],
                                    valueUrl: ele[11],
                                    isCorp: ele[12]
                                }
                            }


                        }
                    }
                    ));
                    $(".search-span-head").parent().parent().css({ "background": "rgba(204,204,204,0.3)", "cursor": "default" })
                    $(".search-span-headAnchor").parent().parent().css({ "background": "rgba(204,204,204,0.3)" });
                    dupreq = false;
                }
                else {
                    //for 1st time of new search
                    if (xhr1 && xhr1.readyState != 4) {
                        xhr1.abort();
                    }
                    xhr1 = $.ajax({
                        type: "GET",
                        url: "/web/search.asmx/GetAutoCompleteProductSearchFixed",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) {
                            prevmsg = msg;
                            var msgd;
                            var lblstr;
                            var ele;
                            var innEle;
                            var aa;
                            if (msg.d) {
                                msgd = msg.d;
                            }
                            else {
                                msgd = msg
                            }
                            msgdlength = msgd.length;
                            prevmsgd = msgd;
                            response($.map(msgd, function (item) {
                                if (item != null) {
                                    ele = item.split("|");

                                    if (ele[1] == 0) {
                                        if (ele[2] != "" && ele[3] == "") {
                                            innEle = ele[2].split("~");

                                            if (innEle[1]) {
                                                lblstr = '<span ><span class="search-span-headAnchor" style="color: #6d6d6d;"><b>' + innEle[0] + '</b></span></span>';
                                                aa = innEle[1];
                                            }
                                            else {
                                                lblstr = '<span ><span class="search-span-head" style="color: #6d6d6d;"><b>' + innEle[0] + '</b></span></span>';
                                                aa = "";
                                            }

                                        }
                                        else {
                                            //for header and link of pages
                                            lblstr = '<span ><span style="color: #6d6d6d;">' + ele[2] + '</span></span>';
                                        }

                                        return {
                                            label: lblstr,
                                            value: "Redirecting",
                                            catid: ele[1],
                                            parent2: ele[6],
                                            innValueUrl: aa,
                                            valueUrl: ele[3]
                                        }

                                    }
                                    else {
                                        //for rar(product pages)
                                        lblstr = '<span ><span style="color: #6d6d6d;">' + ele[0] + '</span>' + ele[12];
                                        if (ele[4] > 0) {
                                            lblstr = lblstr + ' <span style="font-size:11px;color:#44a512;padding-top: 3px;">(' + ele[4] + ' Variants)</span>';
                                        }
                                        lblstr = lblstr + '</span>';
                                        lblstr = lblstr + '<div class="clear"></div>'
                                        lblstr = lblstr + ' <span style="font-size:11px;color:#44a512;padding-top: 3px;">' + ele[7] + '</span>';

                                        return {
                                            label: lblstr,
                                            value: ele[0] + '-' + ele[1],
                                            catid: ele[1],
                                            parent2: ele[6],
                                            level1: ele[8],
                                            ptype: ele[9],
                                            valueUrl: ele[11],
                                            isCorp: ele[12]
                                        }
                                    }


                                }
                            }
                            ));
                            srctype = srctype1;
                            $(".search-span-head").parent().parent().css({ "background": "rgba(204,204,204,0.3)", "cursor": "default" })
                            $(".search-span-headAnchor").parent().parent().css({ "background": "rgba(204,204,204,0.3)" });
                        },
                        error: function (e) {
                        }
                    });
                }
            }
        },
        minLength: 0,
        selectFirst:true,
        select: function (event, ui) {
            if (ui.item.parent2 != "0" && ui.item.parent2 != undefined) {
                let chkcook = getCookie("srchparent2");
                if (chkcook == "" || chkcook == "0") {
                    chkcook = ui.item.parent2;
                } else {
                    chkcook = chkcook + "," + ui.item.parent2;
                }
                setCookiesrch("srchparent2", chkcook);
            }
            if (ui.item.catid != "0" && ui.item.catid != "11111111" && ui.item.catid != "111111" && ui.item.catid != "Redirecting" && ui.item.catid != undefined) {
                let chkcook = getCookie("srchcatid");
                if (chkcook == "" || chkcook == "0") {
                    chkcook = ui.item.catid;
                } else {
                    chkcook = chkcook + "," + ui.item.catid;
                }
                setCookiesrch("srchcatid", chkcook);
            }
            var SearchAction = '';
            var RedirectUrl = '';
            var $ui = $('#ui_element');
            $ui.find('.sb_dropdown')
               .hide();
            if (ui.item.value == 0) {
                var ddSP = document.getElementById('CategorySP');
                var dds = '';
                if (ddSP != null) {
                    dds = '&amp;p=' + ddSP.options[ddSP.selectedIndex].value;
                }
                RedirectUrl = mshost + 'search/prodsrch.aspx?data=' + encodeURIComponent(this.value.toLowerCase()).replace(/%20/g, '+') + decodeURIComponent("%26type=%26p=") + srchcat;
                if (msgdlength > 1)
                    window.location.href = RedirectUrl
                else
                    window.location = RedirectUrl

                insertSearch(document.getElementById("txtRarTabSearch").value, "Clicked on see more", btoa(window.location.href), btoa(RedirectUrl));

            }
            else if (ui.item.value == 111111) {
                window.location.href = ui.item.url;
            }
            else if (ui.item.value == "Redirecting") {
                var valUrl = ui.item.valueUrl;
                var innVarUrl = ui.item.innValueUrl;

                if (valUrl) {
                    window.location.href = valUrl;
                }
                else {

                    if (innVarUrl) {
                        window.location.href = innVarUrl;
                    }
                    else {
                        ui.item.value = "";
                    }
                }
            }
            else {

                var val = ui.item.value;
                var valUrl = ui.item.valueUrl;
                var l1 = ui.item.level1;
                var p2 = ui.item.parent2;
                var ptype = ui.item.ptype;
                //valUrl = valUrl + "-reviews" + val.substr(val.lastIndexOf('-'));
                //RedirectUrl = mshost + getmovielink(p2, l1, ptype) + valUrl + "-srch";
                RedirectUrl = valUrl;
                
                if (ui.item.catid == "11111111") {
                    insertSearch(document.getElementById("txtRarTabSearch").value, "Clicked on Category link", btoa(window.location.href), btoa(RedirectUrl));

                }else {
                    insertSearch(document.getElementById("txtRarTabSearch").value, "Clicked on product link", btoa(window.location.href), btoa(RedirectUrl));

                }
                window.location.href = RedirectUrl;
                document.getElementById("txtRarTabSearch").value = '';
            }

        }

    })
    
    $("#txtRarTabSearch").click(function () {
        $(this).autocomplete("search");

    });
    //$(window).scroll(function () {

    //    $(".searchDropDown").hide();
    //    //$(".ui-autocomplete").addClass("leftcss");
    //});
});
;
$(document).ready(function () {
    var flagtext = 0;
    $(".w-r-panel textarea").on("click focus", function (e) {
        if (flagtext == 0) {
            $(this).animate({ height: '200' });
            flagtext = flagtext + 1;
        }
        $(this).siblings('.review-help').addClass('review-help-add');
        $(this).siblings('.review-help').css('right', -($('.field-outline .review-help').width() + 46));
        $(this).parent().siblings('.expand-wr').slideDown();
        e.stopPropagation();
    });
    $('.check-wrap input[type="checkbox"]').click(function () {
        if ($(this).prop("checked") == true) {
            $(this).parent().addClass('checked');
        }
        else {
            $(this).parent().removeClass('checked');
        }
    })
    $('.prod-var .view-var').click(function (e) {
        e.preventDefault();
        $(this).siblings('ul').slideToggle();
        $(this).find('span').toggleClass("icon-drop-down icon-next");
    });
    $(function () {
        $('.open-all a').click(function () {
            $(this).parent().siblings('.more-brands-div').slideToggle();
        });
    });

    var textArea = document.getElementsByTagName("textarea")[0];
    var displayCount = document.getElementsByClassName("char-count")[0];
    if (textArea) {
        textArea.onkeyup = function () {
            var value = textArea.value;
            if (document.getElementById('hdfCatID').value == '925642336' || document.getElementById('hdfVerifiedReviews').value != "" || document.getElementById("hdfVerifiedDraft").value == 1) {
                if (value.length == 0) {
                    displayCount.innerHTML = "";
                }
                else {
                    if (value.length >= 50) {
                        displayCount.style.color = "green";
                    }
                    else {
                        displayCount.style.color = "red";
                    }
                    displayCount.innerHTML = value.length;
                }
            }
            else {
                if (value.length == 0) {
                    displayCount.innerHTML = "";
                }
                else {
                    if (value.length >= 100) {
                        displayCount.style.color = "green";
                    }
                    else {
                        displayCount.style.color = "red";
                    }
                    displayCount.innerHTML = value.length;
                }
            }
        }
    };

    $(function () {
        $('.pages li').click(function () {
            $(this).find("button").addClass("active");
            $(this).siblings().find("button").removeClass("active");
        });
    });
    $('.toggle div.obtitle').click(function () {
        $(this).siblings(".toggle-content").slideToggle();
        $(this).find('.icon-drop-down').toggleClass('icon-next', 'icon-drop-down');
    });
    $('button.quote').click(function () {
        $(this).parent().parent().hide().siblings('.thank-quote').show();
    });

    $('.edit-comment').click(function (e) {
        e.preventDefault();
        $(this).hide();
        var closest = $(this).parent().siblings(0).find(".brand-comment");
        $(this).parent().siblings(0).find(".brand-comment").hide(0, function () {
            var spanText = $(this).text().replace(/\.../g, '').replace('READ MORE', '').replace('Read More', '');
            var input = $('<textarea/>').attr('id', 'txtResponse');
            input.val(spanText);
            $(input).insertAfter(closest);
            $('.button-events').show();
        });
        $('.corp-response #btnCancel').click(function () {
            $('.brand-comment,.edit-comment').show();
            $('#txtResponse,.button-events').hide();
        });
    });

    $('.grid-view').click(function () {
        $('.categories .list .box').wrap("<div class='col-3'></div>").addClass('gridl');
        $('.categories .bygdbox,.categories .cat-pagination').wrap("<div class='col-12'></div>");
        $('.categories .list').css('margin', '0px -15px');
        $('.list-view').css('pointer-events', 'auto');
        $('.grid-view').css('pointer-events', 'none');
        $('.grid-view > span').removeClass('unrated-star');
        $('.list-view > span').addClass('unrated-star');
        $('.gridview').show();
        $('.gridview > div').show();
        $('.dvListingAds').hide();
        try {
            var heights = $(".row.list .col-3 div.rtitle").map(function () {
                return $(this).height();
            }).get(),
            maxHeight = Math.max.apply(null, heights);
            if (maxHeight > 0) {
                $(".row.list .col-3 .gridl div.rtitle").css({
                    'height': maxHeight + 'px'
                });
            }
        }
        catch (e) { }
        try {
            var maxHeight = 0;
            var heights = $(".row.list .col-3").map(function () {
                return $(this).height();
            }).get(),
            maxHeight = Math.max.apply(null, heights);
            if (maxHeight > 0) {
                $(".row.list .col-3 .gridl").css({
                    'height': maxHeight - 35 + 'px'
                });
            }
        }
        catch (e) { }
    });

    $('.list-view').click(function () {
        $(".row.list .col-3 .gridl").removeAttr("style");
        $(".row.list .col-3 .gridl .rtitle").removeAttr("style");
        $('.categories .list .box').unwrap().removeClass('gridl');
        $('.categories .bygdbox,.categories .cat-pagination').unwrap();
        $('.list-view').css('pointer-events', 'none');
        $('.grid-view').css('pointer-events', 'auto');
        $('.categories .list').css('margin', '0px');
        $('.grid-view > span').addClass('unrated-star');
        $('.list-view > span').removeClass('unrated-star');
        $('.gridview').hide();
        $('.dvListingAds').show();
    });

    $(function () {
        if ($('#tablist').length > 0) {
            $(window).on('scroll', function () {
                var tabpos = $('#tablist').position();
                var divTop = tabpos.top;
                var currentPos = divTop - $(window).scrollTop();
                if (currentPos < 0) {
                    $(".fixed-menu").slideDown();
                    $('.list-menu >li:first-child').addClass('active');
                    var scrollPos = $(document).scrollTop();
                    $('.fixed-menu .list-menu .scroll').each(function () {
                        var currLink = $(this);
                        var refElement = $(currLink.find('a').attr("href"));
                        if (refElement.is(':visible')) {
                            var refEle = refElement.position();
                            if (refEle.top - 60 < scrollPos + $("#fixed-menu").height() && refEle.top + refElement.height() >= scrollPos + $("#fixed-menu").height() - 60) {
                                $('.fixed-menu .list-menu .scroll').removeClass("active");
                                currLink.addClass("active");
                            }
                            else {
                                currLink.removeClass("active");
                            }
                        }
                    });
                }
                else {
                    $(".fixed-menu").slideUp();
                }
            });
        };
    });

    $(".scroll, .gallery-thumbnails .thumb-count, .full-spec").on("click", function () {
        $("body, html").animate({ scrollTop: $($(this).find("a").attr('href')).position().top - $("#fixed-menu").height() }, 'fast');
    });

    $(".to-top").click(function (e) {
        e.preventDefault();
        $("html,body ").animate({ scrollTop: 0 }, 600);
    });
    $('.tabable-accordion .table-head.open+.table-content').css('display', 'block');
    $('.tabable-accordion .table-head').click(function () {
        if ($(this).hasClass('open') == true) {
            $(this).siblings('.table-content').slideUp({
                duration: 300,
                easing: "easeInQuad",
                complete: function () {
                    $(this).siblings('.table-head').removeClass('open');
                }
            });
        }
        else {
            var scrollPos;
            $(this).siblings('.table-content').slideDown({
                duration: 300,
                easing: "easeInQuad",
                complete: function () {
                    $(this).siblings('.table-head').addClass('open');
                    $('.tabable-accordion .table-content').not(this).slideUp({
                        duration: 300,
                        easing: "easeInQuad",
                        complete: function () {
                            $(this).siblings('.table-head').removeClass('open');
                        }
                    });
                }
            });
        }
        scrollPos = $('#explore .tabable-accordion').offset().top - 50;
        $("html,body").animate({ scrollTop: scrollPos }, "slow");
    });
    var openFileOption = function () {
        document.getElementsByClassName("choosephoto")[0].click();
    };

    $(".get-file").on("click", function () {
        $(this).parent().find('.choosephoto').click();
    });

    $(".chosefile").on("click", function () {
        openFileOption();
    });

    $("#choosephoto").change(function () {
        readURL(this);
    });

    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            var fsize = input.files[0].size / 1024 / 1024;
            var fname = input.files[0].name;
            var x = fname.split(".").pop();
            console.log(x + " " + fsize + " MB");
            reader.onload = function (e) {
                $('.up-img').attr('src', e.target.result).show();
                $('.upload-section .icon-add').hide();
                $(".get-file").unbind("click");
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    $('.add-image .icon-close').click(function (event) {
        $('.upload-section .icon-add').show();
        $('.up-img').hide();
        event.stopPropagation();
        $(".get-file").bind('click', function (e) {
            openFileOption();
        });
    })

    $(".w-r-panel textarea").on("focusout", function (e) {
        e.preventDefault();
        $('.review-help').removeClass('review-help-add').css('right', '-300px');
    });

    $(".tolerence-div h4").on("click", function () {
        $(".tolerence-div > ul").slideToggle();
        $(this).find("span").toggleClass('icon-expand icon-collapse');
    });

    (function () {
        if ($('.product-details .more-guide').parent().find('.specification table').height() > 270) {
            $('.product-details .more-guide').parent().find('.specification .col-6:eq(0)').css('height', '270px');
            $('.product-details .more-guide').show();
            $('.product-details .more-guide').click(function (e) {
                e.preventDefault();
                $(this).hide().parent().find('.specification .col-6:eq(0)').css({ 'height': 'auto' }).height();
            });

        }
        else {
            $('.product-details .more-guide').hide();
        }
    })();

    askQuestionNew = function (event) {
        $('#quesdata').siblings('#emptytext').hide();

        event.preventDefault();
        $("#quesdata").slideToggle({
            easing: "easeInQuad"
        });
    };
    answerQuesNew = function (event, elem) {
        event.preventDefault();
        event.stopPropagation();
        $(elem).parent().siblings().find(".answer-field").slideToggle({
            easing: "easeInQuad"
        });
    };
    userAnswerNew = function (event, elem) {
        event.preventDefault();
        $(elem).siblings(".user-answers").slideToggle({
            easing: "easeInQuad"
        });
    };

    $('.tabs li a').click(function (e) {
        e.preventDefault();
        $(this).parent().addClass('active').siblings().removeClass('active');
    });

    $('.notify-me').click(function () {
        openModal('.email-alert-box');
    });
    $('#quote').click(function () {
        openModal('.get-quote');
    });

    $('.salesfrm').click(function () {
        openModal('.sales-frm');
    });

    $('.review .read-more').click(function (e) {
        e.preventDefault();
        $(this).toggle().parent().siblings('.expand-review').slideToggle();
    });

    $('.like-count').click(function (e) {
        e.preventDefault();
        openModal('.user-rating-show');
    });

    $('.comment-clk,div > .icon-not-useful-filled').click(function (e) {
        e.preventDefault();
    });

    $('.breply-clk').click(function (e) {
        e.preventDefault();
        $(this).parent().parent().siblings('.cresbox').toggleClass('corp-resbox').slideToggle();
    });
    setTimeout(function () {

        $('.fullcommunictn a').unbind('click').parent('.fullcommunictn').click(function (e) {

            e.preventDefault();
            $(this).hide().siblings('.comment').slideDown();
        });
    }, 2000);


    $('.cust-share').click(function () {
        if ($(this).find('.dropdown-tip').is(':visible') == false) {
            $(this).find('.dropdown-tip').css('display', 'block');
        }
        else {
            $(this).find('.dropdown-tip').css('display', 'none');
        }
    });

    $('.addfrbx span a').click(function (e) {
        e.preventDefault();
        $(this).parent().hide().siblings().addClass('show');
    });
    $(".comment textarea").on("click focus", function (e) {
        $(this).css('height', '100px'); $(this).off(); $(this).parent().siblings('.expand-comment').slideDown('fast');
    });
    rate(".expressrating", "rated-star", "unrated-star");
    $(".your-rating-star").on({
        mouseover: function () {
            $(this).children().removeClass("unrated-star").addClass("rated-star");
        },
        mouseleave: function () {
            $(this).children().removeClass("rated-star").addClass("unrated-star");
        }
    });
});
function Rebindcorp() {

    $('.icon-reply').parent('a').unbind('click').click(function (e) {
        if ($(this).find('span:eq(1)').text() == 'Brand Response') {
            e.preventDefault();
            $(this).closest('.count-section').siblings('.response').slideToggle();
        }
    });
    $(".comment textarea").on("click focus", function (e) {
        $(this).css('height', '100px'); $(this).off(); $(this).parent().siblings('.expand-comment').slideDown('fast');
    });
}

function openModal(element) {
    $('.black-layer').css('visibility', 'visible');
    $(element).addClass('modal');
    $(element).find('.icon-close').remove();
    $(element).append('<span class="icon-close"></span>');
    $('body').css({ 'overflow-y': 'hidden', 'width': '100%' });
    $('.black-layer, ' + element + '.modal .icon-close').click(function () {
        $('.black-layer').css('visibility', 'hidden');
        $('body').css('overflow-y', 'auto');
        $(element).hide().removeClass('modal');
    });
};

(function () {
    $('#lightgallery > div:lt(4)').show();
})();

var rate = function (element, ratedClass, unratedClass) {
    $(element).on({
        mouseover: function () {
            $(this).prevAll().andSelf().removeClass(unratedClass).addClass(ratedClass);
        },
        mouseleave: function () {
            $(this).prevAll().andSelf().removeClass(ratedClass).addClass(unratedClass);
            if (element != ".w-r-panel .express-ratings div") {
                $('.click-star-txt').text("YOUR RATING ON");
            }
        }
    });
};

function editContent(cname) {
    var edtCmd = $(cname).attr('class');
    if (edtCmd == "bold") {
        document.execCommand('bold');
    }
};
var showcommentafterlogin = false;
var chkERC = 0;
var chkMRC = 0;
var revAuthor = ''
var count = 0;
var arrSelectedVal = new Array();
var arrSelectedname = new Array();
var strSelectedValues = "";
var bool = "";
var pos;
var ratingbox = '';
var urlredirectTo;
var dvRating;
var count_chk_comp = 0;
var submitclick = false;
var cnt = 0;
var params = {};
var psortexp = 0;
var psortorder = 0;
var order = 0;
var resload = 0;
var skipCnt = 0
var c = 0;
var bool1 = 0;
var variant_cnt;
var Querystring = 0;
var src;
var opengalary
var str_count = 0;
var profileArray = [];

$(window).load(function () {
    setfocus();
});
$(document).ready(function () {

    try {
        dvRating = document.getElementById("dvRating");
        src = $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_customheader_btnwritereview').attr("onclick");
        opengalary = window.locatioctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_customheader_btnwritereviewn.hash;
    }
    catch (e) { }

    try {
        if (lt2 != "" && lt2 != "0") {
            //google.maps.event.addDomListener(window, 'load', initialize1);
            $('#locationmap').show();

        }
        else {
            $('#locationmap').hide();
        }
    }
    catch (e) { }

    $('#noreviewwrite').attr("onclick", src);

    if (googlebot == "0") {
        //setTimeout(function () {
        //    getnearbyprod();
        //}, 500);
        
        if (isExplore || parent2 == 169) {

            $('#specification').hide();
            $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_tabs1_tdSpec2').hide();
            $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_tabs1_tdSpec').hide();
        }
        else {
            var chkbindspecs = setInterval(function () {
                if (document.readyState == "complete") {
                    bindspecs();
                    clearInterval(chkbindspecs);
                }
            }, 200);
        }
        $.get(mshost + 'product/product_discussion_readall.aspx?cid=' + CatId + '&timestamp=' + new Date().getTime(), function (data) {
            $('#dvaskquestion').html(data);

        });
    }
    else {
        bindspecs();
    }

    $('.clsHidSkip').val('13');


    if (opengalary == '#photogallery') {
        if (corporateName == '' && strSession > 0) {
            document.getElementById("readallphotosection").style.display = "block";
            $('#modal-bck_photo').show();
        }
    }
    $('#modal-bck_photo,#closephoto').click(function () {
        document.getElementById("readallphotosection").style.display = "none";
        $('#modal-bck_photo').hide();
    });
    //if (document.getElementById('writereviewpanel').style.display == 'none' && opengalary != '#photogallery') {
    //    
    //    $('.black-layer').css('visibility', 'hidden');
    //    $('html,body').animate({
    //        scrollTop: 0
    //    }, 'fast');
    //}

    var urlPost = mshost + 'web/webservice3.asmx/InsertReadCount'
    var i = 0;
    setTimeout(function () {
        var cat_id;
        $.post(urlPost, { cat_id: CatId }, function (data) {
            if (data != '0') {
            }
        });
    }, 200);
});

function corp_text() {
    if (iscorp != '') {
        $.ajax({
            url: "/review/CorporateResponse.ashx",
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            dataType: "text",
            data: { catid: CatId, mergedprods: mergeprods, mergeparent: merge_parent, corp: true },
            responseType: "text/html",
            success: function (data) {
                $('#idcorpresp').html(data); $('#idcorpresp').show();
            },
            error: function (data, status, jqXHR) { }
        });
    }
}
function showmenus(cat_id) {
    $.ajax({
        url: "/review/CorporateResponse.ashx",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "text",
        data: { type: 'menus', catid: cat_id, corp: false, isbot: googlebot },
        responseType: "text/html",
        success: function (data) {
            $('#imgProd1').hide();
            if (data != '') {
                var arrimagedata = data.split('^');
                if (parent2 == 169) {
                    $('#divphotos1').html(arrimagedata[0]);
                    $('#divphotos1 > div').hide();
                    $('#divphotos1 > div:lt(4)').show();
                    $('#divphotos1').lightGallery();
                    $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_dvAdminImg1').show();
                    $('#lightgallery1').html(arrimagedata[1]);
                    $('#lightgallery1 > div').hide();
                    $('#lightgallery1 > div:lt(4)').show();
                    $("#photo-sec-div").show();
                    $('#lightgallery1').lightGallery();
                }
                else {
                    $('#photogallery1').hide();
                }
                $('#dvgallery').show();
            }
            else {
                $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_dvAdminImg1').hide();
                $('#divphotos1').hide();
                $('#emptytext1').show();
            }
        },
        error: function (data, status, jqXHR) { }
    });
}
function showtop10(cat_id) {
    $.ajax({
        url: "/review/CorporateResponse.ashx",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "text",
        data: { type: 'Top10', catid: cat_id, corp: false },
        responseType: "text/html",
        success: function (data) {
            if (data != '') {
                var arrimagedata = data.split('^');
                $('#divtop10').html(arrimagedata[0]);
                $('#divtop10 > div:lt(4)').show();
                $('#dv_rec_articles').show();
            }
            else {
                $('#divtop10').hide();
            }
        },
        error: function (data, status, jqXHR) { }
    });
}

function showDashboardimages(cat_id) {
    $.ajax({
        url: "/review/CorporateResponse.ashx",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "text",
        data: { type: 'dashboardimages', catid: cat_id, corp: false },
        responseType: "text/html",
        success: function (data) {
            $('#imgProd2').hide();
            if (data != '') {
                var arrimagedata = data.split('^');
                if (parent2 == 169 || parent2 == 170 || parent2 == 925642274 || parent2 == 925602729 || parent2 == 925235 || parent2 == 925236 || parent2 == 925039310 || parent2 == 145 || iscorp != '') {
                    $('#divphotos').html(arrimagedata[0]);
                    $('#divphotos > div').hide();
                    $('#divphotos > div:lt(4)').show();
                    $('#divphotos').lightGallery();

                   // $('#lightgallery2').html(arrimagedata[1]);
                   //$('#lightgallery2 > div').hide();
                   // $('#lightgallery2 > div:lt(5)').show();
                   // $("#photo-sec-div").show();
                   // $('#lightgallery2').lightGallery();
                   // $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_dvAdminImg').show();
                   // if ($('#lightgallery2 > div:lt(5)').length > 4) {
                   //     $('#lightgallery').hide();
                   //     $("#photo-sec-div").hide();
                   // }

                    $('#lightgallery').html(arrimagedata[1]);
                    $('#lightgallery > div').hide();
                    $('#lightgallery > div:lt(4)').show();
                    $("#photo-sec-div").show();
                    $('#lightgallery').lightGallery();
                    $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_dvAdminImg').show();
                    //if ($('#lightgallery2 > div:lt(5)').length > 4) {
                    //    $('#lightgallery').hide();
                    //    $("#photo-sec-div").hide();
                    //}
                    
                }
                else {
                    $('#divphotos').html(arrimagedata[0]);
                    $('#divphotos > div').hide();
                    $('#divphotos > div:lt(4)').show();
                    $('#divphotos').lightGallery();
                }
                try {
                    if (data.indexOf('play-button.png') > -1) {
                        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_h2catname').text($('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_h2catname').text() + ' & Videos')

                        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_ProdName').text('Photos & Videos for ' + prod.replace("#", "-"))
                    }
                }
                catch (E) {
                }
                $('#dvgallery').show();
            }
            else {
                $('#divphotos').hide();
                $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_dvAdminImg').hide();
                $('#emptytext').show();
            }
        },
        error: function (data, status, jqXHR) { }
    });
}
function showimages(cat_id) {


    $.ajax({
        url: "/review/CorporateResponse.ashx",
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        dataType: "text",
        data: { type: 'images', catid: cat_id, corp: false },
        responseType: "text/html",
        success: function (data) {
            $('#imgProd').hide();
            
            if (data != '') {
                var arrimagedata = data.split('^');
                if (parent2 == 169 || parent2 == 925642274 || parent2 == 925602729 || parent2 == 925235 || parent2 == 925236 || parent2 == 925039310 || parent2 == 145 || iscorp != '') {
                    $('#divphotos').html(arrimagedata[0]);
                    $('#divphotos > div').hide();
                    $('#divphotos > div:lt(4)').show();
                    $('#divphotos').lightGallery();

                    $('#lightgallery').html(arrimagedata[1]);
                    $('#lightgallery > div').hide();
                    $('#lightgallery > div:lt(4)').show();
                    $("#photo-sec-div").show();
                    $('#lightgallery').lightGallery();
                }
                else {
                    $('#divphotos').html(arrimagedata[0]);
                    $('#divphotos > div').hide();
                    $('#divphotos > div:lt(4)').show();
                    $('#divphotos').lightGallery();
                }
                try {
                    if (data.indexOf('play-button.png') > -1) {
                        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_h2catname').text($('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_h2catname').text() + ' & Videos')

                        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_ProdName').text('Photos & Videos for ' + prod.replace("#", "-"))
                    }
                }
                catch (E) {
                }
                $('#dvgallery').show();
            }
            else {
                $('#divphotos').hide();
                $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_dvAdminImg').hide();
                $('#emptytext').show();
            }
        },
        error: function (data, status, jqXHR) { }
    });
}

function FacebookPostModalrr(message, shareurl, type, catid, imagetype, review_key) {
    var FbMessage = '';
    var FbLink = '';
    reviewkey = review_key;
    if (type == "1") {
        FbMessage = decodeURI(message);
        FbLink = shareurl;
    }
    else {
        FbMessage = 'Join me on MouthShut.com and get a chance to win cash prizes daily';
        FbLink = 'https://www.mouthshut.com/contest';
    }
    FB.getLoginStatus(function (response) {
        if (response.status == "connected") {
            FB.ui({
                method: 'share',
                display: 'popup',
                quote: FbMessage + ' #MouthShut ',
                href: FbLink,
            }, function (response) {
                if (response && !response.error_code) {
                    fbshareTrack(FbLink)
                }
            });
        }
        else {
            FB.login(function (response) {
                if (response.status == "connected") {
                    FB.ui({
                        method: 'share',
                        display: 'popup',
                        quote: FbMessage + ' #MouthShut ',
                        href: FbLink,
                    }, function (response) {
                        if (response && !response.error_code) {
                            fbshareTrack(FbLink)
                        }
                    });
                }
            }, { scope: 'email' });
        }
    });
}

function FacebookPostModal(message, shareurl, type, catid, imagetype, review_key) {
    var FbMessage = '';
    var FbLink = '';
    reviewkey = review_key;
    if (type == "1") {
        FbMessage = message;
        FbLink = shareurl;
    }
    else {
        FbMessage = 'Join me on MouthShut.com and get a chance to win cash prizes daily';
        FbLink = 'https://www.mouthshut.com/contest';
    }
    FB.getLoginStatus(function (response) {
        if (response.status == "connected") {
            FB.ui({
                method: 'share',
                display: 'popup',
                quote: FbMessage + ' #MouthShut ',
                href: FbLink,
            }, function (response) {
                if (response && !response.error_code) {
                    fbshareTrack(FbLink)
                }
            });
        }
        else {
            FB.login(function (response) {
                if (response.status == "connected") {
                    FB.ui({
                        method: 'share',
                        display: 'popup',
                        quote: FbMessage + ' #MouthShut ',
                        href: FbLink,
                    }, function (response) {
                        if (response && !response.error_code) {
                            fbshareTrack(FbLink)
                        }
                    });
                }
            }, { scope: 'email' });
        }
    });
}

function getnearbyprod() {
    try {
        
        var clsAjax = new CreateRequest()
        var parameters = "level1=" + level1 + "&cat_id=" + CatId   + "&isadvice=" + isAdvice + "&parent2=" + parent2 + "&parent=" + parent_name + "&corp=" + iscorp;
        clsAjax.ajaxObject.onreadystatechange = function () {
            if (clsAjax.ajaxObject.readyState == 4) {
                var rt = clsAjax.ajaxObject.responseText;
                if (rt != "empty") {
                    document.getElementById('nearby').innerHTML = rt;

                }
                else {
                    document.getElementById('nearby').style.display = 'none';
                }
                setTimeout(function () {
                    var bLazy = new Blazy();
                }, 1000);
            }
        }
        clsAjax.ajaxObject.open("POST", "/review/RAR_RHS.aspx", true)
        clsAjax.ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
        clsAjax.ajaxObject.send(parameters)
    }
    catch (e) { }
}

function FacebookPostModalParm() {
    return params;
}
function TwitterShare(message, url, review_key) {
    reviewkey = review_key;
    Twitterurl = url;
    var urlshare = "https://twitter.com/share?url=" + url + "&related=mouthshut&text=" + message + "&via=MouthShut ";
    window.open(urlshare, 'welcome', 'width=500,height=400,top=200,left=400');
    if (strSession > 0) {
        $.get(mshost + 'tracking/hits.php?sharecnt=t&key=' + url + '&user=' + strSession, function (res) {
        });
    }
}
function bindvariants(data) {
    if (data != '') {
        if (isparent) {
            $('#variants').show();
            $('#variants').html(data);
            $('.variants-table > .table-content > div:lt(4)').show();
            $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_spec').hide();
            $('#dvdropvarients').hide();
        }
        else {
            $('#variants').show();
            $('#variants').html(data);
            $('.variants-table > .table-content > div:lt(4)').show();
        }
    }
    setheight();
}
function bindspec(data) {
    if (data == '') {
        $('#specification').hide();
        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_spec').hide();
        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_tabs1_tdSpec2').hide();
        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_tabs1_tdSpec').hide();
    }
    else {
        $('#specification .idspec').html(data);
        $('#specification').show();
        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_tabs1_tdSpec2').show();
        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_tabs1_tdSpec').show();
    }
}

function bindspecs() {

    if (parent2 != 169 && parent2 != 118) {
        if (CatId == merge_parent) {
            isparent = true;
            $.ajax({
                url: mshost + "Comparison/compareproducts.php?PType=spec&ov=1&mpar=1&id=" + parent2 + "|1|" + CatId + "&CatName=" + prod.replace("#", "-") + "&pname=" + encodeURIComponent(parentname) + "&rar=1",
                success: function (data) {
                    bindvariants(data);
                    CompareProductsDiv();
                    CompareProductsCheckBox();
                    CompareProductsReset();
                    $('#specification').hide();
                }
            });
        }
        else {            
            isparent = false;
            $.ajax({
                url: "/review/CorporateResponse.ashx",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                data: { type: 'spec', PType: 'spec', id: CatId, CatName: prod.replace("#", "-"), maincat: parent1, subcat: level1, isbbot: googlebot, corp: false },
                responseType: "text/html",
                success: function (data) {
                    bindspec(data);
                }
            });
            if (merge_parent != '0')
                $.ajax({
                    url: mshost + "Comparison/compareproducts.php?PType=spec&ov=1&mpar=1&id=" + parent2 + "|1|" + CatId + "&CatName=" + prod.replace("#", "-") + "&pname=" + encodeURIComponent(parentname) + "&rar=1",
                    success: function (data) {
                        bindvariants(data)
                        CompareProductsDiv();
                        CompareProductsCheckBox();
                        CompareProductsReset();
                    }
                });
        }
    }
    else
        $('#specification').hide();
}

function submit_review_verified() {
    alert(vdrmsg);
    return false;
}
function writereview_disabled() {
    alert(drmsg);
    return false;
}
function dopaging(ds) {
    var url;
    var isarchive = "";
    if (rev_type != '')
        isarchive = "ar-";
    if (ds.value == 0) //Review Date
    {
        url = mainurl + "-sort-" + isarchive + "msdate" + "-order-" + sortorder.charAt(0);
    }
    if (ds.value == 1) //Member's Rating
    {
        url = mainurl + "-sort-" + isarchive + "rating" + "-order-" + sortorder.charAt(0);
    }
    if (ds.value == 2) //Review Usefulness
    {
        url = mainurl + "-sort-" + isarchive + "avgrating" + "-order-" + sortorder.charAt(0);
    }
    if (ds.value == 3) //Trusted Circle
    {
        url = mainurl + "-sort-" + isarchive + "trustedcircle" + "-order-" + sortorder.charAt(0);
    }
    if (ds.value == 4) //Read Volumes
    {
        url = mainurl + "-sort-" + isarchive + "read" + "-order-" + sortorder.charAt(0);
    }
    if (ds.value == 5) //Read Recommend
    {
        url = mainurl + "-sort-" + isarchive + "recommeded" + "-order-" + sortorder.charAt(0);
    }
    window.location = url;
}

function showcommentsrr(divcommentid, Rid, linkpostid, commentcntid, hidskipid, cmts) {
    Ajaxrr(ShowMoreCommentsrr, 'ShowMoreComments=' + Rid + '&Random=' + Math.random() + '&skip=' + $('#' + divcommentid).next().val() +
        "&mergeparent=" + merge_parent + "&parent=" + parent1 + "&rar=1", divcommentid, linkpostid, commentcntid, hidskipid, $('#' + divcommentid).next().val(), cmts);
}

function checklogin() {
    if (login_id == 0) {
        indesof1 = LoginUrl.indexOf("/review/");
        urlredirectTo1 = LoginUrl.substr(indesof1);
        ajaxLogin(urlredirectTo1);
        return false;
    }
    else
        return true;
}
function checkloginCorp() {
    if (login_id == 0) {
        indesof1 = LoginUrl.indexOf("/review/");
        urlredirectTo1 = LoginUrl.substr(indesof1);
        ajaxLoginCorp(urlredirectTo1);
        return false;
    }
    else
        return true;
}

function hidewarningmsg() {
    $('#' + warningmsgid).hide();
}
function PostQuestion(id) {
    if ($(id).siblings('.field-outline').find('textarea').val() == '') {
        $(id).siblings('.warning').html("This information is required.").show();
        return false;
    }
    else {
        ajaxLogin('/product/product_discussion_ajax.aspx?cid=' + CatId + '&ques=' + $(id).siblings('span').children('textarea')[0].value + '&ask=0');
        return false;
    }
}

function PostAnswer(id, questid) {
    if ($(id).siblings('.field-outline').find('textarea').val() == '') {
        $(id).siblings('.warning').html("This information is required.").show();
        return false;
    }
    else {
        ajaxLogin('/product/product_discussion_ajax.aspx?cid=' + CatId + '&anstxt=' + $(id).siblings('span').children('textarea')[0].value + '&quesId=' + questid + '&ans=0');
        return false;
    }
}

function initialize1() {
    
    if (lt2 == '0' || lt2 == '') {
        $('#locationmap').hide();
    }
    else {
        $('#locationmap').show();
        var myLatlng1 = new google.maps.LatLng(lt2, lng2);
        var mapProp1 = {
            center: myLatlng1,
            zoom: 17,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scaleControl: true,
            zoomControl: true,
            zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE }
        };
        try {
            var map1 = new google.maps.Map(document.getElementById("map"), mapProp1);
            map1.setTilt(45);
            var marker1 = new google.maps.Marker({
                position: myLatlng1,
                map: map1,
                draggable: false
            });
            marker1.setMap(map1);
        }
        catch (e) { $('#locationmap').hide(); }
        var infowindow2 = new google.maps.InfoWindow({
            content: '<p>Marker Location:' + marker1.getPosition() + '</p>'
        });
        google.maps.event.addListener(marker1, 'click', function () {
            infowindow.open(map1, marker1);
        });
        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_tabs1_tablocation').show();
        $('#ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_tabs1_tablocation1').show();
    }
}

function thankyou_upload() {
    window.location.href = mshost + movielink + catnameurl + '-photos-' + CatId + '#tablist';
}
function thankyou_upload_menu() {
    window.location.href = mshost + movielink + catnameurl + '-photos-' + CatId + '#tablistmenu';
}

function setfocus() {
    var uri = window.location.toString();
    if (uri.indexOf("#dv") > 0 || uri.indexOf("#div") > 0) {
        var split = uri.split('#')
        if (split.length > 0) {
            var divname = split[1];
            try {
                var height = 0;
                if ($('#dvAdminImg'))
                    height = $('#dvAdminImg').height();
                if ($('#divrestinfo'))
                    height += $('#dvAdminImg').height();
                var pos = 0;
                pos = ($('#' + divname).offset().top - 100);
                $("body, html").animate({
                    scrollTop: pos
                }, 600);
                $("#" + divname).blur();
            } catch (e) { }
        }
    }
}
window.onload = (function () {
    function question() {
        document.getElementById('ask').style.visibility = 'hidden';
        document.getElementById('question-box').style.display = '';
        $('#txtQueArea').focus();
    }
});


var chkReadyState = setInterval(function () {
    if (document.readyState == "complete") {
        $.each(profileArray, function (key, val) {
            $.ajax({
                url: "/review/CorporateResponse.ashx",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                data: { type: 'GetProfileData', rev_id: val.reviewid, user_id: val.userid, post_s: val.posts, tcount: val.tc, is_del: val.isdeleted, img: val.image, review: val.reviews, corp: false, show_userid: val.show_userid },
                responseType: "text/html",
                success: function (data) {
                    var spl = data.split('^');
                    $('#' + val.divid).html(spl[0]);
                    $('#' + val.spnid).html(spl[1]);
                    $('#' + val.smdateid).html(spl[2]);
                    $('#' + val.spnid.replace('spnview', 'commentspan')).html(spl[3]);
                    $('#' + val.spnid.replace('spnview', 'hidCmmtCnt')).val(spl[4]);
                    (function () {
                        var bLazy = new Blazy();
                    })();
                }
            });
        });
        clearInterval(chkReadyState);
    }
}, 100);

function getuserprofile(reviewid, userid, posts, tc, isdeleted, image, divid, reviews, spnid, smdateid, show_userid) {
    profileArray.push({
        reviewid: reviewid,
        userid: userid,
        posts: posts,
        tc: tc,
        isdeleted: isdeleted,
        image: image,
        divid: divid,
        reviews: reviews,
        spnid: spnid,
        smdateid: smdateid,
        show_userid: show_userid
    });
}

function getuserratingsel(username, userid) {
    $.ajax({
        url: "/review/CorporateResponse.ashx",
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        data: { type: 'GetRarUserRating', name: username, id: userid, corp: false },
        responseType: "text/html",
        success: function (data) {
            $('#userratingsel').html(data);
        }
    });
}
function getuserratingsel1(username, userid) {
    $.ajax({
        url: "/review/CorporateResponse.ashx",
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        data: { type: 'GetRarUserRating', name: username, id: userid, corp: false },
        responseType: "text/html",
        success: function (data) {
            $('#userratingsel1').html(data);
        }
    });
}

function FacebookPostModalrr(message, shareurl, type, catid, imagetype, review_key) {
    //rar
    var FbMessage = '';
    var FbLink = '';
    reviewkey = review_key;
    if (type == "1") {
        FbMessage = message;
        FbLink = shareurl;
    }
    else {
        FbMessage = 'Join me on MouthShut.com and get a chance to win cash prizes daily';
        FbLink = 'https://www.mouthshut.com/contest';
    }
    FB.getLoginStatus(function (response) {
        if (response.status == "connected") {
            FB.ui({
                method: 'share',
                display: 'popup',
                quote: FbMessage + ' #MouthShut ',
                href: FbLink,
            }, function (response) {
                if (response && !response.error_code) {
                    fbshareTrack(FbLink)
                }
            });
        }
        else {
            FB.login(function (response) {
                if (response.status == "connected") {
                    FB.ui({
                        method: 'share',
                        display: 'popup',
                        quote: FbMessage + ' #MouthShut ',
                        href: FbLink,
                    }, function (response) {
                        if (response && !response.error_code) {
                            fbshareTrack(FbLink)
                        }
                    });
                }
            }, { scope: 'email' });
        }
    });
}

function FacebookPostModal(message, shareurl, type, catid, imagetype, review_key) {
    var FbMessage = '';
    var FbLink = '';
    reviewkey = review_key;
    if (type == "1") {
        FbMessage = message;
        FbLink = shareurl;
    }
    else {
        FbMessage = 'Join me on MouthShut.com and get a chance to win cash prizes daily';
        FbLink = 'https://www.mouthshut.com/contest';
    }
    FB.getLoginStatus(function (response) {
        if (response.status == "connected") {
            FB.ui({
                method: 'share',
                display: 'popup',
                quote: FbMessage + ' #MouthShut ',
                href: FbLink,
            }, function (response) {
                if (response && !response.error_code) {
                    fbshareTrack(FbLink)
                }
            });
        }
        else {
            FB.login(function (response) {
                if (response.status == "connected") {
                    FB.ui({
                        method: 'share',
                        display: 'popup',
                        quote: FbMessage + ' #MouthShut ',
                        href: FbLink,
                    }, function (response) {
                        if (response && !response.error_code) {
                            fbshareTrack(FbLink)
                        }
                    });
                }
            }, { scope: 'email' });
        }
    });
}


function FacebookPostModalParm() {
    return params;
}

$(document).ready(function () {
    
    showtop10(CatId);
    showDashboardimages(CatId);
    //showimages(CatId);
    showmenus(CatId);
    corp_text();

   
   
});

var prevScrollpos = window.pageYOffset;
$(window).scroll(function () {
    var currentScrollPos = window.pageYOffset;
    if (prevScrollpos > currentScrollPos || prevScrollpos < currentScrollPos) {
        var elms = document.querySelectorAll("#searchDropDown");
        for (var i = 0; i < elms.length; i++) {
            if (elms[i].style.display == "block") {
                elms[i].style.display = "none";
            }
        }
    }
    prevScrollpos = currentScrollPos;
});;
