﻿//Simple object to contain all the static methods
var $SCOUT = {
	WebAnalyticsTracking: {
		launchAllWebAnalyticsTracking: function(anchorElem) {
			var trackingFunction = "";
			var classNamesArray = anchorElem.className.split(' ');
			var omniModuleName = "";
			var atlasTagName = "";
			for (var i = 0; i < classNamesArray.length; i++) {
				if (classNamesArray[i].match('omniModuleName') != null) {
					omniModuleName = classNamesArray[i].substring(14, classNamesArray[i].length);
				}
				else if (classNamesArray[i].match('atlasTagName') != null) {
					atlasTagName = classNamesArray[i].substring(12, classNamesArray[i].length);
				}
			}

			if (omniModuleName != "") {
				trackingFunction = $SCOUT.WebAnalyticsTracking.getOmniModTrackingFunction(anchorElem, omniModuleName);
			}
			if (atlasTagName != "") {
				var atlasTrackingFunction = "globaltracking.trackatlasonclick('http://view.atdmt.com/jaction/" + atlasTagName + "');";
				trackingFunction = trackingFunction + atlasTrackingFunction;
			}
			if (trackingFunction != "")
				eval(trackingFunction);
		},
		omniModTracking: function(anchorElem, omniModuleName) {
			eval($SCOUT.WebAnalyticsTracking.getOmniModTrackingFunction(anchorElem, omniModuleName));
		},
		getOmniModTrackingFunction: function(anchorElem, omniModuleName) {
			var trackingFunction = "omniModTracking(this, '" + omniModuleName + "', '', '" + $(anchorElem).attr("href") + "', 1, '" + ($(anchorElem).text()).replace("'", "") + "', '');";
			if (omniModuleName == "Feedback5Percent") { // special case for feedback auto pop up impression call
				trackingFunction = "omniModTracking(this, '" + omniModuleName + "', '', '" + $(anchorElem).attr("href") + "', 0, '" + ($(anchorElem).text()).replace("'", "") + ": 5% chance auto pop up feedback', '');";
			}
			return trackingFunction;
		},
		omniModAutoClickTrack: function(anchorElem, omniModuleName) {
			var trackingFunction = "omniModTracking(this, '" + omniModuleName + "', '', '" + $(anchorElem).attr("href") + "', 1, '" + $(anchorElem).text() + "', '');";
			eval(trackingFunction);
		}
	},
	Filters: {
		//click handler for pretty checkboxes in filters section
		updateCheckboxStyle: function(checkbox, raiseControllerOnCheckboxFilterChanged) {
			var cb = $(checkbox),
            li = cb.closest('li'),
            bChecked = cb.attr('checked'),
            bClass = li.hasClass('scoutFiltersCheckboxChecked');

			if ((bChecked && !bClass) || (!bChecked && bClass)) {
				li.toggleClass('scoutFiltersCheckboxChecked');
				if (raiseControllerOnCheckboxFilterChanged)
					BrowsePCsController.OnCheckBoxFilterChanged(checkbox, bChecked);
			}
		},

		//click handler for show all/clear all in filters section
		updateMultipleCheckboxes: function(anchor) 
		{	
			var $anchor = $(anchor),
				$cbs = $anchor.closest('ul').siblings('ul').find('input[type=checkbox]');

			// The brand show/clear all links are structured differently than the cat links
			if ($(anchor).attr("id") == "brandClearAll" || $(anchor).attr("id") == "brandShowAll") 
			{	
				var inputs = $("#brands_checkboxes_container ul li input[type=checkbox]");
				inputs.each(function(i, cb) {
					if ($(anchor).attr("id") == "brandShowAll") {
						cb.checked = true;
					} else if ($(anchor).attr("id") == "brandClearAll") {
						cb.checked = false;
					}
					$SCOUT.Filters.updateCheckboxStyle(cb, false);
					//TODO: call code to maintain the state of the filter
				});
			}
			else 
			{
				$cbs.each(function(i, cb) {
					if ($anchor.hasClass('scoutShowAll')) {
						cb.checked = true;
					} else if ($anchor.hasClass('scoutClearAll')) {
						cb.checked = false;
					}
					$SCOUT.Filters.updateCheckboxStyle(cb, false);
					//TODO: call code to maintain the state of the filter
				});
			}

			var isShowAll = $anchor.hasClass('scoutShowAll');
			BrowsePCsController.OnCategoryShowOrClearAll($anchor[0].id, isShowAll);
		},

		//click handler for reset anchor in "Additional Detials" filters
		resetAdditionalDetails: function(anchor) {
			var o = this,
            $anchor = $(anchor),
            $cbs = $anchor.closest('fieldset').find('input[type=checkbox]');
			$cbs.each(function(i, cb) {
				switch (cb.id) {
					case "brand_acer_checkbox":
						cb.checked = true;
						break;
					case "brand_alienware_checkbox":
						cb.checked = true;
						break;
					case "brand_compaq_checkbox":
						cb.checked = true;
						break;
					case "brand_dell_checkbox":
						cb.checked = true;
						break;
					case "brand_fujitsu_checkbox":
						cb.checked = true;
						break;
					case "brand_hp_checkbox":
						cb.checked = true;
						break;
					case "brand_lenovo_checkbox":
						cb.checked = true;
						break;
					case "brand_sony_checkbox":
						cb.checked = true;
						break;
					case "brand_toshiba_checkbox":
						cb.checked = true;
						break;
					case "brand_asus_checkbox":
						cb.checked = true;
						break;
					case "brand_samsung_checkbox":
						cb.checked = true;
						break;
					case "brand_falconnw_checkbox":
						cb.checked = true;
						break;
					case "brand_gateway_checkbox":
						cb.checked = true;
						break;
					case "proc_intel_checkbox":
						cb.checked = true;
						break;
					case "proc_amd_checkbox":
						cb.checked = true;
						break;
					default:
						cb.checked = false;
						break;
				}
				o.updateCheckboxStyle(cb);
				//TODO: call code to maintain the state of the filter
			});
			BrowsePCsController.ResetAdditionalDetails();
		},

		//click handler for sliding the "additional details" filter
		slideAdditionalDetails: function(anchor) {
			var $anchor = $(anchor),
                $resetAnchor = $anchor.siblings('.scoutFiltersReset'),
                $pane = $('.scoutFiltersModuleInnerContainer');

			$pane.slideToggle(500);
			$anchor.toggleClass('scoutFiltersLess');

			if ($anchor.hasClass("scoutFiltersLess")) {
				document.cookie = "additionalDetailsExpanded=true;";
			}
			else {
				document.cookie = "additionalDetailsExpanded=false;";
			}
		},

		hideLandingPage: function() {
			$('.scoutCategoriesContainer').remove();
			$('.scoutPcsLandingContainer').remove();
			$('.scoutPcsListContainer').show();
		}
	},

	Compare: {

		_pcList: [],
		_pcImgUrlList: [],

		generateComparePageUrlParams: function() {
			var pcs = $SCOUT.Compare._pcList;
			var url = "";
			if (pcs.length > 0) {
				url = "?";
				for (var i = 1; i <= pcs.length; i++)
					url += "pcid" + i + "=" + pcs[i - 1] + "&";
				url = url.substring(0, url.length - 1);
			}
			return url;
		},

		removePcFromCompare: function(index) {
			if (index == null || index == '' || isNaN(index))
				return;
			index = parseInt(index, 10);

			// remove from the memory obj
			$SCOUT.Compare._pcList.splice(index, 1);

			// reset img src cookie:
			var compareItemsImgSrcArray = new Array();
			compareItemsImgSrcArray[0] = GetCookieValue("comparepc1imgsrc");
			compareItemsImgSrcArray[1] = GetCookieValue("comparepc2imgsrc");
			compareItemsImgSrcArray[2] = GetCookieValue("comparepc3imgsrc");
			compareItemsImgSrcArray[3] = GetCookieValue("comparepc4imgsrc");
			var prefix = "comparepc";
			var imgSuffix = "imgsrc";
			for (var i = 1; i <= 4; i++) {
				document.cookie = prefix + i + imgSuffix + "=empty";
			}
			compareItemsImgSrcArray[index] = "";
			var newCompareItemsImgSrcArray = new Array();
			newCompareItemsImgSrcArray[0] = "empty";
			newCompareItemsImgSrcArray[1] = "empty";
			newCompareItemsImgSrcArray[2] = "empty";
			newCompareItemsImgSrcArray[3] = "empty";

			var newCompareItemsImgSrcArrayIndex = 0;
			for (var i = 0; i < 4; i++) {
				if (compareItemsImgSrcArray[i] != "") {
					newCompareItemsImgSrcArray[newCompareItemsImgSrcArrayIndex] = compareItemsImgSrcArray[i];
					newCompareItemsImgSrcArrayIndex++;
				}
			}
			for (var i = 1; i <= 4; i++) {
				document.cookie = prefix + i + imgSuffix + "=" + newCompareItemsImgSrcArray[i - 1];
			}
			//end reset img src cookie

			// update UI
			$SCOUT.Compare.removeColumnFromCompareTableByIndex(index);
			$SCOUT.Compare.moveColumnsOver(index);
			$SCOUT.Compare.removePcFromCookie();
		},

		// Remove PC from Compare cookie
		removePcFromCookie: function() {
			var prefix = "comparepc";

			var ids = $SCOUT.Compare._pcList;

			// reset current cookie numbering so there's no gaps
			for (var i = 1; i <= 4; i++)
				document.cookie = prefix + i + "=empty";

			// rewrite cookie values with updated model object
			for (var i = 1; i <= ids.length; i++)
				document.cookie = prefix + i + "=" + ids[i - 1];
		},

		//removes the data from one column in the compare table
		removeColumnFromCompareTableByIndex: function(index) {
			if (index != undefined) {
				var strTd = 'td:eq(' + (index + 1) + ')';
				$('table.scoutCompareTable tr.data').each(function(i, el) {
					$(strTd, el).html('');
				});

				$('table.scoutCompareTable tr.scoutCompareRetailers').each(function(i, el) {
					$(strTd, el)
						.html('')
						.attr('class', '');
				});

				$('table.scoutCompareTable tr.scoutComparePcs th:eq(' + index + ') div.scoutPcsPc')
					.html('Add another laptop for comparison.')
					.attr("class", '')
					.addClass('scoutPcsPcEmpty');
			}
		},

		//moves columns to the lef tin the compare table if a column is removed
		moveColumnsOver: function(index) {
			var arrIndex = []
			$('table.scoutCompareTable tr.scoutComparePcs th a.scoutCompareRemoveLink').each(function(i, el) {
				var idx = parseInt(el.rel, 10);
				if (idx > index)
					arrIndex.push(idx);
			});

			$('table.scoutCompareTable tr.data').each(function(i, el) {
				for (var j = 0; j < arrIndex.length; j++) {
					var $tdNew = $('td:eq(' + arrIndex[j] + ')', el),
                        $tdOld = $('td:eq(' + (arrIndex[j] + 1) + ')', el);
					$tdNew.html($tdOld.html());
				}
			});

			$('table.scoutCompareTable tr.scoutCompareRetailers').each(function(i, el) {
				for (var j = 0; j < arrIndex.length; j++) {
					var $tdNew = $('td:eq(' + arrIndex[j] + ')', el),
                        $tdOld = $('td:eq(' + (arrIndex[j] + 1) + ')', el);
					$tdNew
                        .html($tdOld.html())
                        .attr('class', $tdOld.attr('class'));
				}
			});

			var $headers = $('table.scoutCompareTable tr.scoutComparePcs')
			$headers.each(function(i, el) {
				for (var j = 0; j < arrIndex.length; j++) {
					var $thNew = $('th:eq(' + (arrIndex[j] - 1) + ')', el),
                        $thOld = $('th:eq(' + (arrIndex[j]) + ')', el);
					$thNew.html($thOld.html());
				}
				for (var j = 0; j < 4; j++) {
					$('th:eq(' + j + ')')
                        .find('a.scoutCompareRemoveLink')
                            .attr('rel', j);
				}
			});

			this.removeColumnFromCompareTableByIndex(arrIndex.pop());
		}

	},

	Tooltip: {
		_container: null,
		_header: null,
		_content: null,
		_width: null,
		_height: null,
		_timeoutId: null,
		_timeoutIdNew: null,
		_currentElement: null,
		_compareLink: null,

		initialize: function() {
			var that = this,
                $tooltipContainer = $('<div class="scoutTooltip" />'),
                $tooltipBg = $('<div class="scoutTooltipBg" />'),
                $tooltipContent = $('<div class="tooltipContent" />'),
                $tooltipContentHeader = $('<h5></h5>'),
                $tooltipContentInner = $('<div class="tooltipContentInner" />');

			$tooltipContent.append($tooltipContentHeader).append($tooltipContentInner);
			$tooltipContainer.append($tooltipBg).append($tooltipContent).appendTo('body');

			this._container = $tooltipContainer;
			this._header = $tooltipContentHeader;
			this._content = $tooltipContentInner;
			this._width = $tooltipContainer.width();
			this._height = $tooltipContainer.height();

			this._container
                .data('tooltip_mouseover', false)
                .data('trigger_mouseover', false)
                .bind('mouseover', function() {
                	$(this).data('tooltip_mouseover', true);
                })
                .bind('mouseout', function() {
                	$(this).data('tooltip_mouseover', false);
                	that.hide();
                });
		},

		moveTo: function(el) {
			var $el = $(el),
                o = $el.offset(),
                h = this._height - 8,
                w = (this._width - $el.outerWidth()) / 2;
			this._container.css({ top: o.top - h, left: o.left - w });

			if (this._currentElement != null) {
				this._currentElement.removeClass('scoutCategoryLinkHover');
			}
			this._currentElement = $el;
			this._currentElement.addClass('scoutCategoryLinkHover');
		},

		update: function(header, content, isError) {
			if (isError) {
				this._container.addClass('scoutTooltipError');
			} else {
				this._container.removeClass('scoutTooltipError');
			}
			this._header.text(header);
			this._content.html(content);
		},

		show: function() {
			this._container.show();
		},

		hide: function(el) {
			var that = this;
			clearTimeout(this._timeoutId);
			this._timeoutId = setTimeout(function() {
				if (!(that._container.data('tooltip_mouseover') || that._container.data('trigger_mouseover'))) {
					that._container.hide();
					if (that._currentElement != null) {
						that._currentElement.removeClass('scoutCategoryLinkHover');
						that._currentElement = null;
					}
				}
			}, 500);
		},

		createCategoryTooltip: function(el) {
			var that = this;
			clearTimeout(this._timeoutIdNew);
			this._timeoutIdNew = setTimeout(function() {

				if (that._container.data('trigger_mouseover')) {
					var $categories = $($('#scoutTooltipCategory').html()),
                        $category = $categories.filter('#' + el.rel),
                        link = $categories.filter('div#scoutTooltipCategoryLink').text(),
                        header = $category.find('div.header').text(),
                        linkUrl = $category.find('div.categoryLinkUrl').text(),
                        content = ['<p>', $category.find('div.description').text(), '</p><p><a href="', linkUrl, '" onclick="omniModTracking(this, \'CategoryTooltip\', \'\', \'', linkUrl, '\', 1, \'', el.rel, '\', \'\');">', link, '</a></p>'].join('');

					that.update(header, content, false);
					that.moveTo(el);
					that.show();
				}

			}, 400);
		},

		createErrorTooltip: function(el, error) {
			if (this._compareLink == null)
				this._compareLink = $("a[id*='lnkSidebarStep5']");
			clearTimeout(this._timeoutIdNew);
			var $categories = $($('#scoutTooltipCategory').html()),
                $error = $categories.filter('#' + error),
                header = $error.find('div.header').text(),
                content = ['<p>', $error.find('div.description').text(), '</p><p><a href="', this._compareLink.attr('href'), '">', this._compareLink.text(), '</a></p>'].join('');

			this.update(header, content, true);
			this.moveTo(el);
			this.show();
		}
	},

	Share: {

		_bindBrowsePCFilters: false,

		createSocialBookmarks: function() {
			$("#sb_share")
                .bind("mouseenter", { state: "show" }, $SCOUT.Share.toggleSocialBookmarks)
                .bind("mouseleave", { state: "hide" }, $SCOUT.Share.toggleSocialBookmarks);

			$("#social_bookmarks li a").bind("click", function(e) {
				$SCOUT.Share.generateBookmarkUrl(e);
				setTimeout(function() {
					$SCOUT.Feedback.showFeedbackFrame();
				}, 3000);
			});
			$('a.scoutShareEmail').click(function(e) {
				$SCOUT.Share.generateEmail(e)
				setTimeout(function() {
					$SCOUT.Feedback.showFeedbackFrame();
				}, 3000);
			});
		},

		toggleSocialBookmarks: function(e) {
			if (e.data.state == "hide") {
				$("#social_bookmarks").addClass("hidden");
			}
			else {
				$("#social_bookmarks").removeClass("hidden");
			}
		},

		generateBookmarkUrl: function(e) {
			var params = "";
			var shareUrl = window.location.href.replace("#nogo", "");
			shareUrl = shareUrl.replace("#", "");
			shareUrl = shareUrl.replace(/&/g, "%26");

			var getBrowsePageToGenerateFullUrl = true;
			if (typeof BrowsePCsController != "undefined") {
				if (shareUrl.match("mode=") && !BrowsePCsController.HasFilterValuesBeenChanged()) {
					getBrowsePageToGenerateFullUrl = false;
				}
			}
			if ($SCOUT.Share._bindBrowsePCFilters && typeof BrowsePCsController != "undefined") {
				if (!shareUrl.match("mode=") || (shareUrl.match("mode=") && getBrowsePageToGenerateFullUrl)) {
					params = BrowsePCsController.GenerateUrlParams();
					shareUrl = window.location.href.split('?')[0] + params.replace(/&/g, "%26");
				}
			}

			var href = e.target.href;
			href = href.replace("=www.microsoft.com/windows", "=" + shareUrl)
			href = href.replace("{ShareTitle}", $("#socialMediaShareTitle").text());
			e.target.target = "_blank";
			e.target.href = href;

			return true;
		},

		generateEmailUrlString: function() {
			var url = window.location.href.replace("#nogo", "");
			url = url.replace("#", "");
			if (url.match("compare-laptops") && !url.match("mode="))
				url = url.split('?')[0];
			if (url.match("brands=all") || url.match("addf=showmaxnumpcs") || url.match("cbid=guided-tour"))
				url = url.split('?')[0];

			var getBrowsePageToGenerateFullUrl = true;
			if (typeof BrowsePCsController != "undefined") {
				if (url.match("mode=") && !BrowsePCsController.HasFilterValuesBeenChanged()) {
					getBrowsePageToGenerateFullUrl = false;
				} else {
					url = url.split('?')[0];
				}
			}

			if ($SCOUT.Share._bindBrowsePCFilters && typeof BrowsePCsController != "undefined" && getBrowsePageToGenerateFullUrl) {
				url += BrowsePCsController.GenerateUrlParams();
			}
			else if (url.match("compare-laptops") != null) {
				url = url.split('?')[0];
				if ($SCOUT.Compare._pcList.length != 0) {
					url += '?';
					for (var i = 0; i < $SCOUT.Compare._pcList.length; i++) {
						if (i > 0) {
							url += '&';
						}
						url += 'pcid' + (i + 1) + '=';
						url += $SCOUT.Compare._pcList[i];
					}
				}


				url = url.replace(/&/g, "%26");
			}

			return url;
		},
		generateEmail: function(e) {
			if (e.target.href.match("{LINK_BACK}") != null)
				$SCOUT.Share._mailtoHrefTemplate = e.target.href;
			var url = $SCOUT.Share.generateEmailUrlString();
			url = url.replace(/&/g, "%26");
			e.target.href = $SCOUT.Share._mailtoHrefTemplate.replace("{LINK_BACK}", url);
			return true;
		}
	},

	Feedback: {
		_tooltip: null,
		_trigger: null,
		_hiddenTrigger: null,
		_tooltipTrigger: null,
		_closeButton: null,
		_showedFeedbackFrame: null,
		_percentage: 5,

		initialize: function() {
			var that = this;
			this._tooltip = $('.scoutFeedbackTooltip');
			this._trigger = $('.scoutShareContainer a.scoutFeedback');
			this._hiddenTrigger = $('.scoutFeedbackHidden');
			this._tooltipTrigger = $('.scoutFeedbackTooltipTrigger', this._tooltip);
			this._closeButton = $('p.scoutFeedbackTooltipClose a', this._tooltip);

			var showedFeedbackFrame = GetCookieValue('showedFeedbackFrame');
			if (showedFeedbackFrame != null && showedFeedbackFrame == 'true') {
				this._showedFeedbackFrame = true;
			}

			this._closeButton.bind('click', function(e) {
				that.hideTooltip();
			});

			this._trigger.bind('click', function(e) {
				that.hideTooltip();
				that.setCookie();
			});

			this._hiddenTrigger.bind('click', function(e) {
				that.hideTooltip();
				that.setCookie();
			});

			this._tooltipTrigger.bind('click', function(e) {
				that.hideTooltip();
				that.setCookie();
			});
		},

		showFeedbackFrame: function() {
			if (!this._showedFeedbackFrame) {
				if (Math.floor(Math.random() * 100) < this._percentage) {
					this._hiddenTrigger.click();
					this.hideTooltip();
				}
			}
		},

		setCookie: function() {
			document.cookie = 'showedFeedbackFrame=true;';
			this._showedFeedbackFrame = true;
		},

		hideTooltip: function() {
			this._tooltip.hide();
			document.cookie = 'hideFeedbackTooltip=true;';
		}

	},

	Scoutbox: {
		_isShowing: false,
		_showing: null,
		_width: 0,
		_height: 0,

		/**
		* Wire the Scout lightbox events
		*/
		createScoutbox: function() {
			$("a[rel*='scoutbox']").bind("click", $SCOUT.Scoutbox.show);
			$(".close a").bind("click", $SCOUT.Scoutbox.close);
			$(window).bind("resize", $SCOUT.Scoutbox.update);
		},

		addContentDelegate: function(relKey, delegate) {
			$SCOUT.Scoutbox[relKey] = { contentDelegate: delegate };
		},

		/**
		* Show the Scout lightbox
		*/
		show: function(e) {
			e.preventDefault();
			e.stopPropagation();

			if (e.currentTarget.className.match('webanalyticsTracking')) {
				$SCOUT.WebAnalyticsTracking.launchAllWebAnalyticsTracking(e.currentTarget);
			}
			$(".scoutFeedbackTooltipContentInner .scoutFeedbackTooltipClose a").click(); //hide the survey popup

			var elemId;
			// find the id of the content elem and move it into the lightbox
			if ($(this).attr("rel") != undefined) {
				var len = $(this).attr('rel').length;

				// use the scoutbox[value] substring to parse the container element id
				elemId = $(this).attr('rel').substring(9, len - 1);
				$SCOUT.Scoutbox._showing = $("#" + elemId);

				// HACK: For now, if this is a JV pop-up, turn the close link white
				if (elemId == "jv101") {
					$("#scoutbox .close a").css("color", "#FFFFFF");
				}
				else {
					$("#scoutbox .close a").css("color", "#005A88");
				}
			}

			var showing = $SCOUT.Scoutbox._showing;
			$SCOUT.Scoutbox._isShowing = true;
			$SCOUT.Scoutbox._width = parseInt(showing.css("width"));
			$SCOUT.Scoutbox._height = parseInt(showing.css("height"));

			// update the box position
			$SCOUT.Scoutbox.update();

			// move the container element into the box.
			showing.appendTo("#content").removeClass("hidden");

			// show the popup
			$("#scoutbox").removeClass("hidden");
			$("#scoutbox .close a").focus();
			$(document).bind('keydown.scoutbox', function(e) {
				if (e.which == 27) {
					$SCOUT.Scoutbox.close();
				}
			});
			// if a content delegate method was provided, append the return value of the delegate.
			if ($SCOUT.Scoutbox[elemId].contentDelegate != null && $SCOUT.Scoutbox[elemId].contentDelegate != undefined)
				showing.append($SCOUT.Scoutbox[elemId]["contentDelegate"](e));
		},

		/**
		* Update the Scout lightbox. Called when lightbox is opened and on window resize.
		*/
		update: function() {
			if ($SCOUT.Scoutbox._isShowing) {
				var width = $SCOUT.Scoutbox._width;
				var height = $SCOUT.Scoutbox._height;

				// position the shade affect
				$("#boxWrapper").css("min-width", width);
				var screen_width = document.documentElement.clientWidth + document.documentElement.scrollLeft;
				var screen_height = document.documentElement.clientHeight;
				$("#shade").css("width", screen_width);
				$("#shade").css("height", document.documentElement.scrollHeight);

				// position the box
				var box = $("#box");
				box.css("left", (screen_width / 2) - (width / 2));
				box.css("top", (screen_height / 2) - (height / 2) + $SCOUT.Scoutbox.getPageScroll());
				box.css("width", width);
				box.css("height", height);
			}
		},

		getPageScroll: function() {
			var yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
			}
			return yScroll;
		},

		/**
		* Close the Scout lightbox
		*/
		close: function() {
			$SCOUT.Scoutbox._isShowing = false;
			$("#scoutbox").addClass("hidden");
			$SCOUT.Scoutbox._showing.addClass("hidden").children().remove();
			$(document).unbind('keydown.scoutbox');
		}
	}
};





$(function()
{
	//bind web analytics tracking:
	$('a.webanalyticsTracking').live('click', function(e)
	{
		$SCOUT.WebAnalyticsTracking.launchAllWebAnalyticsTracking(this);
	});
	$('a.analyticsDefaultPageRetailerTracking').each(function(i, elem)
	{
		var currentHref = elem.href;

		var clickedMboxName = 'usWinRedirScoutHome';
		var newHref = "http://microsoftwindowscom.tt.omtrdc.net/m2/microsoftwindowscom/ubox/page" +
		"?mbox=" + clickedMboxName + "&mboxSession=" +
		mboxFactoryDefault.getSessionId().getId() +
		"&mboxPC=" + mboxFactoryDefault.getPCId().getId() +
		"&mboxXDomain=disabled&mboxDefault=" + escape(currentHref);

		elem.href = newHref;

		var atlasTrackingFunction = "";
		var omniSCTrackingFunction = "";
		if (elem.innerText == "Amazon.com")
		{
			atlasTrackingFunction = "globaltracking.trackatlasonclick('http://view.atdmt.com/jaction/asc_pshptips_amazon');";
			omniSCTrackingFunction = "omniModTracking(this,'ScoutPartner','Amazon','" + currentHref + "',1,'Amazon.com','');";
		}
		else if (elem.innerText == "Best Buy")
		{
			atlasTrackingFunction = "globaltracking.trackatlasonclick('http://view.atdmt.com/jaction/asc_pshptips_bestbuy');";
			omniSCTrackingFunction = "omniModTracking(this,'ScoutPartner','Best Buy','" + currentHref + "',1,'Best Buy','');";
		}
		else if (elem.innerText == "Wal-Mart")
		{
			atlasTrackingFunction = "globaltracking.trackatlasonclick('http://view.atdmt.com/jaction/asc_pshptips_walmart');";
			omniSCTrackingFunction = "omniModTracking(this,'ScoutPartner','Wal Mart','" + currentHref + "',1,'Wal-Mart','');";
		}

		$(elem).click(function(e)
		{
			eval(atlasTrackingFunction);
			eval(omniSCTrackingFunction);
		});
	});

	//determine if details page was loaded from compare page:
	$(window).bind('unload', function(event)
	{
		if (window.location.href.match("compare-laptops") != null)
		{
			var comparePageUrl = $SCOUT.Share.generateEmailUrlString();
			comparePageUrl = comparePageUrl.replace(new RegExp(/=/g), "%3D");
			document.cookie = "isfromcomparepage=true|" + comparePageUrl + ";";
		} else
		{
			document.cookie = "isfromcomparepage=false;";
		}
	})

	//bind tooltip behavior to category links
	$('.scoutCompareContainer .scoutCategoryIdentifierLink, .scoutDetailsCategoryIdentifierLink, .scoutHomeCategoryIdentifierLink')
        .live('mouseover',
            function(e)
            {
            	$SCOUT.Tooltip._container.data('trigger_mouseover', true);
            	$SCOUT.Tooltip.createCategoryTooltip(this);
            }
        )
        .live('mouseout',
            function(e)
            {
            	$SCOUT.Tooltip._container.data('trigger_mouseover', false);
            	$SCOUT.Tooltip.hide(this);
            }
        );

	$('.scoutHomeCategoryIdentifierLink')
        .focus(function(e)
        {
        	$SCOUT.Tooltip._container.data('trigger_mouseover', true);
        	$SCOUT.Tooltip.createCategoryTooltip(this);
        })
        .blur(function(e)
        {
        	$SCOUT.Tooltip._container.data('trigger_mouseover', false);
        	$SCOUT.Tooltip.hide(this);
        });

	//disable click behavior from category links in browse page
	$('.scoutPcsContainer .scoutCategoryIdentifierLink')
        .live('click', function(e)
        {
        	e.preventDefault();
        	e.stopPropagation();
        });

	$('.scoutCompareContainer .scoutCategoryIdentifierLink, .scoutDetailsCategoryIdentifierLink')
        .live('click', function(e)
        {
        	e.preventDefault();
        	e.stopPropagation();
        	$SCOUT.Tooltip._container.data('trigger_mouseover', true);
        	$SCOUT.Tooltip.createCategoryTooltip(this);
        });


	//bind click for See All links in set-criteria.aspx?mode=categories page:
	$('.allAroundSeeAllCategoryClicked').live('click', function(e)
	{
		eval("omniModTracking(this, 'CategorySeeAll', '', 'laptop-set-criteria.aspx?cat=1&brands=all&addf=showmaxnumpcs', 1, 'All Around Category - See All', '');");
		window.location = 'laptop-set-criteria.aspx?cat=1&brands=all&addf=showmaxnumpcs';
	});
	$('.mobileStudioSeeAllCategoryClicked').live('click', function(e)
	{
		eval("omniModTracking(this, 'CategorySeeAll', '', 'laptop-set-criteria.aspx?cat=2&brands=all&addf=showmaxnumpcs', 1, 'Mobile Studio Category - See All', '');");
		window.location = 'laptop-set-criteria.aspx?cat=2&brands=all&addf=showmaxnumpcs';
	});
	$('.moviesSeeAllCategoryClicked').live('click', function(e)
	{
		eval("omniModTracking(this, 'CategorySeeAll', '', 'laptop-set-criteria.aspx?cat=3&brands=all&addf=showmaxnumpcs', 1, 'Movies on the go Category - See All', '');");
		window.location = 'laptop-set-criteria.aspx?cat=3&brands=all&addf=showmaxnumpcs';
	});
	$('.gamingSeeAllCategoryClicked').live('click', function(e)
	{
		eval("omniModTracking(this, 'CategorySeeAll', '', 'laptop-set-criteria.aspx?cat=4&brands=all&addf=showmaxnumpcs', 1, 'Power gaming Category - See All', '');");
		window.location = 'laptop-set-criteria.aspx?cat=4&brands=all&addf=showmaxnumpcs';
	});
	$('.workSeeAllCategoryClicked').live('click', function(e)
	{
		eval("omniModTracking(this, 'CategorySeeAll', '', 'laptop-set-criteria.aspx?cat=5&brands=all&addf=showmaxnumpcs', 1, 'Work from anywhere Category - See All', '');");
		window.location = 'laptop-set-criteria.aspx?cat=5&brands=all&addf=showmaxnumpcs';
	});
    $('.netbooksSeeAllCategoryClicked').live('click', function(e) {
        eval("omniModTracking(this, 'CategorySeeAll', '', 'laptop-set-criteria.aspx?cat=6&brands=all&addf=showmaxnumpcs', 1, 'Netbooks Category - See All', '');");
        window.location = 'laptop-set-criteria.aspx?cat=6&brands=all&addf=showmaxnumpcs';
    });

	//bind the click handler for pretty checkboxes in filters section
    $('li.scoutFiltersCheckbox input.hiddenInput').live("click", function(e)
    {
	    $SCOUT.Filters.updateCheckboxStyle(this, true);
	    //TODO: call code to maintain the state of the filter
    });

	//bind the click handler for show all/clear all in filters section
    $('.scoutFilters ul.scoutShowClear a').click(function(e) 
	{
		e.preventDefault();
		e.stopPropagation();
		$SCOUT.Filters.updateMultipleCheckboxes(this);
	});

	//hide landing text/category list if the filters are used
	//TODO:add same for sliders
	$('.scoutFilters input.hiddenInput, .scoutFilters ul.scoutShowClear a, a.resetAdditionalDetails, a.resetSliders').bind('click.hideLanding', function(e)
	{
		$SCOUT.Filters.hideLandingPage();
		$('.scoutFilters input.hiddenInput, .scoutFilters ul.scoutShowClear a, a.resetAdditionalDetails, a.resetSliders').unbind('click.hideLanding');
	});

	//bind the click handler for sliding the "additional details" filter
	$('a.scoutFiltersMoreless').click(function(e)
	{
		e.preventDefault();
		e.stopPropagation();
		$SCOUT.Filters.slideAdditionalDetails(this);
	});

	$('#scoutAdditionalDetailsHeaderLink').click(function(e)
	{
		e.preventDefault();
		e.stopPropagation();
		$(this).parent().siblings('a.scoutFiltersMoreless').trigger('click');
	});

	//prevent clicks on the "View Details" menu item
	$('ol.scoutSidebarSteps li a.scoutSidebarStep4').click(function(e)
	{
		e.preventDefault();
		e.stopPropagation();
	});


	//click handler for the [x] button in the compare page
	$('a.scoutCompareRemoveLink').live('click', function(e)
	{
		e.preventDefault();
		e.stopPropagation();

		$SCOUT.Compare.removePcFromCompare(this.rel);
	});

	//event handler for reset button on "Additional Detials" filters
	$('a.resetAdditionalDetails').click(function(e)
	{
		e.preventDefault();
		e.stopPropagation();
		$SCOUT.Filters.resetAdditionalDetails(this);
	});

	// event handler for "Start Over" link
	$('a.scoutStartOver').live('click', function(e)
	{
		e.preventDefault();
		e.stopPropagation();
		BrowsePCsController.StartOver();
	});

	// wire social bookmarks
	$SCOUT.Share.createSocialBookmarks();

	// wire scoutbox
	$SCOUT.Scoutbox.createScoutbox();

	// wire social bookmarks
	$SCOUT.Share.createSocialBookmarks();

	// wire scoutbox
	$SCOUT.Scoutbox.createScoutbox();

	//bind print functionality    
	$('.scoutSharePrint').click(function(e)
	{
		e.preventDefault();
		e.stopPropagation();
		print();
	});

	$('.scoutPcsPcLinks li.scoutPcsPcSeeAll a').click(function(e)
	{
		e.preventDefault();
		e.stopPropagation();
		BrowsePCsController.SeeAllLinkClicked(this.rel);
		window.location = this.href;
	});

	//keyboard accessibility enhancements
	$('.scoutFilters input.hiddenInput')
        .focus(function(e)
        {
        	$(this).siblings('label').addClass('focus');
        })
        .click(function(e)
        {
        	$(this).siblings('label').addClass('focus');
        })
        .blur(function(e)
        {
        	$(this).siblings('label').removeClass('focus');
        });

	$('.scoutFiltersReset')
        .focus(function(e)
        {
        	$(this).addClass('scoutHelperLinkFocus');
        })
        .blur(function(e)
        {
        	$(this).removeClass('scoutHelperLinkFocus');
        });

	$('.scoutFiltersMoreless ')
        .focus(function(e)
        {
        	$(this).addClass('scoutFiltersMorelessFocus');
        })
        .blur(function(e)
        {
        	$(this).removeClass('scoutFiltersMorelessFocus');
        });

	$('ul.scoutShowClear a')
        .focus(function(e)
        {
        	$(this).addClass('focus');
        })
        .blur(function(e)
        {
        	$(this).removeClass('focus');
        });

	$('a.scoutRetailerLink').click(function(e)
	{
		$SCOUT.Feedback.showFeedbackFrame();
	});

	$(window).bind('load', function(event)
	{
		InitializeStateFromUrl();
	});

	$SCOUT.Tooltip.initialize();
	$SCOUT.Feedback.initialize();
});

function GetCookieValue(variableName)
{
	var initialIndex = document.cookie.indexOf(variableName);
	if (initialIndex != -1)
	{
		var endOfVariableNameIndex = document.cookie.indexOf(";", initialIndex);
		if (endOfVariableNameIndex == -1)
		{
			endOfVariableNameIndex = document.cookie.length;
		}
		var fullVariable = document.cookie.substring(initialIndex, endOfVariableNameIndex);
		var variableValue = fullVariable.split("=")[1];
		if (variableValue != "empty")
		{
			return variableValue;
		}
	}
	return null;
}

function GetQueryString(name)
{
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null)
		return "";
	else
		return results[1];
}


function atlasFirePCModelJAction(atlastag, pcmodel)
{
	var friendlyModelNameArray = new Array();
	friendlyModelNameArray[0] = atlastag;
	var friendlyModelNameArrayIndex = 1;
	var isFirstWord = true;
	for (var i = 0; i < pcmodel.length; i++)
	{
		if (pcmodel.charAt(i) == ' ' && isFirstWord)
		{
			friendlyModelNameArray[friendlyModelNameArrayIndex] = '_'; //change the first space after the brand into underscore
			friendlyModelNameArrayIndex++;
			isFirstWord = false;
		}
		else if (pcmodel.charAt(i) == ' ' || pcmodel.charAt(i) == '-'
			|| pcmodel.charAt(i) == '(' || pcmodel.charAt(i) == ')')
		{
			//don't append anything to string builder if it's a special character
		}
		else
		{
			friendlyModelNameArray[friendlyModelNameArrayIndex] = pcmodel.charAt(i);
			friendlyModelNameArrayIndex++;
		}
	}
	var atlasTrackingFunction = "globaltracking.trackatlasonclick('http://view.atdmt.com/jaction/" + (friendlyModelNameArray.join('')).toLowerCase() + "');";
	eval(atlasTrackingFunction);
}

function InitializeStateFromUrl()
{
	if (window.location.hash.match(new RegExp('#tour', 'i')))
	{
		$("a[rel='scoutbox[jv101]']").click();
	}
}

/* Start Fast Facts behavior */
FastFacts = function()
{
}

FastFacts.prototype =
{
	initialize: function()
	{
		$("#scoutFastfactWidgetNextID").click(function(e)
		{
			e.preventDefault();
			e.stopPropagation();
			FastFacts.OnNextClicked(this);
		});
	},
	OnNextClicked: function(element)
	{
		var previousElementIsShown = false;
		var nextElementSetToShown = false;
		$("dl.fastfactsWidgetContainerCss div").each(function(i, elem)
		{
			if (!$(elem).hasClass("hidden"))
			{
				previousElementIsShown = true;
				$(elem).addClass("hidden");
			}
			else
			{
				if (previousElementIsShown && !nextElementSetToShown)
				{
					$(elem).removeClass("hidden");
					nextElementSetToShown = true;
				}
			}
		});
		if (!nextElementSetToShown)
			$("#fastfactsFirstItem").removeClass("hidden");


		previousElementIsShown = false;
		nextElementSetToShown = false;
		$(".scoutFastfactWidget h4 img").each(function(i, elem)
		{
			if (!$(elem).hasClass("hidden"))
			{
				previousElementIsShown = true;
				$(elem).addClass("hidden");
			}
			else
			{
				if (previousElementIsShown && !nextElementSetToShown)
				{
					$(elem).removeClass("hidden");
					nextElementSetToShown = true;
				}
			}
		});
		if (!nextElementSetToShown)
			$("#fastfactsFirstImgItem").removeClass("hidden");


		previousElementIsShown = false;
		nextElementSetToShown = false;
		$(".scoutFastfactWidget h5 a").each(function(i, elem)
		{
			if (!$(elem).hasClass("hidden"))
			{
				previousElementIsShown = true;
				$(elem).addClass("hidden");
			}
			else
			{
				if (previousElementIsShown && !nextElementSetToShown)
				{
					$(elem).removeClass("hidden");
					$(elem).addClass("scoutFastfactWidgetMore webanalyticsTracking omniModuleNameFastFacts");
					nextElementSetToShown = true;
				}
			}
		});
		if (!nextElementSetToShown)
			$("#fastfactsTitleLinkFirstItem").removeClass("hidden");

		previousElementIsShown = false;
		nextElementSetToShown = false;
		$(".scoutFastfactWidget #scoutFastfactWidgetHeadlineContainer div").each(function(i, elem)
		{
			if (!$(elem).hasClass("hidden"))
			{
				previousElementIsShown = true;
				$(elem).addClass("hidden");
			}
			else
			{
				if (previousElementIsShown && !nextElementSetToShown)
				{
					$(elem).removeClass("hidden");
					nextElementSetToShown = true;
				}
			}
		});
		if (!nextElementSetToShown)
			$("#fastfactsHeadlineFirstItem").removeClass("hidden");
	}
}
FastFacts.Initialize = function()
{
	FastFacts._staticInstance = new FastFacts();
	FastFacts._staticInstance.initialize();
}
FastFacts.OnNextClicked = function(element)
{
	FastFacts._staticInstance.OnNextClicked(element);
}
/* End Fast Facts behavior */

