﻿// Global Variables
var resizeTimer = null;
var quickViewTimer = null;
var quickViewImg = null;
var ProductURL = null;

/********** Quick View **********/

if (isValidBrowser() && typeof window.jQuery != "undefined")
{
	$(document).ready(function()
	{
		// hide popup on esc key press
		$addHandler(document, "keydown", onKeyDown);

		// Use a timer so that multiple resize events are not queued up
		$(window).bind('resize', function()
		{
			if (resizeTimer) { clearTimeout(resizeTimer); }
			resizeTimer = setTimeout(CenterQuickView, 100);
		});

		// setup slider
		//		$("#ratingSlider").slider({
		//			min: 1,
		//			max: 5,
		//			range: "min",
		//			value: 1,
		//			orientation: 'horizontal',
		//			animate: true,
		//			change: function(e, ui)
		//			{
		//				//alert(ui.value);
		//			}
		//		});

		// initialize quick view icons as showing
		$("div.productList > div.productItem > a.showQuickView > img").each(function()
		{
			$(this).fadeTo(1, 0);
		});

		// click away function
		$("div#popupExpose").click(function()
		{
			ToggleQuickView();
		});

		setTimeout(HookUpQuickViewHover, 1000);

	});
}

function HookUpQuickViewHover()
{
	// product hover function
	$("div.mbitem, div.productItem").hover(function()
	{
		quickViewImg = $(this).find("a.showQuickView > img.quickViewImg");

		// position quick look button relative to product box
		quickViewImg.css({ "top": $(this).offset().top + "px" });
		quickViewImg.css({ "left": $(this).offset().left + 30 + "px" });

		// set show timer
		if (quickViewTimer) { clearTimeout(quickViewTimer); }
		quickViewTimer = setTimeout(ShowQuickViewIcon, 100);
	},
	function()
	{
		if (quickViewTimer) { clearTimeout(quickViewTimer); }
		if (quickViewImg == null)
		{
			quickViewImg = $(this).find("a.showQuickView > img.quickViewImg");
			quickViewImg.stop(true, true);

			// no fade in ie
			if (jQuery.browser.msie)
			{
				quickViewImg.hide();
				quickViewImg.css({ display: "none" });
			}
			else
			{
				quickViewImg.fadeTo(400, 0, function()
				{
					if (quickViewImg != null)
					{
						quickViewImg.css({ display: "none" });
					}
				});
			}
		}
	});

	// no fade in ie (black background jquery issue)
	if (!jQuery.browser.msie)
	{
		$("a.showQuickView > img.quickViewImg").hover(function()
		{
			$(this).fadeTo(100, 1);
		},
			function()
			{
				$(this).fadeTo(100, .75);
			});
	}
}

function ShowQuickViewIcon()
{
	if (quickViewImg != null)
	{
		// no fade for ie
		if (jQuery.browser.msie)
		{
			quickViewImg.stop(true, true);
			quickViewImg.css({ display: "inline" });
			quickViewImg.show();
			quickViewImg = null;
		}
		else
		{
			quickViewImg.stop(true, true);
			quickViewImg.css({ display: "inline" });
			quickViewImg.fadeTo(10, .75);
			quickViewImg = null;
		}
	}
}

// center quick view when screen size changes
function CenterQuickView()
{
	$("div#popupBox").centerEasing(500, 'easeOutExpo');
	$("div#popupExpose").css({ height: $(window).height(), width: $(window).width() });
}
function CenterQuickViewHorizontal()
{
	$("div#popupBox").centerHorizontal();
	$("div#popupExpose").css({ height: $(window).height(), width: $(window).width() });
}

// on successful ajax post, show popup box
function ToggleQuickView(productID, productURL)
{
	var quickViewBox = $("div#popupBox");
	var quickViewExposeBG = $("div#popupExpose");

	// set global image path
	ProductURL = productURL;

	// stop current animation and clear queue
	quickViewBox.stop(true, true);
	quickViewExposeBG.stop(true, true);

	// when showing, wait for the centering to happen
	if (quickViewBox.is(":hidden"))
	{
		getProduct(productID);
		getCustomerReviews(productID, "1", "false", "HR");


		// render in full size, center, then return to display none state so jquery toggle works
		quickViewBox.css({ display: "block", visibility: "hidden" });
		CenterQuickView();
		quickViewBox.css({ display: "none", visibility: "visible" });

		CenterQuickViewHorizontal();

		// wait until window is no longer being resized to begin re-centering
		setTimeout(function()
		{
			quickViewBox.stop(true, true);
			quickViewExposeBG.stop(true, true);

			if (jQuery.browser.msie)
			{
				quickViewBox.animate({ opacity: "toggle" }, 0);
			}
			else
			{
				quickViewBox.animate({ opacity: "toggle" }, 400, 'easeOutExpo');
			}
			quickViewExposeBG.animate({ opacity: "toggle" }, 0);
		}, 500);
	}
	else
	{
		if (jQuery.browser.msie)
		{
			quickViewBox.animate({ opacity: "toggle" }, 0);
		}
		else
		{
			quickViewBox.animate({ opacity: "toggle" }, 400, 'easeOutExpo');
		}
		quickViewExposeBG.animate({ opacity: "toggle" }, 0);
    }

    // use partsDetail Tab to start.
    showPartsDetail();	
}

// Webservice call to get product for quickview
function getProduct(productID)
{
	var categoryID = 0;
	if (typeof CategoryID != 'undefined')
	{
		categoryID = CategoryID;
	}
	CategoryNavigationWebService.GetProductQuickViewPopup(visitID, visitorID, storeID, productID, categoryID, getProductQuickViewPopupCallback, getProductQuickViewPopupError);
}

function getProductQuickViewPopupCallback(result)
{
	if (result != null)
	{
		var tableRowDisplayValue = "table-row";

		// ie7 does not recognize "table-row"
		if (jQuery.browser.msie)
		{
			tableRowDisplayValue = "block"
		}

		if (result.CustomerReviewCount == 0)
		{
			$get("partsDetailTab").style.display = "none";
			$get("customerReviewsTab").style.display = "none";
		}
		else
		{
			$get("partsDetailTab").style.display = "block";
			$get("customerReviewsTab").style.display = "block";
		}

		$get("brandLogo").style["display"] = result.BrandImageFileName != '' ? "block" : "none";
		$get("brandLogoImg").src = ImagePath + result.BrandImageFileName;

		if (result.ProductImages.MediumImages.length > 0)
		{
			$get("largeFilenamePopup").src = ImagePath + result.ProductImages.MediumImages[0].MediaFilename;
			$get("largeFilenamePopup").alt = ImagePath + result.ProductImages.MediumImages[0].MediaAltTag;
		}
		else
		{
			// set to no image available image
			//$get("largeFilenamePopup").src = ImagePath + 
		}

		$get("productNamePopup").innerHTML = "<a href=\"" + ProductURL + "\">" + result.ProductName + "</a>";

		$get("listPricePlaceHolder").style["display"] = result.ListPriceText != "" ? tableRowDisplayValue : "none";
		$get("listPriceLable").innerHTML = result.ListPriceText;

		$get("AAPricePlaceHolder").style["display"] = (result.IsMap == false && (result.SalePriceText != "" || result.RegularPriceText != "")) ? tableRowDisplayValue : "none";
		$get("AutoAnythingPriceLable").innerHTML = result.SalePriceText == "" ? result.RegularPriceText : result.SalePriceText + result.DisplayProductSoldByDescription;
		$get("savings").innerHTML = result.SavingsPercentage != "" ? "(save " + result.SavingsPercentage + ")" : "";

		$get("shippingCost").innerHTML = result.ShippingCost;

		$get("productRatingPlaceHolder").style["display"] = result.StarRating > 1 ? tableRowDisplayValue : "none";
		$get("customerReviewStarImg").src = ImagePath + "/rating/stars/red/" + result.StarRating.toFixed(2) + ".gif";
		$get("customerReviewCount").innerHTML = "(" + result.CustomerReviewCount + " Reviews)";

		$get("productCustomerRecommendationPlaceHolder").style["display"] = result.IsRecommendedCount > 0 ? tableRowDisplayValue : "none";
		$get("productCustomerRecommendation").innerHTML = result.IsRecommendedCount + " out of " + result.CustomerReviewCount + " people recommended this product";

		$get("productShippingContent").style["display"] = result.ProductHolidayShippingInfo != "" ? tableRowDisplayValue : "none";
		$get("productHolidayShipping").innerHTML = result.ProductHolidayShippingInfo;

		if (result.ProductImages.SwatchImages.length > 1)
		{
			$get("availableColors").style["display"] = result.ProductImages.SwatchImages[0].ColorID != undefined ? "block" : "none";
			$get("swatchesDiv").innerHTML = getSwatchesHTML(result);
		}
		else
		{
			$get("availableColors").style["display"] = "none";
		}

		$get("productIDPopup").value = result.ProductID;

		if (result.CategoryShortDescription.length > 0)
		{
			$get("productDetailsTop").style["display"] = "block";
			$get("productDetails").innerHTML = "<h2>Description</h2><p>" + result.CategoryShortDescription + "</p>";
		}
		else
		{
			$get("productDetailsTop").style["display"] = "none";
		}

		$get("seeDetailsButton").innerHTML = "<a style=\"float: right;\" href=\"" + ProductURL + "\"><img alt=\"\" src=\"" + ImagePath + "/website3/buttons/see_details.gif\" /></a>";
	}
}

function getProductQuickViewPopupError(error)
{
	alert("An error has occurred while trying to process your request. Please refresh the browser and try again.");
}

function getSwatchesHTML(result)
{
	var htmlResult = "";
	for (var i = 0; i < result.ProductImages.SwatchImages.length; i++)
	{
		if (getMediumMediaFilenameByColor(result, result.ProductImages.SwatchImages[i].ColorID).length > 0)
		{
			htmlResult = htmlResult + " <a href=\"javascript:UpdatePopupMediumImage('" + ImagePath + getMediumMediaFilenameByColor(result, result.ProductImages.SwatchImages[i].ColorID) + "','" + result.ProductImages.SwatchImages[i].ColorDescription + "');\"><img class=\"colorSwatch\" src=\"" + ImagePath + result.ProductImages.SwatchImages[i].MediaFilename + "\"</img></a>";
		}
		else
		{
			htmlResult = htmlResult + " <a href=\"javascript:UpdatePopupMediumImage('','" + result.ProductImages.SwatchImages[i].ColorDescription + "');\"><img class=\"colorSwatch\" src=\"" + ImagePath + result.ProductImages.SwatchImages[i].MediaFilename + "\"</img></a>";
		}
	}

	return htmlResult;
}

function UpdatePopupMediumImage(mediumMediaFilename, colorDesc)
{
	if (mediumMediaFilename != '')
	{
		$("img#largeFilenamePopup").animate({ opacity: "toggle" }, 100, 'easeOutQuad',
		function()
		{
			$get("largeFilenamePopup").src = mediumMediaFilename;
			$("img#largeFilenamePopup").animate({ opacity: "toggle" }, 400, 'easeInQuad');
		});
	}

	if (colorDesc != '' && colorDesc != undefined)
	{
		$get("availableColorDesc").innerHTML = "Available Colors (" + colorDesc + ")";
	}
	else
	{
		$get("availableColorDesc").innerHTML = "Available Colors";
	}
}

function getMediumMediaFilenameByColor(result, ColorID)
{
	for (var i = 0; i < result.ProductImages.LargeImages.length; i++)
	{
		if (result.ProductImages.MediumImages[i].ColorID == ColorID)
		{
			return result.ProductImages.MediumImages[i].MediaFilename;
		}
	}

	return "";
}


/********** Helper Functions **********/

// helper function to hide popup when esc key is pressed
function onKeyDown(args)
{
	if (args.keyCode == Sys.UI.Key.esc && $("div#popupBox").is(":visible"))
	{
		ToggleQuickView();
	}
}

// helper function to check for ie6
function isValidBrowser()
{
	isValid = false;
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		var ua = navigator.userAgent;

		// ie8 fakes its signature to look like ie6 so we need to use a regex to filter it
		var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
		{
			// if browser version > 6 then browser is valid
			if (parseFloat(RegExp.$1) > 6)
			{
				isValid = true;
			}
		}
	}
	else
	{
		// if not ie then valid
		isValid = true;
	}
	return isValid;
}


/********** Same Code as PartsProductPopup.js for popup cutsomer review functionality **********/

function showCustomerReviews()
{
	// switch selected tab
	$get("customerReviewsTab").className = "customerReviewsTabSelected";
	$get("partsDetailTab").className = "partsDetailTab";

	$("div#partsDetailBody").fadeOut(100, function()
	{
		$("div#customerReviewBody").fadeIn(400);
	});

	var productID = $get("productIDPopup").value;
	var pageID = "1";
	var showSummary = "false";
	var sortBy = "";
	getCustomerReviews(productID, pageID, showSummary, sortBy);

	window.location.hash = "#top";
}

function showPartsDetail()
{
	// switch selected tab
	$get("customerReviewsTab").className = "customerReviewsTab";
	$get("partsDetailTab").className = "partsDetailTabSelected";

	$("div#customerReviewBody").fadeOut(100, function()
	{
		$("div#partsDetailBody").fadeIn(400);
	});
}

function sortCustomerReviews(sortBy)
{
	var productID = $get("productIDPopup").value;
	var pageID = "1";
	var showSummary = "true";
	getCustomerReviews(productID, pageID, showSummary, sortBy);

	window.location.hash = "#top";
}

function getCustomerReviewsPagination(productID, pageID, showSummary, sortBy)
{
	CategoryNavigationWebService.GetCustomerReviews(productID, pageID, showSummary, sortBy, vehicleMakeID, vehicleModelID, vehicleYearID, getCustomerReviewsCallback, onGetProductError);

	window.location.hash = "#middle";
}

function getCustomerReviews(productID, pageID, showSummary, sortBy)
{


	CategoryNavigationWebService.GetCustomerReviews(productID, pageID, showSummary, sortBy, vehicleMakeID, vehicleModelID, vehicleYearID, getCustomerReviewsCallback, onGetProductError);
}

function onGetProductError(error)
{
	alert("An error has occurred while trying to process your request. Please refresh the browser and try again.");
}

function getCustomerReviewsCallback(result)
{
	if (result != null)
	{
		// Set the SortBy Dropdown.
		if (result.SortBy != "")
		{
			var sortByDropDown = $get("sortByOne");

			if (result.SortBy == "HR")
			{
				sortByDropDown.selectedIndex = 1;
			}
			else if (result.SortBy == "LR")
			{
				sortByDropDown.selectedIndex = 2;
			}
			else if (result.SortBy == "NEW")
			{
				sortByDropDown.selectedIndex = 3;
			}
			else if (result.SortBy == "OLD")
			{
				sortByDropDown.selectedIndex = 4;
			}
			else if (result.SortBy == "MH")
			{
				sortByDropDown.selectedIndex = 5;
			}
		}

		// Display Average Customer Rating Stars.
		if (result.StarRatingUrl.length > 0)
		{
			var averageRatingsStars = "<img src=\"" + result.StarRatingUrl + "\" alt=\"" + result.StarRating + "\" align=\"absmiddle\" />";
			$get("averageRatingsStars").innerHTML = averageRatingsStars;
			$get("customerReviewsTop").style["display"] = "block";
		}
		else
		{
			$get("customerReviewsTop").style["display"] = "none";
		}

		// Display Average Customer Rating items.
		var s = new Array();
		for (var i = 0; i < result.OverallRatings.length; i++)
		{
			s[s.length] = "<div id=\"averageStarItem\">";
			s[s.length] = "<div id=\"starText\"><strong>Average " + result.OverallRatings[i].AttributeTypeDesc + "</strong></div>";
			s[s.length] = "<div id=\"starImg\"><img src=\"" + result.OverallRatings[i].StarRatingUrl + "\" alt=\"" + result.OverallRatings[i].StarRating + "\" align=\"absmiddle\" /></div>";
			s[s.length] = "</div>";
		}
		$get("averageRatingsContainerStars").innerHTML = s.join("");

		// Loop through all reviews.
		var r = new Array();
		for (var i = 0; i < result.Reviews.length; i++)
		{
			r[r.length] = "<div id=\"customerReviewEntry\">";

			r[r.length] = " <div id=\"customerReviewHeading\">";
			r[r.length] = "  <div id=\"customerReviewStarRating\">";
			r[r.length] = "   <img src=\"" + result.Reviews[i].StarRatingUrl + "\" alt=\"\" align=\"absmiddle\" />";
			r[r.length] = "  </div>";
			r[r.length] = "  <span><strong>" + result.Reviews[i].ReviewTitle + "</strong></span>";
			r[r.length] = " </div>";

			r[r.length] = "<p id=\"customerReviewDate\">";
			r[r.length] = result.Reviews[i].ThumbsUp;
			r[r.length] = "<em>Posted on <strong>" + result.Reviews[i].CreateDate + "</strong> by ";

			r[r.length] = result.Reviews[i].MemberProfileLink + " - " + result.Reviews[i].VehicleDesc

			//<asp:PlaceHolder ID="memberProfileVehiclePlaceHolder" runat="server" />
			r[r.length] = " (" + result.Reviews[i].CityNameTitleCase + ", " + result.Reviews[i].StateCode + ")</em>";
			r[r.length] = "</p>";

			r[r.length] = "<p id=\"customerReviewRating\" " + result.Reviews[i].HelpfulIndicatorFormated + " >";

			r[r.length] = "<strong><span id=\"yesCount" + result.Reviews[i].CustomerReviewID + "\">" + result.Reviews[i].HelpfulSum + "</span>";
			r[r.length] = "</strong> of <strong><span id=\"totalCount" + result.Reviews[i].CustomerReviewID + "\">" + result.Reviews[i].HelpfulIndicator + "</span>";
			r[r.length] = "</strong> people found the following review helpful.";

			r[r.length] = "</p>";

			// Loop through all Individual Rating attributes.
			r[r.length] = "<div class=\"individualRatingsContainer\">";
			if (result.Reviews[i].IndividualRatings.length > 0)
			{
				for (var j = 0; j < result.Reviews[i].IndividualRatings.length; j++)
				{
					r[r.length] = "<div class=\"individualRatingsInfo\">";
					r[r.length] = "<img src=\"" + result.Reviews[i].IndividualRatings[j].StarRatingUrl + "\" alt=\"\" align=\"absmiddle\" />";
					r[r.length] = result.Reviews[i].IndividualRatings[j].AttributeTypeDesc;
					r[r.length] = "</div>";
				}
			}
			else
			{
				r[r.length] = "<img src=\"" + ImagePath + "/website3/category_navigation/quick_view/no_review_details_available.gif\" alt=\"\" align=\"absmiddle\" />";
			}
			r[r.length] = "</div>";

			r[r.length] = "<p id=\"customerReviewText\">&quot;" + result.Reviews[i].ReviewText + "&quot;</p>";

			r[r.length] = "<p class=\"customerReviewHelpful\" id=\"voteContainer" + result.Reviews[i].CustomerReviewID + "\">";
			r[r.length] = "Was this review helpful? <a href=\"javascript:void(0);\" onclick=\"javascript:vote(" + result.Reviews[i].CustomerReviewID + ", true);\" id=\"yes" + result.Reviews[i].CustomerReviewID + "\" rel=\"nofollow\"><strong>Yes</strong></a> ";
			r[r.length] = "<a href=\"javascript:void(0);\" onclick=\"javascript:vote(" + result.Reviews[i].CustomerReviewID + ", false);\" id=\"no" + result.Reviews[i].CustomerReviewID + "\" rel=\"nofollow\"><strong>No</strong></a>";
			r[r.length] = "</p>";

			r[r.length] = "</div>";

			if (i != result.Reviews.length - 1)
			{
				r[r.length] = "<div id=\"reviewBreak\">&nbsp;</div>";
			}
		}

		$get("customerReviewsMiddle").innerHTML = r.join("");

		// Add Pagination.
		if (result.Pagination.length > 0 && result.PageCount > 14)
		{
			$get("customerReviewsBottom").innerHTML = result.Pagination + "<a class=\"moreLink\" href=\"" + ProductURL + "#customerReview\" >More</a>";
		}
		else
		{
			$get("customerReviewsBottom").innerHTML = result.Pagination;
		}
	}
}

function showProfilePanel(panelID, linkID)
{
	var menu = new YAHOO.widget.Menu(panelID,
		{
			context: [linkID, "tl", "bl"],
			visible: true,
			clicktohide: true,
			underlay: "none",
			effect: { effect: YAHOO.widget.ContainerEffect.FADE, duration: 0.09 }
		}
	);
	var kl = new YAHOO.util.KeyListener(document, { keys: 27 }, { fn: menu.hide, scope: menu, correctScope: true });
	menu.cfg.queueProperty("keylisteners", kl);
	kl.enable();
	menu.render();
}

function disableVoteLinks(customerReviewID)
{
	var voteContainer = document.getElementById("voteContainer" + customerReviewID);
	if (voteContainer != null)
	{
		voteContainer.innerHTML = "Thank you for voting.";
	}
}

function vote(customerReviewID, bIsReviewHelpful)
{
	disableVoteLinks(customerReviewID);
	CategoryNavigationWebService.Vote(customerReviewID, visitorID, bIsReviewHelpful, voteCallback, onCustomerReviewError);
}

function voteCallback(result)
{
	if (result != null)
	{
		var yesCount = document.getElementById("yesCount" + result.CustomerReviewID);
		var totalCount = document.getElementById("totalCount" + result.CustomerReviewID);

		if (yesCount != null && totalCount != null)
		{
			yesCount.innerHTML = result.YesVotes;
			totalCount.innerHTML = " " + result.TotalVotes;
		}
	}
}

function onCustomerReviewError(error)
{
	alert("An error has occurred while trying to process your request. Please refresh the browser and try again.");
}