﻿/* 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;
};

/* 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');
	});
};

/* Sets the top nav */
$j(document).ready(function() {
	$j("#topnav ul li:last-child").addClass("last");
});

/* Set product blocks height after content is 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("h1").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 });

	$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"
			};
		};
	});
};

/* 
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("#content").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)

		// 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();

		// 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);
		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.buttons = {};
		options.buttons[Cancel] = function() { CcDialog.close(); };
		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, function() {
					$j('.ui-dialog').fadeTo("slow", 1);
				});
			} else {
				$j('.ui-dialog').stop().css('opacity', 0.01);
				$j('.ui-dialog').fadeTo("slow", 1);
			}

		};
	},
	close: function() {
		this._destroy();
		return false;
	},
	_widgetID: 'cc-dialog',
	_defaultOptions: {
		close: function() { CcDialog._destroy() },
		closeOnEscape: true,
		draggable: false,
		height: 'auto',
		modal: true,
		autoResize: true,
		resizable: false,
		width: 500
	},
	_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('body');
		} 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('body');
		}
	},
	_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').click(function(e) {
		e.preventDefault();
		CcDialog.openIframe($j(this).attr('href'));
	});

	$j('.cc-dialog-iframe-create-wishlist').click(function(e) {
		e.preventDefault();
		CcDialog.openIframe($j(this).attr('href'), { width: 440, modal: false });
	});

	$j('.cc-dialog-content').click(function(e) {
		e.preventDefault();
		CcDialog.openContent(this.href);
	});

	$j('.cc-dialog-embedded').click(function(e) {
		e.preventDefault();
		CcDialog.openEmbedded(this.name);
	});
});

// 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);
            })
        });
    });
}

// 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");
					}
				});
			}
		});
	}
});

/// <summary>
/// Loops through all of the form fields and returns a JSON object with the values found
/// </summary>
$j.fn.serializeObject = function () {
    var o = {};
    var formElements = this.find("input, select, textarea");
    $j.each(formElements, function () {
        if (o[this.name]) {

            if (this.type == "checkbox" || this.type == "radio") {
                if (this.checked == true) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }

                    o[this.name].push(true || '');
                }
            }
        }
        else {

            if (this.type == "checkbox" || this.type == "radio") {
                if (this.checked == true) {
                    o[this.name] = true || '';
                }
            }
            else {
                o[this.name] = this.value || '';
            }
        }
    });
    return o;
};

/// <summary>
/// Loops through all of the form fields and returns a JSON object with the values found
/// </summary>
$j.fn.serializeObject = function () {
    var o = {};
    var formElements = this.find("input, select, textarea");
    $j.each(formElements, function () {
        if (o[this.name]) {

            if (this.type == "checkbox" || this.type == "radio") {
                if (this.checked == true) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }

                    o[this.name].push(true || '');
                }
            }
        }
        else {

            if (this.type == "checkbox" || this.type == "radio") {
                if (this.checked == true) {
                    o[this.name] = true || '';
                }
            }
            else {
                o[this.name] = this.value || '';
            }
        }
    });
    return o;
};

//Search Default Field
$j(document).ready(function () {
	$j('[id*=CategoryDropDown]').val("");
});

//Contest Form Submit Function
$j(document).ready(function () {
    enableForm = function () {
        if ($j('[name=firstname]').val().length > 0 && $j('[name=lastname]').val().length > 0 && $j('[name=email]').val().length > 0 &&
    $j('[name=company]').val().length > 0 && $j('[name=TermsAndConditions]').attr('checked')) {
            $j('.submitContest').attr("disabled", false);
            $j('.submitContest').removeClass("icEnterButtonDisabled");
        } else {
            $j('.submitContest').attr("disabled", true);
            $j('.submitContest').addClass("icEnterButtonDisabled");
        }
    }

    //disable on the first load
    $j('.submitContest').attr("disabled", true);
    $j('.submitContest').addClass("icEnterButtonDisabled");

    $j('[name=firstname]').blur(enableForm);
    $j('[name=lastname]').blur(enableForm);
    $j('[name=email]').blur(enableForm);
    $j('[name=company]').blur(enableForm);
    $j('[name=newslettersignup]').change(enableForm);
    $j('[name=TermsAndConditions]').change(enableForm);
    $j('.submitContest').click(function () {
        var postBackData = $j('.submitContestForm').serializeObject();
        var innerhtml = $j('.submitContestFormInnerContent').html();
        $j('#legal-notice').hide();

        $j.ajax({
            url: "/_layouts/SubmitHandler.ashx",
            data: postBackData,
            dataType: "json",
            type: "POST",
            success: function (result) {
                window.location = "/pages/qrend.aspx";
            },
            error: function (result) {
                window.location = "/pages/qrend.aspx";
            }
        });

    });
});
