﻿// JScript File

// Add selected ensemble products to the shopping bag.
function AddEnsembleToBag()
{
    alert("This will add ensemble products to the bag.");
}

// Total price for all selected ensemble products.
var runningEnsembleTotal = 0.00;

// Remove a product from the selected products or add a selected one.
function ChangeEnsembleProductSelection(controlSetId, selected, price, discounted)
{
    if (selected)
    {
        SelectEnsembleProductWebPID(controlSetId, price);        
    }
    else
    {
        UnselectEnsembleProductWebPID(controlSetId);
    }

    if (discounted) {
        DiscountItemSelectionChanged(selected);
    }
}

// Hide the flyout displaying an ensemble's description.
function CloseEnsembleProductDescription()
{
    var flyout = $("ensemble_product_description");
    if (flyout)
    {        
        flyout.style.display = 'none';
        if(isIE6 && DescriptionShim != null){
            DescriptionShim.style.display = 'none';
        }
    }
}

// Show the flyout displaying an ensemble's description.
var DescriptionShim = null;
function ShowEnsembleProductDescription(controlSetId, sourceDivID, locationDivID, alignBottom)
{
    var source = $(sourceDivID);
    var target = $("ensemble_product_description");
    if(isIE6 && DescriptionShim == null){
        DescriptionShim = document.createElement("<iframe frameborder='0' scrolling='no'>");
        $(DescriptionShim).setStyle({'position': 'absolute'});
        $('bodyBlock').appendChild(DescriptionShim);
    }
    var locationDiv = $(locationDivID);
    if (typeof alignBottom == "undefined") { alignBottom = false; }
    if (source && target && locationDiv)
    {
        // Strip out the the control set id so that javascript doesn't update the wrong element.
        target.innerHTML = source.innerHTML.replace(new RegExp(controlSetId + '"', "g"), '"');
        Position.clone(
            locationDiv, 
            target, 
            {
                setWidth: false, 
                setHeight: false, 
                offsetTop: alignBottom ? (Element.getHeight(locationDiv) - Element.getHeight(target)) : 0
            }
        );
        target.style.display = 'block';
        
        if(isIE6 && DescriptionShim != null){
            // Move shim to the same location
            Position.clone(target, DescriptionShim);
            DescriptionShim.style.display = 'block';
        }
    }
}

// Create a list of PDOptionInfo objects
var selectedEnsembleProductControlSetIDs = new Array();
var selectedEnsembleProductWebPIDs = new Array();
var selectedEnsembleProductQuantities = new Array();
var selectedEnsembleProductPrices = new Array();
function SelectEnsembleProductWebPID(controlSetId, price)
{   
    var webPID = GetWebPIDForControlSet(controlSetId);
    var actualPrice = price;
    if (eval("window.Matrix" + controlSetId + "ProductList != undefined"))
    {
        var productList = eval("Matrix" + controlSetId + "ProductList");
        var i;
        for (i = 0; i < productList.length; i++)
        {
            if (productList[i].WebPId == webPID)
            {
                actualPrice = productList[i].SalePrice;
                break;
            }
        }
    }    
    if (selectedEnsembleProductWebPIDs)
    {
        var quantity = GetEnsembleProductQuantity(controlSetId);
        selectedEnsembleProductControlSetIDs.push(controlSetId);
        selectedEnsembleProductWebPIDs.push(webPID);
        selectedEnsembleProductQuantities.push(quantity);
        selectedEnsembleProductPrices.push(actualPrice * quantity);
        
        // Update the running totals
        DisplayRunningEnsembleTotals();
    }
}

// Remove an ensemble product from the list of selected products
function UnselectEnsembleProductWebPID(controlSetId)
{
    if (selectedEnsembleProductWebPIDs)
    {        
        // Find the selected webPID
        var targetIndex;
        for (index = 0; index < selectedEnsembleProductWebPIDs.length; index++)
        {
            if (selectedEnsembleProductControlSetIDs[index] == controlSetId)
            {
                targetIndex = index;
                break;
            }
        }
        
        // Remove the selected webPID, if it was found
        if (targetIndex != undefined)
        {
            selectedEnsembleProductControlSetIDs.splice(targetIndex, 1);
            selectedEnsembleProductWebPIDs.splice(targetIndex, 1);
            selectedEnsembleProductQuantities.splice(targetIndex, 1);
            selectedEnsembleProductPrices.splice(targetIndex, 1);
        }
    }
    
    // Update the running total
    DisplayRunningEnsembleTotals();        
}

// Get the selected quantity for an ensemble product
function GetEnsembleProductQuantity(controlSetId)
{        
    var ddlQty = $(eval("itemQuantityDropDownClientID" + controlSetId));
    var quantity = 1;
    if(ddlQty)
    {
        quantity = parseInt(ddlQty.options[ddlQty.selectedIndex].value);
        if (isNaN(quantity) || quantity == 0)
        {
            quantity = 1;
        }
    }
    return (quantity);
}

// Display the running total price of all selected ensemble products
function DisplayRunningEnsembleTotals()
{
    var totalDiv = $("EnsembleRunningTotal");
    var countDiv = $("EnsembleRunningCount");

    // Sum up all prices and quantities
    var totalPrice = 0;
    var totalQuantity = 0;
    var index;
    for (index = 0; index < selectedEnsembleProductQuantities.length; index++)
    {
        totalPrice += selectedEnsembleProductPrices[index];
        totalQuantity += selectedEnsembleProductQuantities[index];
    }
    
    // Display calculated values
    if (totalDiv)
    {
        totalDiv.innerHTML = (totalPrice / 100).toFixed(2);
    }
    if (countDiv)
    {
        countDiv.innerHTML = totalQuantity;
    }
}

function GetWebPIDForControlSet(controlSetId)
{
    if (eval("window.Matrix" + controlSetId + "CurrentWebPID != undefined") && eval("Matrix" + controlSetId + "CurrentWebPID != ''"))
    {
        webPID = eval("Matrix" + controlSetId + "CurrentWebPID")
    }
    else
    {
        webPID = controlSetId;
    }
    return webPID;
}

// Called when a product's quantity is changed
function ProductQuantityChanged(controlSetId)
{
    var webPID = GetWebPIDForControlSet(controlSetId);
    var index;
    for (index = 0; index < selectedEnsembleProductWebPIDs.length; index++)
    {
        if (selectedEnsembleProductWebPIDs[index] == webPID)
        {
            var newQuantity = GetEnsembleProductQuantity(controlSetId);
            var oldQuantity = selectedEnsembleProductQuantities[index];                
            selectedEnsembleProductPrices[index] = (selectedEnsembleProductPrices[index] / oldQuantity) * newQuantity;
            selectedEnsembleProductQuantities[index] = newQuantity;
            DisplayRunningEnsembleTotals();
            break; 
        }
    }
}

// Add all selected ensemble products to the shopping cart
function AddEnsembleProductsToBag(element, url, crrRequest)
{
    if (selectedEnsembleProductWebPIDs && selectedEnsembleProductWebPIDs.length)
    {   
        // Show busy pointer
        document.body.style.cursor = "wait";
        element.style.cursor = "wait";
        
        // Prepare the flyout to be shown
        if(flyoutTimerID && flyoutTimerID != null)
        {
            window.clearTimeout(flyoutTimerID);
        }
       
        // Build query string segment for each product
        url = url + "?CurrentPage=" 
                    + crrRequest;
        var productInfo;
        var pdOptions;
        var currentControlSet;
        var currentWebPId;
        var errorFound = false;
        for (index = 0; index < selectedEnsembleProductWebPIDs.length; index++)
        {                       
            currentControlSet = selectedEnsembleProductControlSetIDs[index];
            currentWebPId = selectedEnsembleProductWebPIDs[index];
            pdOptions = new PDOptionsInfo(currentControlSet);
            pdOptions = addPaymentOptions(pdOptions, currentControlSet);
            
            //do form check
            if(formCheckV7("addtocart", pdOptions, currentControlSet))
            {
                productInfo = eval("PDVarInfo" + currentControlSet);                
                url = url 
                    + "&webp_id=" 
                    + currentWebPId 
                    + "&web_id=" 
                    + (productInfo.webid == null ? currentWebPId : productInfo.webid)
                    + constructQuerystringFromOptions(pdOptions)
                    + "[,]";
            }
            else
            {
                errorFound = true;
                break;
            }            
        }     
        
        if (!errorFound)
        {
            // Remove the last ampersand and divider
            url = url.substr(0, url.length - 3);
            
            var opt = {
                // Use POST
                method: 'post',    
                // Handle successful response
                onSuccess: function(t) 
                {               
                    checkStats(t.responseText, element);
                    allowAjaxCall = true;
                    
                    // Insert Cormetrics Tags
    //                    addShop5Tags();                        
                },
                // Handle 404
                on404: function(t) 
                {
                    document.body.style.cursor = "default";
                    element.style.cursor = "pointer";
                    allowAjaxCall = true;
                    alert('Error 404: location "' + t.statusText + '" was not found.');    
                },
                // Handle other errors
                onFailure: function(t) {
                    document.body.style.cursor = "default";
                    element.style.cursor = "pointer";
                    allowAjaxCall = true;
                    alert('Error ' + t.status + ' -- ' + t.statusText);
                }
            }
                
            if(allowAjaxCall)
            {
                new Ajax.Request(url, opt);
                allowAjaxCall = false;
            }
        }
        else
        {
            document.body.style.cursor = "default";
            element.style.cursor = "pointer";
            allowAjaxCall = true;         
        }
    }
    else
    {
        document.body.style.cursor = "default";
        element.style.cursor = "pointer";
        allowAjaxCall = true;     
        alert("Oops - you forgot to select an item.");
    }    
}

// Determine if all variants for a product have been set by the user.
// Return false if one variant has not been selected.  Otherwise, return true.
// Optionally, highlights a drop-down list if no value has been selected with it.
function CheckVariantSelections(controlSetId, highlightError)
{
	var info = eval("PDVarInfo" + controlSetId);
	var option, select0, select1, select2, allSelected = true;
	if (typeof hightlightError == "undefined")
	{
	    hightlightError = false;
	}
	
	// Get relevant dropdowns
	if(info && info != null)
	{	
	    option = $(eval("itemOptionDropDownID" + controlSetId ));
	    select0 = info.ddlvariant1;
	    select1 = info.ddlvariant2;
	    select2 = info.ddlvariant3;	    
	}

	// process each variant select if they exist
	if (option != null && option.options[option.selectedIndex].value == "") 
	{ 
	    allSelected = false;
		if (highlightError)
		{
		    option.className = "productOptionDropDownError";
        }
	}
	else
	{
	    allSelected = true;
	}
	if (allSelected && select0 != null) { allSelected = CheckElementSelection(select0, highlightError); }
	if (allSelected && select1 != null) { allSelected = CheckElementSelection(select1, highlightError); }
	if (allSelected && select2 != null) { allSelected = CheckElementSelection(select2, highlightError); }
	
	return allSelected;
}

// Check whether a dropdown has a selected value.
// Optionally, highlight it if it does not.
function CheckElementSelection(dropdown, highlightError)
{
    var selected = true;
	if (dropdown.selectedIndex <= 0)
	{
	    selected = false;
		if (highlightError)
		{
		    dropdown.className = "productOptionDropDownError";
        }
	}
	return selected;
}

// Keep track of the number of selected items that have discounts applied to them.
var SelectedDiscountItemCount = 0;

// Change whether the discount messaging needs to be shown in the summary area.
function DiscountItemSelectionChanged(checked) {
    SelectedDiscountItemCount += checked ? 1 : -1;
    if (SelectedDiscountItemCount < 0) SelectedDiscountItemCount = 0;
    $("EnsembleSummaryDiscountMessage").style.display = SelectedDiscountItemCount > 0 ? "block" : "none";
}