﻿// JScript File

var Text2GoPrice                = 25;
var Text2GoDiscountPrice        = 15;
var VoicePrice                  = 35;
var VoiceDiscountPrice          = 30;
var PremuimVoicePrice           = 45;
var PremiumVoiceDiscountPrice   = 40;

var quantityColumn = 4;
var LineItemDiscountColumn = 6;
var LineItemTotalColumn = 7;

var products = 
{
    text2go: { product_id: '/text2go', price: Text2GoPrice, discount_price: Text2GoDiscountPrice },
    full_price_text2go: { product_id: '/text2go', price: Text2GoPrice, discount_price: Text2GoPrice },
    voice_amy: { product_id: '/ivonaamyvoice', price: PremuimVoicePrice, discount_price: PremiumVoiceDiscountPrice },
    voice_brian: { product_id: '/ivonabrianvoice', price: PremuimVoicePrice, discount_price: PremiumVoiceDiscountPrice },
    voice_samantha: { product_id: '/realspeaksamantha', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_jill: { product_id: '/realspeakjillvoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_tom: { product_id: '/realspeaktomvoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_jennifer: { product_id: '/realspeakjennifervoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_karen: { product_id: '/realspeakkarenvoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_lee: { product_id: '/realspeakleevoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_emily: { product_id: '/realspeakemilyvoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_serena: { product_id: '/realspeakserenavoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_daniel: { product_id: '/realspeakdanielvoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_moira: { product_id: '/realspeakmoiravoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_sangeeta: { product_id: '/realspeaksangeetavoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_isabel: { product_id: '/realspeakisabelvoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_monica: { product_id: '/realspeakmonicavoice', price: VoicePrice, discount_price: VoiceDiscountPrice },
    voice_diego: { product_id: '/realspeakdiegovoice', price: VoicePrice, discount_price: VoiceDiscountPrice }
};

// Register event handler
var previousHandler = window.onload;
window.onload = setInitialPageState;

function setInitialPageState()
{
    if(previousHandler != null)
    {
        previousHandler();
    }

    updateTotalAndSavings();
}

function getProductPrice(strId)
{
    if(strId in products)
    {
        return products[strId].price;
    }
    return 0;
}

function getProductDiscountPrice(strId) {
    if (strId in products) {
        return products[strId].discount_price;
    }
    return 0;
}

function CheckboxText2Go_onclick() 
{
    updateTotalAndSavings()
}

function calculateDiscount(text2goCount, voiceCount)
{
    var text2goDiscounts = voiceCount > 0 ? text2goCount : 0;
    var voiceDiscounts = voiceCount + text2goCount > 1 ? voiceCount : 0;
    return text2goDiscounts * (Text2GoPrice - Text2GoDiscountPrice) + voiceDiscounts * (VoicePrice - VoiceDiscountPrice);
}

function isText2GoProduct(id)
{
    return id.indexOf('text2go') == 0;
}

function isVoiceProduct(id)
{
    return id.indexOf('voice') == 0;
}

function updateTotalAndSavings()
{
    var productsTable = document.getElementById('product selection');
    var text2goCount = 0;
    var voiceCount = 0;
    var voiceTotalPrice = 0;
    var total = 0;
    var discount = 0;
    var coupon = getCouponCode();
    var matchArray = /\d*$/.exec(coupon);
    var couponDiscount = 0;
    if(matchArray.length > 0 && matchArray[0].length > 0)
    {
        couponDiscount = Math.min(10, parseInt(matchArray[0]));
    }
    
    var rowQuantity = new Array(productsTable.rows.length);
    for(i = 0; i < productsTable.rows.length; i++)
    {
        var checkBoxCell = productsTable.rows[i].cells[0];
        rowQuantity[i] = 0;
        if(checkBoxCell.firstChild && 'checked' in checkBoxCell.firstChild)
        {
            var quantityInput = productsTable.rows[i].cells[quantityColumn].firstChild;
            quantityInput.disabled = !checkBoxCell.firstChild.checked;
            var checkBox = checkBoxCell.firstChild;
            if(checkBox.checked)
            {
                rowQuantity[i] = Math.max(1, parseInt(quantityInput.value));
                quantityInput.value = rowQuantity[i];
            }
                
            if(isText2GoProduct(checkBox.id))
            {
                text2goCount += rowQuantity[i];
            }
            else if(isVoiceProduct(checkBox.id))
            {
                voiceCount += rowQuantity[i];
                voiceTotalPrice += rowQuantity[i] * getProductPrice(checkBox.id);
            }
            productsTable.rows[i].cells[LineItemDiscountColumn].innerHTML = "";
            if(rowQuantity[i] > 0)
            {
                productsTable.rows[i].cells[LineItemTotalColumn].innerHTML = getProductPrice(checkBox.id) * rowQuantity[i];
            }
            else
            {
                productsTable.rows[i].cells[LineItemTotalColumn].innerHTML = "";
            }
        }
    }

    var text2goDiscounts = voiceCount > 0 ? text2goCount : 0;
    var areVoicesDiscounted = voiceCount + text2goCount > 1;
    
    if(text2goDiscounts > 1 || areVoicesDiscounted || couponDiscount > 0)
    {
        for(i = 0; i < productsTable.rows.length; i++)
        {
            if(rowQuantity[i] > 0)
            {               
                productsTable.rows[i].cells[LineItemDiscountColumn].innerHTML = "";
                var checkBox = productsTable.rows[i].cells[0].firstChild;
                if(isText2GoProduct(checkBox.id))
                {
                    if(text2goDiscounts > 0 || couponDiscount > 0)
                    {
                        discount = text2goDiscounts * (Text2GoPrice - Text2GoDiscountPrice) + couponDiscount;
                        productsTable.rows[i].cells[LineItemDiscountColumn].innerHTML = discount;
                        productsTable.rows[i].cells[LineItemTotalColumn].innerHTML = (getProductPrice(checkBox.id) * rowQuantity[i]) - discount;
                    }
                }
                else if(isVoiceProduct(checkBox.id))
                {
                    if(areVoicesDiscounted)
                    {
                        discount = rowQuantity[i] * (VoicePrice - VoiceDiscountPrice);
                        productsTable.rows[i].cells[LineItemDiscountColumn].innerHTML = discount;
                        productsTable.rows[i].cells[LineItemTotalColumn].innerHTML = (getProductPrice(checkBox.id) * rowQuantity[i]) - discount;
                    }
                }
            }
        }
    }

    total = text2goCount * Text2GoPrice + voiceTotalPrice;
    discount = calculateDiscount(text2goCount, voiceCount);
    if(text2goCount > 0)
    {
        discount += couponDiscount; 
    }
    total -= discount;
    
    var totalRow = productsTable.rows.length - 1;
    productsTable.rows[totalRow].cells[LineItemDiscountColumn].innerHTML = discount > 0 ? "<strong>" + discount + "</strong>" : "&nbsp;";
    productsTable.rows[totalRow].cells[LineItemTotalColumn].innerHTML = total > 0 ? "<strong>" + total + "</strong>" : "&nbsp;";
    
    var checkoutButtonId = 1;
    var checkoutButton = document.getElementById('checkout_' + checkoutButtonId++);
    while(checkoutButton != null)
    {
        if(total == 0)
        {
            checkoutButton.src = "/portals/0/checkout-disabled.png";
            checkoutButton.alt = "You need to add at least one item to your cart before proceeding to checkout";
        }
        else
        {
            checkoutButton.src = "/portals/0/checkout.png";
            checkoutButton.alt = "Proceed to Checkout";
        }

        checkoutButton = document.getElementById('checkout_' + checkoutButtonId++);
    }
}


function getSelectedProductQuantityPrices()
{
    var productQuantityPrice = new Array();
    var text2goCount = 0;
    var voiceCount = 0;
    var productsTable = document.getElementById('product selection');
    for(i = 0; i < productsTable.rows.length; i++)
    {
        var checkBoxCell = productsTable.rows[i].cells[0];
        if(checkBoxCell.firstChild && checkBoxCell.firstChild.checked)
        {
            var checkBox = checkBoxCell.firstChild;
            
            if(checkBox.id in products)
            {
                var quantity = 1;
                var quantityCell = productsTable.rows[i].cells[quantityColumn];
                if(quantityCell.firstChild)
                {
                    quantity = Math.max(1, parseInt(quantityCell.firstChild.value));
                }
                if(isText2GoProduct(checkBox.id))
                {
                    text2goCount += quantity;
                }
                else if(isVoiceProduct(checkBox.id))
                {
                    voiceCount += quantity;
                }
                
                productQuantityPrice.push(new Array(checkBox.id, quantity, ''));
            }
        }
    }
    var text2goDiscounts = voiceCount > 0 ? text2goCount : 0;
    var areVoicesDiscounted = voiceCount + text2goCount > 1;
    var productName;
    for(i = 0; i < productQuantityPrice.length; i++)
    {
        productName = productQuantityPrice[i][0];
        if(isText2GoProduct(productName))
        {
            var price = Text2GoPrice;
            var discountPrice = Text2GoDiscountPrice;
            if(text2goDiscounts == 0)
            {
                // No discounts
                productQuantityPrice[i][2] = price;
            }
            else if(text2goDiscounts == text2goCount)
            {
                // All discounted
                productQuantityPrice[i][2] = discountPrice;
            }
            else
            {
                // Some discounted
                var fullPriceQuantity = text2goCount - text2goDiscounts;
                productQuantityPrice.splice(i, 0, productQuantityPrice[i].concat()); // Copy and insert line
                productQuantityPrice[i][1] = text2goDiscounts;    // Adjust quantity
                productQuantityPrice[i][2] = discountPrice;
                i++;
                productQuantityPrice[i][0] = 'full_price_text2go';
                productQuantityPrice[i][1] = fullPriceQuantity;    // Adjust quantity
                productQuantityPrice[i][2] = '';
            }
        }
        else if(isVoiceProduct(productName))
        {
            if(areVoicesDiscounted)
            {
                productQuantityPrice[i][2] = getProductDiscountPrice(productName);
            }
            else
            {
                productQuantityPrice[i][2] = getProductPrice(productName);
            }
        }
    }
    
    return productQuantityPrice;
}


function ButtonSubmit_onclick() 
{
    var productQuantityPrice = getSelectedProductQuantityPrices();
    if(productQuantityPrice.length == 0)
    {
        return;
    }

    // Create the form to submit the order
    var productform = document.createElement('form');
    productform.setAttribute('method', 'post');
    productform.setAttribute('action', 'http://sites.fastspring.com/text2go/api/order');
    var input = document.createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('name', 'action');
    input.setAttribute('value', 'create');
    productform.appendChild(input);
    input = document.createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('name', 'destination');
    input.setAttribute('value', 'checkout');
    productform.appendChild(input);
    
    var text2goCount = 0;
    var voiceCount = 0;
    for(i = 0; i < productQuantityPrice.length; i++)
    {
        var productCode = products[productQuantityPrice[i][0]].product_id;

        var inputpath = document.createElement('input');
        inputpath.setAttribute('type', 'hidden');
        inputpath.setAttribute('name', 'product_' + (i + 1).toString() + '_path');
        inputpath.setAttribute('value', productCode);
        productform.appendChild(inputpath);

        var inputquantity = document.createElement('input');
        inputquantity.setAttribute('type', 'hidden');
        inputquantity.setAttribute('name', 'product_' + (i + 1).toString() + '_quantity');
        inputquantity.setAttribute('value', productQuantityPrice[i][1]);
        productform.appendChild(inputquantity);

        if(isText2GoProduct(productQuantityPrice[i][0]))
        {
            text2goCount += productQuantityPrice[i][1];
        }
        if(isVoiceProduct(productQuantityPrice[i][0]))
        {
            voiceCount += productQuantityPrice[i][1];
        }
    }

    var vt = voiceCount > 0 && (text2goCount + voiceCount) >= 2 ? '1234' : '4321';
    input = document.createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('name', 'tags');
    input.setAttribute('value', 'vt=' + vt);
    productform.appendChild(input);

    document.body.appendChild(productform);
    productform.submit();
}


var keybNumeric = new keybEdit('01234567890');

function keybEdit(strValid, strMsg) {
	/*	Function:		keybEdit
		Creation Date:	October 11, 2001
		Programmer:		Edmond Woychowsky
		Purpose:		The purpose of this function is to be a constructor for
						the keybEdit object.  keybEdit objects are used by the
						function editKeyBoard to determine which keystrokes are
						valid for form objects.  In addition, if an error occurs,
						they provide the error message.
						
						Please note that the strValid is converted to both
						upper and lower case by this constructor.  Also, that
						the error message is prefixed with 'Error:'.
						
						The properties for this object are the following:
							valid	=	Valid input characters
							message	=	Error message
							
						The methods for this object are the following:
							getValid()	=	Returns a string containing valid
											characters.
							getMessage()=	Returns a string containing the
											error message.

		Update Date:	Programmer:			Description:
	*/

	//	Variables
	var reWork = new RegExp('[a-z]','gi');		//	Regular expression\

	//	Properties
	if(reWork.test(strValid))
		this.valid = strValid.toLowerCase() + strValid.toUpperCase();
	else
		this.valid = strValid;

	if((strMsg == null) || (typeof(strMsg) == 'undefined'))
		this.message = '';
	else
		this.message = strMsg;

	//	Methods
	this.getValid = keybEditGetValid;
	this.getMessage = keybEditGetMessage;
	
	function keybEditGetValid() {
	/*	Function:		keybEdit
		Creation Date:	October 11, 2001
		Programmer:		Edmond Woychowsky
		Purpose:		The purpose of this function act as the getValid method
						for the keybEdit object.  Please note that most of the
						following logic is for handling numeric keypad input.

		Update Date:		Programmer:			Description:
	*/

		return this.valid.toString();
	}
	
	function keybEditGetMessage() {
	/*	Function:		keybEdit
		Creation Date:	October 11, 2001
		Programmer:		Edmond Woychowsky
		Purpose:		The purpose of this function act as the getMessage method
						for the keybEdit object.

		Update Date:	Programmer:			Description:
	*/
	
		return this.message;
	}
}




void function editKeyBoard(objForm, objKeyb) {
	/*	Function:		editKeyBoard
		Creation Date:	October 11, 2001
		Programmer:		Edmond Woychowsky
		Purpose:		The purpose of this function is to edit edit keyboard input
						to determine if the keystrokes are valid.
	
		Update Date:		Programmer:			Description:
	*/

	strWork = objKeyb.getValid();
	strMsg = '';							// Error message
	blnValidChar = false;					// Valid character flag

	// Part 1: Validate input
	if(!blnValidChar)
		for(i=0;i < strWork.length;i++)
			if(window.event.keyCode == strWork.charCodeAt(i)) {
				blnValidChar = true;

				break;
			}

	// Part 2: Build error message
	if(!blnValidChar) {
		if(objKeyb.getMessage().toString().length != 0)
			alert('Error: ' + objKeyb.getMessage());

		window.event.returnValue = false;		// Clear invalid character
		objForm.focus();						// Set focus
	}
}

function getArgs()
{
    var args = new Object();
    var query = location.search.substring(1);
    var pairs = query.split("&");
    for(var i = 0; i < pairs.length; i++)
    {
        var pos = pairs[i].indexOf('=');
        if(pos == -1) continue;
        var argname = pairs[i].substring(0, pos);
        var value = pairs[i].substring(pos + 1);
        value = decodeURIComponent(value);
        args[argname] = value;
    }
    return args;
}

function getCouponCode()
{
    var args = getArgs();
    return args.c17  || "";
}
