/* Utility.js */

jQuery(document).ready(function() {


$('.printCard').click(function() {

$('#printStyles').attr("href","css/printcard.css");
	window.print();
	var t = setTimeout(function() { $('#printStyles').attr("href","css/print.css"); }, 1);
});

    // activate product page 'fakeDD' Sears DHTML
    $('#product .fakeDD').click(function(){
        //console.log('Received click: %o',$(this));
        if ((SEARS.Item) && (typeof SEARS.Item.fakeDDshow === "function")) {
            //console.log('running Sears function fakeDDshow()');
            SEARS.Item.fakeDDshow();
        }
    });
    // display lightbox on page load via query string
    lightboxByQueryString();

	// handles ff2 footer issue
    if ($.browser.mozilla && ($.browser.version < 3)) {
        $('#footer #footerContent ul li.headline').css("background-position", "0 3px !important");
    }

	if ($.browser.safari) { 
		if (!($('#content').hasClass('cclub'))) { $('.my_profile .col_2').css("margin-left","0"); } 
	} 
	
	//fix for dropdown over select boxes.
    $('.sub').bgiframe();
	
    /* for tables matching classname for collapsable behavior, 
       create an instance of CollapsableTable class and load it into
       globally available array */
    CollapsableTables = new Array();
    var tableSelector = '.collapsableTable';
    $(tableSelector).each(function(){
        var newCT = new CollapsableTable({ "tableSelector": tableSelector }); 

        CollapsableTables.push(newCT);
    });
	
	// compare products table	
	if ($('#mainCompareTable').length > 0) {
		
		// get actual width of table
		var tableW = $('#mainCompareTable').width();
		var minTableW = 950;
		
		// # of products = # of td cells outside of headCol
		var products = $('#mainCompareTable tr:first').children("td").length - 1;
		
		// resize other elements relative to length of table
		if ($('#mainCompareTable').width() > 950) {
			
			// count # of cells
			var cells = products + 1;
			// min-width of table is 191*cells + 1px for each td outside of headCol
			var minWidth = (191 * cells) + products;
			
			// add 20px to min-widths due to 10px margin on each side
			$('#header').css("min-width", minWidth+20 );
			$('#sectionImage').css("min-width", (minWidth+20)*1.05 );	// 1.05 is because of the margins outside of container
			$('#breadcrumb').css("min-width", minWidth+20 );
			$('#content').css("min-width", minWidth+20 );
			$('#footer').css("min-width", minWidth+20 );
			$('#footerSponsors').css("min-width", minWidth+20 );
	
        }
		
		// set width of table to 100%
		$('#mainCompareTable').css("width", "100%");
		
		// get width of head column
		var headColWidth = $('#mainCompareTable tr:first td.headCol').width();
		// get % of headCol
		var headColPct = 100 * (headColWidth / minTableW);
		// determine % of other columns
		var tdColPct = (100 - headColPct) / products;
		
		$('#mainCompareTable tr:first td').each(function() {
			
			// assign the width to the first set of td's
			if (!($(this).hasClass("headCol"))) {
				$(this).css("width", tdColPct + "%");
			}
		});
		
		
		$('#showDetails').click(function() {
			$('#mainCompareTable tr.category th').addClass("open");
			if ($.browser.mozilla) {
				$('#mainCompareTable tr.categoryRow').attr("style", "display: table-row;");	
			} else {
				$('#mainCompareTable tr.categoryRow').attr("style", "display: table-row");	
			}
			openCompareRows();
		});
		$('#hideDetails').click(function() {
			$('#mainCompareTable tr.category th').removeClass("open");
			if ($.browser.mozilla ) {
				$('#mainCompareTable tr.categoryRow').attr("style", "display: none;");
			} else {
				$('#mainCompareTable tr.categoryRow').attr("style", "display: none");
			}
		});
		$('#mainCompareTable tr.category th').each(function() {
			$(this).click(function() {
				var _this=$(this);
                var _thisId=_this.attr("id"); 
				
				if (_this.hasClass("open")) {
					if ($.browser.mozilla) {
                		eval("$('."+_thisId+"Child').attr('style','display: none;')");
					} else {
                		eval("$('."+_thisId+"Child').attr('style','display: none')");
					}
					_this.removeClass('open');
				} else {
					if ($.browser.mozilla) {
                		eval("$('."+_thisId+"Child').attr('style','display: table-row;')");
					} else {
                		eval("$('."+_thisId+"Child').attr('style','display: table-row');");
					}
					_this.addClass('open');
				}
				
				openCompareRows();
			});
		});
	}
	
	function openCompareRows() {
		$('#mainCompareTable tr.categoryRow').each(function() {
			
			if ($(this).attr("style") != "display: none;" ||
				$(this).attr("style") != "display: none") {
				$(this).mouseover(function() {
					$(this).addClass("hover");
				});
				$(this).mouseout(function() {
					$(this).removeClass("hover");
				});
			}
		});	
	}
	
	openCompareRows();
	
	// carousel tabs 
	$('.tabs li a').click(function() {
		$('.tabs li').each(function(node) {
			$(this).removeClass("selected");
		});
		$(this.parentNode).addClass("selected");								
	});
	
	// product listing item shown tabs
	$('#subcategory #sortByBar #itemShown ul li a').click(function() {
		$('#subcategory #sortByBar #itemShown ul li a').each(function(node) {
			$(this).removeClass("on");
		});
		$(this).addClass("on");								
	});
	
	// search results item shown tabs 
	$('#searchResults #sortByBar #itemShown ul li a').click(function() {
		$('#searchResults #sortByBar #itemShown ul li a').each(function(node) {
			$(this).removeClass("on");
		});
		$(this).addClass("on");								
	});
	
	// search results item shown tabs 
	$('#searchResults .dlWrap dl dt a').click(function() {
		$('#searchResults .dlWrap dl dt a').each(function(node) {
			$(this.parentNode).removeClass("active");
		});
		$(this.parentNode).addClass("active");								
	});
	
	// product detail color swatches
	$('div.color a').click(function() {
		if ( $(this).html() == "[Edit]" ) {
			$(this).html("[close]");
			$('div.colors').show('blind',{},1000);
		} else {
			$(this).html("[Edit]");
			$('div.colors').hide('blind',{},1000);
		}
	});
	$('div.colors ul li a').click(function() {
		$('div.color span').html($(this).children("img").attr("alt"));
		//$('div.color a').html("[Edit]");
		//$('div.colors').hide('blind',{},1000);
	});


	$('.sendalert .lb_content .lb_inputs a.ok').click(function() {
		hidebox('#lb_sendalert');
		showbox('#lb_sendalertThanks');
	});
	
	// product detail thumbnails 
	$('ul.thumbs li a').click(function() {
									   
		$('ul.thumbs li a').each(function() {
			if ($(this).hasClass("selected")) {
				$(this).removeClass("selected");
			}
		});
									   
		if (!($(this.parentNode).hasClass("video")) || (!($(this.parentNode).hasClass("video-nomsg")))) {
			$('#zoomImg').children("img").attr("src", $(this).children("img").attr("src").replace('hei=64&wid=64','hei=400&wid=400'));
			$('#zoomImg').children("img").attr("height", 400);
			$('#zoomImg').children("img").attr("width", 400);
			
			$(this).addClass("selected");
		}
		return false;
	});
	
	// product detail - no results
	$('#noresults input').click(function() {
		$('#noresults').hide();
		$('#body-curtain').attr("style", "display:none !important");								 
	});
	
    indicatorLoading = new ProgressIndicator({ "overlayEl":"#body-curtain", "progressEl":"div.progress" });
    indicatorProcessing = new ProgressIndicator({ "overlayEl":"#body-curtain", "progressEl":"div.processing" });
	
});
function ProgressIndicator(ArgsObj) {
    /* Argument Defaults */
    var NewArguments = {
        overlayEl: "#body-curtain", 
        progressEl: "div.progress"
    };
    /* Replace Default Args with New Args */
    for (var argName in ArgsObj) {
        NewArguments[argName] = ArgsObj[argName];
    }
    /* Set Properties with Latest Arguments */
    this.overlayEl = NewArguments.overlayEl;
    this.progressEl = NewArguments.progressEl;
    
    /* Other Properties */
    this.active = false;
    
    var self = this;

    this.init = function() {
    }

    this.setupDOM = function() {
        var overlay = self.overlayEl;
        var progress = self.progressEl;
        var className;
        var imgAlt;
        var toAppend = Array();
        var appendStr;

        if ($(self.progressEl).length < 1) {
            if (self.progressEl.indexOf("progress") > 0) {
                className = "progress";
                imgAlt = "loading results...";
                imgUrl = imagePath+"images/img/loader/pre-loader2.gif";
            } else {
                className = "processing";
                imgAlt = "processing in progress...";
                imgUrl = imagePath+"images/img/loader/processing_pre-loader_cman.gif";
            }
            var toAppend = Array(); 
            toAppend.push("<div class=\""+className+"\" style=\"display:none\">");
                toAppend.push("<img alt=\""+imgAlt+"\" src=\""+imgUrl+"\" />");
            toAppend.push("</div>");
            appendStr = toAppend.join('');  
            $('body').prepend(appendStr);
        }

        // reset
        toAppend = Array();
        if ($(self.overlayEl).length < 1) {
            //trim hash from id string if it exists
            var hashPos = self.overlayEl.indexOf("#");
            var leftTrim = (hashPos < 0) ? 0 : hashPos+1;
            var idStr = self.overlayEl.substring(leftTrim);
            toAppend.push("<div id=\""+idStr+"\"></div>"); 
            appendStr = toAppend.join('');  
            $('body').prepend(appendStr);
        }
    }

    this.show = function() {
        var haveProgress = $(self.progressEl).length;
        var haveOverlay = $(self.overlayEl).length;
        if (!(haveProgress && haveOverlay)) {
            self.setupDOM();
        }
        if ($.browser.msie) { // mask select widgets and plug-in UIs
            $(self.overlayEl).show().bgiframe();
        } else {
            $(self.overlayEl).show();
        }
        var newHeight = documentHeight(); // external util 
        $(self.overlayEl).css({ "height" : newHeight });

        $(self.progressEl).show().centerOnScreen();
        self.active = true;
    }

    this.hide = function() {
        $(self.overlayEl).hide();
        $(self.progressEl).hide();
        self.active = false;
    }
    
    this.toggle = function() {
        if (self.active) {
            self.hide();
        } else {
            self.show();
        }
    }

    self.init();
}

function changeLayout(i) {
    var flashWrap = $('#ProductDetailsHolder');
    var flash = $('#ProductDetailsHolder embed');
    if ($(flash).length < 1) {
        flash = $('#ProductDetailsHolder object');
    }
    //document.getElementById("ProductDetailsHolder").style.height = i + "px";
    //window.status = i;
    if ($(flashWrap).length && $(flash).length){
        $(flashWrap).height(i + "px")
        $(flash).height(i + "px")
    }
}


jQuery(function($) {
    var h1 = $('h1');
    if (h1.length) {
	    $(h1).pngfix();		
    }
	
	if ($('#advantage').length) {
		$('#projectEdison span').pngfix();
	}
	
	//inline images with .png class on em.
	var myPngz = $('img.png');
    if (myPngz.length) {
	    $(myPngz).pngfix();
    }

	// CraftsmanClub pngs
	$("#header .logo a img").pngfix();
	$(".firstColTop").pngfix();
	$(".pushpin.left").pngfix();
	$(".pushpin.right").pngfix();
	$(".loginPanelsTop").pngfix();
	$(".loginPanelsBot").pngfix();
	$(".headerCallout img").pngfix();
	$(".facebook a span").pngfix();
	$(".talkForum a span").pngfix();
	$(".virtualcatalog a span").pngfix();
	$("#CraftsmanClubHome .facebook a span").pngfix();
	$(".goldStar").pngfix();
	$(".features.deals h4").pngfix();
	$(".memberHomeFeatures .catalog .view").pngfix();
	$(".memberHomeFeatures .projectEdison a span").pngfix();
	
	$(".facebook a").mouseover(function() {
		$(".facebook a span").css("margin-top","-124px");
});
	$(".facebook a").mouseout(function() {
		$(".facebook a span").css("margin-top","0");								   
	});

	$(".talkForum a").mouseover(function() {
		$(".talkForum a span").css("margin-top","-168px");
	}); 
	$(".talkForum a").mouseout(function() {
		$(".talkForum a span").css("margin-top","0");								   
	});
	
	$(".virtualcatalog a").mouseover(function() {
		$(".virtualCatalog a span").css("margin-top","-127px");										  
	});
	$(".virtualcatalog a").mouseout(function() {
		$(".virtualCatalog a span").css("margin-top","0");										 
	});
	
	$("#CraftsmanClubHome .facebook a").mouseover(function() {
		$("#CraftsmanClubHome .facebook a span").css("margin-top","-128px");
	}); 
	$("#CraftsmanClubHome .facebook a").mouseout(function() {
		$("#CraftsmanClubHome .facebook a span").css("margin-top","0");								   
	});
	
	$(".memberHomeFeatures .projectEdison a").mouseover(function() {
		$(".memberHomeFeatures .projectEdison a span").css("margin-top","-272px");															 
	});
	$(".memberHomeFeatures .projectEdison a").mouseout(function() {
		$(".memberHomeFeatures .projectEdison a span").css("margin-top","0");															 
	});
});

jQuery(document).ready(function() {
	
	var accordionHeight;
	var accordionLinkHeight;
	
	$('#leftCol li.open li a').each(function(node){
		if ($(this).next('ul').length == 0) {
			$(this).css("background-image", "none");
		}
	});


	$('#leftCol li.open div.filters').children('ul').children('li').children('a').click(function() {
		if ($(this).next('ul').length > 0) {
			if ($(this.parentNode).hasClass('open')) {
		        var accordionLinkHeight = $(this).outerHeight();
				//$(this.parentNode).animate({ height: accordionLinkHeight }, 'fast', 'swing', $(this.parentNode).toggleClass('open'));
                $(this).next().hide();
                $(this.parentNode).css({ height:"" });
				$(this.parentNode).toggleClass('open')
			} else {
                var clicked = this;
                $(this).next().show(1,function(){
		            var accordionHeight = $(this).outerHeight();
                    var maxHeight = 200;
                    var openHeight = 0;
                    if (maxHeight > accordionHeight) {
                        openHeight = accordionHeight;
                        $(this).css({ "overflow-y" : "hidden", "overflow-x" : "hidden" });
                    } else {
                        openHeight = maxHeight;
                        $(this).css({ "overflow-y" : "auto", "overflow-x" : "hidden" });
                    }
                    // for IE, set height of parent to opened element + anchor 
                    var parentHeight = $(clicked).outerHeight() + openHeight;
                    $(this.parentNode).height(parentHeight);

                    // set height of opened element to new neight
                    $(this).height(openHeight);
				    $(this.parentNode).addClass('open');
                    //console.log('opening left nav filter group, to height "%s", set parent to "%s"; based on accordionHeight "%s" and maxHeight "%s"',openHeight,parentHeight,accordionHeight,maxHeight);
                    //alert('opening left nav filter group, to height "'+openHeight+'", based on accordionHeight "'+accordionHeight+'" and maxHeight "'+maxHeight+'"');
                });
				//$(this.parentNode).animate({ height: openHeight }, 'fast', 'swing');
			}
		};
		return false;
	});
	

    /* handling a.clearAll click in subcat_Dk.js 
	$('#leftCol .filters a.clearAll').click(function() {
		$(this).nextAll('ul').find('input:checkbox').removeAttr("checked");
		$(".filters .ui-slider").slider('moveTo', sliderStart, 1, true);
		$('.filters div.sliderMax').text( '$' + sliderStart );
		$('.filters div.ui-slider input').val( sliderStart );
		return false;
	}); */

    /* handling filter clear click in subcat_Dk.js
	$('#leftCol .filters a.clear').click(function() {
		$(this).nextAll('ul').find('input:checkbox').removeAttr("checked");
		return false;
	});*/
	if ($(".filters .ui-slider").length > 0 && (location.href.indexOf("#") < 0  || location.href.indexOf("#") >= location.href.length-1)) {
    	init_FilterSlider();
    }
});

function init_FilterSlider() {
    //console.log('extending slider methods for object %o',$.ui.slider);
    // Extend jQuery UI slider since 1.5.3 version does not provide methods
    // we need including a reset. Not upgrading to latest jQuery UI since it requires
    // jQuery 1.3.1, to which Sears cannot upgrade for dependencies on jQuery 1.2.6
    $.extend($.ui.slider.prototype, {
        getMax: function(axis) {
            if (typeof axis === "undefined") {
                axis = "x";
            }
            var options = this.options;
            max = options.max[axis];
            return max;
        },
        setMax: function(newMax,axis) {
            if (typeof axis === "undefined") {
                axis = "x";
            }
            var options = this.options;

            options.max[axis] = newMax;
            options.realMax[axis] = newMax;
            // we want the right handle, which is second in the array 
            if (options.handles[1]) {
                options.handles[1].max = newMax;
                options.handles[1].start = newMax;
            }
            // this.currentHandle is defined only after click in range area, if handle
            // was dragged it will be undefined, so use reference handles property,
            // we want the right handle, which is second in the array 
            var handle = (this.currentHandle) ? this.currentHandle : $(this.handle[1]);
            if (handle.data("mouse").sliderValue[axis]) {
                handle.data("mouse").sliderValue[axis] = newMax;
            }
	        $('.filters div.ui-slider input').val(newMax);

        },
        setRangeValue: function() {
	        var priceWidth =  (3 - ($('.filters div.sliderMax').width() / 2)) + 'px';
	        $('.filters div.sliderMax').css({ left: priceWidth })
        },
        updateDataStore: function() { // set hidden input, based on user action  
            var userValue = $(".filters .ui-slider").slider('value');
	        $('.filters div.ui-slider input').val(userValue);
        },
        updateLabelText: function() {
            var userValue = $(".filters .ui-slider").slider('value');
	        $('.filters div.sliderMax').text( '$' + userValue );
        },
        reset: function(newMax) {
            var max;
            if (newMax) {
                max = newMax;
                this.setMax(max);
            } else {
                max = this.getMax("x");
            }
            //var max = this.getMax("x");

            // this.currentHandle is defined only after click in range area, if handle
            // was dragged it will be undefined, so use reference handles property,
            // we want the right handle, which is second in the array 
            var handle = (this.currentHandle) ? this.currentHandle : $(this.handle[1]);

            this.moveTo(max,handle,true);
            this.updateLabelText();
            this.updateDataStore();
        },
        moveToValue: function(val) {
            var handle = (this.currentHandle) ? this.currentHandle : $(this.handle[1]);
            this.moveTo(val,handle,true);
            this.updateLabelText();
            this.updateDataStore();
        }
    });
    $.ui.slider.getter = "value getMax";

	var sliderStart = $('.filters div.sliderMax').text().replace('$','');

	if ($(".filters .ui-slider").length > 0) {
	
	    FilterSlider = $(".filters .ui-slider").slider({
			animate: false,
			range: true,
			min: 0,
			max: sliderStart,
			handles: [ 
				{start: 0, min: 0, max: 0}, 
				{start: sliderStart, min: 1, max: sliderStart} 
			],
			slide: function(event, ui) {
				//$('.filters div.sliderMax').text( '$' + $(this).slider('value') );
                $(this).slider("updateLabelText");
				//setRangeValue();
				$(this).slider("setRangeValue");
			},
			change: function(event, ui) {
                var userValue = $(this).slider('value');
				//$('.filters div.ui-slider input').val(userValue);
                $(this).slider("updateDataStore");

                /* integrate with Sears filters from subcat_Dk.js */
                if (userValue != sliderStart) {
                    $(".filters .ui-slider").addClass("selected");
                } else {
                    $(".filters .ui-slider").removeClass("selected");
                }
                if($("div.categories ul:eq(0) a.clearAll").length<1){
					$(this).parent().parent().prepend("<a class='clearAll' href='javaScript:;'>Clear All</a>");
					$("div.categories ul:eq(0) a.clearAll").click(clearAll);
				}
				
				/* integrate with Sears filters from subcat_Dk.js */
				lastFilter=lastFilter+",Price:empty";
				if($(this).slider("getMax") != $(this).find("input[type='hidden']").val()) {
					userSelectedPrice = $(this).find("input[type='hidden']").val();
				} else {
					userSelectedPrice = "";
				}
                if (typeof prefilter === "function") {
                	prefilter(); 
                    gotoPage(1);
                    ajaxImpl();
                }
			}
		});

		//setRangeValue();
        $(FilterSlider).slider("setRangeValue");
        $(FilterSlider).slider("updateDataStore");

        //var userValue = $(".filters .ui-slider").slider('value');
	    //$('.filters div.ui-slider input').val(userValue);
	
	}
}

function setRangeValue() {
	var priceWidth =  (3 - ($('.filters div.sliderMax').width() / 2)) + 'px';
	$('.filters div.sliderMax').css({ left: priceWidth })
}

jQuery(document).ready(function() {
    /*
	var selector = '.tabSwitcher dl';
    $(selector).each(function() {
        var tabSwitcher = new TabSwitcher({controlSelector:selector+' dt',tabSelector:selector+' .tab',tabActiveClass:'active',tabHoverClass:'active'});
    }); */

    var controlSelector = '.quickView .tabs li';
    var tabSelector = '.quickView .content > div';
    DocumentTabs = new Array();
    $('.quickView .tabs').each(function(){
        var tabSwitcher = new TabSwitcher({controlSelector:controlSelector,tabSelector:tabSelector,tabActiveClass:'active',tabHoverClass:'active'});
        DocumentTabs.push(tabSwitcher);
    });
	
	var prodControlSelector = '.tabSwitcher dl dt';
	var prodTabSelector = '.tabSwitcher dl dd.tab .firstCol > div';
	$('.dlWrap').each(function(){
        var tabSwitcher = new TabSwitcher({controlSelector:prodControlSelector,tabSelector:prodTabSelector,tabActiveClass:'active',tabHoverClass:'active'});
        DocumentTabs.push(tabSwitcher);
    });

	var prodControlSelector = '.tabSwitcher ul li';
	var prodTabSelector = '.detailContent .firstCol > div';
	$('.prodContent').each(function(){
        /* limit to Product Detail page only, seperate block for Bundle page below */
        if (!$('body').hasClass("collection")) {
            var tabSwitcher = new TabSwitcher({controlSelector:prodControlSelector,tabSelector:prodTabSelector,tabActiveClass:'active',tabHoverClass:'active'});
            DocumentTabs.push(tabSwitcher);
        }
    });

	var prodControlSelector = '.tabSwitcher ul li';
	var prodTabSelector = '.bundleDetail .firstCol > div';
	$('.collection .prodContent').each(function(){
        var tabSwitcher = new TabSwitcher({controlSelector:prodControlSelector,tabSelector:prodTabSelector,tabActiveClass:'active',tabHoverClass:'active'});
        DocumentTabs.push(tabSwitcher);
    });
	
});

var TabSwitcher = function(ArgumentsObj) {
    /* Argument Defaults */
    var NewArguments = {
        controlSelector: false,
        tabSelector: false,
        tabActiveClass: 'tabActive',
        tabHoverClass: 'tabHover'
    };
    /* Replace Default Args with New Args */
    for (var argName in ArgumentsObj) {
        NewArguments[argName] = ArgumentsObj[argName];
    }
    /* Set Properties with Latest Arguments */
    this.controlSelector = NewArguments.controlSelector;
    this.tabSelector = NewArguments.tabSelector;
    this.tabActiveClass = NewArguments.tabActiveClass;
    this.tabHoverClass = NewArguments.tabHoverClass;

    /* Other Properties */
    this.tabControls = new Array();

    this.init = function(){
        var controls = $(self.controlSelector);
        $(controls).each(function(){
            self.tabControls.push({ DOMObj: this, active: false });
        });
        self.tabs = $(self.tabSelector);
        self.registerEvents(); 
        self.showTab(0);
    }
    this.registerEvents = function() {
        //console.log('registerEvents() for object %o',self);
        $(self.tabControls).each(function(index){
            var tC = this;
            $(tC.DOMObj).click(function(){ self.showTab(index); });
            $(tC.DOMObj).mouseover(function(){ $(this).addClass(self.tabHoverClass); });
            $(tC.DOMObj).mouseout(function(){
                /* handle edge case where hover and active class are same name */
                if (self.tabActiveClass === self.tabHoverClass){ 
                    if (tC.active) {
                        /* don't remove the classname, it's the active state */
                    } else {
                        $(this).removeClass(self.tabHoverClass);
                    }
                }
            });
        });
    }
    this.showTab = function(tabRef) {
        var tab = false;
        var tabNumb;
        if (self.isInteger(tabRef)) {
            tabNumb = tabRef;
        } else {
            tabJ = $('.'+tabRef);
            var allTabs = $(tabJ).parent().children();
            $(allTabs).each(function(i){
                if ($(this).hasClass(tabRef)) {
                    tabNumb = i;
                }
            });
        }
        tab = self.tabs[tabNumb];
        //console.log('showTab(): selected tab as "%o"',tab);
        /* only switch if new tab body exists */
        if (tab) {
            self.hideTabs();
            self.tabControls[tabNumb].active = true;
            $(self.tabControls[tabNumb].DOMObj).addClass(self.tabActiveClass);
            $(tab).show();
        }
    }
    this.hideTabs = function() {
        $(self.tabControls).each(function(index) {
            this.active = false;
            $(this.DOMObj).removeClass(self.tabActiveClass);
        });
        $(self.tabs).each(function(index){
            $(this).hide();
        });
    }
    this.isInteger = function(s) {
        return (s.toString().search(/^-?[0-9]+$/) == 0);
    }

    var self = this;
    self.init();
}

function lightboxByQueryString() {
    var self = this;
    self.init = function() {
        /* set properties */
        self.locationStr = window.location.toString();
        self.delimiter = "#";
        self.query = "";
        self.lightboxIDRegex = /^lb_.*?$/;

        /* run methods */
        self.parseQuery();
        self.evaluateQuery();
    }
    self.parseQuery = function() {
        var matchIndex = self.locationStr.lastIndexOf(self.delimiter);
        var queryStr = self.locationStr.substr(matchIndex+1);
        self.query = queryStr;
        //console.log('have query string as "%s", found position of # as "%s", gaining result of "%s"',self.locationStr,matchIndex,queryStr);
    }
    self.evaluateQuery = function () {
        if (self.query.match(self.lightboxIDRegex)) {
            //console.log('have match');
            self.doLightbox();
        }
    }
    self.doLightbox = function() {
        if (typeof showbox === "function") {
            var argString = '#'+self.query;
            showbox(argString);
        }
    }
    
    self.init();
}

// Lightbox
// calculate viewport & offset dimensions
function viewPortHeight() { 
	return self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; }
function viewPortWidth() { 
	return self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;}
function scrollOffsetHeight() { 
	return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;}
function scrollOffsetWidth() { 
	return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;}
function documentHeight() {
    var myHeight = 0;
    if (document.documentElement) {
        myHeight = document.documentElement.scrollHeight;
    } else if (document.body) {
        myHeight = document.documentElement.scrollHeight;
    }
    return myHeight;
}



function showbox(el, returnToQuickView) {
    // el: layout box to show
    // returnToQuickView: Integration with external Sears function,
    //   used for custom flow where we always return to Quick View 
    //   if showbox() has been called from Quick View
    //console.log('showbox("%s",%s)...',el,returnToQuickView);

    // hide any other lightboxes that are showing
	$(".lightbox").hide();		
	// hide zipFinder
	$("#zipFinder").hide();

	// compute the height and width of the overlay
	// $("#overlay").css("height",Math.round($(el).height() + 28));
	// 		$("#overlay").css("width",Math.round($(el).width() + 28));
    var oHeight = documentHeight();
	var oWidth = viewPortWidth();
	$("#overlay").css("height",oHeight);
	//$("#overlay").css("width",oWidth); //set in CSS file
		
    // --- using jQuery .centerOnScreen() after showing, below
	// setup positioning for lightbox (centered)	
    //var leftPos = ( Math.round(viewPortWidth()/2) + scrollOffsetWidth() - Math.round($(el).width()/2) ); 
    //var topPos = ( Math.round(viewPortHeight()/2) + scrollOffsetHeight() - Math.round($(el).height()/2) );
    //console.log('showbox(%o): setting left and top positions as: ("%s","%s")',el,leftPos,topPos);
	//$(el).css("left",leftPos);
	//$(el).css("top",topPos);
		
	// setup positioning for the overlay (centered) 
	// $("#overlay").css("left",Math.round(viewPortWidth()/2) + scrollOffsetWidth() - Math.round($(el).width()/2 + 14));
	// 		$("#overlay").css("top",Math.round(viewPortHeight()/2) + scrollOffsetHeight() - Math.round($(el).height()/2 + 14));	
	$("#overlay").css("left",0);
	$("#overlay").css("top",0);	
	//To hide the alertmessage label inside the overlay
		if(null != document.getElementById("tabular") )
		{
	
		document.getElementById('tabular').style.display="block";
		}
		
		if(null != document.getElementById("popuperrormsg") )
		{
	
		document.getElementById('popuperrormsg').style.display="none";
		}
		
	//To change the values in the textboxes in the overlay to null
	
		if(null != document.getElementById("phno"))
		{		
		document.MemberInfo.phno.value="";
		}
		if(null != document.getElementById("fname"))
		{
		document.MemberInfo.fname.value="";
		}
		if(null != document.getElementById("lname"))
		{
		document.MemberInfo.lname.value="";
		
		}
		
    // based on optional argument, re-open Sears Quick View if it was closed for this showbox()
    if (returnToQuickView) {
        $(el).find('a.close').unbind().click(function(){
            //console.log('doing return to Quick View routines....');
            hidebox(el);
            if ((SEARS.QuickView) && (typeof SEARS.QuickView.launch == "function")) { // external
                SEARS.QuickView.launch();
            }
        });
    } else {
        $(el).find('a.close').unbind().click(function(){
            //console.log('hiding box, no return to Quick View....');
            hidebox(el);
        });
    }
	// show lightbox
	$(el).show().centerOnScreen();
    
	
	// show overlay 
	$("#overlay").show().bgiframe();

}

function hidebox(el, overlay) {
	// hide lightbox
	$(el).hide();
	
	// hide overlay if there is one
	if (overlay == null) {
		$("#overlay").hide();
	}
}

function showpickup(el) {
	$(".lb_inputs").hide();
	$(el).show();
	$("#overlay").css("height",Math.round($(".addtocart").height() + 28));
	$("#overlay").show();
}

// Toggles the shareStory and bookmarks divs on the Product Detail Page

function toggleshare() {
	$(".saveStory").toggle();
	$(".bookmarks").toggle();
	$(".shareItem").toggleClass('active');
}

/* flickr api */
function jsonFlickrApi(rsp) {
 if (rsp.stat != "ok"){
  // If this executes, something broke!
  return;
 }
 
 //variable "s" is going to contain 
 //all the markup that is generated by the loop below
 var s = "";
 
 //this loop runs through every item and creates HTML 
 for (var i=0; i < rsp.photos.photo.length; i++) {
  photo = rsp.photos.photo[ i ];
  
  //notice that "t.jpg" is where you change the
  //size of the image
  t_url = "http://farm" + photo.farm + 
  ".static.flickr.com/" + photo.server + "/" + 
  photo.id + "_" + photo.secret + "_" + "t.jpg";
    
  p_url = "http://www.flickr.com/photos/" + 
  photo.owner + "/" + photo.id;
  
  s +=  '<div class="flickr_badge_image"><a href="' + p_url + '">' + '<img alt="'+ 
  photo.title + '"src="' + t_url + '"/>' + '</a></div>';
 }

 document.writeln(s); 
 //this tells the JavaScript to write 
 //everything in variable "s" onto the page
}
/*Stores or deletes the product details when selected or deselected for Comparing - FROM SEARS*/

function setCheck(box){
 	//If checked

    if(box.checked==true){
    	if(jsonProperties.enableATO_STL == true){
    	    $(box).parent().parent().parent().addClass('selected');
     	}
		else{
	     	box.parentNode.parentNode.parentNode.className="product selected";
		}

		box.parentNode.parentNode.parentNode.className="product selected";
		
        var partNumber = box.name;
        for(i=0;i<partNumberValues.length;i++){
           if(partNumberValues[i]=='' || partNumberValues[i]==null){
               partNumberValues[i]=partNumber;
               break;
        }
    }          

    prodCountCompare++;
    if(prodCountCompare > maxCompares) {
       partNumberValues[--prodCountCompare]='';

       //do not allow to check more than max
       box.checked=false;

       //also remove the css
       if(jsonProperties.enableATO_STL == true){
       	$(box).parent().parent().parent().removeClass('selected');
      	}
      	else{
       	box.parentNode.parentNode.parentNode.className="product";
      	}

       alert("You can compare a maximum of "+maxCompares+" items");
    }

    }else{

        //if unchecked
        prodCountCompare--;
        if(jsonProperties.enableATO_STL == true){
        	$(box).parent().parent().parent().removeClass('selected');
       	}
       	else{
        	box.parentNode.parentNode.parentNode.className="product";       
       	}

		box.parentNode.parentNode.parentNode.className="product";   
		
        var partNumber = box.name;
        for(i=0;i<partNumberValues.length;i++){
            if(partNumberValues[i]==partNumber){
                partNumberValues[i]='';
            }
        }
    }
}


/*When the compare button is clicked - FROM SEARS*/

function compareProducts(){
    var j=0;

    if(prodCountCompare > 1 ){
    	compareParam=compareUrl();
        for(i=0;i<partNumberValues.length;i++) {
            if(partNumberValues[i]!='' && partNumberValues[i]!=null ) {
                j++;
                var temp='&partNumber_'+j+'=';
                compareParam=compareParam+temp+partNumberValues[i];
            }
        }

        compareParam=compareParam+'&prodCount='+j;
        window.location.href=compareParam;
    }
    else{
        alert("You must select atleast 2 items to compare");
    }
}

/* End Compare Products */

// jQuery(function($){
// 	jQuery.fn.imgZoom = function(settings){
// 		settings = jQuery.extend({// Default settings...
// 			container:  'body',
// 			src:		'img/fullsize.jpg',
// 			hideIt:		false
// 		}, settings);
// 		return this.each(function(i){
// 			var set = new Array();
// 			if($(this).is('img')){
// 				set.push(this);
// 			}else{
// 				$(this).find('img').each(function(){
// 					set.push(this);
// 				});
// 			};
// 			$(set).each(function(i){
// 				var global = this;
// 				var zoomtainer = settings.container;
// 				var maxH, maxW, helperHalf, scaleFactor, zoomedSize, helperSize;
// 				var ourSize = { width:$(this).width(), height:$(this).height() };
// 				$(this).wrap('<div class="zzz_imgzoom"/>');
// 				var currentContainer = $(this).parent();
// 				$(currentContainer).css({
// 					width:		$(this).width(),
// 					height:		$(this).height(),
// 					overflow:	'hidden',
// 					position:	'relative'
// 				});
// 				$(zoomtainer).css({
// 					position:	'relative',
// 					overflow:	'hidden'
// 				});
// 				var shade = $('<div class="zzz_shade"/>').css({ 
// 					width:		$(currentContainer).width(),
// 					height:		$(currentContainer).height(),
// 					display:	'none',
// 					position:	'absolute',
// 					top:		0,
// 					left:		0,
// 					background:	'url(img/loading.gif) no-repeat center center #fff',
// 					opacity:	0.75,
// 					filter:		'alpha(opacity=75)'
// 				}).appendTo(currentContainer);;
// 				var helper = $('<div class="zzz_imghelper"/>').css({
// 					border:		'1px solid #fff',
// 					background:	'url('+$(this).attr('src')+') no-repeat -1px -1px #fff',
// 					display:	'none',
// 					position:	'absolute',
// 					top:		0,
// 					left:		0
// 				}).appendTo(currentContainer);;
// 				var zoomed = $('<div class="zzz_zoomed"/>').hide().css({
// 					overflow:	'hidden', 
// 					background:	'url(img/loading.gif) center center no-repeat #fff',
// 					position:	'absolute',
// 					height:		$(zoomtainer).height(),
// 					width:		$(zoomtainer).width(),
// 					top:		$(zoomtainer).css('padding-top'),
// 					left:		$(zoomtainer).css('padding-left')
// 				}).appendTo(zoomtainer);
// 				
// 				$(currentContainer).unbind().hover(function(){
// 					$(shade).fadeIn(200);
// 					$(helper).fadeIn(200);
// 					$(zoomed).fadeIn(200);
// 					if(settings.hideIt){
// 						$(zoomtainer).show()
// 					}
// 				},function(){
// 					$(shade).fadeOut(200);
// 					$(helper).fadeOut(200);
// 					$(zoomed).fadeOut(200);
// 					if(settings.hideIt){
// 						$(zoomtainer).hide()
// 					}
// 				});
// 				var zoomedImg = new Image();
// 				zoomedImg.onload = function(){
// 					zoomedSize = { width:zoomedImg.width, height:zoomedImg.height };
// 					scaleFactor = { x:(zoomedSize.width/ourSize.width), y:(zoomedSize.height/ourSize.height) };
// 					helperSize = {
// 						height: Math.round($(zoomtainer).height()/scaleFactor.y),
// 						width:	Math.round($(zoomtainer).width()/scaleFactor.x)
// 					};
// 					$(helper).css({width:helperSize.width+'px', height:helperSize.height+'px'});
// 					maxH =	$(global).height()-$(helper).height();
// 					maxW =	$(global).width()-$(helper).width();
// 					helperHalf = {width: ($(helper).width()/2), height: ($(helper).height()/2)};
// 					$(zoomed).css({
// 						background:	'url('+this.src+') no-repeat 0 0 #fff'
// 					});
// 					$(shade).css({
// 						backgroundImage:	'none', 
// 						opacity: 			0.75, 
// 						filter:				'alpha(opacity=75)', 
// 						background:			'#ccc'
// 					});
// 					var us = {width: $(global).width(), height: $(global).height(), top: $(global).offset().top, left: $(global).offset().left}
// 					$(currentContainer).unbind().hover(function(){
// 						$(shade).fadeIn(200);
// 						$(helper).fadeIn(200);
// 						$(zoomed).fadeIn(200);
// 						if(settings.hideIt){
// 							$(zoomtainer).show()
// 						}
// 					},function(){
// 						$(shade).fadeOut(200);
// 						$(helper).fadeOut(200);
// 						$(zoomed).fadeOut(200);
// 						if(settings.hideIt){
// 							$(zoomtainer).hide()
// 						}
// 					}).mousemove(function(e){
// 						var us = {width: $(global).width(), height: $(global).height(), top: $(global).offset().top, left: $(global).offset().left}
// 						var top =	(e.pageY - us.top) - helperHalf.height;
// 						var left =	(e.pageX - us.left) - helperHalf.width;
// 						var nleft = left > maxW ? maxW : left < 0 ? 0 : left;
// 						var ntop = top > maxH ? maxH : top < 0 ? 0 : top;
// 						$(zoomed).css({
// 							backgroundPosition: '-'+(nleft*scaleFactor.x)+'px -'+(ntop*scaleFactor.y)+'px'
// 						})
// 						$(helper).css({
// 							top:	ntop,
// 							left:	nleft,
// 							backgroundPosition: '-'+(nleft+1)+'px -'+(ntop+1)+'px'
// 						});
// 					});
// 				};
// 				zoomedImg.src = settings.src;
// 			});
// 		}); 
// 	};
// });
// 
// $(document).ready(function() {
// 	$('#zoomImg').children('img').each(function(){
// 		var srcFile = $(this).attr('src').replace('.jpg','.large.jpg');
// 		$(this).imgZoom({container:'.ztBucket', src:srcFile, hideIt:true});
// 	});					   
// });



	
	

