﻿var products = new Array();
var bundles = new Array();
var product;
var option;
var productLinePage;
var validBundle = true;

/******************************* CONSTANTS *********************************/
var ANCIENT_HISTORY         = 1;
var PRE_RENAISSANCE         = 2;
var EARLY_UNITED_STATES     = 4;
var WORLD_20TH_CENTURY      = 8;

/***************************************************************************\
* Function:     indexOf                                                     *
* Author:       Terry Tice                                                  *
* Created:      10/25/07                                                    *
* Purpose:      Adds indexOf to the products array to find a product by     *
*               the map size.                                               *
\***************************************************************************/
function addMapSizeIndexOf(arrayToChange)
{
    arrayToChange.indexOf = function(mapSize)
    {
        for (var i = 0; i < this.length; i++)
            if (this[i].mapSize == mapSize)
                return i;
                
        return -1;
    }
}

/***************************************************************************\
* Function:     indexOf                                                     *
* Author:       Terry Tice                                                  *
* Created:      10/25/07                                                    *
* Purpose:      Adds indexOf to the bundles array to find a bundle by       *
*               the bundle ID.                                              *
\***************************************************************************/
bundles.indexOf = function(bundleID)
{
    for (var i = 0; i < this.length; i++)
        if (this[i].bundleID == bundleID)
            return i;
            
    return -1;
}

/***************************************************************************\
* Class:    Product                                                         *
* Author:   Terry Tice                                                      *
* Created:  10/25/07                                                        *
* Purpose:  This class represents a product and an array of Price classes   *
*           associated with that product.                                   *
\***************************************************************************/
function Product(mapSize, prices, discount)
{
    this.mapSize = mapSize;
    this.prices = prices;
    this.discount = discount;
    this.prices.indexOf = function(cartValue, description)
    {
        for (var i = 0; i < this.length; i++)
        {
            if (this[i].cartValue == cartValue && 
                createOptionText(this[i].finishing, this[i].price) == description)
            {
                return i;
            }
        }
        
        return -1;  
    }
}

/***************************************************************************\
* Class:    Price                                                           *
* Author:   Terry Tice                                                      *
* Created:  10/25/07                                                        *
* Purpose:  This class represents a finishing option and the associated     *
*           price.                                                          *
\***************************************************************************/
function Price(finishing, cartValue, price, productClass, newProductID, 
               descriptionAsName)
{
    this.finishing = finishing;
    this.cartValue = cartValue;
    this.price = price;
    this.productClass = productClass;
    this.newProductID = newProductID;
    this.descriptionAsName = descriptionAsName;
}

/***************************************************************************\
* Class:    Discount                                                        *
* Author:   Terry Tice                                                      *
* Created:  11/17/07                                                        *
* Purpose:  Specifies discount information for the current product.         *
\***************************************************************************/
function Discount(originalPrice, discountedPrice, qualificationType, 
                  qualification, originalBundleID, discountedBundleID)
{
    this.originalPrice = originalPrice;
    this.discountedPrice = discountedPrice;
    this.qualificationType = qualificationType;
    this.qualification = qualification;
    this.originalBundleID = originalBundleID;
    this.discountedBundleID = discountedBundleID;
}

/***************************************************************************\
* Class:    Bundle                                                          *
* Author:   Terry Tice                                                      *
* Created:  11/17/07                                                        *
* Members:  bundleID        - The bundle ID in the database.                *
*           productsArray   - The array of products associated with this    *
*                             bundle.                                       *
* Purpose:  Specifies discount information for the current product.         *
\***************************************************************************/
function Bundle(bundleID, price, discount)
{
    this.bundleID = bundleID;
    this.price = price;
    this.discount = discount;
}

/***************************************************************************\
* Function: changeSize                                                      *
* Author:   Terry Tice                                                      *
* Created:  10/25/07                                                        *
* Purpose:  Changes the current map size and updates the finishing options  *
*           and prices.                                                     *
\***************************************************************************/
function changeSize(mapSize)
{
    var productIndex = products.indexOf(mapSize);
    
    // Perform this check so that we are aware of errors in the product page.
    if (productIndex == -1)
    {
        alert('That map size does not exist.');
        return;
    }
    
    // Grab the product
    product = products[productIndex];

    if ($('staticSizeCell') != null) {
        $('staticSizeCell').innerHTML="<strong>"+mapSize+"</strong>";
        $('size').value = mapSize;
    }
    
    if($('options') != null && $('options').options != null)
    {
        // Change the lamination options.
        $('options').options.length = product.prices.length;
    
        for (var i = 0; i < product.prices.length; i++)
        {
            $('options').options[i] = 
                new Option(
                    createOptionText(product.prices[i].finishing, 
                        product.prices[i].price), 
                    product.prices[i].cartValue);
        }
        
         // Select the first option.
        changeOptionIndex(0);
        
        // If the selected option is synthetic then select laminated.
        if ($('options').value == 'Synthetic Paper')
            changeOptionIndex(1);
    } 
    else if($('options') != null) 
    {
        changeOptionIndex(0);
    } else {
        changeOption($('options').value, 
            $('options')[$('options').selectedIndex].text);
    }
}

/***************************************************************************\
* Function: createOptionText                                                *
* Author:   Terry Tice                                                      *
* Created:  08/13/08                                                        *
* Purpose:  Creates the text to be displayed in the option box.             *
\***************************************************************************/
function createOptionText(description, price)
{
    return description + " ($" + price.toFixed(2) + ")";
}

/***************************************************************************\
* Function: changeOptionIndex                                               *
* Author:   Terry Tice                                                      *
* Created:  10/25/07                                                        *
* Purpose:  Changes the current finishing option.                           *
\***************************************************************************/
function changeOptionIndex(optionIndex)
{
    // This shouldn't happen, but just in case there is a programmer error.
    if (optionIndex == -1)
    {
        alert("That option does not exist");
        return;
    }
    
    // Grab the select option.
    option = product.prices[optionIndex];
    $('options').selectedIndex = optionIndex;
    
    // Change the computer compatibility, if necessary
    if ($('compatibility') != null)
        $('compatibility').value = option.finishing;
    
    // Calculate the price.
    calculatePrice();
}

/***************************************************************************\
* Function: changeOption                                                    *
* Author:   Terry Tice                                                      *
* Created:  10/25/07                                                        *
* Purpose:  Changes the current finishing option.                           *
\***************************************************************************/
function changeOption(cartOption, description)
{  
    var optionIndex = product.prices.indexOf(cartOption, description);  
    
    return changeOptionIndex(optionIndex);
}

/***************************************************************************\
* Function: calculatePrice                                                  *
* Author:   Terry Tice                                                      *
* Created:  10/25/07                                                        *
* Purpose:  Calculates the price of the current size, finishing and quantity*
*           combination.                                                    *
\***************************************************************************/
function calculatePrice()
{
    var price = 0;
    var quantity;
    
    // If the quantity is empty then don't do anything.
    if ($('quantity').value == "")
        return;
    
    try
    {
        // Grab the integer version of the number.
        quantity = parseInt($('quantity').value);
        
        // If it isn't a number then turn it to 1.
        if (isNaN(quantity))
            quantity = 1;
    }
    catch (ex)
    {
        // An error happened, set the quantity to 1.
        quantity = 1;
    }
    
    // If the quantity is less than 1, set it to 1.
    if (quantity < 1)
        quantity = 1;
    
    // Set the quantity text box to the new quantity.
    $('quantity').value = quantity;
    
    // Make sure an option was pulled.
    if (option != null)
    {
        // Check for a discount
        if (product.discount != null)
        {
            switch (product.discount.qualificationType.toLowerCase())
            {
                case 'quantity':
                    if (product.discount.qualification <= quantity)
                    {
                        option.price = product.discount.discountedPrice;
                        if ($('bundleID') != null)
                            $('bundleID').value = product.discount.discountedBundleID;
                    }
                    else
                    {
                        option.price = product.discount.originalPrice;
                        if ($('bundleID') != null)
                            $('bundleID').value = product.discount.originalBundleID;
                    }
                    break;
            }
        }
        
        price = option.price * $('quantity').value;
    }
    
    // Change the price label and input field.
    $('priceLabel').innerHTML = '$' + addCommas(price.toFixed(2));
    
    // This should be the unit price, not the total price.
    $('price').value = option.price;
    $('productID').value = option.newProductID;
    
    if ($('prodclass') != null)
        $('prodclass').value = option.productClass;
    
    if(option.descriptionAsName)
        $('productName').value = option.finishing;
}

/***************************************************************************\
* Function: loadSizes                                                       *
* Author:   Terry Tice                                                      *
* Created:  10/25/07                                                        *
* Purpose:  Loads the available sizes for the current map.                  *
\***************************************************************************/
function loadSizes()
{
    if ($('size') != null && $('size').options != null)
    {  
        // Loop through all the available products.
        for (var i = 0; i < products.length; i++)
        {
            $('size').options[i] = new Option(products[i].mapSize,
                products[i].mapSize);
        }
        
        // Select the first item in the combo box.
        $('size').options.selectedIndex = 0;
        changeSize($('size').options[0].value);
    }
    else
    {
        changeSize(products[0].mapSize);
    }
}

/***************************************************************************\
* Function: checkProduct                                                    *
* Author:   Terry Tice                                                      *
* Created:  10/25/07                                                        *
* Purpose:  Checks the product information for any problems.                *
\***************************************************************************/
function checkProduct()
{
    // If there is no quantity then specify a quantity of 1
    if ($('quantity').value == "")
        $('quantity').value = "1";
        
    if (!validBundle)
    {
        alert('You must select at least 2 of the 4 maps!');
        return false;
    }
        
    // Make sure the latest price has been calculated.
    calculatePrice();
    
    // Validate the drm
    return validate_drm();
}

/***************************************************************************\
* Function: addCommas                                                       *
* Author:   Unknown (Added by Terry Tice)                                   *
* Created:  Unknown (Added on 10/25/07)                                     *
* Purpose:  Adds commas to the provided number                              *
\***************************************************************************/
function addCommas(num)
{
    var numberParts;
    var beforePeriod;
    var afterPeriod;
    var blockOfThree = /(\d+)(\d{3})/;
    
    // Convert the number to a string.
	num += '';
	
	// Split based upon the period so that anything after the period doesn't
	// receive commas.
	numberParts = num.split('.');
	beforePeriod = numberParts[0];
	afterPeriod = numberParts.length > 1 ? '.' + numberParts[1] : '';
	
	// Loop until there are no more groups of numbers greater than 3.
	while (blockOfThree.test(beforePeriod)) {
		beforePeriod = beforePeriod.replace(blockOfThree, '$1,$2');
	}
	return beforePeriod + afterPeriod;
}

/***************************************************************************\
* Function: changeProductLine                                               *
* Author:   Terry Tice                                                      *
* Created:  11/07/07                                                        *
* Purpose:  Changes the product line using the current product.             *
\***************************************************************************/
function changeProductLine()
{
    if (productLinePage == null)
        location.href = '/';
    else
        location.href = productLinePage;
}

/***************************************************************************\
* Function: updateBundleID                                                  *
* Author:   Terry Tice                                                      *
* Created:  11/26/07                                                        *
* Purpose:  Updates the bundle ID for the selected maps.                    *
\***************************************************************************/
function updateBundleID()
{
    var localBundleID = 0;
    var databaseBundleID = 0;
    var bundle;
    
    if ($('map1').checked)
        localBundleID += ANCIENT_HISTORY;
    if ($('map2').checked)
        localBundleID += PRE_RENAISSANCE;
    if ($('map3').checked)
        localBundleID += EARLY_UNITED_STATES;
    if ($('map4').checked)
        localBundleID += WORLD_20TH_CENTURY;
        
    switch (localBundleID)
    {
        case ANCIENT_HISTORY + PRE_RENAISSANCE:
            databaseBundleID = 29;
            break;
        case ANCIENT_HISTORY + EARLY_UNITED_STATES:
            databaseBundleID = 30;
            break;
        case ANCIENT_HISTORY + WORLD_20TH_CENTURY:
            databaseBundleID = 31;
            break;
        case PRE_RENAISSANCE + EARLY_UNITED_STATES:
            databaseBundleID = 32;
            break;
        case PRE_RENAISSANCE + WORLD_20TH_CENTURY:
            databaseBundleID = 33;
            break;
        case EARLY_UNITED_STATES + WORLD_20TH_CENTURY:
            databaseBundleID = 34;
            break;
        case ANCIENT_HISTORY + PRE_RENAISSANCE + EARLY_UNITED_STATES:
            databaseBundleID = 35;
            break;
        case ANCIENT_HISTORY + PRE_RENAISSANCE + WORLD_20TH_CENTURY:
            databaseBundleID = 36;
            break;
        case ANCIENT_HISTORY + EARLY_UNITED_STATES + WORLD_20TH_CENTURY:
            databaseBundleID = 37;
            break;
        case PRE_RENAISSANCE + EARLY_UNITED_STATES + WORLD_20TH_CENTURY:
            databaseBundleID = 38;
            break;
        case ANCIENT_HISTORY + PRE_RENAISSANCE + EARLY_UNITED_STATES + WORLD_20TH_CENTURY:
            databaseBundleID = 39;
            break;
    }
    
    try
    {
        // Grab the bundle.
        bundle = bundles[bundles.indexOf(databaseBundleID)];
        
        product.prices[0].price = bundle.price;
        product.discount = bundle.discount;
        
        $('bundleID').value = databaseBundleID;
        
        calculatePrice();
        
        validBundle = true;
    } catch (e) {
        validBundle = false;
    }
}

function changeImage(imageToChange, newImage)
{
    newImage = newImage.trim().replace(/ /g, '-');
    $(imageToChange).src = '/products/binder/images/small/' + newImage + '.gif';
}

function changeOutlineMap(imageToChange, newImage)
{
    $(imageToChange).src = '/products/free-content/images/outlines/' + newImage + '.gif';
}

// Populate the special bundles table.
bundles.push(new Bundle(29, 16.95, null));
bundles.push(new Bundle(30, 16.95, null));
bundles.push(new Bundle(31, 16.95, null));
bundles.push(new Bundle(32, 16.95, null));
bundles.push(new Bundle(33, 16.95, null));
bundles.push(new Bundle(34, 16.95, null));
bundles.push(new Bundle(35, 23.95, null));
bundles.push(new Bundle(36, 23.95, null));
bundles.push(new Bundle(37, 23.95, null));
bundles.push(new Bundle(38, 23.95, null));
bundles.push(new Bundle(39, 29.95, null));