// new product index js

$(function () {
    if ($('div.productShadow').length) { productIndex(); }
});

function productIndex() {
    var proShadow = $('div.productShadow'),
			inLinks = proShadow.find('a'),
			labels = $('span.compareLabel'),
			checkBoxes = $('div.compareThisProduct');

    checkBoxes.click(
		function (e) {
		    e.stopPropagation();
		    var sku = $(this).attr("data-productid");
		    if (sku && sku.length > 0) {
		        compareAddRemove(sku);
		    }
		}
	);

		labels.click(
		function () {
		    var cb = $(this).parent().find('input')[0];
		    if (cb) {
		        var sku = $(cb).attr("data-productid");
		        var isChecked = cb.checked;
		        if (isChecked) {
		            //$(this).parent().find('input')[0].checked = false;
		            window.location = "/product_comparison.aspx";
		        }
		        else {
		            $(this).parent().find('input')[0].checked = true;
		            if (sku) {
		                compareAddRemove(sku, true);
		            }
		        }
		    }
		}
	);

    proShadow.hover(
		function () {
		    $(this).addClass('hover');
		},
		function () {
		    $(this).removeClass('hover');
		}
	);

	$('a.toggleFamily').click(function (e) {
		e.preventDefault();
		var parent = $(this).parents('div.productShadow').toggleClass('productFamily');
		var topPos = parent.offset().top;
		if ($('#networkTab a').hasClass('open')) {
		    topPos = topPos - 45;
		}
		if (parent.hasClass('productFamily')) {
		    $('html,body').animate({ scrollTop: topPos }, 800);
		}
	});

	$('a.toggleBullets').click(function(e) {
		e.preventDefault();
		$(this).parents('div.productDesc').toggleClass('showBullets');
	});

    //    inLinks.click(
    //		function (e) {
    //		    e.stopPropagation();
    //		}
    //	);

    //    proShadow.click(
    //		function () {
    //		    window.location = $(this).find('h2 a')[0].href;
    //		}
    //	);

}
// end new product index js

function initPassword(oldObject) {
    var newObject = document.createElement('input');
    newObject.type = "password";
    if (oldObject.name) { newObject.name = oldObject.name; }
    if (oldObject.id) { newObject.id = oldObject.id; }
    if (oldObject.className) { newObject.className = oldObject.className; }
    newObject.style.color = "#333";
    c2.bindEvent(newObject, 'keypress', function (event) {
        if (!enterKey(event, 'accountLoginButton')) {
            c2.preventDefault(event);
        }
    });
    $(newObject).bind('blur', function () {
        if (this.value.length < 1) {
            var textObject = document.createElement('input');
            if (newObject.name) { textObject.name = newObject.name; }
            if (newObject.id) { textObject.id = newObject.id; }
            if (newObject.className) { textObject.className = newObject.className; }
            textObject.style.color = "#969696";
            textObject.value = "Password";
            textObject.onfocus = function () {
                initPassword(this);
            };
            setTimeout(function () { newObject.parentNode.replaceChild(textObject, newObject); }, 10);
        }
    });
    oldObject.parentNode.replaceChild(newObject, oldObject);
    setTimeout(function () { newObject.focus(); }, 10);
    return newObject;
}

function toggle_open(object) {
    $(object.parentNode).toggleClass('open');
    return false;
}

function printSpecs() {
    window.print();
    return false;
}

function createLanguageSelector() {
    var self = this;
    this.hidden = true;
    $('#language').click(function (e) {
        e.preventDefault();
        if (self.hidden) {
            var pos = c2.findElementPos(this, 'utility');
            $('#languageSelector').css('top', pos[1] + 20).css('left', pos[0]).fadeIn('fast');
            self.hidden = false;
        }
        else {
            $('#languageSelector').fadeOut('fast');
            self.hidden = true;
        }
    });
}

function createPawsPrimaryMenu() {
    var self = this;
    this.timer = null;
    this.current = null;
    this.checkActive = function (object, firstLevel) {
        if (!$(object).parents('li').hasClass('active')) {
            $(object).hide();
            if (firstLevel) {
                $('body').removeClass('float');
            }
        }
    };
    var $li1 = $('#primaryMenu>ul>li');
    $li1.hover(function () {
        if (!$(this).parent().hasClass('stick')) {
            var o = this;
            self.timer = setTimeout(function () {
                $('body').addClass('float');
                if ($.browser.msie) {
                    $(o).addClass('active').find('>ul, div.partsSearchBox').show();
                }
                else {
                    $(o).addClass('active').find('>ul, div.partsSearchBox').fadeIn('def', function () { self.checkActive(this, true); });
                }
            }, 50);
        }
    }, function () {
        clearTimeout(self.timer);
        self.timer = null;
        var $this = $(this);
        $this.removeClass('active').find('>ul').hide();
        $this.find('ul.subsub').css({
            display: 'none',
            opacity: 0
        });

        $this.find('li.active').removeClass('active');
        if (!$this.parent().hasClass('stick')) {
            $this.find('div.partsSearchBox').hide();
            $('body').removeClass('float');
        }
    });
    $li1.find('>a').attr('title', '').filter('.partsSearch').click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        var par = $(this).parents('ul');
        if (par.hasClass('stick')) {
            par.removeClass('stick');
            $('body').unbind();
        }
        else {
            par.addClass('stick');
            $('body').click(function () {
                par.removeClass('stick').find('div.partsSearchBox').hide();
                $('body').unbind().removeClass('float');
            });
        }
    })
    var $li2 = $li1.find('>ul>li');
    $li2.mouseover(function () {
        if (!$(this).hasClass('active')) {
            $li2.removeClass('active').find('>ul').hide();
            if ($.browser.msie) {
                $(this).addClass('active').find('>ul').show();
            }
            else {
                $(this).addClass('active').find('>ul').stop().css({ display: 'block', opacity: 0 }).animate({ opacity: 1 }, 400);
            }
            //	Cufon.replace('#primaryMenu>ul>li>ul>li>a', { fontFamily: 'LucidaSans', hover: true });
        }
    });
    $li2.find('>ul>li>a,>ul>li>em').hover(function () {
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    }).attr('title', '').find('img').attr('alt', '');
    $li1.find('div.partsSearchBox').click(function (e) {
        e.stopPropagation();
        $(this).parents('ul').addClass('stick');
        $('body').click(function () {
            $('#primaryMenu>ul').removeClass('stick').find('div.partsSearchBox').hide();
            $('body').unbind().removeClass('float');
        });
    });
    $li2.find('em').click(function () {
        var href = $(this).find('a:first').attr('href');
        window.location = href;
    }).find('a').click(function (e) {
        e.stopPropogation();
    });
}

function createMainMenu() {
    $('#mainMenu a.toggle, #mainMenu span.toggle').click(function () {
        var parent = $(this).parent('li');
        if (parent.hasClass('closed')) {
            parent.removeClass('closed');
        }
        else {
            parent.addClass('closed');
        }
    });
}

function createTipBox(object) {
    var cb = new textLimit();
    cb.input = object;
    cb.remaining = document.getElementById('tipBox_remaining');
    cb.limit = 500;
    cb.settings.defaultValue = cb.input.defaultValue;
    cb.init();
}

function createCommentBox(object) {
    var cb = new textLimit();
    cb.input = object;
    cb.remaining = document.getElementById('commentBox_remaining');
    cb.limit = 500;
    cb.settings.defaultValue = cb.input.defaultValue;
    cb.init();
}

function accordian(anchor) {
    var parent = $(anchor).parents('li');
    if (parent.hasClass('open')) {
        parent.removeClass('open');
    }
    else {
        parent.addClass('open');
    }
}

function createPartsAccordian() {
    $('#parts div.toggle a').click(function (e) {
        e.preventDefault();
        partsAccordian(this, 'toggle');
    });
    $('#partsExpand').click(function (e) {
        e.preventDefault();
        $('#parts div.toggle a.expand').each(function () {
            partsAccordian(this, 'expand');
        });
    });
    $('#partsCollapse').click(function (e) {
        e.preventDefault();
        $('#parts div.toggle a.close').each(function () {
            partsAccordian(this, 'close');
        });
    });
}

function partsAccordian(anchor, action) {
    var parent = $(anchor).parents('li');
    if (parent.hasClass('open') && action != 'expand') {
        parent.removeClass('open');
    }
    else if (!parent.hasClass('open') && action != 'close') {
        var wsData = $(anchor).attr("rel").split("|");
        if (wsData && wsData.length >= 3) {
            var productID = wsData[0];
            var language = wsData[1];
            var section = wsData[2];
            if (section && section.length > 0) {
                parent.addClass('open').find('img.partsLoading').each(function () {

                    var DTO = {};
                    DTO.productID = productID;
                    DTO.language = language;
                    DTO.sectionName = section;

                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/webservices/productDetail.asmx/GetPartsSection",
                        data: JSON.stringify(DTO),
                        dataFilter: function (data) { return TranslateAjaxResponse(data); },
                        success: function (response, textStatus) {

                            var msg = response.message;
                            if (response.errorMsg && response.errorMsg.length > 0) {
                                msg += "\n\n" + response.errorMsg;
                                if (response.errorStackTrace && response.errorStackTrace.length > 0) {
                                    msg += "\n" + response.errorStackTrace;
                                }
                                if (msg && msg.length > 0) {
                                    nativeAlert(msg);
                                }
                            }
                            else if (msg && msg.length > 0) {
                                alert(msg);
                            }

                            if (response.ok) {
                                parent.find('div.partsContainer').html(response.Html);
                            }
                        },
                        error: function (request, status, err) {
                            //alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
                        }
                    });
                });
            }
        }
    }
}

function createAccordian() {
    /*var fulls = $('#accordian div.full');
    for(var x=0;x<fulls.length;x++) {
    var teaser = document.createElement('div');
    teaser.className = "teaser";
    teaser.innerHTML = fulls[x].innerHTML.truncate(120, '&hellip;');
    $(fulls[x]).after(teaser);
    }*/
    $('#accordian div.toggle a').click(function (e) {
        e.preventDefault();
        accordian(this);
    });
}


function createSitemap() {
    $('#sitemapExpand').click(function (e) {
        e.preventDefault();
        $('#sitemap>li').addClass('open');
    });
    $('#sitemap div.toggle a').click(function (e) {
        e.preventDefault();
        var parent = $(this).parents('li');
        if (parent.hasClass('open')) {
            parent.removeClass('open');
        }
        else {
            parent.addClass('open');
        }
    });
}

function createTabs() {
    Cufon.replace('#tabs a', { fontFamily: 'LucidaSans', hover: true });
    var self = this;
    var ul = document.getElementById('tabs');
    var as = ul.getElementsByTagName('a');
    this.getWidth = function () {
        var width = 0;
        for (var x = 0; x < as.length; x++) {
            width += as[x].offsetWidth;
        }
        return width;
    };
    var gap = 644 - (as.length * 2) - this.getWidth();
    // recursive turned off for cufon
    //for(var x=13;x>9;x--) {
    //	if(gap >= 0) {
    //		break;
    //	}
    //	ul.style.fontSize =  x + "px";
    //	gap = 644 - (as.length*2) - this.getWidth();
    //}
    if (gap > 0) {
        var padding = Math.ceil(gap / (as.length * 2));
        for (var x = 0; x < as.length; x++) {
            gap = gap - padding;
            as[x].style.paddingRight = padding + 5 + "px";
            if (gap < padding) {
                padding = gap;
            }
            gap = gap - padding;
            as[x].style.paddingLeft = padding + 5 + "px";
            if (gap === 0) {
                break;
            }
        }
    }

    // In the video section apply class "png" to the png images.
    $('ul.videoRow img').each(function () {
        if (this.src.toLowerCase().indexOf('.png') > 0) {
            $(this).addClass('png');
        }
    });
}

function createAccountLogin() {
    var self = this;
    var login = document.getElementById('accountLogin');
    var loginMenu = document.getElementById('accountLoginMenu');
    this.removeLogin = function () {
        $(loginMenu).removeClass('active');
        login.style.display = "none";
        c2.unbindEvent(document.getElementById('txtSearchBissell'), 'focus', self.removeLogin);
    };
    $(loginMenu).click(function (e) {
        e.preventDefault();
        if ($(this).hasClass('active')) {
            self.removeLogin();
        }
        else {
            clearUtilityMenuFlyouts('myaccount')
            $(this).addClass('active');
            var pos = c2.findElementPos(this, 'page');
            login.style.display = "block";
            login.style.top = pos[1] + 17 + "px";
            login.style.right = 952 - (pos[0] + this.offsetWidth) + "px";
            c2.bindEvent(document.getElementById('txtSearchBissell'), 'focus', self.removeLogin);
        }
    });
}

function clearUtilityMenuFlyouts(ReferringControl) {

    if (ReferringControl != "myaccount") {
        var login = document.getElementById('accountLogin');
        var loginMenu = document.getElementById('accountLoginMenu');
        $(loginMenu).removeClass('active');
        login.style.display = "none";
    }

    if (ReferringControl != "minicart") {
        var mimiCart = $('#miniShoppingCart');
        mimiCart.fadeOut(0);
    }
}

function createBubbles() {
    $('a.bubbletip').hover(function () {
        if (this.rel.length > 0) {
            var content = $('#' + this.rel).css('display', 'block');
            var bubble = null;
            if (content.hasClass('bubble')) {
                bubble = content;
            }
            else {
                bubble = $('#bubble');
                bubble.css('display', 'block');
            }
            var pos;
            if ($(this).parents('#fancybox-content').length > 0) {
                pos = c2.findElementPos(this, 'fancybox-content');
            }
            else {
                pos = c2.findElementPos(this, 'page');
            }
            var left = pos[0] + (this.offsetWidth / 2) - 83;
            var top = pos[1] - bubble.height();

            // flip the bubble if top is negative
            if (top < 0) {
                top = pos[1] + 25;
                bubble.addClass('bubbleflip');
            }
            bubble.css('left', left + 'px');
            bubble.css('top', top + 'px');
        }
    },
	function () {
	    if (this.rel.length > 0) {
	        $('#' + this.rel).css('display', 'none');
	        $('#bubble').css('display', 'none');
	    }
	}).each(function () {
	    if ($(this).hasClass('bubblevoid')) {
	        $(this).click(function (e) {
	            e.preventDefault();
	        });
	    }
	});
}
function createBubblesWide() {
    $('a.bubbletipWide').hover(function () {

        if (this.rel.length > 0) {
            var content = $('#' + this.rel).css('display', 'block');
            var bubble = null;
            if (content.hasClass('bubbleWide')) {
                bubble = content;
            }
            else {
                bubble = $('#bubbleWide');
                bubble.css('display', 'block');
            }
            var pos;
            if ($(this).parents('#fancybox-content').length > 0) {
                pos = c2.findElementPos(this, 'fancybox-content');
            }
            else {
                pos = c2.findElementPos(this, 'page');
            }
            var left = pos[0] + (this.offsetWidth / 2) - 140;
            bubble.css('left', left + 'px');
            var top = pos[1] - bubble.height();
            bubble.css('top', top + 'px');
        }
    },
	function () {
	    $("#bubbleWide").mouseleave(function () {
	        $("#bubbleWide").css("display", "none");
	    });
	    $("body").click(function () {
	        $("#bubbleWide").css("display", "none");
	    });
	});
}

function createAddProducts() {
    var self = this;
    this.open = false;
    $('#addProductsButton').click(function (e) {
        e.preventDefault();
        if (self.open) {
            $('#addProducts').css('display', 'none');
            self.open = false;
        }
        else {
            var pos = c2.findElementPos(this, 'page');
            var left = pos[0] + this.offsetWidth - 421;
            var top = pos[1] + 21;
            $('#addProducts').css('display', 'block').css('left', left + 'px').css('top', top + 'px');
            self.open = true;
        }
    });
}

function createMyProducts() {
    if (jQuery.browser.msie && jQuery.browser.version < 7) {
        $('#myProducts div.img img').each(function () {
            if (this.src.toLowerCase().indexOf('.png') > 0) {
                this.runtimeStyle.width = "81px";
                this.runtimeStyle.height = this.offsetHeight + "px";
                this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "', sizingMethod='scale')";
                this.alt = this.src;
                this.src = "webimages/spacer.gif";
            }
        });
    }
}

function createProductMenu() {
    var self = this;
    var selected = $('#productMenu li.selected')[0].className.rtrim(' selected');
    var t = c2.getQuery('t');
    if (t == "acc" || t == "rep" || t == "bbf") {
        $('#productMenu li.' + selected).removeClass('selected');
        $('#' + selected).hide();
        selected = "tab_parts";
        $('#productMenu li.tab_parts').addClass('selected');
        $('#tab_parts').show();
        $('#' + t).addClass('open');
        Cufon.refresh('#productMenu a', { fontFamily: 'LucidaSans' });
    }
    $('#productMenu a').click(function (e) {

        if ($(this).attr('href').substring(0, 1) != '?') {
            return;
        }

        e.preventDefault();
        $('#productMenu li.' + selected).removeClass('selected');
        $('#' + selected).hide();
        selected = this.parentNode.className;
        $(this.parentNode).addClass('selected');
        $('#' + selected).show();
        Cufon.refresh('#productMenu a', { fontFamily: 'LucidaSans' });

        var elSKU = document.getElementById("sku");
        if (elSKU)
            omnitureClientEvent("showProductTab", this, "", { prop12: "pdp:" + selected, eVar14: "pdp:" + selected, products: ";" + elSKU.value });
    });
    $('a.productTab').click(function (e) {

        if ($(this).attr('href').substring(0, 1) != '?') {
            return;
        }

        if (!document.getElementById($(this).attr('href').ltrim('#'))) {
            e.preventDefault();
        }

        $('#productMenu li.' + selected).removeClass('selected');
        $('#' + selected).hide();
        selected = this.rel;
        $('#productMenu li.' + selected).addClass('selected');
        $('#' + selected).show();
        Cufon.refresh('#productMenu a', { fontFamily: 'LucidaSans' });

        if ($(this).attr('href') == '?tab=Testimonials#shareYours') {
            window.location.hash = "shareYours";
        }
    });
}

function lb() {
    var self = this;
    this.linksMain = $(".galleryControl .frame a.flyout");
    this.current = 0;

    this.fill = function (link) {
        $('#lb_details').html("<h2>" + link.title + "</h2>" + $(link).next('div').html());
        var image = $('#lb_image'); //.css('display', 'none').css('visibility', 'hidden');
        var newImage = new Image();
        newImage.onload = function () {
            image.html('<img src="' + link.href + '" alt="" />'); //.hide();
            self.calculateSize(newImage);
            newImage.onload = function () { };
        };
        newImage.src = link.href;
        this.current = this.links.index(link);
        //If the index = -1, that means the user clicked a link in linksMain, not links.
        if (this.current == -1) {
            this.current = this.linksMain.index(link);
        }
    };
    this.calculateSize = function (img) {
        var width = img.width;
        if (width < 300) {
            width = 300;
        }

        var $lb = $('#lb');
        width = width + $lb.find("#gallery").width() + 10 + 2; //(+10 for gallery margin, +2 for the gallery border)
        $lb.css("width", width);
        var ieVersion = getInternetExplorerVersion();
        if (ieVersion == -1 || ieVersion >= 9.0) {
            $.fancybox.resize();
        }
        Cufon.replace('#lb_details h2', { fontFamily: 'LucidaSans' });
    };
    this.prev = function () {
        var num = this.current - 1;
        if (num < 0) {
            num = this.links.length - 1;
        }
        this.fill(this.links[num]);
    };
    this.next = function () {
        var num = this.current + 1;
        if (num >= this.links.length) {
            num = 0;
        }
        this.fill(this.links[num]);
    };
    this.key = function (e) {
        if (e.keyCode == 27) {
            e.preventDefault();
            this.close();
        }
        else if (e.keyCode == 39 || e.keyCode == 78) {
            e.preventDefault();
            this.next();
        }
        else if (e.keyCode == 37 || e.keyCode == 80) {
            e.preventDefault();
            this.prev();
        }
    };

    $('form:first').append('' +
        '<div style=\"display:none;\"><div id="lb">' +
        '    <div id="gallery">' +
        '        <div class=\"previous\">' +
        '            <a title=\"previous\" id=\"productGallery_previous\" href=\"#previous\">previous</a>' +
        '        </div>' +
        '        <div class=\"frame\" id=\"productGallery\"><ul></ul></div>' +
        '        <div class=\"next\">' +
        '            <a title=\"next\" id=\"productGallery_next\" href=\"#next\">next</a>' +
        '        </div>' +
        '    </div>' +
        '    <div id="detail">' +
        '        <div class="loading">' +
        '            <img src="/webimages/lightbox-ico-loading.gif" alt="" />' +
        '        </div>' +
        '        <a class="lb_directions" id="lb_prev" title="prev"><img src="/webimages/blackCircle_Left.png" alt=""/></a>' +
        '        <a class="lb_directions" id="lb_next" title="next"><img src="/webimages/blackCircle_Right.png" alt=""/></a>' +
        '        <div class="image" id="lb_image"></div>' +
        '        <div class="container">' +
        '            <div class="details" id="lb_details"></div>' +
        '        </div>' +
        '    </div>' +
        '</div></div>');

    $(".galleryControl .frame ul").children(".flyout").clone(false).appendTo("#lb #gallery ul");
    this.links = $('#lb #gallery a.flyout');
    if (this.links.length > 0) {
        initFilmstrip_productGallery_lb();

        this.links.click(function (e) {
            e.preventDefault();
            self.fill(this);
        });
    }

    this.linksMain.click(function (e) {
        e.preventDefault();

        self.fill(this);

        $(document).keydown(function (e) {
            self.key(e);
        });

    });

    this.linksMain.fancybox({
        'type': 'inline'
            , 'href': '#lb'
            , 'titleShow': false
            , 'showCloseButton': true
            , 'centerOnScroll': true
            , 'onComplete': function () {
                $("#fancybox-wrap, #fancybox-content").css('width', 'auto');
                setTimeout("$.fancybox.resize()", 100);
            }
    });

    $("div#tab_overview div.image").click(function () {
        $('.galleryControl .frame a.flyout').first().click();
    });

    if (this.links.length > 1) {
        var $lb_detail = $("#lb #detail");
        var $lb_prev = $('div#lb a#lb_prev');
        var $lb_next = $('div#lb a#lb_next');

        $lb_prev.click(function (e) {
            e.preventDefault();
            self.prev();
        });

        $lb_next.click(function (e) {
            e.preventDefault();
            self.next();
        });

        $lb_detail.hover(
            function (e) {
                $lb_prev.show();
                $lb_next.show();
            },
            function (e) {
                $lb_prev.hide();
                $lb_next.hide();
            }
        );
    }
}

function initFilmstrip_productGallery() {
    var totalVisible = 3;
    if ($(".blockPartDetails").length > 0)
        totalVisible = 6;

    var fs = new filmstrip();
    fs.frame = $(".productGallery #productGallery").get(0);
    fs.next = $(".productGallery #productGallery_next").get(0);
    fs.previous = $(".productGallery #productGallery_previous").get(0);
    fs.settings.pageSlide = true;
    fs.settings.totalVisible = totalVisible;
    fs.settings.scrollWheel = true;
    fs.settings.prefix = "filmstrip_main";
    fs.events.onAfterInit = function () {
        if (fs.count > 3) {
            fs.next.style.display = "block";
            fs.previous.style.display = "block";
        }
        $('ul:first', fs.frame).width(67 * (fs.count));
    };
    fs.init();

    var lightbox = new lb();
}

function initFilmstrip_productGallery_lb() {
    if ($("#lb #gallery #productGallery").length > 0) {
        var fs = new filmstrip();
        fs.frame = $("#lb #gallery #productGallery").get(0);
        fs.next = $("#lb #gallery #productGallery_next").get(0);
        fs.previous = $("#lb #gallery #productGallery_previous").get(0);
        fs.settings.pageSlide = true;
        fs.settings.totalVisible = 6;
        fs.settings.scrollWheel = true;
        fs.settings.direction = 1;
        fs.events.onAfterInit = function () {
            if (fs.count > 6) {
                fs.next.style.display = "block";
                fs.previous.style.display = "block";
            }
            $('ul:first', fs.frame).height(67 * (fs.count));
        };
        fs.init();
    }
}

function createSpecsAccordian() {
    $('#specs div.toggle a').click(function (e) {
        e.preventDefault();
        accordian(this);
    });
    $('#specs_showAll').click(function (e) {
        e.preventDefault();
        if ($('#specs').find('li').slice(0, 1).hasClass('open')) {
            $('#specs>li').removeClass('open');
        }
        else {
            $('#specs>li').addClass('open');
        }
    });
}

function createVariantList() {
    $('#variantList').change(function () {
        $('#btnAddToCart').addClass('hide');
        $('#VariantLoading').removeClass('hide');
        window.location = this.options[this.selectedIndex].value;
    });
}

function createPartsSearch() {
    function triggerSearch() {
        var folderID = document.getElementById('searchFolderID').value;
        var text = document.getElementById('partsSearchInput').value;
        var defaultvalue = document.getElementById('partsSearchInput').defaultValue;

        if (text != '' && text != defaultvalue) {
            window.location = '/product_search.aspx?searchType=parts+and+accessories&mode=' + folderID + '&searchtext=' + text;
        }
    }

    $('#partsSearchButton').click(function (e) {
        e.preventDefault();
        triggerSearch();
    });
    $('#partsSearchInput').keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
            triggerSearch();
        }
    });
}

//$(function() {
//    $('#txtSearchBissell').keyup(function(e) {
//        if(e.keyCode == 13) {
//            searchBissell(null);
//        }
//    });		
//});

function searchGetSuggestions(request, response, searchOptions) {
    var data = {};
    try {
        if (searchOptions) {
            searchOptions.term = request.term;
        }
        else {
            searchOptions = {};
            searchOptions.term = request.term;
            searchOptions.folderIDs = [];
            searchOptions.recursive = true;
            searchOptions.html = true;
            searchOptions.suggestionsIDs = [];
        }
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/webservices/search.asmx/GetSearchSuggestions",
            data: JSON.stringify(searchOptions),
            dataFilter: function (data) { return TranslateAjaxResponse(data); },
            success: function (response) {
                data = response;
            },
            complete: function () {
                response(data);
            }
        });
    }
    catch (err) {
        alert(err.description);
        response(data);
    }
}

function ValidateCompareBoxes() {
    var IDs = '';

    $('a.compare').each(function () {
        if (this.rel.length > 0) {
            IDs += this.rel + ",";
        }
    });

    if (IDs === null || IDs.length === 0) {
        return;
    }
    IDs = IDs.rtrim(',');

    var DTO = {};
    DTO.IDs = IDs;

    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/compare.asmx/ValidateItems",
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (result, textStatus) {
            if (result !== null) {
                var Text = '';
                for (var Compare in result) {
                    if (result[Compare].Checked) {
                        $("a[rel=" + result[Compare].ID + "]").addClass('compareChecked');
                    }
                    else {
                        $("a[rel=" + result[Compare].ID + "]").removeClass('compareChecked');
                    }

                    if (Text == '' && result[Compare].CompareText != '') {
                        Text = result[Compare].CompareText;
                    }
                }

                if (Text != '') {
                    $("#productsSelected").html(Text);
                }
            }
        }
    });
}

function createProductBody() {
    var self = this;
    this.hover = null;
    this.product = null;
    this.over = false;
    this.current = null;
    this.par = null;
    this.delay = null;
    this.productHover = function () {
        if (!this.over) {
            this.over = true;
            this.par = this.current.parentNode;
            var pos = c2.findElementPos(this.current, 'page');
            this.hover.style.left = pos[0] - 6 + "px";
            this.hover.style.top = pos[1] - 6 + "px";
            this.product.appendChild(this.current);
            this.hover.style.display = "block";
        }
    };
    this.productHoverOff = function () {
        if (this.over) {
            this.par.appendChild(this.current);
        }
        this.hover.style.display = "none";
        this.par = null;
        this.current = null;
        this.over = false;
    };

    ValidateCompareBoxes();

    // Create product hover
    this.hover = document.createElement('div');
    this.hover.className = "productHover";
    this.product = document.createElement('div');
    this.product.className = "product";
    var bg = document.createElement('div');
    bg.className = "background";
    this.hover.appendChild(this.product);
    this.hover.appendChild(bg);
    document.getElementById('page').appendChild(this.hover);
    $('#productArea div.productWrap').hover(function () {
        clearTimeout(self.delay);
        self.delay = null;
        if (self.current != this) {
            self.productHoverOff();
            self.current = this;
            self.delay = setTimeout(function () { self.productHover(); }, 30);
        }
    }, function () {
        clearTimeout(self.delay);
        self.delay = null;
        self.delay = setTimeout(function () { self.productHoverOff(); }, 30);
    }
	);

    this.zoomers = $('#productArea a.zoom')
		.click(function (e) { e.preventDefault(); })
		.after('<a class="zoomin" href="#" title="zoom in">zoom in</a>')
		.find('img')
		.attr('alt', '')
		.end();
    $('#productArea a.zoomin').click(function (e) {
        e.preventDefault();
        if ($(this).hasClass('zoominChecked')) {
            $('a.zoom', this.parentNode)
				.unbind()
				.click(function (e) { e.preventDefault(); })
				.css('cursor', 'default');
            $(this).removeClass('zoominChecked');
        }
        else {
            $('a.zoom', this.parentNode)
				.unbind()
				.jqzoom({
				    zoomWidth: 127,
				    zoomHeight: 200,
				    xOffset: 5,
				    yOffset: -5,
				    position: "right",
				    title: false,
				    preloadImages: true
				});
            $(this).addClass('zoominChecked');
        }
    });
    this.windowWidth = $(window).width();
    $(window).resize(function () {
        var ww = $(window).width();
        if (self.windowWidth != ww) {
            $('div.jqZoomWindow, div.jqZoomPup').remove();
            self.zoomers.unbind()
		        .click(function (e) { e.preventDefault(); })
			    .css('cursor', 'default')
			    .next('a.zoomin')
			    .removeClass('zoominChecked');
            self.windowWidth = ww;
        }
    });

    // Refine Results
    $('a.cat, a.changeRefine', 'ul.refineProducts').click(function (e) {
        e.preventDefault();
        $(this).parents('li').toggleClass('open');
    });
    $('ul.refineCheckboxes a').click(function (e) {
        e.preventDefault();
        if ($(this).hasClass('checked')) {
            //this.className = "";
            var siblingCheckedCount = 0;
            $(this.parentNode).find('a').removeClass('checked').end().find('ul').addClass('hide').end().siblings().each(function (e) {
                if ($(this).find('a').hasClass('checked')) {
                    siblingCheckedCount++;
                }
            });
            if (siblingCheckedCount == 0) {
                // all siblings are unchecked, so uncheck and close the parent
                var parentUl = $(this.parentNode.parentNode);
                if (parentUl && parentUl.length >= 1) {
                    var parentLi = parentUl[0].parentNode;
                    if (parentLi) {
                        var gpUl = parentLi.parentNode;
                        if (gpUl) {
                            var isRefineProducts = $(gpUl).hasClass('refineProducts');
                            if (!isRefineProducts) {
                                $(parentLi).find('a').removeClass('checked');
                                $(parentUl).addClass('hide');
                            }
                        }
                    }
                }
            }
        }
        else {
            //this.className = "checked";
            $(this.parentNode).removeClass('open').find('a').addClass('checked').end().find('ul').removeClass('hide');
        }
    });

}

function createComMainFS() {
    var cmfs = new filmstrip();
    cmfs.frame = document.getElementById('comMainFS');
    cmfs.previous = document.getElementById('comMainFS_prev');
    cmfs.next = document.getElementById('comMainFS_next');
    cmfs.settings.scrollWheel = true;
    cmfs.anim.duration = 30;
    cmfs.events.onAfterInit = function () {
        if (cmfs.count > 1) {
            cmfs.next.style.display = "block";
            cmfs.previous.style.display = "block";
        }
    };
    cmfs.init();
}

function createTopicEditors() {
    $('a.toggleEditor').click(function (e) {
        e.preventDefault();
        var href = $(this).attr('href');
        var editor = $(href);
        if (editor.css('display') == "none") {
            editor.css('display', 'block');
        }
        else {
            editor.css('display', 'none');
        }
        var prefix = href[1];
        var id = href.substr(2);
        if (prefix == "r") {
            $("#q" + id).css('display', 'none');
        }
        if (prefix == "q") {
            $("#r" + id).css('display', 'none');
        }
    });
}

function compareAddRemove(object) {
    compareAddRemove(object, false);
}
function compareAddRemove(object, doRedirect) {
    var sku = '';
    if (typeof object == 'string') {
        sku = object;
    }
    else {
        sku = object.rel;
    }

    var DTO = {};
    DTO.ProductID = sku;

    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/compare.asmx/AddRemove",
        data: JSON.stringify(DTO),
        success: function (result, textStatus) {
            if (result && result.d) { result = result.d; }
            if (!result.ok) {
                alert(result.message, { nativeAlert: true });
                window.location.href = '/productCompare.aspx?id=3437';
            }
            else {
                if (object !== null && typeof object != 'string') {
                    if (object.rel.length > 0) {
                        $("a[rel=" + object.rel + "]").toggleClass('compareChecked');
                    }
                    else {
                        $(object).toggleClass('compareChecked');
                    }
                }
                $("#productsSelected").html(result.message);

                if (doRedirect) {
                    window.location.href = '/productCompare.aspx?id=3437';
                }
            }
        },
        error: function (request, status, err) {
            try {
                if (request.readyState == 4) {
                    switch (request.status) {
                        // Page-not-found error  
                        case 404:
                            alert(document.getElementById('jsAlert_WebserviceUrlNotFound').value);
                            break;
                        // Internal server error  
                        case 500:
                            var response = request.responseText;

                            if (response && response.Message) {
                                nativeAlert(response.Message + "\r\n\r\nStack Trace: " + response.StackTrace + "\r\n\r\nException Type: " + response.ExceptionType);
                            }
                            else {
                                alert(request.responseText);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (e) {
                alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
            }
        }
    });

    return false;
}

function compareAddAndRedirect(object) {
    //object should be compareTxt
    var $object = $(object);
    var $compareBox = $object.parent().find("a.compare");


    //check to see if the "checkbox" is checked
    if (!$compareBox.hasClass("compareChecked")) {
        //if it's not selected, select it, and redirect
        compareAddRemove($compareBox.get(0), true);
    } else {
        //if it's already selected, just go to the compare page
        window.location.href = '/productCompare.aspx?id=3437';
    }
}

function compareRemoveColumn(object, sku) {
    compareAddRemove(sku);
    var cBody = document.getElementById('compareBody');
    var table = cBody.getElementsByTagName('table')[0];
    var curLength = parseInt(table.className.ltrim('items'), 10);
    table.className = "items" + (curLength - 1);
    $('th:eq(' + object.rel + ')', cBody).remove();
    $('tr', cBody).find('td:eq(' + object.rel + ')').remove();
    $('td.cat', cBody).attr('colspan', curLength);
    $('a.btnRemove', cBody).each(function (index) {
        this.rel = index + 1;
    });
    if (curLength == 1) {
        $('#noProducts').css('display', 'block');
    }

}

//function createCompareBody() {
//	$('a.btnRemove').click(function(e) {
//		e.preventDefault();
//		var cBody = document.getElementById('compareBody');
//		var table = cBody.getElementsByTagName('table')[0];
//		var curLength = parseInt(table.className.ltrim('items'),10);
//		table.className = "items"+(curLength-1);
//		$('th:eq('+this.rel+')',cBody).remove();
//		$('tr',cBody).find('td:eq('+this.rel+')').remove();
//		$('td.cat',cBody).attr('colspan',curLength);
//		$('a.btnRemove',cBody).each(function(index) {
//			this.rel = index+1;
//		});
//		if(curLength == 1) {
//			$('#noProducts').css('display','block');
//		}
//	});
//}

function modal() {
    var self = this;
    this.current = "";
    this.overlayOn = function () {
        var overlay = null;
        $('body').addClass('float');
        if (!document.getElementById('overlay')) {
            overlay = document.createElement('div');
            overlay.id = "overlay";
            $(overlay).click(function () {
                self.close();
            });
            $('form:first').append(overlay);
        }
        else {
            document.getElementById('overlay').style.display = "block";
        }
    };
    this.close = function () {
        $('#overlay, ' + this.current).hide();
        $(document).unbind();
        $('body').removeClass('float');
    };
    this.key = function (e) {
        if (e.keyCode == 27) {
            e.preventDefault();
            this.close();
        }
    };
    $('a.modal').click(function (e) {
        e.preventDefault();
        self.overlayOn();
        self.current = $(this).attr('href');
        var mod = $(self.current);
        mod.appendTo('form:first');
        mod.css('display', 'block');
        mod.css('margin-top', -mod.outerHeight() / 2);
        $('a.close', mod).click(function (e) {
            e.preventDefault();
            self.close();
        });
        $(document).keydown(function (e) {
            self.key(e);
        });
    });
}

function popup() {
    $('a.popup').click(function (e) {
        e.preventDefault();
        return openWindow(this.href, 'popup');
    });
}

function NewsletterSignup(newsletterId, sref) {
    if (!newsletterId || newsletterId.length == 0) {
        newsletterId = 'newsletter_signup_email';
    }
    if (!sref || sref.length == 0) {
        sref = "footer+form";
    }
    var email = document.getElementById(newsletterId).value;
    var emailDefault = document.getElementById(newsletterId).defaultValue;

    if (email == emailDefault) {
        return;
    }

    window.location.href = document.getElementById('NewsletterFormLink').value + '?sref=' + sref + '&e=' + email;

    //    $.ajax(
    //    {
    //        type: "POST",
    //        contentType: "application/json; charset=utf-8",
    //        url: "/webservices/newsletterSignup.asmx/Subscribe",
    //        data: "{'email':'" + email + "'}",
    //        dataType: "json",
    //        success: function(result, textStatus)
    //        {
    //            //$("#newsletterSignupResults").html(result.message);
    //            alert(result.message);
    //        },
    //        error: function(request, status, err) 
    //		{
    //		    alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
    //		}
    //    });
}

function searchBissell(id) {
    var searchText = $("#txtSearchBissell").val();
    searchText = encodeURIComponent(searchText);

    if (id && id.length > 0) {
        window.location.href = "/product_search.aspx?searchType=main&mode=" + id + "&searchtext=" + searchText;
    }
    else {
        window.location.href = "/product_search.aspx?searchType=main&searchtext=" + searchText;
    }

    return false;
}

function searchCSFolders(ids) {
    var searchText = $("#txtSearch").val().replace(/&/g, "%26");
    window.location.href = "/product_search.aspx?searchType=customer+support+home&mode=" + ids + "&searchtext=" + searchText;
    return false;
}

function Login() {

    var username = document.getElementById('header_username').value;
    var usernamedefault = document.getElementById('header_username').defaultValue;
    var password = document.getElementById('header_password').value;
    var passworddefault = document.getElementById('header_password').defaultValue;

    if (username == '' || username == usernamedefault || password == '' || password == passworddefault) {
        return;
    }

    var DTO = {};
    DTO.username = $("#header_username").val();
    DTO.password = $("#header_password").val();

    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/users.asmx/LoginUser",
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (result, textStatus) {
            if (!result.ok) {
                alert(result.message);
            }
            else {
                window.location.href = result.message;
            }
        },
        error: function (request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                    // Page-not-found error 
                    case 404:
                        alert(document.getElementById('jsAlert_WebserviceUrlNotFound').value);
                        break;
                    // Internal server error 
                    case 500:
                        var response = request.responseText;

                        if (response && response.Message) {
                            nativeAlert(response.Message + "\r\n\r\nStack Trace: " + response.StackTrace + "\r\n\r\nException Type: " + response.ExceptionType);
                        }
                        else {
                            alert(request.responseText);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    });
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 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 Logout() {
    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/users.asmx/LogoutUser",
        data: "{}",
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (result, textStatus) {
            if (!result.ok) {
                alert('Error: User could not be logged out at this time');
            }
            else {
                //window.location.reload(true);
                createCookie("ecm", "", -1);
                //__doPostBack('ReloadImage','');
                window.location.href = window.location.href;
            }
        },
        error: function (request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                    // Page-not-found error 
                    case 404:
                        alert(document.getElementById('jsAlert_WebserviceUrlNotFound').value);
                        break;
                    // Internal server error 
                    case 500:
                        var response = request.responseText;

                        if (response && response.Message) {
                            nativeAlert(response.Message + "\r\n\r\nStack Trace: " + response.StackTrace + "\r\n\r\nException Type: " + response.ExceptionType);
                        }
                        else {
                            alert(request.responseText);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    });
}

function findRetailers_Quick() {
    var HeaderID = "findLocalHeader";
    $("#" + HeaderID).html("<center>Loading Product<br/><img src='/webimages/ajax-loader.gif' alt=''/><br /><br /></center>");

    //transfer zip from Quick to Form
    document.getElementById("zip").value = document.getElementById("zipQuick").value;
    //transfer radius from Quick to Form
    document.getElementById("SearchRadius").value = document.getElementById("SearchRadiusQuick").value;

    var sku = document.getElementById("sku").value;
    GetHeader(sku, 'productdetail');

    findRetailers("findLocalRetailerForm", "findLocalRetailer", "zip", "sku", "SearchRadius", true);
    //$('html, body').animate({ scrollTop: 0 }, 'slow');
}

function findRetailers(formID, resultsID, zipID, skuID, RadiusListID, hasMap, zipStorage, radiusStorage, isProductIndex) {
    var zip = document.getElementById(zipID).value;
    var zipdefault = document.getElementById(zipID).defaultValue;
    var sku = document.getElementById(skuID).value;
    var radius = document.getElementById(RadiusListID).value;

    if (zip == '' || zip == zipdefault) {
        alert('Please enter a zip code.');
        return;
    }

    $("#" + resultsID).html("<center><br/><br/><br/>Loading Retailers<br/><img src='/webimages/ajax-loader.gif'/></center>");

    if (zipStorage && zipStorage.length > 0) {
        $("#" + zipStorage).val(zip);
    }
    if (radiusStorage && radiusStorage.length > 0) {
        $("#" + radiusStorage).val(radius);
    }

    var DTO = {};
    DTO.SKU = sku;
    DTO.PostalCode = zip;
    DTO.FormID = formID;
    DTO.ResultsID = resultsID;
    DTO.Radius = radius;

    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/retailers.asmx/FindLocalRetailers",
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (result, textStatus) {
            if (!sEtailerPageToken) sEtailerPageToken = randomString();

            if (isProductIndex) {
                omnitureClientEvent('findRetailers', this, 'event11,event13:' + sEtailerPageToken + ',event14', { eVar13: 'retailer:' + zip, products: ";" + sku, prop12: "pi:retailer search", eVar14: "pi:retailer search" });
            }
            else {
                omnitureClientEvent('findRetailers', this, 'event11,event13:' + sEtailerPageToken + ',event14', { eVar13: 'retailer:' + zip, products: ";" + sku, prop12: "pdp:retailer search", eVar14: "pdp:retailer search" });
            }

            //$("#" + formID).css('display','none');
            GetRetailersIntro(zip);
            $("#" + resultsID).html(result.message);

            if (hasMap && result.message.indexOf('sorry') < 1) {

                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initLocalRetailerMap";
                document.body.appendChild(script);

            }
        },
        error: function (request, status, err) {
            try {
                if (request.readyState == 4) {
                    switch (request.status) {
                        // Page-not-found error       
                        case 404:
                            alert(document.getElementById('jsAlert_WebserviceUrlNotFound').value);
                            break;
                        // Internal server error       
                        case 500:
                            var response = request.responseText;

                            if (response && response.Message) {
                                nativeAlert(response.Message + "\r\n\r\nStack Trace: " + response.StackTrace + "\r\n\r\nException Type: " + response.ExceptionType);
                            }
                            else {
                                alert(request.responseText);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (e) {
                alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
            }
        },
        complete: function () {
            $('#page').toggleClass('class');
            $('#' + resultsID + ' a.more,#' + resultsID + ' a.less').click(function (e) {
                e.preventDefault();
                $('#' + resultsID).toggleClass('showAllLocations');
                $('#page').toggleClass('class');
            });
            //Cufon.replace('#'+resultsID+' h4', { fontFamily: 'LucidaSans' });
        }
    });
}

var omnat_hover = null, omnat_share = null;
function initAddThisTracking() {
    if (!omnat_hover) {
        omnat_hover = document.getElementById('at_hover');
        $('#at_hover .at_item').click(function () {
            omnitureClientEvent('shareItem', this, '', { eVar15: $("span", this).html() })
        });
    }
    if (!omnat_share) {
        omnat_share = document.getElementById('at_share');
        $('#at_share .at_item').click(function () {
            omnitureClientEvent('shareItem', this, '', { eVar15: $("span", this).html() })
        });
    }
}
var _CrossSellLinksInitialized = false;
function initCrossSellLinks(sProductID, sCrossSellType, sEvents) {
    if (_CrossSellLinksInitialized) return null;
    if (!sEvents) sEvents = 'prodView,event3';
    $("a.xButton").click(function () {
        var sxProductID = this.parentNode ? this.parentNode.getAttribute('xItemID') : '';
        var sTriggerProductID = sProductID;
        if (!sTriggerProductID) sTriggerProductID = this.parentNode ? this.parentNode.getAttribute('tItemID') : '';
        var sProducts = ";" + sxProductID + ";;;;evar16=" + sTriggerProductID + "|evar17=" + sxProductID + "|evar18=" + sCrossSellType;
        omnitureClientEvent('CrossSellLink', this, sEvents, { products: sProducts, eVar3: "cross-sell:" + sCrossSellType });
    });

    $(".xButton a").click(function () {
        var sxProductID = this.parentNode ? this.parentNode.getAttribute('xItemID') : '';
        var sTriggerProductID = sProductID;
        if (!sTriggerProductID) sTriggerProductID = this.parentNode ? this.parentNode.getAttribute('tItemID') : '';
        var sProducts = ";" + sxProductID + ";;;;evar16=" + sTriggerProductID + "|evar17=" + sxProductID + "|evar18=" + sCrossSellType;
        omnitureClientEvent('CrossSellLink', this, sEvents, { products: sProducts, eVar3: "cross-sell:" + sCrossSellType });
    });

    $("a.xAddToCart").click(function () {
        omnitureClientEvent('CrossSellAddToCart', this, '', { eVar28: "cross-sell" });
    });

    $(".xAddToCart a").click(function () {
        omnitureClientEvent('CrossSellAddToCart', this, '', { eVar28: "cross-sell" });
    });

    $("a.psxButton").click(function () {
        var sxProductID = this.parentNode ? this.parentNode.getAttribute('xItemID') : '';
        var sTriggerProductID = sProductID;
        if (!sTriggerProductID) sTriggerProductID = this.parentNode ? this.parentNode.getAttribute('tItemID') : '';
        var sProducts = ";" + sProductID + ";;;;evar16=" + sTriggerProductID + "|evar17=" + sxProductID + "|evar18=" + sCrossSellType;
        omnitureClientEvent('CrossSellLink', this, sEvents, { products: sProducts, eVar3: "cross-sell:" + sCrossSellType });
    });

    _CrossSellLinksInitialized = true;
}
var sEtailerPageToken;
function initEtailerLinks(sProductID, source) {
    // Attach Omniture tagging to the etailer links.
    $("a.etailerLink").click(function () {
        if (!sEtailerPageToken) sEtailerPageToken = randomString();
        var sEtailer = 'etailer:' + this.getAttribute('title');
        if (!source) { source = 'pdp'; }
        if (sProductID)
            omnitureClientEvent('etailerLink', this, 'event11,event13:' + sEtailerPageToken + ',event14', { eVar13: sEtailer, products: ";" + sProductID, prop12: source+":online retailers", eVar14: source+":online retailers" });
        else
            omnitureClientEvent('etailerLink', this, 'event11,event13:' + sEtailerPageToken + ',event14', { eVar13: sEtailer });
    });
}
/*
function initDownloadLinks() {
// Attach Omniture tagging to pdf and download asset links.
$('a').filter(function() { return /(downloadasset\.aspx)|(\.pdf)/i.test(this.href);})
.click(function() {
omnitureClientEvent('downloadLink', this, 'event17',{eVar22:"pdf:" + this.href});
})
.mousedown(function(e) {
if (e.which===3) {
omnitureClientEvent('downloadLink', this, 'event17',{eVar22:"pdf:" + this.href});
}
});
}
*/
function omnitureVisitToken() {
    // return the value of the omniVisitToken cookie.  If omniVisitToken doesn't exist yet, set it, and return it.
    var sToken = $.cookie('omniVisitToken');
    if (!sToken) {
        sToken = randomString();
        $.cookie('omniVisitToken', sToken, { expires: 1 });
    };
    return sToken;
}

function omnitureClientEvent(evtLabel, owner, sEvents, props) {
    //Sample Usage: omnitureClientEvent(evtLabel,sEvents,{prop1Name:prop1Value,prop2Name:Prop2Value});
    try {
        var bDebug = (window.location.href.toLowerCase().indexOf("debugmode") > 0);
        var s = s_gi(document.getElementById('ctl00_hdnOmnitureEvent').value);
        var sVars = (sEvents) ? ',events' : '';
        // products may be reset by props, if necessary.  However in the mean time we blank them out first.
        s.products = '';

        //add required custom props
        props = setClientDefaultProps(props);

        if (props) {
            for (var i in props) {
                if (bDebug) alert(i + '=' + props[i]);
                sVars += ',' + i;
                s[i] = props[i];
            }
        }
        s.events = sEvents;
        if (sVars) sVars = sVars.ltrim(',');
        s.linkTrackVars = sVars;

        if (sEvents) {
            var aEvents = sEvents.split(',');
            for (var i = 0; i < aEvents.length; i++) {
                if (aEvents[i].indexOf(':') >= 0)
                    aEvents[i] = aEvents[i].split(':')[0];
            }
            sEvents = aEvents.join(',');
        }
        s.linkTrackEvents = sEvents;

        s.tl(owner, 'o', evtLabel);
        if (bDebug) alert(evtLabel + '$' + s.linkTrackVars + '$' + s.events + '$' + s.linkTrackEvents);
    } catch (e) { }
}


function omnitureClientTrackEvent(pageName, sEvents, props) 
{
   
   try {
    var s = s_gi(document.getElementById('ctl00_hdnOmnitureEvent').value);
    props = setClientDefaultProps(props);
    s.products = '';

    s.pageName = pageName;

    if (props) {
        for (var i in props) {
            s[i] = props[i];
        }
    }
    s.events = sEvents;
    s.linkTrackEvents = '';
    s.linkTrackVars = '';

    s.t(); 
    } catch (e) {

    }

}


function setClientDefaultProps(props) {
    props['prop24'] = s.getTimeParting('h', '-5');
    props['prop25'] = s.getTimeParting('d', '-5');
    props['prop26'] = s.getTimeParting('w', '-5');
    props['currencyCode'] = "USD";
    return props;
}

var TestimonialButtonClicked = false;
function SubmitTestimonial() {
    if (TestimonialButtonClicked) {
        return;
    }
    TestimonialButtonClicked = true;

    var NameText = $("#testimonialName").val().trim('');
    if (NameText == "") {
        var NameRequiredText = $("#requiredName").val();
        TestimonialButtonClicked = false;
        alert(NameRequiredText);
        return;
    }

    var EmailText = $("#testimonialEmail").val().trim('');
    if (EmailText == "") {
        var EmailRequiredText = $("#requiredEmail").val();
        TestimonialButtonClicked = false;
        alert(EmailRequiredText);
        return;
    }

    var TestimonialText = $("#testimonialText").val().trim('');
    if (TestimonialText == "") {
        var TestimonialRequiredText = $("#requiredTestimonial").val();
        TestimonialButtonClicked = false;
        alert(TestimonialRequiredText);
        return;
    }

    var PrivacyPolicy = $('#testimonialPrivacy')[0].checked;
    if (PrivacyPolicy === false) {
        var PrivacyPolicyRequiredText = $("#requiredPrivacyPolicy").val();
        TestimonialButtonClicked = false;
        alert(PrivacyPolicyRequiredText);
        return;
    }

    var TestimonialLocationText = $("#testimonialLocation").val();
    var TestimonialSuccessMessageText = $("#testimonialSuccessMessage").val();
    var TestimonialErrorMessageText = $("#testimonialErrorMessage").val();

    $("#testimonialSend").css('display', 'none');
    $("#testimonialLoading").css('display', 'block');

    var DTO = {};
    DTO.ProductID = $("#productID").val();
    DTO.Name = NameText;
    DTO.Location = TestimonialLocationText;
    DTO.Email = EmailText;
    DTO.Testimonial = TestimonialText;
    DTO.LanguageID = $("#languageID").val();
    DTO.SuccessMessage = TestimonialSuccessMessageText;
    DTO.ErrorMessage = TestimonialErrorMessageText;

    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/testimonials.asmx/SubmitTestimonial",
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (result, textStatus) {
            $("#testimonialName").val('');
            $("#testimonialLocation").val('');
            $("#testimonialEmail").val('');
            $("#testimonialText").val('');
            $('#testimonialPrivacy')[0].checked = false;
            $("#testimonialSend").css('display', 'block');
            $("#testimonialLoading").css('display', 'none');
            TestimonialButtonClicked = false;
            alert(result.message);
        },
        error: function (request, status, err) {
            try {
                $("#testimonialLoading").html('');
                TestimonialButtonClicked = false;
                if (request.readyState == 4) {
                    switch (request.status) {
                        // Page-not-found error 
                        case 404:
                            alert(document.getElementById('jsAlert_WebserviceUrlNotFound').value);
                            break;
                        // Internal server error 
                        case 500:
                            var response = request.responseText;

                            if (response && response.Message) {
                                nativeAlert(response.Message + "\r\n\r\nStack Trace: " + response.StackTrace + "\r\n\r\nException Type: " + response.ExceptionType);
                            }
                            else {
                                alert(request.responseText);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (e) {
                alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
            }
        }
    });
}

function TestimonialChangePage(ProductID, Language, Page) {

    var DTO = {};
    DTO.ProductID = ProductID;
    DTO.Language = Language;
    DTO.Page = Page;

    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/testimonials.asmx/ChangePage",
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (result, textStatus) {
            if (result.ok) {
                $("#ctl00_cphBody_ProductTestimonials").html(result.message);
            }
        },
        error: function (request, status, err) {
            try {
                if (request.readyState == 4) {
                    switch (request.status) {
                        // Page-not-found error 
                        case 404:
                            alert(document.getElementById('jsAlert_WebserviceUrlNotFound').value);
                            break;
                        // Internal server error 
                        case 500:
                            var response = request.responseText;

                            if (response && response.Message) {
                                nativeAlert(response.Message + "\r\n\r\nStack Trace: " + response.StackTrace + "\r\n\r\nException Type: " + response.ExceptionType);
                            }
                            else {
                                alert(request.responseText);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (e) {
                alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
            }
        }
    });
}

function refineNewProductIndex(sRefinement) {
    var qs = "";

    var id = c2.getQuery("id");
    if (id && id != "") {
        qs = qs + "id=" + id + "&";
    }
    else {
        var idTemp = $("#pageId").val();
        if (idTemp && idTemp.length > 0) {
            qs = qs + "id=" + idTemp + "&";
        }
    }

    //    var p = c2.getQuery("p");
    //    if (p && p != "") {
    //        qs = qs + "p=" + p + "&";
    //    }

    var checks = [];

    $("ul.refineCheckboxes a.checked").each(function () {
        var rel = this.rel.split(":");
        if (rel.length > 1) {
            if (!checks[rel[0]]) {
                checks[rel[0]] = "";
            }
            checks[rel[0]] += rel[1] + ",";
        }
    });

    for (var key in checks) {
        qs += key + "=" + checks[key].rtrim(",") + "&";
    }

    var productSort = $("#pageSort").val();
    if (productSort && productSort.length > 0) {
        qs += "sort=" + productSort + "&";
    }

    if (sRefinement) {
        // if paging is not numeric, it will show the first page.
        qs += "page=" + sRefinement + "&";
    }

    var ItemsPerPage = $("#pageSize").val();
    //    if  (sRefinement && sRefinement == 'bpagesize'){
    //        ItemsPerPage = $("#productItemsPerPageB").val();
    //    }

    if (ItemsPerPage && ItemsPerPage.length > 0) {
        qs += "pagesize=" + ItemsPerPage + "&";
    }

    qs = qs.rtrim("&");

    var url = $("#CurrentTemplateName").val();
    if (!url || url == '') {
        url = "productIndex.aspx";
    }

    if (qs.length > 0) {
        url += "?" + qs;
    }

    window.location.href = "/" + url;
    return false;
}

/// This is the function for the old product index; it is left in so that the old one can continue to function if needed.
function refineProductIndex(sRefinement) {
    var qs = "";

    var id = c2.getQuery("id");
    if (id && id != "") {
        qs = qs + "id=" + id + "&";
    }
    else {
        var idTemp = $("#pageId").val();
        if (idTemp && idTemp.length > 0) {
            qs = qs + "id=" + idTemp + "&";
        }
    }

    //    var p = c2.getQuery("p");
    //    if (p && p != "") {
    //        qs = qs + "p=" + p + "&";
    //    }

    var checks = [];

    $("ul.refineCheckboxes a.checked").each(function () {
        var rel = this.rel.split(":");
        if (rel.length > 1) {
            if (!checks[rel[0]]) {
                checks[rel[0]] = "";
            }
            checks[rel[0]] += rel[1] + ",";
        }
    });

    for (var key in checks) {
        qs += key + "=" + checks[key].rtrim(",") + "&";
    }

    var productSort = $("#pageSort").val();
    if (productSort && productSort.length > 0) {
        qs += "sort=" + productSort + "&";
    }

    if (sRefinement) {
        // if paging is not numeric, it will show the first page.
        qs += "page=" + sRefinement + "&";
    }

    var ItemsPerPage = $("#pageSize").val();
    //    if  (sRefinement && sRefinement == 'bpagesize'){
    //        ItemsPerPage = $("#productItemsPerPageB").val();
    //    }

    if (ItemsPerPage && ItemsPerPage.length > 0) {
        qs += "pagesize=" + ItemsPerPage + "&";
    }

    qs = qs.rtrim("&");

    var url = $("#CurrentTemplateName").val();
    if (!url || url == '') {
        url = "productIndex.aspx";
    }

    if (qs.length > 0) {
        url += "?" + qs;
    }

    window.location.href = "/" + url;
    return false;
}

function clickOnce(object) {
    if (object.rel != "clicked") {
        object.rel = "clicked";
        return true;
    }
    else {
        return false;
    }
}

var ForumCreateTopicButtonClicked = false;
function CreateForumTopic(ForumID) {
    if (ForumCreateTopicButtonClicked) {
        return;
    }
    ForumCreateTopicButtonClicked = true;

    var Title = $("#forumTitle").val().trim('');
    if (Title == "") {
        var TitleRequiredText = $("#requiredForumTitle").val();
        ForumCreateTopicButtonClicked = false;
        alert(TitleRequiredText);
        return;
    }

    var editor = RadEditorGlobalArray[0];
    var oElem = editor.getContentElement();
    var Content = oElem.innerHTML.replace(/(<([^>]+)>)/ig, "").trim('');
    if (Content == "") {
        var ContentRequiredText = $("#requiredForumContent").val();
        ForumCreateTopicButtonClicked = false;
        alert(ContentRequiredText);
        return;
    }

    Content = oElem.innerHTML.trim('');
    $("#startTopicCancel").css('display', 'none');
    $("#startTopicSubmit").css('display', 'none');
    $("#startTopicLoading").css('display', 'inline-block');
    var redirectURL = window.opener.document.getElementById('topicStartURL').value;

    var DTO = {};
    DTO.ForumID = ForumID;
    DTO.Title = Title;
    DTO.Content = Content;

    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/forum.asmx/CreateTopic",
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (result, textStatus) {
            ForumCreateTopicButtonClicked = false;
            if (result.ok) {
                window.opener.location = redirectURL + result.message;
                window.close();
            }
            else {
                alert(result.message);
            }
        },
        error: function (request, status, err) {
            try {
                $("#testimonialLoading").html('');
                ForumCreateTopicButtonClicked = false;
                if (request.readyState == 4) {
                    switch (request.status) {
                        // Page-not-found error 
                        case 404:
                            alert(document.getElementById('jsAlert_WebserviceUrlNotFound').value);
                            break;
                        // Internal server error 
                        case 500:
                            var response = request.responseText;

                            if (response && response.Message) {
                                nativeAlert(response.Message + "\r\n\r\nStack Trace: " + response.StackTrace + "\r\n\r\nException Type: " + response.ExceptionType);
                            }
                            else {
                                alert(request.responseText);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (e) {
                alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
            }
        }
    });
}

function forumSearch(Link) {
    var text = document.getElementById('forumSearchText').value;
    var defaultvalue = document.getElementById('forumSearchText').defaultValue;

    if (text != '' && text != defaultvalue) {
        window.location = Link + text;
    }
}

function forumTopicSubscribe(TopicID, UserID, Subscribing) {
    var WebservicePath;

    if (Subscribing) {
        WebservicePath = '/webservices/forum.asmx/TopicSubcribe';
    }
    else {
        WebservicePath = '/webservices/forum.asmx/TopicUnsubcribe';
    }

    var DTO = {};
    DTO.TopicID = TopicID;
    DTO.UserID = UserID;

    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: WebservicePath,
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (result, textStatus) {
            if (result.ok) {
                if (Subscribing) {
                    $("#forumTopicSubscribe").addClass('hide');
                    $("#forumTopicUnsubscribe").removeClass('hide');
                }
                else {
                    $("#forumTopicSubscribe").removeClass('hide');
                    $("#forumTopicUnsubscribe").addClass('hide');
                }
            }
            alert(result.message);
        },
        error: function (request, status, err) {
            try {
                $("#testimonialLoading").html('');
                if (request.readyState == 4) {
                    switch (request.status) {
                        // Page-not-found error 
                        case 404:
                            alert(document.getElementById('jsAlert_WebserviceUrlNotFound').value);
                            break;
                        // Internal server error 
                        case 500:
                            var response = request.responseText;

                            if (response && response.Message) {
                                nativeAlert(response.Message + "\r\n\r\nStack Trace: " + response.StackTrace + "\r\n\r\nException Type: " + response.ExceptionType);
                            }
                            else {
                                alert(request.responseText);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (e) {
                alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
            }
        }
    });
}

function forumForumSubscribe(ForumID, UserID, Subscribing) {
    var WebservicePath;

    if (Subscribing) {
        WebservicePath = '/webservices/forum.asmx/ForumSubcribe';
    }
    else {
        WebservicePath = '/webservices/forum.asmx/ForumUnsubcribe';
    }

    var DTO = {};
    DTO.ForumID = ForumID;
    DTO.UserID = UserID;

    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: WebservicePath,
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (result, textStatus) {
            if (result.ok) {
                if (Subscribing) {
                    $("#forumForumSubscribe").addClass('hide');
                    $("#forumForumUnsubscribe").removeClass('hide');
                }
                else {
                    $("#forumForumSubscribe").removeClass('hide');
                    $("#forumForumUnsubscribe").addClass('hide');
                }
            }
            alert(result.message);
        },
        error: function (request, status, err) {
            try {
                $("#testimonialLoading").html('');
                if (request.readyState == 4) {
                    switch (request.status) {
                        // Page-not-found error 
                        case 404:
                            alert(document.getElementById('jsAlert_WebserviceUrlNotFound').value);
                            break;
                        // Internal server error 
                        case 500:
                            var response = request.responseText;

                            if (response && response.Message) {
                                nativeAlert(response.Message + "\r\n\r\nStack Trace: " + response.StackTrace + "\r\n\r\nException Type: " + response.ExceptionType);
                            }
                            else {
                                alert(request.responseText);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (e) {
                alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
            }
        }
    });
}

function homeFrame() {
    var $li = $('#homeFrameContainer li.homeFrameBlock');
    var current = 0;
    var max = $li.length;
    var timer;
    var $controller;
    var animating = false;
    var queue = -1;

    function moveTo(num, stopAnimation) {
        if (num != current) {
            queue = -1;
            if (!animating) {
                animating = true;
                $li.eq(num).fadeIn(700, function () {
                    $li.eq(current).css({ display: 'none', zIndex: 12 }).find('div.homeFrameOverlay').show();
                    $(this).css({ zIndex: 11 }).find('div.homeFrameOverlay').fadeOut(700, function () {
                        current = num;
                        clearTimeout(timer);
                        timer = null;
                        animating = false;
                        if (queue >= 0) {
                            moveTo(queue, stopAnimation);
                        }
                        else if (!stopAnimation) {
                            setTimer();
                        }
                    });
                });
                $controller.removeClass('active');
                $controller.eq(num).addClass('active');
            }
            else {
                queue = num;
            }
        }
    }
    function nextFrame() {
        var num = current + 1;
        if (num >= max) {
            num = 0;
        }
        moveTo(num, false);
    }
    function setTimer() {
        timer = setTimeout(function () { nextFrame(); }, 4000);
    }

    if ($li.length > 1) {
        var buttons = '<ul id="homeFrameController"><li class="active">1</li>';
        for (var x = 2; x <= max; x++) {
            buttons += '<li>' + x + '</li>';
        }
        buttons += '</ul>';
        $('#homeFrame').append(buttons);

        $controller = $('#homeFrameController li');
        $controller.each(function (i) {
            $(this).click(function () {
                clearTimeout(timer);
                timer = null;
                moveTo(i, true);
            });
        });

        setTimer();
    }
}
function createProductDetail() {

    if (document.getElementById('productMenu')) {
        createProductMenu();
    }
    if (document.getElementById('specs')) {
        createSpecsAccordian();
    }
    if (document.getElementById('variantList')) {
        createVariantList();
    }

    ValidateCompareBoxes();
}

function setPrimaryMenuHover() {
    $('#primaryMenu li').hoverIntent({
        over: function () {
            $(this).siblings().removeClass('hover');
            $(this).addClass('hover');

            clearUtilityMenuFlyouts('menu');

            //firstLi
            if ($(this).parent().hasClass("ul0")) {
                var firstLi = $('ul.ul0 > li');
                var num = $.inArray(this, firstLi);
                $('ul.ul0 .popBox').eq(num).css('top', -((num * 30) + 2));

                var boxMenuWrap = $('ul.ul0 div.boxMenuWrap');
                boxMenuWrap.eq(num).css('marginTop', -(boxMenuWrap.eq(num).height() / 2));
            }

            //secondLi
            if ($(this).parent().hasClass("ul1")) {
                var secondLi = $('ul.ul1 > li');
                var num = $.inArray(this, secondLi);
                $('ul.ul1 .popBox').eq(num).css('top', -((num * 30) + 2));
            }
        }
        , timeout: 300
        , out: function () {
            $(this).removeClass('hover');
        }
    });

    //secondPopbox
    $('ul.ul1').find('div.popBox').click(function () {
        window.location = $(this).parent().find('a').attr('href');
    });

    $("ul.boxNav > li").hover(

	    function () {
	        var $thisLi = $(this);
	        var $thisProdMenuImage = $thisLi.parent().parent().parent().find("div.prodMenuImage");
	        var altImage = $thisLi.attr("altImage");
	        if (altImage != undefined) {
	            clearTimeout(gTO_ProdMenuImage);
	            $thisProdMenuImage.css("background-image", $thisLi.attr("altImage"));
	        }
	    },
        function () {
            //Using a timeout to prevent the mouseOut event from switching the image back to default before the new mouseOver event changes it to the new alt image.
            gTO_ProdMenuImage = setTimeout(function () {
                var $thisProdMenuImage = $("div#primaryMenu ul.ul0 li.hover div.prodMenuImage")
                //var $thisProdMenuImage = $(this).parent().parent().parent().find("div.prodMenuImage");
                $thisProdMenuImage.css("background-image", $thisProdMenuImage.attr("origImg"));

            }, 10);
        }
	);
}

var gTO_ProdMenuImage = null;

$(document).ready(function () {

    //    $.ajaxSetup({
    //        type: "POST",
    //        contentType: "application/json; charset=utf-8",
    //        dataFilter: function (data) { return TranslateAjaxResponse(data); }
    //    });

    if (document.getElementById('languageSelector')) {
        var languageSelector = new createLanguageSelector();
    }

    if (document.getElementById('paws_primaryMenu')) {
        createPawsPrimaryMenu();
    }
    else if (document.getElementById('primaryMenu')) {
        setPrimaryMenuHover();
    }

    if (document.getElementById('partsSearchButton')) {
        var partsSearch = createPartsSearch();
    }
    if (document.getElementById('mainMenu')) {
        createMainMenu();
    }
    if (document.getElementById('txtTip')) {
        createTipBox(document.getElementById('txtTip'));
    }
    if (document.getElementById('txtComment')) {
        createCommentBox(document.getElementById('txtComment'));
    }
    if (document.getElementById('accordian')) {
        createAccordian();
    }
    if (document.getElementById('sitemap')) {
        createSitemap();
    }
    if (document.getElementById('tabs')) {
        createTabs();
    }
    if (document.getElementById('accountLoginMenu')) {
        createAccountLogin();
    }
    if (document.getElementById('addProductsButton')) {
        createAddProducts();
    }
    if (document.getElementById('myProducts')) {
        createMyProducts();
    }
    if (document.getElementById('productMenu')) {
        createProductDetail();
    }
    if (document.getElementById('productBody')) {
        var productBody = new createProductBody();
    }
    if (document.getElementById('comMainFS')) {
        createComMainFS();
    }
    if (document.getElementById('topicEditors')) {
        createTopicEditors();
    }
    if (document.getElementById('productGallery')) {
        initFilmstrip_productGallery();
    }
    if (document.getElementById('homeFrame')) {
        var hf = new homeFrame();
    }
    if (document.getElementById('parts')) {
        createPartsAccordian();
    }
    popup();

    var modalbox = new modal();

    createBubbles();
    createBubblesWide();

    if (document.getElementById('checkout')) {
        $('#page').toggleClass('class');
    }

    if ($('[class*=fblike]').length > 0) {
        fbGetSDK()
    }

    $(".spotlight").each(function () {
        addSpotLight(this);
    });

});

// Randomly generate a string with the specified length, using the specified characters.
// both fields are optional.
function randomString(string_length, chars) {
    if (!string_length) string_length = 8;
    if (!chars) chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var randomstring = '';
    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }
    return randomstring;
}

function closeNatForm() {
    $('div.natLogin').css('display', 'none');
    $('#overlayNat').css('display', 'none');

}

function LogUserError(message) {
    var DTO = {};
    DTO.errorMessage = message;

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/users.asmx/LogError",
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (txt, textStatus) {

        },
        error: function (request, status, err) {
            //alert(request.responseText);
        }
    });
}


function submitNatForm() {

    var chk = $('#atCB').attr('checked');
    var uName = $('#atUserName').val();

    if (!chk) {
        alert(document.getElementById('jsAlert_NatFormMustAcceptTerms').value);
        return;
    }

    $('#natDiv').css('display', 'none');
    $('div.loadingNat').css('display', 'block');

    var DTO = {};
    DTO.username = uName;
    DTO.accptTerms = chk;
    DTO.referrer = location.href;

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/users.asmx/UpdateUserNat",
        data: JSON.stringify(DTO),
        dataFilter: function (data) { return TranslateAjaxResponse(data); },
        success: function (response, textStatus) {
            var msg = response.message;
            if (response.errorMsg && response.errorMsg.length > 0) {
                msg += "\n\n" + response.errorMsg;
                if (response.errorStackTrace && response.errorStackTrace.length > 0) {
                    msg += "\n" + response.errorStackTrace;
                }
            }
            if (response.ok) {
                if (response.message != "") {
                    $('div.loadingNat').css('display', 'none');
                    $('#natDiv').css('display', 'inline');

                    $('div.natLogin').html(response.message);
                    var submenu = $("#MyAccountSubmenu_forLoginPopup").html();
                    $("#ProductRegistrationSubmenu_Destination").html(submenu);
                } else {
                    $('div.loadingNat').css('display', 'none');
                    $('#natDiv').css('display', 'inline');
                    window.location.href = location.href;
                }
            } else if (response.ok == false) {

                $('div.natLogin').html(response.message);

                LogUserError("User Account Activation error for " + uName);
            }
        },
        error: function (request, status, err) {
            LogUserError("User Account Activation error for " + uName);

            $('div.loadingNat').css('display', 'none');
            $('#natDiv').css('display', 'none');
        }
    });
}

function closeOverlay(obj) {
    if ($.browser.msie && $.browser.version == 7) {
        $('#header').css('z-index', '500');
    }
    $('#' + obj).css('display', 'none').trigger('overlayClose');
}

function displayOverlay(triggerSrc, obj, cssClass) {
    if ($.browser.msie && $.browser.version == 7) {
        $('#header').css('z-index', '-1');
    }
    var modal;
    if (triggerSrc && !obj) {
        $('#' + obj).css('display', 'inline');
    }
    else {
        var modalContainer = $('#' + obj);
        modalContainer.css('display', 'inline').trigger('overlayOpen', { triggerSrc: triggerSrc });
        if (!cssClass || cssClass.length == 0) {
            cssClass = "overlayContent";
        }
        cssClass = cssClass.split(' ')[0];  //BTO - added this in case the overlay uses multiple css classes
        modal = modalContainer.find('.' + cssClass);
    }
    if (modal) {
        var height = modal.height();
        var winHeight = $(window).height();
        var scrollTop = $(window).scrollTop();
        var top = (winHeight - height) / 3;
        if (top < 0) { top = 0; }
        top = top + scrollTop;
        modal.css('top', top).css('display', 'block');
    }
}

function SearchResultsParts_ItemsPerPage(option) {
    var qs = "";

    var id = c2.getQuery("id");
    if (id && id != "") {
        qs = qs + "id=" + id + "&";
    }

    var pci = c2.getQuery("pci");
    if (pci && pci != "") {
        qs = qs + "pci=" + pci + "&";
    }

    var pti = c2.getQuery("pti");
    if (pti && pti != "") {
        qs = qs + "pti=" + pti + "&";
    }

    var pfi = c2.getQuery("pfi");
    if (pfi && pfi != "") {
        qs = qs + "pfi=" + pfi + "&";
    }

    var sc = c2.getQuery("sc");
    if (sc && sc != "") {
        qs = qs + "sc=" + sc + "&";
    }

    var tid = c2.getQuery("tid");
    if (tid && tid != "") {
        qs = qs + "tid=" + tid + "&";
    }

    var searchtext = c2.getQuery("searchtext");
    if (searchtext && searchtext != "") {
        qs = qs + "searchtext=" + searchtext + "&";
    }

    if (option) {
        // if paging is not numeric, it will show the first page.
        qs += "page=" + option + "&";
    }

    var ItemsPerPage = $("#searchPartItemsPerPageT").val();
    if (option && option == 'bpagesize') {
        ItemsPerPage = $("#searchPartItemsPerPageB").val();
    }

    if (ItemsPerPage && ItemsPerPage.length > 0) {
        qs += "pagesize=" + ItemsPerPage + "&";
    }

    qs = qs.rtrim("&");

    var url = $("#CurrentTemplateName").val();
    if (!url || url == '') {
        url = "part_search.aspx";
    }

    if (qs.length > 0) {
        url += "?" + qs;
    }

    window.location.href = "/" + url;
    return false;
}


function SubmitContentEnabledSubscription() {
    $('#cesErrorMessage').html('');
    $('#cesSuccessMessage').html('');
    $('#cesEmail').css('backgroundColor', 'White');
    $('#cesEmailConfirm').css('backgroundColor', 'White');

    var Subscribe = $('#cesJoin:checked').val();
    if (Subscribe == 'true') {

        var EmailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/ig;
        var Email = $('#cesEmail').val()
        var EmailConfirm = $('#cesEmailConfirm').val()

        if (!Email) {
            $('#cesEmail').css('backgroundColor', '#ff6677');
            $('#cesErrorMessage').html('<p>' + $('#cesEmailRequired').val() + '</p>');
            return true;
        }
        else if (!Email.match(EmailRegex)) {
            $('#cesEmail').css('backgroundColor', '#ff6677');
            $('#cesErrorMessage').html('<p>' + $('#cesEmailInvalid').val() + '</p>');
            return true;
        }
        else {
            if (Email == EmailConfirm) {
                EmailSubscribe(Email);
                return true;
            }
            else {
                $('#cesEmailConfirm').css('backgroundColor', '#ff6677');
                var temp = '<p>' + $('#cesEmailsDontMatch').val() + '</p>';
                $('#cesErrorMessage').html(temp);
                return true;
            }
        }
    }
    else {
        return true;
    }

}

function EmailSubscribe(Email) {

    var DTO = {};
    DTO.email = Email;

    $.ajax(
	{
	    type: "POST",
	    contentType: "application/json; charset=utf-8",
	    url: "/webservices/newsletterSignup.asmx/Subscribe",
	    data: JSON.stringify(DTO),
	    dataFilter: function (data) { return TranslateAjaxResponse(data); },
	    success: function (result, textStatus) {
	        if (result.ok) {
	            OmniSendEmailSubscription();
	            $('#cesSuccessMessage').html('<p>' + result.message + '</p>');
	        }
	        else {
	            $('#cesErrorMessage').html('<p>' + result.message + '</p>');
	        }
	    },
	    error: function (request, status, err) {
	        $('#cesErrorMessage').html('<p>We\'re sorry; an unexpected error occurred with adding you to the newsletter. If you continue having problems, please contact us at <a hre="/help" title="www.bissell.com/help" >www.bissell.com/help</a> for assistance.</p>');
	    }
	});


} //EmailSubscribe

//Omniture Client events

function OmniShoppingCartView() {
    omnitureClientEvent('scView', this, 'scView', {});
}

function OmniSendEmailSubscription() {

    omnitureClientEvent('newsletterSubscription', this, 'event19', { eVar29: s.pageName });

} //OmniSendEmailSubscription


function fbGetSDK() {
    window.fbAsyncInit = function () {
        FB.init({ appId: '144789315564923', status: true, cookie: true,
            xfbml: true
        });
    };
    (function () {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
          '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
        $('[class*=fblike]').each(function () { fbSetupLikeLink(this) });
    } ());
}

function fbSetupLikeLink(obj) {
    var attr = $(obj).attr('class').split(';');
    params = [];
    for (x = 0; x < attr.length; x++) {
        if (attr[x] && attr[x].indexOf('=') > 0) {
            var key = attr[x].split('=')[0];
            var value = attr[x].split('=')[1];
            params[key] = value;
        }
    }
    var str = '';
    if (params["href"]) { str += " href=\"" + params["href"] + "\""; }
    if (params["layout"]) { str += " layout=\"" + params["layout"] + "\""; }
    if (params["action"]) { str += " action=\"" + params["action"] + "\""; }

    if (params["thumbimage"]) {
        $("meta[property='og:image']").attr('content', params["thumbimage"]);
    }

    $(obj).append($('<fb:like ' + str + '></fb:like>'));
}

function addSpotLight(obj) {
    var myinfo = $(obj).attr("taginfo");
    var axel = Math.random() + "";
    var a = axel * 10000000000000;
    var url = 'http://fls.doubleclick.net/activityi;' + myinfo + ';ord=1;num=' + a + '?';
    var src = '<iframe src=\"' + url + '\" width=\"1\" height=\"1\" frameborder=\"0\" style=\"display:none\"></iframe>';
    $(obj).html(src);
}

function toggleMiniShoppingCart() {
    miniShoppingCartAnimate("pre_addtocart_display");
    var obj = $('#miniShoppingCart');
    var ov = $('#miniShoppingCart_Overlay');
    var DTO = {};
    $.ajax(
	    {
	        type: "POST",
	        contentType: "application/json; charset=utf-8",
	        url: "/webservices/shoppingcart.asmx/FillMiniShoppingBasket",
	        data: JSON.stringify(DTO),
	        dataFilter: function (data) { return TranslateAjaxResponse(data); },
	        success: function (result, textStatus) {
	            if (result.ok) {
	                //if ($(obj).css('display') != 'block') {
	                    $(obj).html(result.message);
	                    if (result.script) {
	                        eval(result.script);
	                    }
	                    //miniShoppingCartAnimate("menu_display");
	                //}
	            }
	            else {
	            }
	        },
	        error: function (request, status, err) {
	            alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
	        }
	    });
    return false;
}

function updateMiniShoppingCart() {
    var uStr = "";
    var obj = $('#miniShoppingCart');

    $('div.cartItems input').each(function () {
        contentId = $(this).attr('id').split('_')[1];
        uStr += contentId + '|' + $(this).val() + ',';
    });
    uStr = uStr.trim(',');

    miniShoppingCartAnimate("pre_addtocart_display");

    var DTO = {};
    DTO.updateStr = uStr;
    DTO.templateName = templateName;
    DTO.contentId = oContent;
    $.ajax(
	    {
	        type: "POST",
	        contentType: "application/json; charset=utf-8",
	        url: "/webservices/shoppingcart.asmx/UpdateUserBasket",
	        data: JSON.stringify(DTO),
	        dataFilter: function (data) { return TranslateAjaxResponse(data); },
	        success: function (result, textStatus) {
	            if (result.ok) {
	                $(obj).html(result.message);
	                miniShoppingCartDraggable($(obj));
	                if (result.script) {
	                    eval(result.script);
	                }
	            }
	            else {
	            }
	        },
	        error: function (request, status, err) {
	            alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
	        }
	    });

    miniShoppingCartAnimate("mouseOver");
}

var rtn;
function addItemToMiniShoppingCart(btnObj) {
    var SKU = $(btnObj).attr("href").split('=')[1];
    var obj = $('#miniShoppingCart');
    $(obj).stop(true);
    miniShoppingCartAnimate("pre_addtocart_display");
    var DTO = {};
    DTO.productID = SKU;
    DTO.quantity = 1;
    DTO.templateName = templateName;
    DTO.className = $(btnObj).attr('class')
    DTO.contentId = oContent;
    $.ajax(
	    {
	        type: "POST",
	        contentType: "application/json; charset=utf-8",
	        url: "/webservices/shoppingcart.asmx/AddToUserBasket",
	        data: JSON.stringify(DTO),
	        dataFilter: function (data) { return TranslateAjaxResponse(data); },
	        success: function (result, textStatus) {
	            if (result.ok) {
	                $(obj).html(result.message);
	                if (result.script) {
	                    eval(result.script);
	                }
	                miniShoppingCartAnimate("addtocart_display");
	            }
	            else {

	            }
	        },
	        error: function (request, status, err) {
	            alert(document.getElementById('jsAlert_WebserviceCriticalError').value);
	        }
	    });
    return false;
}

function miniShoppingCartAnimate(action) {
    miniShoppingCartPosition();
    var obj = $('#miniShoppingCart');
    switch (action) {
        case "mouseOver":
            if (ms_displayState == "cartAction") { $(obj).stop(true, true).fadeIn(ms_fadeSeconds); };
            break;
        case "mouseOut":
            if (ms_displayState == "cartAction") { $(obj).delay(ms_fadeTimeout).fadeOut(ms_fadeSeconds); };
            break;
        case "pre_addtocart_display":
            var ov = $('#miniShoppingCart_Overlay');
            $(obj).html(ms_waitingMsg).fadeIn(ms_fadeSeconds);
            break;
        case "addtocart_display":
            clearUtilityMenuFlyouts('minicart');
            //$(obj).fadeIn(ms_fadeSeconds).delay(ms_fadeTimeout).fadeOut(ms_fadeSeconds);
            $(obj).stop(true).delay(ms_fadeTimeout).fadeOut(ms_fadeSeconds);
            miniShoppingCartDraggable(obj);
            ms_displayState = "cartAction";
            break;
        case "menu_display":
            clearUtilityMenuFlyouts('minicart');
            ms_displayState = "";
            if ($(obj).css('display') == 'block') {
                $(obj).fadeOut(ms_fadeSeconds);
            } else {
                $(obj).fadeIn(ms_fadeSeconds);
                OmniShoppingCartView();
                miniShoppingCartDraggable(obj);
            }
            break;
        case "networkbanner_slide":
            if ($(obj).css('display') == 'block') {
                if ($('body').css('margin-top') == '36px') {
                    $(obj).animate({ marginTop: '0px' }, 400);
                } else {
                    $(obj).animate({ marginTop: '-36px' }, 400);
                }
            }
            break;
    }
    return false;
}

function miniShoppingCartDraggable(obj) {
    //var hdr = $('#miniShoppingCart').children('div.header').first();
    //$(hdr).mousedown(function() {$(obj).draggable({disabled:false});});
    //$(hdr).mouseup(function () { $(obj).draggable({ disabled: true, stop: function () { $obj.css('opacity', '1')} }); });
}

function miniShoppingCartPosition() {
    try {
        var obj = $('#miniShoppingCart');
        if ($(obj).length > 0) {
            var top = $(obj).offset().top;
            var scMnuTop = $(objMnuSC).offset().top;
            if (scMnuTop > top) $(obj).css('top', scMnuTop + 20);
        }
    } catch (err) {


    }
}

function updateShoppingCartMenuItem(itms) {
    var html = msc_lbl;
    if (itms > 0) {
        html += " (" + itms + ")";
    }
    objMnuSC.html(html);
}

$(document).ready(function () {
    if (document.getElementById('networkBar')) {
        var nb = new networkBar();
    }
});

function networkBar() {
    var open = false;
    var $a = $('#networkTab a');

    function closeBar() {
        $a.removeClass('open');
        if ($.browser.msie && $.browser.version < 7) {
            $('body').css({ marginTop: 0 }).removeClass('fix');
            $('#networkBar').hide();
        }
        else {
            $('body').animate({ marginTop: 0 }, 400);
            $('#networkBar').animate({ top: -36 }, 400, function () { miniShoppingCartAnimate("networkbanner_slide"); });
        }
        open = false;
        createCookie('networkBar', 'closed', 30);
    }
    function openBar() {
        $a.addClass('open');
        if ($.browser.msie && $.browser.version < 7) {
            $('body').css({ marginTop: 36 }).addClass('fix');
            $('#networkBar').show();

        }
        else {
            $('body').animate({ marginTop: 36 }, 400);
            $('#networkBar').animate({ top: 0 }, 400, function () {
                miniShoppingCartAnimate("networkbanner_slide");
            });
        }
        open = true;
        createCookie('networkBar', 'open', 30);
    }

    $a.click(function (e) {
        e.preventDefault();
        if (open) {
            closeBar();
            miniShoppingCartPosition();
        }
        else {
            openBar();
            miniShoppingCartPosition();
        }
    });
    if (readCookie('networkBar') != 'closed') {
        $a.addClass('open');
        if ($.browser.msie && $.browser.version < 7) {
            $('body').css({ marginTop: 36 }).addClass('fix');
            $('#networkBar').show();
        }
        else {
            $('body').css({ marginTop: 36 });
            $('#networkBar').css({ top: 0 });
        }
        open = true;
    }
}

function initLocationMaps(decLat, decLng, intZoom, strShadow) {
    $(function () {
        var map;
        try {
            var searchLatLng = new google.maps.LatLng(decLat, decLng);
            var myOptions = {
                zoom: intZoom,
                center: searchLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scaleControl: true
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            $(".LocationResultsList LI").each(function () {
                var result = $(this);
                var resultLatLng = new google.maps.LatLng(parseFloat(result.attr('mapLat')), parseFloat(result.attr('mapLng')));
                var marker = new google.maps.Marker({
                    position: resultLatLng,
                    title: $("H4", this).text(),
                    icon: result.attr("mapIcon")
                });
                marker.setMap(map);
                google.maps.event.addListener(marker, 'mouseover', function () {
                    marker.setShadow(strShadow); result.addClass("LocationHover")
                });
                google.maps.event.addListener(marker, 'mouseout', function () {
                    marker.setShadow(null); result.removeClass("LocationHover")
                });
                google.maps.event.addListener(marker, 'click', function () {
                    var sClickURL = $(".LocationDirections", result).attr("href");
                    if (_gaq) _gaq.push(['_trackEvent', 'locationSearch', 'clickLocation', marker.title]);
                    window.open(sClickURL);
                });

                result.hover(
                    function () { marker.setShadow(strShadow) },
                    function () { marker.setShadow(null) }
                );
            });
        } catch (e) {
            if (!map) $("#map_canvas").hide();
        }
    });
}

function TranslateAjaxResponse(data) {
    // This Function Is Also In /admin/js/adminScript.js
    if (data) {

        var result;

        if (typeof (JSON) === 'object' && typeof (JSON.parse) === 'function')
            result = JSON.parse(data);
        else
            result = eval('(' + data + ')');

        if (result.hasOwnProperty('d'))
            return result.d;
        else
            return result;
    }
    else {
        return null;
    }
}
/*
function setOverlayPosition() 
{
//dynamically set left position 
    
var docWidth = $(window).width();
var docHeight = $(window).height();
$('div.overlayContent').each(function() {
		
//fix to center on page
$(this).css('left', '50%');
return;
				
var objWidth =  $(this).width();    
var cssLeft = 0;
cssLeft = (docWidth-objWidth)/2;
	
if (cssLeft>0)
{
$(this).css('left', cssLeft);
} 
		
});    
}*/

function clearWmcSession() {
    $.get('/webservices/myDiscounts.asmx/ClearWeMeanCleanSession');
}


function htmlTruncate(htmlString, maxLength, suffix) {
    if (!maxLength) maxLength = 0;
    var emptyTags = "|hr|br|img|input|link|meta|";
    var opClosingTags = "|dt|dd|li|option|";
    var opClosingParent = { 'dt': '|dl|', 'dd': '|dl|', 'li': '|ul|ol|', 'option': '|select|', 'td': '|tr|', 'th': '|tr|', 'tr': '|table|tbody|thead|', 'tbody': 'table', 'thead': 'table' };
    var html = htmlString.replace(/& /g, "&amp; ").replace(/< /g, "&lt; ").replace(/\n|\t/g, "").replace(/(<script\ .*?>.*?<\/script>)|<!.*?>/ig, "").replace(/  /g, " ");
    var re = /(?:(?:<([a-z0-9\/]+)([^<>]*)>)|(&[a-z]+;|#[0-9]+;))([^<&]*)/im;
    var teaser = "";
    if (html.match(re)) {
        teaser = html.substring(0, html.indexOf(html.match(re)[0]));
    }
    else {
        teaser = html;
    }
    var count = teaser.length;
    if (count >= maxLength) {
        teaser = teaser.substring(0, maxLength);
        if (suffix && count != maxLength) {
            teaser += suffix;
        }
    }
    else if (html.length > maxLength) {
        var stack = new Array();
        var startIndex = 0;
        var totalLength = html.length;
        var result, pos, temp;
        while (startIndex < totalLength) {
            result = re.exec(html);
            if (result && result.length > 0 && result[0].length > 0 && count < maxLength) {
                pos = html.indexOf(result[0]);
                startIndex += pos;
                if (result[1] && result[1].indexOf('/') < 0) {
                    if (emptyTags.indexOf('|' + result[1] + '|') == -1 && (result[2].length == 0 || result[2].lastIndexOf('/') != result[2].length - 1)) {
                        stack.push(result[1]);
                    }
                    teaser += "<" + result[1] + result[2] + ">";
                }
                else if (result[3]) {
                    teaser += result[3];
                    count++;
                }
                else {
                    var pop = stack.pop();
                    if ("/" + pop == result[1]) {
                        teaser += "<" + result[1] + ">";
                    }
                    else if (opClosingTags.indexOf('|' + pop + '|') > -1) {
                        pop = stack.pop();
                        while (opClosingTags.indexOf('|' + pop + '|') > -1) {
                            pop = stack.pop();
                        }
                        if ("/" + pop == result[1]) {
                            teaser += "<" + result[1] + ">";
                        }
                        else {
                            alert('invalid html: ' + result[0]);
                            break;
                        }
                    }
                    else {
                        alert('invalid html: ' + result[0]);
                        break;
                    }
                }
                temp = result[4];
                if (count + temp.length > maxLength) {
                    temp = temp.substring(0, maxLength - count);
                    teaser += temp;
                    if (suffix) {
                        teaser += suffix;
                    }
                    break;
                }
                else {
                    teaser += temp;
                    count += temp.length;
                }
                html = html.substr(pos + result[0].length);
                startIndex += result[0].length;
            }
            else if (suffix && count == maxLength && result[4].length > 0) {
                teaser += suffix;
                break;
            }
            else {
                break;
            }
        }
        var needParent = "";
        for (var x = stack.length - 1; x > -1; x--) {
            if (needParent.length == 0 || needParent.length > 0 && needParent.indexOf('|' + stack[x] + '|') > -1) {
                teaser += "</" + stack[x] + ">";
                needParent = "";
            }
            else if (opClosingTags.indexOf('|' + stack[x] + '|') == -1) {
                alert('invalid html: /' + stack[x]);
                break;
            }
            if (opClosingTags.indexOf('|' + stack[x] + '|') > -1) {
                if (needParent.length > 0 && needParent != opClosingParent[stack[x]]) {
                    alert('invalid html: /' + stack[x]);
                    break;
                }
                needParent = opClosingParent[stack[x]];
            }
        }
    }
    else {
        teaser = html;
    }
    return teaser;
}
