﻿var IE4plus = (document.all) ? true : false;
var IE4 = ((document.all) && (navigator.appVersion.indexOf("MSIE 4.") != -1)) ? true : false;
var IE5 = ((document.all) && (navigator.appVersion.indexOf("MSIE 5.") != -1)) ? true : false;
var IE6 = ((document.all) && (navigator.appVersion.indexOf("MSIE 6.") != -1)) ? true : false;
var IE7 = ((document.all) && (navigator.appVersion.indexOf("MSIE 7.") != -1)) ? true : false;
var isIE = (IE4plus || IE4 || IE5 || IE6 || IE7) ? true : false;
var displayStyle = isIE ? "block" : "table-row";

var uniqueIDPopup;
var variantIDPopup;

function showProductPopup()
{
    $find(modalPopupExtenderClientID).show();
}

function addToCartPopup()
{
    addToCartWebService(uniqueIDPopup, variantIDPopup, true);
    closeProductPopup();
}

function closeProductPopup() 
{

    $get("customerReviewsMiddle").innerHTML = "";
    showPartsDetail();
    
    var modal = $find(modalPopupExtenderClientID);
    if (typeof (modal) != 'undefined' && modal != null)
    {
        modal.hide();
    }
}

function pageLoad(sender, args)
{
    $addHandler(document, "keydown", onKeyDown);
}

function onKeyDown(args)
{
    if (args.keyCode == Sys.UI.Key.esc)
    {
        closeProductPopup();
    }
}

function getProduct(recordID, showCustomerReviews)
{
	if (showCustomerReviews == undefined)
	{
		showCustomerReviews = false;
	}
	
	AutoAnything.Website.AutoAnything.WebServices.PartsProductPopupWebService.GetProduct(recordID, vehicleName, fitmentsArray, showCustomerReviews, getProductCallback, onGetProductError);
}

function getProductCallback(result)
{
    if (result != null)
    {
        $get("largeFilenamePopup").src = result.ImagePath + result.AAMediaLargeFilename;

        var productName = $get("productNamePopup");

        if (result.ProductName != "")
        {
            productName.innerHTML = result.ProductName;
        }

        var brandLogoImage = $get("brandLogoImage");
        if (result.BrandImageFilename != "")
        {
            brandLogoImage.parentNode.style.display = "block";
        	brandLogoImage.innerHTML = "<img src=\"" + result.ImagePath + "/" + result.BrandImageFilename + "\" alt=\"" + result.BrandDescription + "\" />";
        }
        else 
        {
        	brandLogoImage.parentNode.style.display = "none";
        }
        
        var productInfoText = $get("productInfoPopup");
        if (result.ProductRemark != "") 
        {
            productInfoText.innerHTML = result.ProductRemark;
            productInfoText.parentNode.parentNode.style.display = displayStyle;
        }
        else 
        {
            productInfoText.parentNode.parentNode.style.display = "none";
        }

        var fitmentNoteText = $get("fitmentNotePopup");
        if (result.Note != "") 
        {
            fitmentNoteText.innerHTML = result.Note;
            fitmentNoteText.parentNode.parentNode.style.display = displayStyle;
        }
        else 
        {
            fitmentNoteText.parentNode.parentNode.style.display = "none";
        }

        var variantPopup = $get("variantIDPopup");
//        if (result.VariantID != "")
//        {
//        	variantPopup.innerHTML = result.VariantID;
//        	variantPopup.parentNode.parentNode.style.display = displayStyle;
//        }
//        else
//        {
        	variantPopup.parentNode.parentNode.style.display = "none";
//        }

        var customerRating = $get("customerRating");
        if (result.CustomerRating > 0 && result.CustomerReviewCount > 0)
        {
        	customerRating.style.display = displayStyle;
        	var customerRatingPopup = $get("customerRatingPopup");
        	var plural = "";
        	if (result.CustomerReviewCount > 1)
        	{
        		plural = "s";
        	}
        	customerRatingPopup.innerHTML = "<a href=\"javascript:showCustomerReviews();\"><img src=" + result.ImagePath + "/rating/stars/red/" + result.CustomerRating.toPrecision(3) + ".gif /><span>(" + result.CustomerReviewCount + " Review" + plural + ")</span></a>";
        }
        else
        {
        	customerRating.style.display = "none";
        }

        var partNumber = $get("partNumber");
//        if (result.PartNumber != "")
//        {
//        	partNumber.innerHTML = result.PartNumber;
//        	partNumber.parentNode.parentNode.style.display = displayStyle;
//        }
//        else
//        {
        	partNumber.parentNode.parentNode.style.display = "none";
//        }

        var positionPopup = $get("positionPopup");
        var position = result.Position;
        if (typeof(position) == 'undefined' || position == null || position == "")
        {
            positionPopup.style.display = "none";
        }
        else
        {
            positionPopup.style.display = "inline";
            positionPopup.innerHTML = "- " + position;
        }

        // hide the dealer price (list price) if lower than the sale price
        var listPrice = $get("listPricePopup");
        if (!result.DisplayListPrice)
        {
            // hide tr (row in the table)
            listPrice.parentNode.parentNode.style.display = "none";
        }
        else
        {
            listPrice.parentNode.parentNode.style.display = "";
            listPrice.innerHTML = result.ListPrice;
        }
        
        $get("salePricePopup").innerHTML = result.SalePrice;
        $get("salePriceCorePopup").innerHTML = result.SalePrice;
        
        $get("unitCoreChargePopup").innerHTML = result.UnitCoreCharge + " core";
        $get("salePriceWithUnitCoreCharge").innerHTML = result.SalePriceWithUnitCoreCharge;

        if (result.SellingIncrement > 1)
        {
        	$get("salePricePopup").innerHTML = $get("salePricePopup").innerHTML + " each<br /><span id=\"sellingIncrement\">(sold in sets of " + result.SellingIncrement + ")</span>";
        	$get("salePriceWithUnitCoreCharge").innerHTML = $get("salePriceWithUnitCoreCharge").innerHTML + " each<br /><span id=\"sellingIncrement\">(sold in sets of " + result.SellingIncrement + ")</span>";
        }

		// Show Core charge pricing
        if (result.UnitCoreCharge == "$0.00") 
        {
        	$get("AutoAnythingPrice").style.display = displayStyle;

        	$get("AutoAnythingSalePrice").style.display = "none";
        	$get("AutoAnythingUnitCoreCharge").style.display = "none";
        	$get("AutoAnythingPriceSalePriceWithUnitCoreCharge").style.display = "none";
        }
        else 
        {
        	$get("AutoAnythingPrice").style.display = "none";

        	$get("AutoAnythingSalePrice").style.display = displayStyle;
        	$get("AutoAnythingUnitCoreCharge").style.display = displayStyle;
        	$get("AutoAnythingPriceSalePriceWithUnitCoreCharge").style.display = displayStyle;
        }

        
        // hide You Save if needed
        var youSave = result.YouSave;
        var youSavePopup = $get("youSavePopup");
        if (typeof (youSave) == 'undefined' || youSave == null || youSave == "")
        {
            // hide tr (row in the table)
            youSavePopup.parentNode.parentNode.style.display = "none";
        }
        else
        {
            youSavePopup.parentNode.parentNode.style.display = "";
            $get("youSavePopup").innerHTML = result.YouSave;
        }

        uniqueIDPopup = result.UniqueID;
        variantIDPopup = result.VariantID;

        $get("productIDPopup").value = result.ProductID;
        $get("partNumberPopup").value = result.PartNumber;
        $get("brandIDPopup").value = result.BrandID;

		// Show add to cart block in popup based on containing page
        var addToCartContainerPopup = $get("addToCartContainerPopup");
        var inStock = $get("inStock" + result.UniqueID);

        addToCartContainerPopup.className = inStock.className;
        addToCartContainerPopup.style.display = inStock.style.display;

        // Show out of stock block in popup based on containing page
        var outOfStockContainerPopup = $get("outOfStockContainerPopup");
        var outOfStock = $get("outOfStock" + result.UniqueID);

        outOfStockContainerPopup.className = outOfStock.className;
        outOfStockContainerPopup.style.display = outOfStock.style.display;

        // Show added to cart block in popup based on containing page
        var viewCartContainerPopup = $get("viewCartContainerPopup");
        var addedToCart = $get("addedToCart" + result.UniqueID);

        viewCartContainerPopup.className = addedToCart.className;
        viewCartContainerPopup.style.display = addedToCart.style.display;

        // create quantity dropdown
        var popupSellingIncrementDD = $get("popupSellingIncrementDD");
        var sellingIncrement = $get("sellingIncrement" + result.UniqueID);
        var maxQuantity = $get("quantityAvailable" + result.UniqueID);
        populateSellingIncrementDropDown(popupSellingIncrementDD, sellingIncrement.value, maxQuantity.value);

        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";
        }
	
        if (result.ShowCustomerReviews == true)
        {
        	showCustomerReviews();
        }
        else
        {
        	showProductPopup();
        }
    }
}

function addFitment(div, name, value, isProperty)
{
    var newdiv = document.createElement('p');

    if (name == "Vehicle")
    {
        newdiv.innerHTML = "<strong>" + value + "</strong>";
    }
    else
    {
        if (!isProperty)
        {
            newdiv.innerHTML = "<strong>" + name + ": " + value; + "</strong>";
        }
        else
        {
        	newdiv.innerHTML = "<span>" + name + ": " + value + "</span>";
        }
    }
    
    div.appendChild(newdiv);
}

function removeAllFitments(div)
{
    if (div.hasChildNodes())
    {
        while (div.childNodes.length >= 1)
        {
            div.removeChild(div.firstChild);       
        } 
    }
}

function onGetProductError(error)
{
    alert("An error has occurred while trying to process your request. Please refresh the browser and try again.");
}


function showCustomerReviews()
{
	// switch selected tab
	$get("customerReviewsTab").className = "customerReviewsTabSelected";
	$get("partsDetailTab").className = "partsDetailTab";

    var partsDetailBody = $get("partsDetailBody");
    var customerReviewBody = $get("customerReviewBody");

    partsDetailBody.style.display = "none";
    customerReviewBody.style.display = "block";

    var productID = $get("productIDPopup").value;
    var partNumber = $get("partNumberPopup").value;
    var brandID = $get("brandIDPopup").value;
    var pageID = "1";
    var showSummary = "false";
    var sortBy = "";
    getCustomerReviews(productID, partNumber, brandID, pageID, showSummary, sortBy);

    window.location.hash = "#top";
    showProductPopup();
}

function showPartsDetail()
{
	// switch selected tab
	$get("customerReviewsTab").className = "customerReviewsTab";
	$get("partsDetailTab").className = "partsDetailTabSelected";

    var partsDetailBody = $get("partsDetailBody");
    var customerReviewBody = $get("customerReviewBody");

    partsDetailBody.style.display = "block";
    customerReviewBody.style.display = "none";
}

function sortCustomerReviews(sortBy)
{
	var productID = $get("productIDPopup").value;
	var partNumber = $get("partNumberPopup").value;
	var brandID = $get("brandIDPopup").value;
    var pageID = "1";
    var showSummary = "true";
    getCustomerReviews(productID, partNumber, brandID, pageID, showSummary, sortBy);

    window.location.hash = "#top";
}

function getCustomerReviewsPagination(productID, partNumber, brandID, pageID, showSummary, sortBy)
{
	AutoAnything.Website.AutoAnything.WebServices.PartsProductPopupWebService.GetCustomerReviews(productID, partNumber, brandID, pageID, showSummary, sortBy, getCustomerReviewsCallback, onGetProductError);
    
    window.location.hash = "#middle";
}

function getCustomerReviews(productID, partNumber, brandID, pageID, showSummary, sortBy)
{
	AutoAnything.Website.AutoAnything.WebServices.PartsProductPopupWebService.GetCustomerReviews(productID, partNumber, brandID, pageID, showSummary, sortBy, getCustomerReviewsCallback, onGetProductError);
}

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.
        var averageRatingsStars = "<img src=\"" + result.StarRatingUrl + "\" alt=\"" + result.StarRating + "\" align=\"absmiddle\" />";
        $get("averageRatingsStars").innerHTML = averageRatingsStars;

        // 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].VehicleYearID + " " + result.Reviews[i].VehicleMakeName + " " + result.Reviews[i].VehicleModelName;
            //<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\">";
            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>";
            }
            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>";
            
//            r[r.length] = "<div id=\"panel" + result.Reviews[i].CustomerReviewID + "\" class=\"customerReviewProfilePanel\">";
//            r[r.length] = "    <div class=\"bd\">";
//            r[r.length] = "        <strong>About " + result.Reviews[i].FullName + "</strong>";
//            for (var k = 0; k < result.Reviews[i].ReviewMembers.length; k++) {
//                r[r.length] = "<div><strong>" + result.Reviews[i].ReviewMembers[k].AttributeName + "</strong></div>";
//                r[r.length] = "<div>" + result.Reviews[i].ReviewMembers[k].AttributeValue + "</div>";
//            }
//            r[r.length] = "    </div>";
//            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.
        $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);
    AutoAnything.Website.AutoAnything.WebServices.PartsProductPopupWebService.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) { }



