var productsTimer = null;
var collectionsTimer = null;
var inspirationTimer = null;
var resourcesTimer = null;
var productsShowTimer = null;
var collectionsShowTimer = null;
var inspirationShowTimer = null;
var resourcesShowTimer = null;
var currentPage = 1;

var mapMarkers = [];

function cssPreload() {
    loadCss = new Image();
    loadCss.src = "/common/css/main.css";

    loadCssMin = new Image();
    loadCssMin.src = "/common/css/main.css";

    loadPrintCss = new Image();
    loadPrintCss.src = "/common/css/print.css";
}

function sendEmailTo(urlOfInterest,pageTitle) {
    var firstName = $("#firstName").val();
    var lastName = $("#lastName").val();
    var toAddress = $("#toAddress").val();
    var fromAddress = $("#fromAddress").val();
    var message = $("#message").val();
    var ccFlag = $("#ccFlag").val();
    if(ccFlag == 'on') {
        ccFlag = true;
    }
    $("#firstNameLabel").removeClass("error");
    $("#firstNameError").hide();
    $("#lastNameLabel").removeClass("error");
    $("#lastNameError").hide();
    $("#toAddressLabel").removeClass("error");
    $("#toAddressError").hide();
    $("#fromAddressLabel").removeClass("error");
    $("#fromAddressError").hide();
    $.ajax(
    {url:"/onlinecatalog/emailToFriend.kls?firstName="+firstName+"&lastName="+lastName+"&fromAddress="+fromAddress+"&toAddress="+toAddress+"&message="+message+"&urlOfInterest=" + urlOfInterest + "&pageName=" + pageTitle + "&copy="+ccFlag,
        dataType:"json",
        success:function(data){
            if(data.emailToFriend.status == "ERROR") {
                $("#errorMsg").show();
                $.each(data.emailToFriend.errors, function(i,item){
                    var errorPart = "#"+item.message+"Error";
                    var errorPartLabel = "#"+item.message+"Label";
                    $(errorPartLabel).addClass("error");
                    $(errorPart).show();
                });
            } else if (data.emailToFriend.status == "SUCCESS") {
                $('#emailForm').css("left","-1000px");
                $('#emailFormThankYou #emailFormThankYou-recipient').text(toAddress);
                var leftPixels = ($(window).width() / 2) - ($('#emailFormThankYou').width() / 2) - 86;
                $('#emailFormThankYou').css("left", leftPixels + "px");

                // send omniture data
                var s=s_gi('kohlerkallista,kohlerglobal');
                s.linkTrackVars='channel,prop1,prop2,pageName,prop9,prop14,eVar26,events';
                s.linkTrackEvents='event11';
                s.prop1='KALLISTA';
                s.channel='KALLISTA:EMAIL CONTENT';
                s.prop2='KALLISTA:EMAIL CONTENT:FORM';
                s.pageName='KALLISTA:EMAIL CONTENT:FORM:CONFIRMATION';
                s.prop9='TOOLS';
                s.events='event11';
                s.prop14 = urlOfInterest;
                s.eVar26 = urlOfInterest;
                void(s.t());
            }
        }
        // , error:function(){console.log(arguments)}
    });
}

/*
function viewPaginated(pageNumber, totalPages) {
    totalPages = Math.ceil(totalPages/5);
    $('#pageNumber').val(pageNumber);
    $('#pageNumberBottom').val(pageNumber);
    $('div.viewPageControls').show();
    $('div.viewPaginated').hide();

    if(pageNumber > 0 && pageNumber <= totalPages) {
        $('.paginatedResults').hide();
        $("#viewAll").hide();
        $("#page"+pageNumber).show();
    }
    currentPage = pageNumber;
    if(currentPage==1) {
        hidePrevArrow();
    } else {
        showPrevArrow();
    }
    if(currentPage>=totalPages) {
        hideNextArrow();
    } else {
        showNextArrow();
    }
    $('.viewAll').removeClass('viewAll').addClass('viewAll-inactive');
    $('.viewAll').css("font-weight", "bold");
    $('.viewPaginated').css("font-weight", "normal");

    $("#document-overlay").css('height', $('body').height());
    $.cookie('paginatedcookie', 'true', { expires: new Date(2025,12,31)});

}

function viewPrevious(totalPages) {
    var totPages = Math.ceil(totalPages/5);
    if(currentPage<=1) {
        currentPage = 1;
        hidePrevArrow();
    } else {
        currentPage = (currentPage*1) - 1;
        if(currentPage == (totPages - 1)) {
            showNextArrow()
        }
        if(currentPage==1) {
            hidePrevArrow();
        } else {
            showPrevArrow();
        }
    }
    viewPaginated(currentPage,totalPages);
}
function viewNext(totalPages) {
    var totPages = Math.ceil(totalPages/5);
    if(currentPage>=totPages) {
        currentPage = totPages;
        hideNextArrow();
    } else {
        currentPage = (currentPage*1) + 1;
        if(currentPage == 2) {
            showPrevArrow()
        }
        if(currentPage == totPages) {
            hideNextArrow();
        } else {
            showNextArrow();
        }
    }
    viewPaginated(currentPage,totalPages);
}

function showPrevArrow() {
    $(".previous-navigationArrow").parents('a:first').css('cursor',(($.browser.msie)?'hand':'pointer'));
    $(".previous-navigationArrow").attr('src','/common/images/pagination-arrowLeft-off.png');
}

function hidePrevArrow() {
    $(".previous-navigationArrow").parents('a:first').css('cursor','default');
    $(".previous-navigationArrow").attr('src','/common/images/pagination-arrowLeft-deact.png');
}

function showNextArrow() {
    $(".next-navigationArrow").parents('a:first').css('cursor',(($.browser.msie)?'hand':'pointer'));
    $(".next-navigationArrow").attr('src','/common/images/pagination-arrowRight-off.png');
}

function hideNextArrow() {
    $(".next-navigationArrow").parents('a:first').css('cursor','default');
    $(".next-navigationArrow").attr('src','/common/images/pagination-arrowRight-deact.png');
}

function viewAll(totalPages) {
    totalPages = Math.ceil(totalPages/5);
    $('div.viewPageControls').hide();
    $('div.viewPaginated').show();
    $('.paginatedResults').hide();
    $('.viewAll-inactive').removeClass('viewAll-inactive').addClass('viewAll');
    $("#viewAll").show();
    $("#document-overlay").css('height', $('body').height());
    $.cookie('paginatedcookie', 'false', { expires: new Date(2025,12,31)});
}
*/

function hideMenu(name, time) {
    eval('clearTimeout(' + name + 'Timer)');
    eval('clearTimeout(' + name + 'ShowTimer)');
    $("#" + name).find("img").attr("src", $("#" + name).find("img").attr("src").replace("-on","-off"));
    $('#dropdown-' + name).stop(false, true); // these parameters ensure that menu doesn't get frozen mid-animation
    if (time > 0) {
        $('#dropdown-' + name).slideUp(time);
    } else {
        $('#dropdown-' + name).hide();
    }
}

function hideAllMenus(time) {
    hideMenu('products', time);
    hideMenu('collections', time);
    hideMenu('inspiration', time);
    hideMenu('resources', time);
}

function showMap(map, id, latitude, longitude, name, address1, address2, city, stateAbbr, postalCode, country) {
    if (map != null) {
        map.clearOverlays();
        var point = new GLatLng(latitude, longitude)
        map.setCenter(point, 13);

        if (mapMarkers[id] == null) {
            var marker = new GMarker(point);
            var content = '<div class="mapBubbleText">';
            content += '<p><strong>' + name + "</strong></p><p>" + address1 + "</p>";
            if (address2 != '') {
                content += '<p>' + address2 + "</p>";
            }

            content += '<p>' + city;
            var addressUrlString = address1 + ', ' + city;
            if (stateAbbr != '') {
                content += ", " + stateAbbr;
                addressUrlString += ", " + stateAbbr;
            }
            if (postalCode != '') {
                content += " " + postalCode;
                addressUrlString += " " + postalCode;
            }
            content += '</p>';

            if (country != '') {
                content += '<p>' + country + "</p>";
                addressUrlString += ', ' + country;
            }
            addressUrlString = encodeURIComponent(addressUrlString);
            content += '<a href="http://maps.google.com/maps?f=d&saddr=' + addressUrlString + '" target="_blank">Get Directions</a></div>';

            marker.bindInfoWindowHtml(content);
            mapMarkers[id] = marker;
        }

        map.addOverlay(mapMarkers[id]);

        var leftPixels = ($(window).width() / 2) - ($('#whereToBuy-mapPopup-canvas').width() / 2) + 35;
        setTimeout("$('#whereToBuy-mapPopup-canvas').css('left','" + leftPixels + "px')", 200);
        $('#document-overlay').show();
    }
}

    function changeContent(divId) {
        $(".cadContent").hide();
        $("#"+divId).show();
    }
      

(function($) {
    $(document).ready(function() {
        /*
        if($.cookie('paginatedcookie')== "true"&& $('div.viewPaginated').length >1){
            viewPaginated(1,$('#PRODUCT_LIST').val());
        }
        */
        $('#products').hover(
                function() {
                    hideMenu('collections', 0);
                    hideMenu('inspiration', 0);
                    hideMenu('resources', 0);
                    if (productsTimer) { clearTimeout(productsTimer); }
                    productsShowTimer = setTimeout("$('#dropdown-products').slideDown(200)", 250);
                    $(this).find("img").attr("src", $(this).find("img").attr("src").replace("-off","-on"));
                }, function() {
            productsTimer = setTimeout("hideAllMenus(200)",200);
        });
        $("#dwgConsoles").show();
        $(".secondary-nav a").click(function() {
            changeContent($(this).attr("ref"));
            $(".secondary-nav a").removeClass("active");
            $(this).addClass("active");
        });

        $(".cad-files").click(function () {
            if ($(this).next("ul:first").is(":hidden")) {
                $(this).next("ul:first").slideDown("slow");
                $(this).removeClass("cad-open");
                $(this).addClass("cad-close");
            } else {
                $(this).next("ul:first").slideUp("slow");
                $(this).removeClass("cad-close");
                $(this).addClass("cad-open");
            }
        });

        $("#dropdown-products").hover(
                function() {
                    hideMenu('collections', 0);
                    hideMenu('inspiration', 0);
                    hideMenu('resources', 0);
                    if (productsTimer) { clearTimeout(productsTimer); }
                },
                function() {
                    productsTimer = setTimeout("hideAllMenus(200)",200);
                }
                );

        $('#collections').hover(
                function() {
                    hideMenu('products', 0);
                    hideMenu('inspiration', 0);
                    hideMenu('resources', 0);
                    if (collectionsTimer) { clearTimeout(collectionsTimer); }
                    collectionsShowTimer = setTimeout("$('#dropdown-collections').slideDown(200)", 250);
                    $(this).find("img").attr("src", $(this).find("img").attr("src").replace("-off","-on"));
                }, function() {
            collectionsTimer = setTimeout("hideAllMenus(200)",200);
        }
                );

        $("#dropdown-collections").hover(
                function() {
                    hideMenu('products', 0);
                    hideMenu('inspiration', 0);
                    hideMenu('resources', 0);
                    if (collectionsTimer) { clearTimeout(collectionsTimer); }
                },
                function() {
                    collectionsTimer = setTimeout("hideAllMenus(200)",200);
                }
                );

        $('#inspiration').hover(
                function() {
                    hideMenu('products', 0);
                    hideMenu('collections', 0);
                    hideMenu('resources', 0);
                    if (inspirationTimer) { clearTimeout(inspirationTimer); }
                    inspirationShowTimer = setTimeout("$('#dropdown-inspiration').slideDown(200)", 250);
                    $(this).find("img").attr("src", $(this).find("img").attr("src").replace("-off","-on"));
                }, function() {
            inspirationTimer = setTimeout("hideAllMenus(200)",200);
        }
                );

        $("#dropdown-inspiration").hover(
                function() {
                    hideMenu('products', 0);
                    hideMenu('collections', 0);
                    hideMenu('resources', 0);
                    if (inspirationTimer) { clearTimeout(inspirationTimer); }
                },
                function() {
                    inspirationTimer = setTimeout("hideAllMenus(200)",200);
                }
                );

        $('#resources').hover(
                function() {
                    hideMenu('products', 0);
                    hideMenu('collections', 0);
                    hideMenu('inspiration', 0);
                    if (resourcesTimer) { clearTimeout(resourcesTimer); }
                    resourcesShowTimer = setTimeout("$('#dropdown-resources').slideDown(200)", 250);
                    $(this).find("img").attr("src", $(this).find("img").attr("src").replace("-off","-on"));
                }, function() {
            resourcesTimer = setTimeout("hideAllMenus(200)",200);
        }
                );

        $("#dropdown-resources").hover(
                function() {
                    hideMenu('products', 0);
                    hideMenu('collections', 0);
                    hideMenu('inspiration', 0);
                    if (resourcesTimer) { clearTimeout(resourcesTimer); }
                },
                function() {
                    resourcesTimer = setTimeout("hideAllMenus(200)",200);
                }
                );

        $(".dropdown-nav ul li a, .footerLinks ul li a").hover(
                function() {
                    $(this).parent("li").addClass("link-light");
                },
                function() {
                    $(this).parent("li").removeClass("link-light");
                }
                )

        $("#leftnav ul li.tertiary-nav a").hover(
                function() {
                    $(this).parent("li").css("background-image","url('/common/images/bullet-link.gif')")
                },
                function() {
                    $(this).parent("li").css("background-image","url('/common/images/bullet-arrowBlack.gif')")
                }
                )

        $("#leftnav ul li.tertiary-nav-expanded a").hover(
                function() {
                    $(this).parent("li").css("background-image","url('/common/images/bullet-nextLevelExpanded-over.gif')")
                },
                function() {
                    $(this).parent("li").css("background-image","url('/common/images/bullet-nextLevelExpanded.gif')")
                }
                )

        $('#searchBox input').focus(
                function() {
                    if($(this).val() == 'Keyword or Item #') {
                        $(this).val('');
                    }
                }
                );

        $('#searchBox input').blur(
                function() {
                    if($(this).val() == '') {
                        $(this).val('Keyword or Item #');
                    }
                }
                );

        $('img.paginationArrow').hover(
                function() {
                    $(this).attr("src",$(this).attr("src").replace("-off","-on"));
                },function() {
            $(this).attr("src",$(this).attr("src").replace("-on","-off"));
        }
                );

     
        $('img.enlargeResultsImagepress').click(
                function() {
                    var whichImg = $(this).attr('id');
                    $('#lb-enlargeImage img#enlargedImage').attr({src:'/common/images/spacer.gif'});
                    if (whichImg.indexOf("pr-") == 0 && typeof(largeImgs) != 'undefined') {
                        $('#lb-enlargeImage img#enlargedImage').attr({alt:'', width:450, height:450});
                        var thisWidth = 450;
                        var thisHeight = 450;
                        if (!isNaN(parseInt(largeImgs[whichImg + "-wdth"]))) {
                            thisWidth = parseInt(largeImgs[whichImg + "-wdth"]);
                        }
                        if (!isNaN(parseInt(largeImgs[whichImg + "-hght"]))) {
                            thisHeight = parseInt(largeImgs[whichImg + "-hght"]);
                        }
                        var widthHeight = getScaledImageDimensions(thisWidth, thisHeight, 450, 450);
                        $('#lb-enlargeImage img#enlargedImage').attr({
                            src:largeImgs[whichImg + "-src"],
                            alt:largeImgs[whichImg + "-alt"],
                            width:widthHeight['width'],
                            height:widthHeight['height']
                        });

                    } else {
                        $('#lb-enlargeImage img#enlargedImage').attr({src:'http://s7d4.scene7.com/is/image/Kohler/' + whichImg + '?layer=comp&wid=450&hei=450&fmt=jpeg&qlt=85,1&op_sharpen=1&resMode=sharp2&op_usm=1.0,1.0,5,0&iccEmbed=0'});
                    }
                    if((document.documentElement.scrollTop > -1) && (!$.browser.safari)) {
                        $('#lb-enlargeImage').css("top", (document.documentElement.scrollTop + 123) + "px");
                    } else {
                        $('#lb-enlargeImage').css("top", (self.pageYOffset + 123) + "px");
                    }
                    $('#lb-enlargeImage').css("left","50%");
                    $('#document-overlay').show();
                }
                );

        $('img#enlargedImage-close, #document-overlay').click(
                function() {
                    $('#lb-enlargeImage').css("left","-1000px");
                    $('#document-overlay').hide();
                }
                );
        

        $('img#otherViews-close, #document-overlay').click(
                function() {
                    $('#lb-otherViews').css("left","-2000px");
                    $('link[rel*=style]').each(function(i) {
                        if ($(this).attr('href').indexOf('printS7.css') > -1) $(this).attr('href', '/common/css/print.css');
                    });

                    $('#document-overlay').hide();
                }
        );

        $('div.productDetails-tab').click(
                function() {
                    $('div.productDetails-tab').removeClass('active');
                    $(this).addClass('active');
                    var tabId = $(this).attr("id");
                    var tabName = tabId.substring(tabId.indexOf("-") + 1, tabId.length);
                    $('.productDetail-content').css("display","none");
                    $('#productDetail-' + tabName + 'Content').css("display","block");
                }
                );

        $('a#emailFriend').click(
                function() {
                    var leftPixels = ($(window).width() / 2) - ($('#emailForm').width() / 2) - 86;
                    $('#emailForm').css("left", leftPixels + "px");
                    $('#emailFormThankYou').css("left","-1000px");
                    $('#document-overlay').show();

                    // send omniture data
                    var s=s_gi('kohlerkallista,kohlerglobal');
                    s.linkTrackVars='channel,prop1,prop2,pageName,prop9';
                    s.prop1='KALLISTA';
                    s.channel='KALLISTA:EMAIL CONTENT';
                    s.prop2='KALLISTA:EMAIL CONTENT:FORM';
                    s.pageName='KALLISTA:EMAIL CONTENT:FORM';
                    s.prop9='TOOLS';
                    void(s.t());
                }
                )

        $('#emailForm-content img.closeEmail, #document-overlay').click(
                function() {
                    $('#emailForm').css("left","-1000px");
                    $('#document-overlay').hide();
                }
                )

        $('#emailFormThankYou-content img, #document-overlay').click(
                function() {
                    $('#emailFormThankYou').css("left","-1000px");
                    $('#document-overlay').hide();
                }
                )

        $('a.collection-bioLink').click(
                function() {
                    var leftPixels = ($(window).width() / 2) - ($('#designerBio-canvas').width() / 2) + 76;
                    $('#designerBio-canvas').css("left", leftPixels + "px");
                    $('#document-overlay').show();
                }
                )

        $('img.close-collectionBio, #document-overlay').click(
                function() {
                    $('#designerBio-canvas').css("left","-1830px");
                    $('#document-overlay').hide();
                }
                )

        $('img.close-mapPopup, #document-overlay').click(
                function() {
                    $('#whereToBuy-mapPopup-canvas').css("left","-1830px");
                    $('#document-overlay').hide();
                }
                )

        $('div.newArrivals-tab').click(
                function() {
                    $('div.newArrivals-tab').removeClass('active');
                    $(this).addClass('active');
                    var tabId = $(this).attr("id");
                    $('.newArrivals-content').css("display","none");
                    $('#newArrivals-' + tabId).css("display","block");
                }
                );

        if (!($.browser.mozilla && $.browser.version < "1.9.1.5") && !($.browser.msie && $.browser.version < "7")) {
            $('.catalogResult-description a').hover(
                    function() {
                        $(this).parents('tr:first').find('a').css('color','#99610E');
                    }, function() {
                        $(this).parents('tr:first').find('a').css('color','#000000');
            });
        }

        $('#pageNumber').keyup(
                function() {
                    $('#pageNumberBottom').val($('#pageNumber').val());
                }
                );

        $('#pageNumberBottom').keyup(
                function() {
                    $('#pageNumber').val($('#pageNumberBottom').val());
                }
                );

        if (location.href.indexOf('/wheretobuy/') == -1) {
            $('#whereToBuy li').hover(function() {
                $(this).addClass('link-black-whereToBuy');
                //$('#whereToBuy').css('padding', '32px 12px 0 10px');
            }, function() {
                $(this).removeClass('link-black-whereToBuy');
                //$('#whereToBuy').css('padding', '32px 2px 0 20px');
            });
        }

        if (location.href.indexOf('/newsletter/') == -1) {
            $('#enewsSignUp li').hover(function() {
                $(this).addClass('link-black-whereToBuy');
                //$('#enewsSignUp').css('padding', '32px 15px 0 7px');
            }, function() {
                $(this).removeClass('link-black-whereToBuy');
                //$('#enewsSignUp').css('padding', '32px 5px 0 17px');
            });
        }

        $('.rollover').hover(function() {
            var src = $(this).attr('src');
            $(this).attr('src', src.replace('-off', '-on'));
        }, function() {
            var src = $(this).attr('src');
            $(this).attr('src', src.replace('-on', '-off'));
        });

        // apply select element fix to ie6 overlays
        $('#whereToBuy-mapPopup-canvas').bgiframe();
        $('#dropdown-products,#dropdown-collections,#dropdown-inspiration,#dropdown-resources').bgiframe();

        // prepare document overlay so that we can close popups by clicking outside them
        $("#document-overlay").css('height', $(document).height());
        $("#document-overlay").css('width', $(document).width());
    });
})(jQuery);

function getScaledImageDimensions(w, h, maxW, maxH) {
    var result = new Array();

    if (w <= maxW && h <= maxH) {
        result['width'] = w;
        result['height'] = h;

        //return here, the image is fine
        return result;
    }

    var width = parseFloat(w);
    var height = parseFloat(h);

    var ratio = parseFloat(maxW) / parseFloat(maxH);
    var thisRatio = width / height;

    if (thisRatio > ratio) {
        result['width'] = maxW;
        result['height'] = parseInt(height / thisRatio);
    } else if (thisRatio == ratio) {
        result['width'] = maxW;
        result['height'] = maxH;
    } else {
        result['width'] = parseInt(width * thisRatio);
        result['height'] = maxH;
    }

    return result;
}

