jQuery.query = function() {
    var r = {};
    var q = location.search;
    q = q.replace(/^\?/,''); // remove the leading ?
    q = q.replace(/\&$/,''); // remove the trailing &
    jQuery.each(q.split('&'), function(){
        var key = this.split('=')[0];
        var val = this.split('=')[1];
                // convert floats
        if(/^[0-9.]+$/.test(val))
            val = parseFloat(val);
                // ingnore empty values
        if(val)
            r[key] = val;
    });
    return r;
};

function openBrightcoveWindow(brightcoveUrl) {
    var url = "http://link.brightcove.com/services/link/bcpid1078541307/bclid1896835944/bctid1896776658";
    if (brightcoveUrl) {
        url = brightcoveUrl;
    }
    window.open(url, 'videolibrary', 'width=1000,height=660,resizable=yes');
}

function submitOver() {
    $('.submit').hover(
            function() {
                $(this).attr("src",$(this).attr("src").replace("-off","-on"));
            },
            function() {
                $(this).attr("src",$(this).attr("src").replace("-on","-off"));
            }
            );
}

function spiffOver() {
    $('.spiff').hover(
		function() {
			$(this).css("background-image", "url('/common/images/bg-leftNav-spiff-on.jpg')");
		}, function() {
			$(this).css("background-image", "url('/common/images/bg-leftNav-spiff-off.jpg')");
		}
	);

    $('.shop-spiff').hover(
		function() {
			$(this).css("background-image", "url('/common/images/bg-leftNav-spiff-store-on.jpg')");
		}, function() {
			$(this).css("background-image", "url('/common/images/bg-leftNav-spiff-store-off.jpg')");
		}
	);

    $('.jackson-square-spiff').hover(
		function() {
			$(this).css("background-image", "url('/common/images/spiffs/spiff-jacksonsquare-on.jpg')");
		}, function() {
			$(this).css("background-image", "url('/common/images/spiffs/spiff-jacksonsquare-off.jpg')");
		}
	);

    $('.sweepstakes-spiff').hover(
		function() {
			$(this).css("background-image", "url('/common/images/spiffs/spiff-sweepstakes-on.jpg')");
		}, function() {
			$(this).css("background-image", "url('/common/images/spiffs/spiff-sweepstakes-off.jpg')");
		}
	);

        $('.sale-spiff').hover(
		function() {
			$(this).css("background-image", "url('/common/images/spiffs/spiff-sale-on.jpg')");
		}, function() {
			$(this).css("background-image", "url('/common/images/spiffs/spiff-sale-off.jpg')");
		}
	);

    $('.pick-fabric-spiff').hover(
		function() {
			$(this).css("background-image", "url('/common/images/spiffs/spiff-pick-fabric-on.jpg')");
		}, function() {
			$(this).css("background-image", "url('/common/images/spiffs/spiff-pick-fabric-off.jpg')");
		}
	);
    
	$('.spiff-subzero').hover(
		function() {
			$(this).css("background-image", "url('/common/images/bg-leftNav-spiff-subzero-on.jpg')");
		}, function() {
			$(this).css("background-image", "url('/common/images/bg-leftNav-spiff-subzero-off.jpg')");
		}
	);
}

function downloadOver() {
    $('li.download a').hover(
            function() {
                $(this).parent().css("background-image", "url('/common/images/bullet-upDown-over.gif')");
            },
            function() {
                $(this).parent().css("background-image", "url('/common/images/bullet-downloadIcon.gif')");
            }
            );
}

function popupOver() {
    $('li.quicklook a, span.quicklook a').hover(
            function() {
                $(this).parent().css("background-image", "url('/common/images/bullet-upDown-over.gif')");
            },
            function() {
                $(this).parent().css("background-image", "url('/common/images/bullet-quicklookIcon.gif')");
            }
            );
}


function newProductIconOver() {
    var myTimeout;
    var removeFunction = function() { $("#newProduct-hover").remove() };
    var hover = $('<div id="newProduct-hover">' +
                              '<div class="newProduct-1"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                              '<div class="icon-text">New Arrival</div>' +
                              '<div class="newProduct-1"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                              '</div>');
    $('img.newproduct-results').hover(
            function() {
                clearTimeout(myTimeout);
                $("#saleProduct-hover").remove();
                $(hover).css('left', this.offsetLeft - 60);
                $(hover).hover(
                        function() { clearTimeout(myTimeout); },
                        function() { myTimeout = setTimeout(removeFunction, 150); }
                );
                $(this).parent('.productIcon-container').append(hover);
            },
            function() {
                myTimeout = setTimeout(removeFunction, 150);
            }
    );
    $('img.newproduct').hover(
            function() {
                clearTimeout(myTimeout);
                $("#saleProduct-hover").remove();
                $(hover).css('left', $(this).parent()[0].offsetLeft + 20);
                $(hover).hover(
                        function() { clearTimeout(myTimeout); },
                        function() { myTimeout = setTimeout(removeFunction, 150); }
                );
                $('#prodDtl-tools').before(hover);
            },
            function() {
                myTimeout = setTimeout(removeFunction, 150);
            }
    );
}

function saleProductIconOver() {
    var myTimeout;
    var removeFunction = function() { $("#saleProduct-hover").remove() };
    var hover = $('<div id="saleProduct-hover">' +
                              '<div class="saleProduct-1"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                              '<div class="icon-text">Sale</div>' +
                              '<div class="saleProduct-1"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                              '</div>');
    $('img.saleproduct-results').hover(
            function() {
                clearTimeout(myTimeout);
                $("#newProduct-hover").remove();
                $(hover).css('left', this.offsetLeft - 30);
                $(hover).hover(
                        function() { clearTimeout(myTimeout); },
                        function() { myTimeout = setTimeout(removeFunction, 150); }
                );
                $(this).parent('.productIcon-container').append(hover);
            },
            function() {
                myTimeout = setTimeout(removeFunction, 150);
            }
    );
    $('img.saleproduct').hover(
            function() {
                clearTimeout(myTimeout);
                $("#newProduct-hover").remove();
                $(hover).css('left', $(this).parent()[0].offsetLeft + 20);
                $(hover).hover(
                        function() { clearTimeout(myTimeout); },
                        function() { myTimeout = setTimeout(removeFunction, 150); }
                );
                $('#prodDtl-tools').before(hover);
            },
            function() {
                myTimeout = setTimeout(removeFunction, 150);
            }
    );
}

   function iconOver(whichOne,imgname) {
       var imgsrc="/common/images/" + imgname;
       var term="";
    $(whichOne).attr("src",imgsrc);
       if(imgname=='sale_on.gif'){
         term='<b>Sale</b> - This item is currently on sale.' ;
       }else if (imgname=='new_on.gif'){
            term= '<b>New</b> - This is a new item.';
       } else if (imgname=='classic_on.gif'){
          term='<b>Classic "Made-To-Order"</b> - This item is not stocked  at<br>'+'McGuire, rather it is manufactured per customer order and may<br> have up to a 16-20 week lead time. ';
       }else if(imgname=='finish_on.gif'){
           term= '<b>Limited Finishes</b> - Finishes for this item do not follow the <br> standard McGuire finish convention. See "Finishes" tab for<br>options.';
       }else if (imgname='availability_on.gif'){
               term= '<b>Limited Availability</b> - Item is currently in-stock at McGuire<br>but will not be replenished once sold. Please check with McGuire<br> customer service at (415) 626-1414 for availability before <br> placing an order.';
       }
   $('#iconText').html(term);

}

 function iconOut(whichOne,imgname) {
       var imgsrc="/common/images/" + imgname;
       $(whichOne).attr("src",imgsrc);
       $('#iconText').html('(roll over icon for info)');

}

 

function newProduct(obj) {
    $(obj).each(function(i){
        var thisLink = $(this).children();
        thisLink.after('<div style="position:absolute; top:-11px; right:10px;"><img src="/common/images/icon-new.png" width="25" height="8" alt="New" border="0" /></div>');
    });
};

function saleProduct(obj) {
    $(obj).each(function(i){
        var thisLink = $(this).children();
        thisLink.after('<div style="position:absolute; top:-11px; right:10px;"><img src="/common/images/icon-sale.png" width="27" height="7" alt="Sale" border="0" /></div>');
    });
};

function roomScene(obj) {
    $(obj).each(function(i){
        $(this).before('<div class="relative"><img src="/common/images/icon-roomScene.gif" width="10" height="10" alt="View Room Scene" border="0" class="roomScene-icon" /></div>');
    });
};

function roomSceneKeyVisual(objs) {
    $(objs).each(function(j){
        $(this).after('<div class="relative"><img src="/common/images/icon-roomScene.gif" width="10" height="10" alt="View Room Scene" border="0" class="roomScene-keyVisual-icon" /></div>');
    });
};

function enlargeKeyVisual(objs) {
    $(objs).each(function(j){
        $(this).after('<div class="relative"><a href="#" onclick="showEnlargedImages(\'0\'); return false;"><img src="/common/images/icon-roomScene.gif" width="10" height="10" alt="View Room Scene" border="0" class="roomScene-keyVisual-icon" /></a></div>');
    });
};

function launchVideo(whichVideo) {
    var videoCode =
            '<div id="videoPlayer">' +
            '<div class="lightbox-canvasClose"><img src="/common/images/btn-closeLightbox.gif" width="9" height="9" alt="Close" border="0" onClick="killLightbox();" /></div>' +
            '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="508" height="327" name="flashvideo" id="flashvideo">' +
            '<param name="movie" value="/common/swf/' + whichVideo + '.swf">' +
            '<param name="quality" value="best">' +
            '<param name="wmode" value="opaque">' +
            '<param name="allowscriptaccess" value="always">' +
            '<param name="scale" value="noscale">' +
            '<embed src="/common/swf/' + whichVideo + '.swf" quality="best" scale="noscale" allowscriptaccess="always" id="flashvideo" name="flashvideo" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="508" height="327"></embed>' +
            '</object>';
    '</div>';
    createLightbox();
    $('#lightbox-copy').html(videoCode);
    ieWidthFix();
    fireOmnitureVideoEvent(whichVideo);
}

function fireOmnitureVideoEvent(video) {
    var s=s_gi('kohlerinteriorsmcguire,kohlerglobal');
    s.linkTrackVars='channel,prop1,prop2,pageName,prop9,events';
    s.linkTrackEvents='event13';
    s.prop1='MCGUIRE';
    s.channel='MCGUIRE:VIDEO';
    s.prop2='MCGUIRE:VIDEO:VIDEO';
    s.pageName='MCGUIRE:VIDEO:VIDEO:' + video.toUpperCase();
    s.prop9='VIDEO';
    s.events='event13';
    void(s.t());
}

function createLightbox() {
    $('#lightbox').css("display","block");
    $('#lightbox-canvas').css("display","block");
    if((document.documentElement.scrollTop > -1) && (!$.browser.safari)) {
        $('#lightbox-canvas').css("top", (document.documentElement.scrollTop + 10) + "px");
    } else {
        $('#lightbox-canvas').css("top", (self.pageYOffset + 10) + "px");
    }
}

function killLightbox() {
	$('#glasstopdata').hide();
    $('#lightbox').css("display","none");
    $('#lightbox-canvas').css("display","none");
    if($.browser.msie) {
        $('.lightbox-canvas-3').css("width",'1px');
        $('.lightbox-canvas-2').css("width",'1px');
        $('.lightbox-canvas-1').css("width",'1px');
    }
}

function populateEnlarge() {
    $('#lightbox-copy').html(enlargeImageHtml);
}

function getNavQueryString() {
    var sectionNumber = $.query()['sectionNumber'];
    var subsectionNumber = $.query()['subsectionNumber'];
    var tertiarySectionNumber = $.query()['tertiarySectionNumber'];
    var navQueryString = ""
    if (sectionNumber != null) navQueryString += "&sectionNumber=" + sectionNumber;
    if (subsectionNumber != null) navQueryString += "&subsectionNumber=" + subsectionNumber;
    if (tertiarySectionNumber != null) navQueryString += "&tertiarySectionNumber=" + tertiarySectionNumber;

    return navQueryString;
}

function populateQuicklookProduct(prodId) {
    var navQueryString = getNavQueryString();
    $.get('/ajax/quicklook.mcg?productNumber=' + prodId + navQueryString, function(transport) {
        $('#lightbox-copy').html(transport);
        createLightbox();
        ieWidthFix();
    });
}

function populateQuicklookTextile(prodId) {
    var navQueryString = getNavQueryString();
    $.get('/ajax/textileQuicklook.mcg?productNumber=' + prodId + navQueryString, function(transport) {
        $('#lightbox-copy').html(transport);
        createLightbox();
        ieWidthFix();
    });
}

function swapQlImg(whichImg,shownIn,qlObj) {
    if(qlObj != undefined) {
        $('#ql-otherImages img').removeClass("active");
        $(qlObj).addClass("active");
    }
    $('#ql-image img').attr({src:'/onlinecatalog/resources/images/jpg375x375/' + whichImg});
    $('#shownIn').html(shownIn);
    if(shownIn=="") {
        $('#shownIn-copy').hide();
    } else {
        $('#shownIn-copy').show();
    }
}

function populateEnlargeImage(hasScene7) {
    if (hasScene7) {
		$('#lightbox-copy').append($("#lb-otherViews-content"));
    } else {
        createEnlargedCode();
        $('#lightbox-copy').html(enlargedImage);
    }
}

function populateGlassTop() {
	$('#glasstopdata').show();
    $('#lightbox-copy').html($('#glasstopdata').html());
		   
}

function populateEnlargeTextile() {
    createEnlargedTxtlCode();
    $('#lightbox-copy').html(enlargedTxtl);
}

function ieWidthFix() {
    if($.browser.msie) {
        var setLineWidth = $('#lightbox-copy').width();
        $('.lightbox-canvas-3').css("width",setLineWidth + 5 + 'px');
        $('.lightbox-canvas-2').css("width",setLineWidth + 7 + 'px');
        $('.lightbox-canvas-1').css("width",setLineWidth + 9 + 'px');
    }
}

function wtbDefinition(term, define, whichOne) {
    $(whichOne).after('<div id="definition-canvas">' +
                      '<div class="definition-top"><img src="/common/images/spacer.gif" width="184" height="11" alt="" border="0" /></div>' +
                      '<div class="definition-copy"><span id="definition-term"></span><br /><span id="definition-define"></span></div>' +
                      '<div class="definition-bottom"><img src="/common/images/spacer.gif" width="184" height="15" alt="" border="0" /></div>' +
                      '</div>');
    $('#definition-term').html(term);
    $('#definition-define').html(define)
}



function dimensionDefinition(whichOne) {
    $(whichOne).after('<div id="definition-canvas">' +
                      '<div class="definition-top"><img src="/common/images/spacer.gif" width="184" height="11" alt="" border="0" /></div>' +
                      '<div class="definition-copy"><span id="definition-term">COM</span><br /><span id="definition-define">Customer\'s Own Material based on 54\" plain goods</span><br /><span id="definition-term">COL</span><br /><span id="definition-define">Customer\'s Own Leather</span></div>' +
                      '<div class="definition-bottom"><img src="/common/images/spacer.gif" width="184" height="15" alt="" border="0" /></div>' +
                      '</div>');
}

function dimensionDefinitionMetric(whichOne) {
    $(whichOne).after('<div id="definition-canvas">' +
                      '<div class="definition-top"><img src="/common/images/spacer.gif" width="184" height="11" alt="" border="0" /></div>' +
                      '<div class="definition-copy"><span id="definition-term">COM</span><br /><span id="definition-define">Customer\'s Own Material based on 137cm plain goods</span><br /><span id="definition-term">COL</span><br /><span id="definition-define">Customer\'s Own Leather</span></div>' +
                      '<div class="definition-bottom"><img src="/common/images/spacer.gif" width="184" height="15" alt="" border="0" /></div>' +
                      '</div>');
}


$(function() {
    saleProduct('li.sale');
    newProduct('li.new');
    roomScene('img.roomScene');
    roomSceneKeyVisual('img.roomScene-keyVisual');
    enlargeKeyVisual('img.enlarge-keyVisual');
    submitOver();
    spiffOver();
    downloadOver();
    popupOver();
    //newProductIconOver();
    //saleProductIconOver();
   
});


function legalLinkActivation(whichOne) {
     
   $('.active').removeClass("active");

    $(whichOne).addClass("active");
}

function isValidEmail(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return reg.test(email);
}

(function($){
    $(function() {
        var pageHeight;
        if (document.documentElement && document.documentElement.scrollHeight) {
            pageHeight = document.documentElement.scrollHeight;
        } else if (document.body) {
            pageHeight = document.body.scrollHeight;
        }

        $('#footer').after(
                '<div id="lightbox">&nbsp;</div>' +
                '<div id="lightbox-canvas">' +
                '<div class="lightbox-canvas-3"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                '<div class="lightbox-canvas-2"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                '<div class="lightbox-canvas-1"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                '<div class="rightShadow">' +
                '<div id="lightbox-copy">&nbsp;</div>' +
                '<div class="lightbox-canvas-1"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                '<div class="lightbox-canvas-2"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                '<div class="lightbox-canvas-3"><img src="/common/images/spacer.gif" width="1" height="1" border="0" alt="" /></div>' +
                '</div>' +
                '<div class="bottomShadow"><div><img src="/common/images/spacer.gif" width="1" height="11" border="0" alt="" /></div></div>' +
                '</div>'
                );

        $("div.roundedCorners").corner("round 3px");

        $('#lightbox').css('height', pageHeight)


        var searchBox = $("#search-box input");
        var defaultSearchText = searchBox.val();
        searchBox.focus(function() {
            if ($(this).val() == defaultSearchText) {
                $(this).val("");
            }
        });
        searchBox.blur(function() {
            if ($.trim($(this).val()) == "") {
                $(this).val(defaultSearchText);
            }
        });
        $("#search-box a").click(function() {
            if ($.trim(searchBox.val()) == "" || $.trim(searchBox.val()) == $.trim(defaultSearchText)) {
                return false;
            }
            $(this).parent().get(0).submit();
            return false;
        });

        $('a.print').click(
                function() {
                    createLightbox();
                    populatePrint();
                    ieWidthFix();
                }
                );

	  $('#glasstoplink').click(
		  
                function() {
					createLightbox();
					populateGlassTop();
                    ieWidthFix();
                }
                );

        $('a.enlarge').click(
                function() {
                    var hasScene7 = false;
                    if ($(this).hasClass('has_scene7')) {
                        hasScene7 = true;
                    }
                    createLightbox();
                    populateEnlargeImage(hasScene7);
                    ieWidthFix();
                }
                );

        $('a.enlargeTxtl').click(
                function() {
                    createLightbox();
                    populateEnlargeTextile();
                    ieWidthFix();
                }
                );

        $('a.unsubscribe').click(
                function() {
                    createLightbox();
                    populateUnsubscribe();
                    submitOver();
                    ieWidthFix();
                }
                );

        $('a.quickLook-product').click(
                function() {
                    populateQuicklookProduct($(this).attr('id').substring(3,$(this).attr('id').length));
                }
                );

        $('a.quickLook-textile').click(
                function() {
                    populateQuicklookTextile($(this).attr('id').substring(3,$(this).attr('id').length));
                }
                );



      /*  $('.limitedIcon').hover(
                function() {
                    $(this).next('.limitedCopyHolder').css("display", "block");
                },
                function() {
                    $(this).next('.limitedCopyHolder').css("display", "none");
                }

                );    */

        $('img.definition').mouseout(
                function() {
                    $('#definition-canvas').remove();
                }
                );

        $('#lightbox').add('.lightbox-canvasClose img').click(
                function() {
                    killLightbox();
                }
                );
                
        //E-newsletter dropdown
        var mouseInNewsletterForm = false;
        $('div.e-newsletter-form').hover(function(){ 
            mouseInNewsletterForm = true; 
        }, function(){ 
            mouseInNewsletterForm = false; 
        });

        /*
        $('#newsletter-link').click(function(){
            $("div.e-newsletter-form").slideDown();
        });
        
        $('body').click(function(){
            if (!mouseInNewsletterForm) { $("div.e-newsletter-form").hide(); };
        });
        */
        
        $('#e-newsletter-email').focus(function() {
            if (this.value == 'Email'){
                this.value = '';
            }
            if(this.value != 'Email'){
                this.select();
            }
        });
        $('#e-newsletter-email').blur(function() {
            if ($.trim(this.value) == ''){
                this.value = 'Email';
            }
        });
        
        $('#e-newsletter-submit').click(function(){
            $("#e-newsletter-form .error-message").hide();
            if (isValidEmail($("#e-newsletter-email").val())){
                $("#e-newsletter-form").submit();
            } else {
                $("#e-newsletter-form .error-message").fadeIn();
            }
            
        });
        
        /* CONFIGURABLE PRODUCT JS */
        function isJsonEmpty(jsonObj){
             for(var prop in jsonObj) {
                return false;
            }
            return true;
        }
        
        /* If this is a configurable product, bind events */
        if(typeof productOptions != "undefined" && !isJsonEmpty(productOptions)) {

            var options = $(".prod-option-select").has("option"); 
            var hasOptions = false;
            options.each(function() {
                if ($(this).find("option").size() > 0) {
                    hasOptions = true;
                    $(this).parent(".prod-option").show();
                }
            });

            if (!hasOptions) {
                $("#productDetail").addClass("no-options");
                for (var key in productOptions) {
                    $("#online-price p span").html("$" + productOptions[key].price  + " USD");
                    $("#online-price p").append( productOptions[key].strategy);
                    break;
                }
            }

            options.change(function() {
                $(this).siblings(".product-error-message").remove();
                
                var selectedOption = $(this).attr("name");
                var selectedValue = $(this).val();
                var selectedCombo = getCurrentSelectedOptions();

                // populate the dropdowns
                options.each(function(idx) {
                    $(this).find("option").each(function() {
                        $(this).removeAttr("disabled");
                    });

                    var thisSelect = $(this).attr("name");

                    var matchCombo = {};
                    var matchComboIdx = 0;
                    for (var key in selectedCombo) {
                        if (matchComboIdx == 0) {
                            matchCombo[key] = "*";
                        } 
                        if (matchComboIdx < idx) {
                            if (selectedCombo[key].length > 0) {
                                matchCombo[key] = selectedCombo[key];
                            } else {
                                matchCombo[key] = "";
                            }
                        } 
                        matchComboIdx++;
                    }

                    var matchingOptions = getProductOptions(matchCombo);
                    var availableOptions = {};
                    
                    $.each(matchingOptions, function(matchIdx, matchOption) {
                        availableOptions[matchOption.optionCombo[thisSelect]] = 1;
                    });


                    $(this).find("option").each(function() {
                        if (availableOptions[$(this).attr("value")] == null) {
                            $(this).attr("disabled", "disabled");
                            if ($(this).is(":selected")) {
                                $(this).removeAttr("selected");
                            }
                        }
                    });
                });
                

                // Update the price
                $("#online-price p span").html("$X,XXX USD");
                var currentProduct = getCurrentSelectedProduct();
                if (currentProduct != null) {
                    $("#online-price p span").html("$" + currentProduct.price  + " USD");
                     $("#online-price p").append(currentProduct.strategy);
                }

                // update the swatches
                options.each(function() {
                    var swatches = $(this).siblings(".swatches").find("img");
                    swatches.removeClass("inactive").removeClass("disabled").removeClass("active");

                    $(this).find("option").each(function() {
                        var swatch = null;
                        for (var i = 0; i < swatches.size(); i++) {
                            var colorName = null;
                            var relSplit = $(swatches[i]).attr("rel").split("|");
                            if (relSplit.length > 1) {
                                colorName = relSplit[relSplit.length - 1];
                            }
                            if (colorName == $(this).attr("value")) {
                                swatch = swatches[i];
                            }
                        }
                        if ($(this).attr("disabled") == "disabled") {
                            $(swatch).addClass("disabled");
                        }
                        if ($(this).is(":selected")) {
                            $(swatch).addClass("active");
                        } else {
                            $(swatch).addClass("inactive");
                        }
                    });

                });
            });

            $(".prod-option .swatches img").click(function(){
                var colorName = null;
                var relSplit = $(this).attr("rel").split("|");
                if (relSplit.length > 1) {
                    colorName = relSplit[relSplit.length - 1];
                }
                $(this).parents(".prod-option").find(".prod-option-select").val(colorName).trigger('change');
            });
                        
            $("#product-qty select").change(function(){
                $("#product-qty select").removeClass('invalid');
                $("#product-qty .product-error-message").remove();;
            });
            
            $('#add-to-cart-wrapper a').click(function(){
                var isValid = validateProductConfig();
                if (validateProductConfig()) {
                    updateCartLink();
                    return true;
                } else {
                    return false;
                }
            });

            function getProductOptions(optionCombo) {
                var options = [];

                // productOptions is a global var set in the view
                $.each(productOptions, function(optionIdx, option) {
                    var combo = option.optionCombo;
                    var isMatch = true;
                    for (var key in optionCombo) {
                        if (optionCombo[key] != "*" && optionCombo[key] != combo[key]) {
                            isMatch = false;
                        }
                    }
                    if (isMatch) {
                        options.push(option);
                    }
                });

                return options;
            }

            function getCurrentSelectedOptions() {
                var options = $(".prod-option-select");
                var selectedCombo = {};
                options.each(function() {
                    if ($(this).val() != null && $(this).val().length > 0) {
                        selectedCombo[$(this).attr("name")] = $(this).val(); 
                    }
                });
                return selectedCombo;
            }

            function getCurrentSelectedProduct() {
                var optionCombo = getCurrentSelectedOptions();
                var matchingOptions = getProductOptions(optionCombo);
                if (matchingOptions.length > 0) {
                    return matchingOptions[0];
                }
                return null;
            }
            
            function validateProductConfig(){
                $("#product-addToCart .product-error-message").remove();
                $("#product-addToCart select").removeClass("invalid");
                if ($("#finish-select options").size() > 0 && $("#finish-select").val().length == 0) {
                    $("#finish-options").append("<p class='product-error-message'>Please select a finish</p>");
                    $("#finish-options select").addClass("invalid");
                    return false;
                }
                
                if ($("#textile-select options").size() > 0 && $("#textile-select").val().length == 0) {
                    $("#textile-options").append("<p class='product-error-message'>Please select a textile</p>");
                    $("#textile-options select").addClass("invalid");
                    return false;
                }
                
                if ($("#product-qty select").val().length == 0) {
                    $("#product-qty").append("<p class='product-error-message'>Please specify a quanity</p>");
                    $("#product-qty select").addClass("invalid");
                    return false;
                }
                
                return true;
            };
        
            function updateCartLink(){
                var currentProduct = getCurrentSelectedProduct();
                var baseUrl = "http://order.store.yahoo.net/mcguire-literature/cgi-bin/wg-order?";
                
                var params = {
                    'sectionId' : "ysco.cart",
                    'ysco_key_store_id' : "mcguire-literature",
                    'vwitem' : currentProduct.productNumber,
                    'vwitemCode' : currentProduct.productNumber,
                    'vwquantity' : $("#product-qty select").val(),
                    'vwprice' : currentProduct.price.replace(',',''),
                    'vwname' : '<kohler:textscrubber text="${head}" />'.replace(' ', '+'),
                    '.autodone' : window.location
                }

                $('#add-to-cart-wrapper a').attr("href", baseUrl + $.param(params, true));
            }


            // init on page load
            options.first().trigger("change");
            
        } else {
            $("#product-addToCart").remove();
        }
        
        /* shop by look landing page */
        var lookgroupWidth = $(".look-groups .pages").width();
        var numPages = $(".look-groups .page").size();
        var currentPage = 0;
        $(".look-groups .pages").width(lookgroupWidth * numPages);

        var lbnavTimer = null;
        $(".look-groups .lookbook-nav").hover(function() {
            clearTimeout(lbnavTimer);
            $(this).find("div").fadeIn("fast");
        }, function() {
            clearTimeout(lbnavTimer);
            var that = this;
            lbnavTimer = setTimeout(function() {
                $(that).find("div").fadeOut("fast");
            }, 400);
        });

        $(".look-groups .prev").click(function() {
            var offset = 0 - (currentPage - 1) * lookgroupWidth;
            $(".look-groups .pages").animate({"left": offset + "px"}, "normal");
            currentPage--;

            updateLookbookBtnState();
        });

        $(".look-groups .next").click(function() {
            var offset = 0 - (currentPage + 1) * lookgroupWidth;
            $(".look-groups .pages").animate({"left": offset + "px"}, "normal");
            currentPage++;

            updateLookbookBtnState();
        });

        updateLookbookBtnState();

        function updateLookbookBtnState() {
            $(".look-groups .lookbook-nav").css("display", "");
            $(".look-groups .lookbook-nav div").css("display", "none");
            if (currentPage == 0) {
                $(".look-groups .prev").css("display", "none");
            }
            if (currentPage >= numPages - 1) {
                $(".look-groups .next").css("display", "none");
            }
        }

        
        /* LOOKBOOK */
        if ($(".lookbook-js-flag").length > 0){
            
            var lookJson = {
               "looks_kitchen":[
                      { "imgSrc":"/common/images/store/portrait_large/jaa01106.jpg", "productIds": [ "516", "M-407" ] },
                      { "imgSrc":"/common/images/store/portrait_large/jaa01150.jpg", "productIds": [ "M-405", "O-409" ] },
                      { "imgSrc":"/common/images/store/portrait_large/jaa01153.jpg", "productIds": [ "O-403" ] },
                      { "imgSrc":"/common/images/store/portrait_large/jaa01016.jpg", "productIds": [ "515", "M-402" ] },
                      { "imgSrc":"/common/images/store/portrait_large/jaa01015.jpg", "productIds": [ "O-401" ] },
                      { "imgSrc":"/common/images/store/portrait_large/jaa01148.jpg", "productIds": [ "M-411" ] },
                      { "imgSrc":"/common/images/store/landscape_large/ddd02828-half1.jpg", "productIds": [ "519S", "M-413" ] },
                      { "imgSrc":"/common/images/store/landscape_large/ddd02828-half2.jpg", "productIds": [ "519S", "M-413" ] },  
                      { "imgSrc":"/common/images/store/portrait_large/jaa01010.jpg", "productIds": [ "O-408T" ] }
                ],
               "looks_jacksonsquare":[
                      { "imgSrc":"/common/images/store/portrait_large/zaa53017.jpg", "productIds": [ "JST25", "JSC75" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53026.jpg", "productIds": [ "JST407", "JSC58" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53012.jpg", "productIds": [ "JSL29" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53009.jpg", "productIds": [ "JST95", "JST95T" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53022.jpg", "productIds": [ "JSC300", "JST514" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53024.jpg", "productIds": [ "JST95", "JSL53" ] },
                      { "imgSrc":"/common/images/store/landscape_large/zaa53018-half1.jpg", "productIds": [ "JSC301", "JSC304", "JSC58", "JSC17", "JSC290" ] },
                      { "imgSrc":"/common/images/store/landscape_large/zaa53018-half2.jpg", "productIds": [ "JSC301", "JSC304", "JSC58", "JSC17", "JSC290" ] },  
                      { "imgSrc":"/common/images/store/portrait_large/zaa53028.jpg", "productIds": [ "JST23" ] },

                      { "imgSrc":"/common/images/store/landscape_large/zaa53016-half1.jpg", "productIds": [ "JSC300", "JSC17", "JSC75", "JSC151", "JSC152", "JST22" ] },
                      { "imgSrc":"/common/images/store/landscape_large/zaa53016-half2.jpg", "productIds": [ "JSC300", "JSC17", "JSC75", "JSC151", "JSC152", "JST22" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53021.jpg", "productIds": [ "JSL90" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53010.jpg", "productIds": [ "JSC24", "JST32" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53008.jpg", "productIds": [ "JSL24" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53011.jpg", "productIds": [ "JSC290" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53029.jpg", "productIds": [ "JST33", "JSC301" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53025.jpg", "productIds": [ "JSL28" ] },
                      { "imgSrc":"/common/images/store/portrait_large/zaa53027.jpg", "productIds": [ "JST14", "JSC303" ] }
                ]
            };
            
            var startIdx = 0;
            if (window.location.hash != null && window.location.hash.length > 0){
                startIdx = window.location.hash.replace("#", "").replace("look", "");
                if (!isNaN(startIdx)){
                    startIdx -= 1
                } else { 
                    startIdx = 0;
                }
            }

            var scrollImages = "";
            var looks = lookJson.looks_kitchen;
            if ($(".lookbook-wrapper").hasClass("jacksonsquare")) {
                looks = lookJson.looks_jacksonsquare;
            }

            for (var idx in looks) {
                var look = looks[idx];
                var cssClass = "item";
                if (look.imgSrc.indexOf("half1") > 0) cssClass += " wide1";
                scrollImages += "<li class='" + cssClass + "'><a rel='" + idx + "' href='javascript:void(0);'><span></span><img src='" + look.imgSrc + "' border='0'/></a></li>";
            }
            $("#scrollable ul.items").append(scrollImages);
            
            
            $("#scrollable").jCarouselLite({
                btnNext: "a.next",
                btnPrev: "a.prev",
                visible: 2,
                start: startIdx
            });

            $("#scrollable .items .item a").click(function(){
                $("#scrollable").removeClass("scroll-active");
                if ($(this).offset().left > 300){
                    $("#scrollable a.next").click();
                }
                
                var $prodContainer = $("#product-container");
                $prodContainer.attr("class", "");
                $(".product", $prodContainer).remove();
                var productIds = looks[$(this).attr("rel")].productIds;
                var numberOfProducts = productIds.length;
                
                var params = "";
                $.each(productIds, function(idx,productId){
                    params += "&productNumber=" + productId;
                });
                
                var products = null;
                $.get('productJSON.mcg', params, function(data){
                    products = data.products;
                    
                    populateProducts(0);

                }, 'json');

                var currentSet = 0;
                function populateProducts(startIdx) {
                    $("#product-container .product").remove();
                    var idx = 0;
                    for (var i = 0; i < products.length; i++) {
                        var product = products[(i + startIdx) % products.length];
                        var $productTemplate = $("#product-template").clone();

                        var cssClass = "product";
                        cssClass += idx % 2 == 0 ? " col-left" : " col-right";
                        cssClass += idx % 4 <= 1 && idx < 4 ? " row-top" : "";
                        $productTemplate.addClass(cssClass);
                        $prodContainer.append($productTemplate);

                        if (idx >= 4) {
                            $productTemplate.css("display", "none");
                        }
                        
                        $productTemplate.removeAttr('id');

                        if (i + startIdx >= products.length) {
                            $productTemplate.find("*").css("display", "none");
                            idx++;
                            continue;
                        }

                        
                        if (product.isNew == 'false') {
                            $(".new-product-flag", $productTemplate).remove();
                        }
                        
                        $(".product-image", $productTemplate).attr('src', '/common/images/store/Silhouettes/' + product.imgSrc);
                        $(".product-title a", $productTemplate).html(product.title);
                        $(".product-number", $productTemplate).html("No. " + product.productNumber);
                        $(".product-price", $productTemplate).html("$" + product.price + " USD");
                        
                        var productDetailUrl = "/onlinecatalog/detail.mcg?productNumber=" + product.productNumber + "&sectionNumber=Online+Store";
                        $(".product-detail-link", $productTemplate).attr("href", productDetailUrl);
                        $(".add-to-cart-link", $productTemplate).attr("href", productDetailUrl);
                        
                        $(".quickLook-product", $productTemplate).bind('click', function(){
                            populateQuicklookProduct(product.productNumber); return false;
                        });

                        idx++;
                    }

                    // extra products 
                    if (products.length > 4) {
                        $("#product-container .product:gt(2)").css("display", "none");
                        $("#product-container .product").eq(2).after('<div class="product col-right lookbook-prodlist-nav"><img src="/common/images/lookbook-prodlist-next-off.gif" alt="next" border="0"/></div>');

                        $(".lookbook-prodlist-nav img").hover(function() {
                            $(this).attr("src",$(this).attr("src").replace("-off","-on"));
                        }, function() {
                            $(this).attr("src",$(this).attr("src").replace("-on","-off"));
                        });

                        $(".lookbook-prodlist-nav img").click(function() {
                            currentSet = (currentSet + 1) % Math.ceil(products.length / 3);
                            populateProducts(currentSet * 3);
                        });
                    }
                }

                $prodContainer.addClass("product-count-" + Math.min(4, numberOfProducts));

                  
                $("#product-container").fadeIn('slow', function(){
                    $("#scrollable .border-overlay").show();
                    $("#scrollable a.prev, #scrollable a.next").hide();
                    $("#scrollable a.close").show();
                });
            });
            
            $("#scrollable a.close").click(function(){
                $("#product-container").fadeOut('slow', function(){
                    $("#scrollable .border-overlay").hide();
                    $("#scrollable").addClass("scroll-active");
                    $("#scrollable a.close").hide();
                    $("#scrollable a.prev, #scrollable a.next").show();
                });

            });
        }
        
    })

    $(document).ready(function() {
        $(".pick-fabric-spiff").click(function() {
            var content = $("#lb-spiff-terms").clone();
            $('#lightbox-copy').html(content);
            $('#lightbox-copy #lb-spiff-terms').css("display", "block");
            createLightbox();
        });
    });

})(jQuery);

