﻿/* SITE-WIDE SCRIPTS */

/* Miscellaneous */

tabClicked = function (tabObj, tabContentPrefixId) {
    var parsed = tabObj.id.split("_");
    var tabSet = parsed[0] + "_";
    var selectedTab = parsed[1];
    var tabNum = 0;
    // set all tabs as unselected
    while (document.getElementById(tabSet.concat(tabNum))) {
        document.getElementById(tabSet.concat(tabNum)).className = "tab";
        tabNum++;
    };
    // set selected tab
    document.getElementById(tabSet.concat(selectedTab)).className = "tab selected";
    document.getElementById(tabObj.id).blur();
    // set tab contents
    if (tabContentPrefixId) {
        var tabContentSet = tabContentPrefixId + "_";
        var tabContentNum = 0;
        // set all content as hidden
        while (document.getElementById(tabContentSet.concat(tabContentNum))) {
            $j('#' + tabContentSet.concat(tabContentNum)).hide();
            tabContentNum++;
        };
        // show selected content
        $j('#' + tabContentSet.concat(selectedTab)).show();

    }
    return false;
};

/* PDP methods */
function openPrintPage(basePath, catalogQueryKey, catalog, productIdQueryKey, productId, variantIdKey) {
    var variantId = $j('select[name*="VariantPicker"]').attr("value");
    var location = basePath + "?" + catalogQueryKey + "=" + catalog + "&" + productIdQueryKey + "=" + productId + "&" + variantIdKey + "=" + variantId;
    // alert(location);
    window.open(location, "", "scrollbars = yes, location = no, menubar = no, width = 650"); //"menubar=1,resizable=1,width=650"); //"scrollbars=yes,location=no,menubar=no,width=650");
    return false;
}

/* Cart methods */

function DisableCheckout(evt) {
    var key = (window.Event) ? evt.which : evt.keyCode;
    MarkChange();
    if (key == 13) {
        return false;
    }
    else {
        $j('#CartContentsHasChanged').show();
    }
    return true;
}

function MarkChange() {
    var elements = document.getElementsByTagName('*');
    for (var i = 0; i < elements.length; i++) {
        var id = elements[i].getAttribute('id');
        if (id != null && (id.match('updateRequired') != null)) {
            var updateRequired = document.getElementById(id);
            updateRequired.value = '1';
        }
    }
}

/* jQuery */

var $j = jQuery.noConflict();

// Reassign jQuery back to telerik is dependant on 1.4.2
$telerik.$ = $j;

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

/* jQuery extensions */

jQuery.fn.placeholder = function (settings) {
    settings = settings || {};
    var placeholderKey = settings.dataKey || "placeholderValue";
    var attr = settings.attr || "placeholder";
    var className = settings.className || "placeheld";
    var value = settings.value || "";
    var submitElement = settings.submitElement || jQuery(this).siblings("a");
    var postBackHref = new Array();

    return this.filter(":input").each(function (index) {
        jQuery.data(this, placeholderKey, jQuery(this).attr(attr));
    }).each(function () {
        if (jQuery.trim(jQuery(this).val()) === "")
            jQuery(this).addClass(className).val(jQuery.data(this, placeholderKey));
    }).focus(function () {
        if (jQuery.trim(jQuery(this).val()) === jQuery.data(this, placeholderKey))
            jQuery(this).removeClass(className).val(value)
    }).blur(function () {
        if (jQuery.trim(jQuery(this).val()) === value)
            jQuery(this).addClass(className).val(jQuery.data(this, placeholderKey));
    }).each(function (index, elem) {
        postBackHref[index] = jQuery(elem).siblings("a").attr("href");
        jQuery(elem).bind("keypress", function (e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (code == 13) {
                if (jQuery.trim(jQuery(elem).val()) === jQuery.data(elem, placeholderKey) || jQuery.trim(jQuery(elem).val()) === "") {
                    jQuery(elem).siblings("a").attr("href", "javascript:void(0);");
                } else {
                    jQuery(elem).siblings("a").attr("href", postBackHref[index]);
                }
            }
        });
        jQuery(elem).siblings("a").hover(function () {
            if (jQuery.trim(jQuery(elem).val()) === jQuery.data(elem, placeholderKey) || jQuery.trim(jQuery(elem).val()) === "") {
                jQuery(elem).siblings("a").attr("href", "javascript:void(0);");
            } else {
                jQuery(elem).siblings("a").attr("href", postBackHref[index]);
            }
        });
    });
};

jQuery.fn.equalHeight = function () {
    var height = 0;
    var maxHeight = 0;

    // Store the tallest element's height
    this.each(function () {
        height = jQuery(this).outerHeight();
        maxHeight = (height > maxHeight) ? height : maxHeight;
    });

    // Set element's min-height to tallest element's height
    return this.each(function () {
        var t = jQuery(this);
        var minHeight = maxHeight - (t.outerHeight() - t.height());
        var property = jQuery.browser.msie && jQuery.browser.version < 7 ? 'height' : 'min-height';
        t.css(property, minHeight + 'px');
    });
};

$j(document).ready(function () {
    /* Sets the top nav */
    $j("#topnav ul li:last-child").addClass("last");
    /* Set product blocks height for a first time */
    setEqualHeight(".wp-product-query .product .top");
    //setEqualHeight(".wp-product-query .product .top h3");
    setEqualHeight(".wp-product-query .product .content");
    setEqualHeight(".review-blocks > div");
});

/* Set product blocks height after content is fully loaded */
jQuery(window).load(function () {
    setEqualHeight(".wp-product-query .product .top");
    setEqualHeight(".wp-product-query .product .content");
});

hideCheckoutH1 = function () {
    $j(document).ready(function () {
        $j(".checkout-progress").parents("#inner-content").children("div.primary-title-bar").addClass("hidden");
    });
};

setEqualHeight = function (selector) {
    $j(document).ready(function () {
        $j(selector).equalHeight();
    });
};

// Combined method for fixing product images, all standard sizes.
fixBrokenProductImages = function () {
    $j(window).bind("load", function () {
        //$j('img.highslide-image').addClass('product-image-xl'); // main image
        //$j('.highslide-thumbstrip-inner img').addClass('product-image-s'); // all thumbnails
        fixBrokenProductImagesBySize('s');
        fixBrokenProductImagesBySize('m');
        fixBrokenProductImagesBySize('l');
        fixBrokenProductImagesBySize('xl');
    });
};

// Single method for fixing product images.
// Size is specified by passed param.
fixBrokenProductImagesBySize = function (imageSize) {
    $j('.product-image-' + imageSize).each(function () {
        if (!this.complete || ((!$j.browser.msie && !$j.browser.opera) && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0))) {
            this.src = "/publishingImages/Images/common/pictures/image-not-available-" + imageSize + ".png";
            if (imageSize == 'l') {
                $j(this).parent().attr("href", "/publishingImages/Images/common/pictures/image-not-available-xl.png");
            }
        }
    });

    $j('.department-image-' + imageSize).each(function () {
        if (!this.complete || ((!$j.browser.msie && !$j.browser.opera) && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0))) {
            this.src = "/publishingImages/Images/common/pictures/department-image-not-available-" + imageSize + ".png";
        }
    });
};

// Read the page's <meta http-equiv="content-language" content="fr-ca" />,
// return the value of "content" in lowercase
getMetaContentLanguage = function () {
    if ($j("meta[http-equiv='content-language']").attr("content")) {
        return $j("meta[http-equiv='content-language']").attr("content").toLowerCase();
    } else {
        //IE will not read tag properties that are hyphenated (e.g. "http-equiv").
        //Had to add <meta name="content-language" content="fr-ca" /> just for IE.
        var m = document.getElementsByTagName('meta');
        for (var i in m) {
            if (m[i]["name"] && m[i]["name"].toLowerCase() === "content-language") {
                return m[i]["content"].toLowerCase();
                break;
            };
        };
    };
};

// Set language of datepickers if not default English US/Canada.
// Set misc options, such as adding a clickable calendar icon.
// Set date format as per passed "options" arguments.
initJqueryUiDatepicker = function (options) {
    var culture, script, o, x;

    // Load the datepicker's language as JS file, if it's not the default "en-us".
    culture = getMetaContentLanguage();
    if (!(culture === "en-us" || culture === "en-ca")) {
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = cdnUrlScripts + "/Style Library/JS/jquery.ui.datepicker-" + culture + ".js";
        // note: std $j methods not working when adding script to page
        document.getElementsByTagName('head')[0].appendChild(script);
    };

    // When document is ready, init the datepicker's options
    $j(document).ready(function () {
        // set default options
        o = {
            showOn: "both",
            buttonImage: "/PublishingImages/Images/common/buttons/calendar.gif",
            buttonImageOnly: true,
            buttonText: "Choose"
        };

        // copy any options that may have been passed
        if (typeof options !== "undefined") {
            for (x in options) { o[x] = options[x] };
        };

        $j("input.ui-datepicker").datepicker(o);
    });
};

// Pass the date in the format of "mm/dd/yy" (US standard, see also http://docs.jquery.com/UI/Datepicker/formatDate)
setJqueryUiDatepickerDefaultDate = function (selector, date, options) {
    var dateFormat = $j(selector).datepicker("option", "dateFormat"); // cache the current date format

    $j(selector).datepicker("option", "dateFormat", "mm/dd/yy"); // set the date format to a known format
    $j(selector).datepicker("setDate", date); // set the date
    $j(selector).datepicker("option", "dateFormat", dateFormat); // return the date format to it's original setting
};

// Pass the .Net date format, return the jQuery date format.
// Works for long and short dates.
mapDotNetDateToJqueryDate = function (format) {
    format = format.toLowerCase();

    //Day
    if (format.indexOf('dddd') > -1) {
        format = format.replace(/dddd/, 'DD');
    } else if (format.indexOf('ddd') > -1) {
        format = format.replace(/ddd/, 'D');
    } else if (format.indexOf('dd') > -1) {
        format = format.replace(/dd/, 'dd');
    } else if (format.indexOf('d') > -1) {
        format = format.replace(/d/, 'd');
    };

    //Month
    if (format.indexOf('mmmm') > -1) {
        format = format.replace(/mmmm/, 'MM');
    } else if (format.indexOf('mmm') > -1) {
        format = format.replace(/mmm/, 'M');
    } else if (format.indexOf('mm') > -1) {
        format = format.replace(/mm/, 'mm');
    } else if (format.indexOf('m') > -1) {
        format = format.replace(/m/, 'm');
    };

    //Year
    if (format.indexOf('yyyy') > -1) {
        format = format.replace(/yyyy/, 'yy');
    } else if (format.indexOf('yy') > -1) {
        format = format.replace(/yy/, 'y');
    };

    return (format);
};

// Sets the default values for Order History's date fields, but only if fields are empty.
initOrderHistoryDatepickers = function (shortDate) {

	shortDate = mapDotNetDateToJqueryDate(shortDate);

	initJqueryUiDatepicker({ dateFormat: shortDate, beforeShowDay: $j.datepicker.noWeekends});

	$j(document).ready(function () {
		var d, today, month, year, options;

		if ($j(".datepicker-from").val() === "" || $j(".datepicker-to").val() === "") {
			d = new Date();
			today = d.getDate();
			month = d.getMonth() + 1;
			year = d.getFullYear();

			if ($j(".datepicker-from").val() === "") {
				setJqueryUiDatepickerDefaultDate(".datepicker-from", "1/1/" + (year - 1)); // i.e. "1/Jan/last year"
			};
			if ($j(".datepicker-to").val() === "") {
				setJqueryUiDatepickerDefaultDate(".datepicker-to", month + "/" + today + "/" + year); // i.e. "today"
			};
		};
	});
};
initAutoReorderDatepickers = function (shortDate) {

	shortDate = mapDotNetDateToJqueryDate(shortDate);


	$j(document).ready(function () {
		initJqueryUiDatepicker({ dateFormat: shortDate, beforeShowDay: $j.datepicker.noWeekends, minDate: +1 });
	});
};

/* 
Currently only used on product comparison page 
To enable, change any <tr> to <tr class="collapse-if-empty">
*/

collapseTableRowIfEmpty = function () {
    $j(document).ready(function () {
        if ($j("table tr.collapse-if-empty")) {
            var td, tdContentCount;
            $j.each($j("table tr.collapse-if-empty"), function () {
                td = $j(this).find("td");
                if (td.length > 0) {
                    tdContentCount = 0;
                    $j.each(td, function () {
                        if (($j(this).text()).replace(/[\s\xA0]+/g, "") != "" || $j(this).find("img").length > 0)
                            tdContentCount++;
                    });
                    if (tdContentCount == 0)
                        $j(this).css({ display: "none" });
                }
            });
        };
    });
};


// jQuery-UI Dialog
// default settings and some automated code generation
CcDialog = {
	openIframe: function (url, options) {
		var c, d, o, winHeight;
		var winHeight = this._getWindowHeight();
		this._destroy(); // just in case

		this._createHTML('iframe');
		d = $j('#' + this._widgetID);
		c = $j('#' + this._widgetID + '-iframe'); // returns reference to dialog box's content container (iframe)
		d.css({ 'padding': '0' }); // remove padding from around iframe parent

		// copy passed options to default options
		options = options || {}; // if options = null, then init as empty object
		o = this._copyOptions(options);

		// init dialog box
		d.dialog(o);
		this.show();
		AjaxLoader.show();

		// load iframe contents
		c.attr("src", url);

		// callback after the iframe has loaded
		c.load(function () {
			$j("#ajax-loader").hide(500, function () {
				// set the height of the dialog to the height of the contents of the iframe
				// note: getting the outerHeight(true) does include margin, border and padding
				var h = Math.min(winHeight, c.contents().find(".wrapper").outerHeight(true));

				//d.dialog('option', 'height', h);
				$j(".ui-dialog").animate({ top: eval((($j(window).height() + ($j(window).scrollTop() * 2)) - h) / 2) });

				d.animate({ height: h }, function () {
					// recenter after loading content
					//d.dialog('option', 'position', 'center');
					c.animate({ opacity: 1 });
				});
				c.css("height", "100%");
			});
		});

		return { dialogBox: d, dialogContent: c };
	},
	openContent: function (url, options) {
		var c, d, o;
		var winHeight = this._getWindowHeight();
		this._destroy(); // just in case

		this._createHTML('content');
		d = $j('#' + this._widgetID);
		c = $j('#' + this._widgetID + '-content'); // returns reference to dialog box's content container (div)

		// copy passed options to default options
		options = options || {}; // if options = null, then init as empty object
		o = this._copyOptions(options);

		// init dialog box
		d.dialog(o);
		this.show();
		AjaxLoader.show();
		c.hide();

		// load the html and on callback...

		c.load(unescape(url), function () {
			$j("#ajax-loader").hide(500, function () {
				// set the height of the dialog to the height of the contents of the iframe
				// note: getting the outerHeight(true) does include margin, border and padding
				var h = Math.min(winHeight, c.outerHeight(true));
				//d.dialog('option', 'height', h);
				if (c.height() > d.height()) {
					$j(".ui-dialog").animate({ top: eval((($j(window).height() + ($j(window).scrollTop() * 2)) - h) / 2) });
				}
				d.animate({ height: h }, function () {
					// recenter after loading content
					//d.dialog('option', 'position', 'center');
					c.fadeIn();
				});
			});
		});

		return { dialogBox: d, dialogContent: c };
	},
	openEmbedded: function (name, options) {
		var c, d, o;
		var winHeight = this._getWindowHeight();
		this._destroy(); // just in case

		this._createHTML('content');
		d = $j('#' + name);
		c = $j('#' + name + '-content'); // returns reference to dialog box's content container (div)

		$j('#' + name).clone().insertAfter('#' + name).attr('id', name + '-dupe');

		// copy passed options to default options
		options = options || {}; // if options = null, then init as empty object
		o = this._copyOptions(options);

		//try this
		o.close = function () {
			var originalId = this.id;
			var dupedElement = $j('#' + this.id + '-dupe');
			$j('#' + this._widgetID).remove();
			$j('#' + this.id).remove();
			dupedElement.attr('id', originalId);
		}

		// init dialog box
		d.dialog(o);
		this.show();

		// set the height of the dialog to the height of the contents of the iframe
		// note: getting the outerHeight(true) does include margin, border and padding
		var h = Math.min(winHeight, d.outerHeight(true));
		d.dialog('option', 'height', h+30);
//		if (c.height() > d.height()) {
//			$j(".ui-dialog").animate({ top: eval((($j(window).height() + ($j(window).scrollTop() * 2)) - h) / 2) });
//		}
//		d.animate({ height: h }, function () {
//			c.fadeIn();
//		});

		return false;
	},
	confirm: function (ref, obj, options) {
		var c, d, o;
		var OK = "OK", Cancel = "Cancel";
		this._destroy(); // just in case

		this._createHTML('content');
		d = $j('#' + this._widgetID);
		c = $j('#' + this._widgetID + '-content'); // returns reference to dialog box's content container (div)

		// override default "OK" and "Cancel" buttons
		if (typeof (obj.OK) != 'undefined') {
			OK = obj.OK;
		}
		if (typeof (obj.Cancel) != 'undefined') {
			Cancel = obj.Cancel;
		}

		// copy passed options to default options
		options = options || {}; // if options = null, then init as empty object
		//options.modal = false;
		options.buttons = {};
		options.buttons[Cancel] = function () { CcDialog.close(); };
		if (obj.callback != undefined) {
			options.buttons[OK] = obj.callback;
		} else {
			options.buttons[OK] = function () { document.location = ref.href; };
		}

		o = this._copyOptions(options);

		// init dialog box
		c.append(obj.msg);
		d.dialog(o);
		this.show();

		// update "<button>text" to "<button><span><span>text" to allow for future styling
		$j('.ui-dialog-buttonpane button').wrapInner('<span class="outer"><span class="inner"></span></span>');

		//return false; // doesn't work, needs to be explicitly added after calling CcDialog.confirm(), e.g. onclick="CcDialog.confirm(...); return false;"
	},
	show: function (showNow) {
		if (showNow) {
			$j('.ui-widget-overlay').stop().show();
			$j('.ui-dialog').stop().show();
		} else {
			if ($j('.ui-widget-overlay').length != 0) {
				$j('.ui-widget-overlay').stop().css('opacity', 0.01); // don't use ".stop().hide();", as it may break the UI
				$j('.ui-dialog').stop().css('opacity', 0.01);
				$j('.ui-widget-overlay').fadeTo("slow", 0.6);
				$j('.ui-dialog').fadeTo("slow", 1);
			} else {
				$j('.ui-dialog').stop().css('opacity', 0.01);
				$j('.ui-dialog').fadeTo("slow", 1);
			}

		};
	},
	close: function () {
		CcDialog._destroy();
		return false;
	},
	_widgetID: 'cc-dialog',
	_defaultOptions: {
		close: function () { CcDialog._destroy() },
		closeOnEscape: true,
		draggable: false,
		height: 'auto',
		modal: true,
		autoResize: true,
		resizable: false,
		width: 620,
		open: function () { $j(this).parent().appendTo("form") }
	},
	_destroy: function () {
		$j('#' + this._widgetID).remove();
	},
	_createHTML: function (contentType) {
		if (contentType === 'iframe') {
			// create this string » <div id="cc-dialog"><iframe id="cc-dialog-iframe" frameborder="0" /></div>
			$j('<div id="' + this._widgetID + '"><iframe id="' + this._widgetID + '-iframe" frameborder="0" /></div>').appendTo('form');
		} else {
			// create this string » <div id="cc-dialog"><div id="cc-dialog-content"></div></div>
			$j('<div id="' + this._widgetID + '"><div id="' + this._widgetID + '-content"></div></div>').appendTo('form');
		}
	},
	_copyOptions: function (options) {
		var o = {};
		// copy default options
		for (var i in this._defaultOptions) {
			o[i] = this._defaultOptions[i];
		};
		// copy user options
		for (var i in options) {
			o[i] = options[i];
		};
		// return copy
		return o;
	},
	_getWindowHeight: function () {
		return ($j(window).height() - 60);
	}
};

// Applies to CcDialog object
$j(document).ready(function () {
	$j('.cc-dialog-iframe').live("click", function (e) {
		e.preventDefault();
		CcDialog.openIframe($j(this).attr('href'));
	});

	$j('.cc-dialog-iframe-create-wishlist').live("click", function (e) {
		e.preventDefault();
		CcDialog.openIframe($j(this).attr('href'), { width: 490, modal: true });
	});

	$j('.cc-dialog-iframe-finder').live("click", function (e) {
		e.preventDefault();
		CcDialog.openIframe($j(this).attr('href'), { width: 200 });
	});

	$j('.cc-dialog-content').live("click", function (e) {
		e.preventDefault();
		CcDialog.openContent(this.href);
	});

	$j('.cc-dialog-embedded').live("click", function (e) {
		e.preventDefault();
		CcDialog.openEmbedded(this.name);
	});

	$j('.cc-dialog-iframe-tell-friend').live("click", function (e) {
		e.preventDefault();
		CcDialog.openIframe($j(this).attr('href'), { width: 490 });
	});
});

// Applies to CcDialog object
AjaxLoader = {
    show: function () {
        $j('<img id="ajax-loader" src="/PublishingImages/Images/common/pictures/ajax-loader.gif" />').appendTo("#cc-dialog");
    },
    hide: function () {
        $j("#ajax-loader").remove();
    }
};



// Applies to Extended Mini-Cart
$j(document).ready(function () {
    $j(".close-flyout").click(function () {
        $j("#cartFlyout").clearQueue()
        $j("#cartFlyout").fadeOut(500);
    });
    $j(".mini-cart-title").mouseover(function () {
        $j('#cartFlyout').fadeIn(500);
        $j('#cartFlyout').mouseleave(function () {
            $j('#cartFlyout').fadeOut(500);
        })
    });
});

function miniCartHandles() {
    $j(document).ready(function () {
        $j(".close-flyout").click(function () {
            $j("#cartFlyout").clearQueue()
            $j("#cartFlyout").fadeOut(500);
        });
        $j(".mini-cart-title").mouseover(function () {
            $j('#cartFlyout').fadeIn(500);
            $j('#cartFlyout').mouseleave(function () {
                $j('#cartFlyout').fadeOut(500);
            })
        });
    });
}


$j(document).ready(function () {
    // Applies to SignIn Flyout
    $j(".close-flyout").click(function () {
        $j("#signInFlyout").clearQueue()
        $j("#signInFlyout").fadeOut(500);
    });
    $j(".sign-in-title").mouseover(function () {
        $j('#signInFlyout').fadeIn(500);
        $j('#signInFlyout').mouseleave(function () {
            $j('#signInFlyout').fadeOut(500);
        })
    });
    // Applies to custom flyouts
    ShowFlyout._bind();
});

/* CUSTOM FLYOUT */

/* Center element on the page */
/* e.g. $j(element).center(); */
jQuery.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", (($j(window).height() - this.outerHeight()) / 2) + $j(window).scrollTop() + "px");
    this.css("left", (($j(window).width() - this.outerWidth()) / 2) + $j(window).scrollLeft() + "px");
    return this;
}

ShowFlyout = {
    _bind: function () {
        $j('.show-custom-flyout').click(function (e) {
            var obj = $j('#' + this.name);
            obj.prepend('<div class="custom-flyout-header"><a name="' + this.name + '" class="close-custom-flyout"></a></div>');
            CloseFlyout._bind();
            FlyoutOverlay._show();
            obj.center();
            obj.fadeIn(600);
        });
    },
    _forceshow: function (flyoutid) {
        var obj = $j('#' + flyoutid);
        obj.prepend('<div class="custom-flyout-header"><a name="' + this.name + '" class="close-custom-flyout"></a></div>');
        CloseFlyout._forceclose(flyoutid);
        FlyoutOverlay._show();
        obj.center();
        obj.fadeIn(600);
    }
};
CloseFlyout = {
	_bind: function () {
		$j('.close-custom-flyout').click(function (e) {
			$j(this).parents(".custom-flyout").find(".to-clear").val("");
			var obj = $j('#' + this.name);
			$j('.custom-flyout-header').remove();
			obj.hide();
			FlyoutOverlay._hide();
		});
	},
	_forceclose: function (flyoutid) {
		$j('.close-custom-flyout').click(function (e) {
			$j(this).parents(".custom-flyout").find(".to-clear").val("");
			var obj = $j('#' + flyoutid);
			$j('.custom-flyout-header').remove();
			obj.hide();
			FlyoutOverlay._hide();
		});
	}
};
FlyoutOverlay = {
    _show: function () {
        // create / show flyout overlay
        $j('<div class="flyout-overlay" />').appendTo('body');
    },
    _hide: function () {
        // remove flyout overlay
        $j('.flyout-overlay').remove();
    }
};
/* // */

// Applies to FAST Search LeftNav
(function ($) {
$.belowthefold = function (element, settings) {
var fold = $(window).height() + $(window).scrollTop();
return fold <= $(element).offset().top + settings.threshold;
};
$.extend($.expr[':'], {
"below-the-fold": function (a, i, m) {
return $.belowthefold(a, { threshold: eval($j(".ms-searchref-main div.nav-1").last().outerHeight(true) + 35) });
}
});
})(jQuery);
$j(document).ready(function () {
var count = $j(".filtered-nav input:checkbox:checked").length;
var lastCat = $j(".ms-searchref-main div.nav-1").last();
var lastCatHeight = $j(".ms-searchref-main div.nav-1").last().outerHeight(true);
if (count >= 1) {
$j(".refine-results").css("bottom", 0);
} else {
$j(".refine-results").css("bottom", -30);
}
if (count >= 1) {
if ($j(lastCat).is(":below-the-fold")) {
$j(".refine-results").removeClass("locked");
} else {
$j(".refine-results").addClass("locked");
}
}
$j(".show-more, .show-less").click(function () {
if (count >= 1) {
if ($j(lastCat).is(":below-the-fold")) {
$j(".refine-results").removeClass("locked");

} else {
$j(".refine-results").addClass("locked");
}
}
});

$j(".filtered-nav input:checkbox").click(function () {
count = $j(".filtered-nav input:checkbox:checked").length;
if (count >= 1) {
if ($j(lastCat).is(":below-the-fold")) {
$j(".refine-results").animate({ bottom: "0px" }, 500);
} else {
$j(".refine-results").addClass("locked");
$j(".refine-results").css("bottom", 0);
}
} else {
if ($j(lastCat).is(":below-the-fold")) {
$j(".refine-results").animate({ bottom: "-30px" }, 500);
} else {
$j(".refine-results").removeClass("locked");
$j(".refine-results").css("bottom", -30);
}
}
});
$j(window).scroll(function () {
if (count >= 1) {
if ($j(lastCat).is(":below-the-fold")) {
$j(".refine-results").removeClass("locked");
} else {
$j(".refine-results").addClass("locked");
}
}
});
});

function ToggleRefMoreLessFilters(a, b) {
if (b) {
$j(a).parents().siblings(".filters-list").show();
$j(a).parents(".more-filters-link").hide();
$j(a).parents().siblings(".less-filters-link").show();
}
else {
$j(a).parents().siblings(".filters-list").hide();
$j(a).parents(".less-filters-link").hide();
$j(a).parents().siblings(".more-filters-link").show();
}
}

var cc_selectedValues = new Array();

function cc_SubmitQuery(baseUrl, existingFilters, filterQueryParam) {
var newQuery = "";

for (var i = 0; i < cc_selectedValues.length; i += 2) {
var mpName = cc_selectedValues[i];
var propertyValueArray = cc_selectedValues[i + 1];

if (propertyValueArray.length > 0) {

for (var j = 0; j < propertyValueArray.length; j++) {

newQuery += mpName + ":\"" + propertyValueArray[j] + "\" "
}
}
}

var currentUrl = baseUrl += "&" + filterQueryParam + "=" + escape("(" + existingFilters + " " + newQuery + ")");

window.location.href = currentUrl;
}

function cc_RegisterSelection(elem, managedPropertyName) {

if (elem == null) {
return;
}

var propertyValueArray = cc_GetPropertyArray(managedPropertyName);
var elemValue = elem.value;

if (elem.checked == true) {
var found = false;
var foundIndex = 0;

for (foundIndex; foundIndex < propertyValueArray.length; foundIndex++) {
if (propertyValueArray[foundIndex] == elemValue) {
found = true;
break;
}
}

if (found == false) {
propertyValueArray.push(elemValue);
}
}
else {
var foundIndex = 0;

for (var foundIndex = 0; foundIndex < propertyValueArray.length; foundIndex++) {
if (propertyValueArray[foundIndex] == elemValue) {
found = true;
break;
}
}

if (found == true) {
propertyValueArray.splice(foundIndex, 1);
}
}
}

function cc_GetPropertyArray(managedPropertyName) {

for (var i = 0; i < cc_selectedValues.length; i += 2) {
if (managedPropertyName == cc_selectedValues[i]) {
return cc_selectedValues[i + 1];
}
}

cc_selectedValues.push(managedPropertyName);
cc_selectedValues.push(new Array());

return cc_selectedValues[cc_selectedValues.length - 1];
}

/* Z-Index fix for IE */
$j(document).ready(function () {
	// If the browser is IE,
	if ($j.browser.msie) {
		/*
		** For each div with class menu (i.e.,
		** the thing we want to be on top),
		*/
		$j(".rmRootGroup").parents().each(function () {
			var p = $j(this);
			var pos = p.css("position");

			// If it's positioned,
			if (pos == "relative" ||
			   pos == "absolute" ||
			   pos == "fixed") {
				/*
				** Add the "on-top" class name when the
				** mouse is hovering over its
				*/
				p.hover(function () {
					if (!$j(this).hasClass("on-top")) {
						$j(this).addClass("on-top");
					}
				});
			}
		});
	}
});

/* CC Tabs */
$j(document).ready(function () {
	CcTabs._init();
});
/* 
TABS object
Paul Balchin, 23 Apr 2010
====================================
EXTERNAL METHODS
A "CcTabs.onClick(tab, group)" is triggered after (the user has clicked a tab AND after the UI has completed it's change).
"group" is a jQuery collection,
"tab" is a number used to reference the tabs and is zero-based (0=first tab, 1=second tab, etc.),
Private/internal methods start with an underscore ("_"), public methods do not
NOTE 1
There may be one or more tabbed ui on the page.
The CSS classes under "TABS STRUCTURE" must be copied to the site's CSS file.
The CSS classes under "TABS STYLE" must be copied and modified on a per-site basis.
NOTE 2: Preselecting and hiding tabs
Although I created the ability to have multiple, functional tabs on the same page,
the ability to preselect and hide certain tabs by passing params on the url is hard
to apply to more than one tab set. So, I've written enough code where any passed params 
will apply only to the first tab set found on the page
		
*/
CcTabs = {
	// INTERNAL METHODS
	_init: function () {
		if ($j('.cc-tab-group').length === 0) {
			return;
		};

		$j('.cc-tab-group').each(function () {
			var group = $j(this);
			var savedTabState = CcTabs._getState(group);
			// IF FOUND, PRE-SELECT TAB FROM PREVIOUS POST-BACK
			if (savedTabState.length > 0) {
				CcTabs._click(savedTabState, group);
			} else {
				// ELSE AUTO SELECT FIRST TAB OF EACH GROUP
				var tabIsSelected = false; // there is no "break" in $j().each()
				$j(this).find('.cc-tab').each(function (i) {
					if (!(tabIsSelected || $j(this).hasClass('cc-tab-disabled') || $j(this).hasClass('cc-tab-hidden'))) {
						CcTabs._click(i, group);
						tabIsSelected = true;
					}
				});
			}
		});

		// OVERRIDE SELECTED TAB IF FOUND ON URL
		CcTabs._applyUrlParams();

		// SET UP CALLBACK EVENTS FOR EACH TAB
		$j('.cc-tab').click(function () {
			var group = $j(this).parent().parent();
			var tab = group.find('.cc-tab').index(this);
			CcTabs._click(tab, group);
		});
	},
	_click: function (tab, group) {
		// ERROR HANDLING: if group is undefined, then set to first group on the page
		if (typeof group === 'undefined')
			group = $j('.cc-tab-group:first');
		// ERROR HANDLING: if tab is not valid, then set to 0
		tab = Number(!isNaN(tab) ? tab : 0);
		// ERROR HANDLING: if tab is outside normal length, then set to 0
		if (tab < 0 || tab >= group.find('.cc-tab').length) {
			tab = 0;
		}
		// if tab is disabled or hidden or already selected, then stop action
		var currentTab = group.find('.cc-tab:eq(' + tab + ')');
		if (currentTab.hasClass('cc-tab-disabled') || currentTab.hasClass('cc-tab-hidden') || currentTab.hasClass('cc-tab-selected')) {
			return false;
		};
		// else set tabs
		group.find('.cc-tab').removeClass('cc-tab-selected'); // unselect all tabs
		group.find('.cc-tab:eq(' + tab + ')').addClass('cc-tab-selected'); // set selected tab
		// set panels
		group.find('.cc-tab-panel').removeClass('cc-tab-panel-visible'); // hide all content
		group.find('.cc-tab-panel:eq(' + tab + ')').addClass('cc-tab-panel-visible'); // show related content

		CcTabs._setState(tab, group);

		if (typeof CcTabs.onClick == 'function') {
			CcTabs.onClick(group, tab); // Create your own callback function as "CcTabs.onClick = function(tab, group){/*do stuff*/}" outside of this class
		}
	},
	_hide: function (tab) {
		$j('.cc-tab:eq(' + tab + ')').addClass('cc-tab-hidden');
	},
	// for _getState() and _endState() to function
	// ensure that <asp:HiddenField ID="CcTabState" runat="server" Value="0" /> is a child of <div class="cc-tab-group"> (anywhere)
	_getState: function (group) {
		var val = group.find('input[id*="CcTabState"]').val() || 0; // as long as the id *contains* "CcTabState", then it's good
		return (val);
	},
	_setState: function (tab, group) {
		group.find('input[id*="CcTabState"]').val(tab); // as long as the id *contains* "CcTabState", then it's good
	},
	// Currently only applies to first tab group found on the page
	_applyUrlParams: function () {
		// simple, returns array, e.g. ["a=0", "b=1", "c=2"]
		var getUrlParams = function () {
			return (location.href.replace(/.*\?(.*?)/, "").split('&'));
		};
		// URL PARAM "hideTab": check if any tabs have been hidden via url
		// can be "hideTab=1" for single or "hideTab=1;hideTab=2;hideTab=3" for multiple (note: ADD ";"... REMOVE "&"... very important!)
		if (location.href.indexOf('hideTab') > -1) {
			var params = getUrlParams();
			var hideTabs = [], tab;
			for (var i = 0; i < params.length; i++) {
				if (params[i].split('=')[0].toLowerCase() === 'hidetab') {
					hideTabs = params[i].split(';');
					for (var j = 0; j < hideTabs.length; j++) {
						tab = hideTabs[j].split('=')[1];
						CcTabs._hide(tab);
					};
					break;
				}
			};
		}
		// URL PARAM "selectTab": check if any tab has been preset as selected via url
		// this url param test must be the LAST url param test
		if (location.href.indexOf('selectTab') > -1) {
			var params = getUrlParams();
			var tab;
			for (var i = 0; i < params.length; i++) {
				if (params[i].split('=')[0].toLowerCase() === 'selecttab') {
					tab = Number(params[i].split('=')[1]);
					CcTabs._click(tab);
					break;
				}
			};
		}
	},
	// EXTERNAL METHODS
	click: function (groupID, tab) {
		var group = $j('#' + groupID + '.cc-tab-group');
		CcTabs._click(tab, group);
	},
	// returns <li>...</li> as a jQuery object
	getTab: function (group, tab) {
		if (typeof (tab) === "undefined") {
			return group.find('.cc-tab.cc-tab-selected');
		} else {
			return group.find('.cc-tab:eq(' + tab + ')');
		}
	},
	// returns tab number
	getSelectedTabNumber: function (group) {
		return group.find('.cc-tab.cc-tab-selected').index();
	},
	// returns any text found
	getLabel: function (group, tab) {
		return this.getTab(group, tab).text();
	}
};

