﻿/**
 * main.js
 *
 * Requires: jquery.js
 */

var DAMICO = 
{       
    init: function ()
    {
        DAMICO.ErrorHandler.init();
        DAMICO.Validator.init();
        DAMICO.Form.init();
    }
}

DAMICO.Form =
{
    /**
     * Current numeric item id
     */
    item_counter: 0,
    
    /**
     * Current custom item id
     */
    custom_counter: 1,
    
    /**
     *
     */
    init: function ()
    {
        //DAMICO.Form.errors = new Array();
        DAMICO.Form.setPayPalForm_Submit();
        DAMICO.Form.setAddCustomInputLink_Click();
        DAMICO.Form.setGcc1Link_Click();
    },
    
    /**
     * Overrides the default FORM.submit() event. Prepares the input data for PayPal.
     *
     * @return void
     */
    setPayPalForm_Submit: function ()
    {
        $("#paypal").submit(function ()
        {
            // Reset error handling.
            DAMICO.ErrorHandler.reset();
            // Check items.
            DAMICO.Form.checkItems();
            // Check cart.
            DAMICO.Form.checkCart();
            // Check error count.
            if (DAMICO.ErrorHandler.error == 0)
            {
                // Proceed with form submission.
                return true;
            }
            else
            {
                // Display error message.
                DAMICO.ErrorHandler.displayError("e");
                // Prevent form submission.
                return false;
            }
        });
    },
    
    /**
     * Collects, then checks, gift card items.
     *
     * @return void
     */
    checkItems: function()
    {
        var items = $(".item");
        var num_items = items.length;
        for (var i = 0; i < num_items; i++)
        {
            var item = items[i].id;
            var name = document.getElementById(item + "_name").value;
            var amt = document.getElementById(item + "_amt").value;
            var qty = document.getElementById(item + "_qty").value;
            DAMICO.Form.checkItem(item, name, amt, qty);
        }
    },
    
    /**
     * Determines if a specific item should be included in the cart data passed to PayPal.
     *
     * @param string item_id
     * @param string item_name
     * @param string item_amt
     * @param string item_qty
     * @return void
     */
    checkItem: function(item_id, item_name, item_amt, item_qty)
    {
        // Validate the item's input.
        var amount_is_valid = DAMICO.Validator.isValidAmount(item_id, item_amt);
        var quantity_is_valid = DAMICO.Validator.isValidQuantity(item_id, item_qty);
        // If the inputs are valid and the quantity is > 0, add item to cart.
        //if ((Number(item_amt) > 0) && (Number(item_qty) > 0))
        if ((amount_is_valid == true) &&
            (quantity_is_valid == true) &&
            (Number(item_qty) > 0))
        {
            DAMICO.Form.addItemToCart(item_name, item_amt, item_qty);
        }
    },
        
    /**
     * Prepares the data PayPal will need to process the order.
     *
     * @param string item_name
     * @param string item_amt
     * @param string item_qty
     * @return void
     */
    addItemToCart: function(item_name, item_amt, item_qty)
    {
        var amt = item_amt + ".00";
        // Increment input counter.
        DAMICO.Form.item_counter++;
        // Add "item_name_x" input.
        //DAMICO.Form.addCartInput(DAMICO.Form.item_counter, "item_name", "hidden", item_name);
        DAMICO.Form.addCartInput(DAMICO.Form.item_counter, "item_name", "hidden", "$" + amt + " Gift Card");
        // Add "amout_x" input.
        DAMICO.Form.addCartInput(DAMICO.Form.item_counter, "amount", "hidden", amt);                        
        // Add "quantity_x" input.
        DAMICO.Form.addCartInput(DAMICO.Form.item_counter, "quantity", "hidden", item_qty);
    },
    
    /**
     * Checks for cart-level errors.
     *
     * @return void
     */
    checkCart: function()
    {
        // Check for empty cart error.
        if ((DAMICO.Form.item_counter == 0) && (DAMICO.ErrorHandler.error == 0))
        {
            DAMICO.ErrorHandler.setError(201);
        }
    },
    
    /**
     *
     * @return void
     */
    setAddCustomInputLink_Click: function()
    {
        var a = document.getElementById("add-custom-input-link");
        a.onclick = function()
        {
            DAMICO.Form.addCustomAmountInput();
            return false;
        }
    },
    
    /**
     * Adds an additional custom amount gift card option.
     *
     * @return void
     */
    addCustomAmountInput: function()
    {
        // Determine item id.
        DAMICO.Form.custom_counter++;
        var item_id = "gcc" + DAMICO.Form.custom_counter;
        
        var parent = document.getElementById("custom-inputs");
        
        // <div class="custom-input-box">
        var div1 = document.createElement("div");
        div1.setAttribute("class", "custom-input-box");        
        div1.style.position = "relative";
        div1.style.margin = "20px 0 0 0";
        parent.appendChild(div1);
        
        /*
        // <p class="name"><img src="images/custom-amount.gif" alt="Custom Amount Gift Card" width="191" height="11" /></p>
        var p1 = document.createElement("p");
        p1.setAttribute("class", "name");
        p1.style.padding = "0";
        p1.style.margin = "0 0 5px 0";
        div1.appendChild(p1);
        
        var p1_img = document.createElement("img");
        p1_img.setAttribute("src", "images/custom-amount.gif");
        p1_img.setAttribute("alt", "Custom Amount Gift Card");
        p1_img.setAttribute("width", 191);
        p1_img.setAttribute("height", 11);
        p1.appendChild(p1_img);
        */
        
        // <div class="custom-input-box-fieldset">
        var div2 = document.createElement("div");
        div2.setAttribute("class", "custom-input-box-fieldset");
        div2.style.position = "relative";
        div2.style.height = "35px";
        div1.appendChild(div2);
        
        // <input type="hidden" id="gcc1" name="gcc1" class="item" value="gcc1"/>
        var input1 = document.createElement("input");
        input1.setAttribute("type", "hidden");
        input1.setAttribute("id", item_id);
        input1.setAttribute("name", item_id);
        input1.setAttribute("class", "item");
        input1.setAttribute("value", item_id);
        div2.appendChild(input1);
        
        // <input type="hidden" id="gcc1_name" name="gcc1_name" value="Custom Amount Gift Card"/>
        var input2 = document.createElement("input");
        input2.setAttribute("type", "hidden");
        input2.setAttribute("id", item_id + "_name");
        input2.setAttribute("name", item_id + "_name");
        input2.setAttribute("value", "Custom Amount Gift Card");
        div2.appendChild(input2);
        
        // <label class="label amt" for="gcc1_amt"><img src="images/amount.gif" alt="Amount" width="48" height="14" /></label>
        var label1 = document.createElement("label");
        label1.setAttribute("class", "label amt");
        label1.style.position = "absolute";
        label1.style.top = "11px";
        label1.style.left = "0px";
        label1.setAttribute("for", item_id + "_amt");
        div2.appendChild(label1);
        
        var label1_img = document.createElement("img");
        label1_img.setAttribute("src", "images/amount.gif");
        label1_img.setAttribute("alt", "Amount");
        label1_img.setAttribute("width", 48);
        label1_img.setAttribute("height", 14);
        label1.appendChild(label1_img);        
        
        // <input type="text" id="gcc1_amt" name="gcc1_amt" class="input amt" size="3" maxlength="5" value="0"/>
        var input3 = document.createElement("input");
        input3.setAttribute("type", "text");
        input3.setAttribute("id", item_id + "_amt");
        input3.setAttribute("name", item_id + "_amt");
        input3.setAttribute("class", "input amt");
        input3.style.position = "absolute";
        input3.style.top = "6px";
        input3.style.left = "55px";
        input3.style.padding = "2px 2px 2px 2px";
        input3.style.margin = "0 0 5px 0";
        input3.style.fontFamily = "Arial, Sans-Serif";
        input3.style.fontSize = "1em";
        input3.style.textAlign = "right";    
        input3.setAttribute("size", 3);
        input3.setAttribute("maxlength", 5);
        input3.setAttribute("value", 0);
        div2.appendChild(input3);
        
        // <p class="cents">.00</p>
        var p2 = document.createElement("p");
        p2.setAttribute("class", "cents");
        p2.style.position = "absolute";
        p2.style.top = "9px";
        p2.style.left = "125px";
        p2.style.padding = "0";
        p2.style.margin = "0";
        p2.style.fontFamily = "Arial, Sans-Serif";
        p2.style.fontSize = "1em";
        div2.appendChild(p2);
        
        var p2_text = document.createTextNode(".00");
        p2.appendChild(p2_text);
        
        // <img class="vbar" src="images/vbar.gif" alt="" width="3" height="30" />
        var vbar = document.createElement("img");
        vbar.setAttribute("class", "vbar");
        vbar.style.position = "absolute";
        vbar.style.top = "2px";
        vbar.style.left = "191px";
        vbar.style.padding = "0";
        vbar.style.margin = "0";
        vbar.setAttribute("src", "images/vbar.gif");
        vbar.setAttribute("alt", "");
        vbar.setAttribute("width", 3);
        vbar.setAttribute("height", 30);
        div2.appendChild(vbar);
        
        // <label class="label" for="gcc1_qty"><img src="images/quantity.gif" alt="Quantity" width="53" height="14" /></label>
        var label2 = document.createElement("label");
        label2.setAttribute("class", "label amt");
        label2.style.position = "absolute";
        label2.style.top = "11px";
        label2.style.left = "212px";
        label2.setAttribute("for", item_id + "_qty");
        div2.appendChild(label2);
        
        var label2_img = document.createElement("img");
        label2_img.setAttribute("src", "images/quantity.gif");
        label2_img.setAttribute("alt", "Quantity");
        label2_img.setAttribute("width", 53);
        label2_img.setAttribute("height", 14);
        label2.appendChild(label2_img); 
        
        // <input type="text" id="gcc1_qty" name="gcc1_qty" class="input qty" size="3" maxlength="3" value="0"/>
        var input4 = document.createElement("input");
        input4.setAttribute("type", "text");
        input4.setAttribute("id", item_id + "_qty");
        input4.setAttribute("name", item_id + "_qty");
        input4.setAttribute("class", "input qty");
        input4.style.position = "absolute";
        input4.style.top = "6px";
        input4.style.left = "273px";
        input4.style.padding = "2px 2px 2px 2px";
        input4.style.margin = "0 0 5px 0";
        input4.style.fontFamily = "Arial, Sans-Serif";
        input4.style.fontSize = "1em";
        input4.setAttribute("size", 3);
        input4.setAttribute("maxlength", 3);
        input4.setAttribute("value", 0);
        div2.appendChild(input4);
        
        // <p id="remove-link"><a id="gcc1_link" href="#gcc1"><img src="images/remove.gif" alt="Remove" width="50" height="20" /></a></p>
        var p3 = document.createElement("p");
        p3.setAttribute("class", "remove-link");
        p3.style.position = "absolute";
        p3.style.top = "9px";
        p3.style.left = "360px";
        p3.style.padding = "0";
        p3.style.margin = "0";    
        div2.appendChild(p3);
        
        var a = document.createElement("a");
        a.setAttribute("id", item_id + "_link");
        a.href = "#" + item_id;
        a.onclick = function()
        {
            DAMICO.Form.removeCustomAmountInput(item_id);
        }
        p3.appendChild(a);
        
        var a_img = document.createElement("img");
        a_img.setAttribute("src", "images/remove.gif");
        a_img.setAttribute("alt", "Remove");
        a_img.setAttribute("width", 50);
        a_img.setAttribute("height", 20);
        a.appendChild(a_img);
    },
    
    /**
     * Removes a DIV containging a custom amount gift card set of nodes.
     *
     * @param string item_id
     * @return void
     */
    removeCustomAmountInput: function(item_id)
    {
        var target = document.getElementById(item_id).parentNode;
        var container = target.parentNode;
        container.parentNode.removeChild(container);
    },
    
    /**
     * Inserts an INPUT into the DOM.
     *
     * @param number id
     * @param string name
     * @param string type
     * @param string value
     * @return void
     */
    addCartInput: function(id, name, type, value)
    {
        var input = document.createElement("input");
        var idname = name + "_" + id;
        input.setAttribute("id", idname);
        input.setAttribute("name", idname);
        input.setAttribute("type", type);
        input.setAttribute("value", value);
        var form = document.getElementById("paypal");
        form.appendChild(input);
    },
    
    /**
     *
     * @return void
     */
    setGcc1Link_Click: function()
    {
        document.getElementById("gcc1_link").onclick = function()
        {
            DAMICO.Form.removeCustomAmountInput("gcc1");
        }
    }
}

DAMICO.Validator =
{
    init: function()
    {
    },
    
    isValidAmount: function(id, value)
    {
        var errors = 0;
        
        if (DAMICO.Validator.isValidNotEmpty(value) == false)
        {
            //errors++;
            //DAMICO.ErrorHandler.setError(301);
            value = 0;
            document.getElementById(id + "_amt").value = "0";
        }
        if (DAMICO.Validator.isValidNumber(value) == false)
        {
            errors++;
            DAMICO.ErrorHandler.setError(302);
        }
        if (DAMICO.Validator.isValidInRange(value, 0, 1000) == false)
        {
            errors++;
            DAMICO.ErrorHandler.setError(303);
        }
        
        // Amount must be > 0, if quantity > 0.
        if (Number(document.getElementById(id + "_qty").value) > 0)
        {
            if (Number(value) == 0)
            {
                errors++;
                DAMICO.ErrorHandler.setError(303);
            }
        }
        
        if (errors == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    },
    
    isValidQuantity: function(id, value)
    {        
        var errors = 0;
        
        if (DAMICO.Validator.isValidNotEmpty(value) == false)
        {
            //errors++;
            //DAMICO.ErrorHandler.setError(401);
            value = 0;
            document.getElementById(id + "_qty").value = "0";
        }
        if (DAMICO.Validator.isValidNumber(value) == false)
        {
            errors++;
            DAMICO.ErrorHandler.setError(402);
        }
        if (DAMICO.Validator.isValidInRange(value, 0, 100) == false)
        {
            errors++;
            DAMICO.ErrorHandler.setError(403);
        }
        
        if (errors == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    },
    
    /**
     * Checks if the value is not empty.
     *
     * @param string value Value to test.
     * @return boolean
     *     TRUE: value is not empty
     *     FALSE: value is empty
     */
    isValidNotEmpty: function(value)
    {
        var regex = /^.+$/
        if (Boolean(String(value).match(regex)) == true)
        {
            return true;
        }
        return false;
    },
    
    /**
     * Checks if the value represents a number.
     *
     * @param value Value to test.
     * @return boolean
     *     TRUE: value represents a number
     *     FALSE: value does not represent a number
     */
    isValidNumber: function(value)
    {
        var regex = /^\d+$/
        if (Boolean(String(value).match(regex)) == true)
        {
            return true;
        }
        return false;
    },
    
    /**
     * Checks if the value is within the specified range.
     *
     * @param value Value to test.
     * @param min Minimum value.
     * @param max Maximum value.
     * @return boolean
     *     TRUE: value is within the specified range
     *     FALSE: value is no withing the specified range
     */
    isValidInRange: function(value, min, max)
    {
        if ((Number(value) >= min) && (Number(value) <= max))
        {
            return true;
        }
        return false;
    }
}

DAMICO.ErrorHandler =
{
    /**
     * Current error number.
     * 100 = generic - unspecified error
     * 101 = generic - invalid input
     * 200 = cart - generic error
     * 201 = cart - empty cart
     * 300 = amount - generic error
     * 301 = amount - empty
     * 302 = amount - invalid
     * 303 = amount - out of range
     * 400 = quantity - generic error
     * 401 = quantity - empty
     * 402 = quantity - invalid
     * 403 = quantity - out of range
     */
    error: 0,
    
    init: function()
    {
    },
    
    /**
     * Resets the ErrorHandler to default state.
     *
     * @return void
     */
    reset: function()
    {
        // Reset the error flag.
        DAMICO.ErrorHandler.setError(0);
        
        // Remove the error message display.
        DAMICO.ErrorHandler.hideError();
    },
    
    /**
     * Sets the currently stored error number.
     *
     * @param string error
     * @return void
     */
    setError: function(error)
    {
        DAMICO.ErrorHandler.error = error;
    },
    
    /**
     * Shows the current error message.
     *
     * @param string container Id of the node to attach the error message display to.
     * @return void
     */
    displayError: function(container)
    {
        // Create the error container element.
        var div = document.createElement("div");
        div.setAttribute("id", "error-container");
        // Style the error container element.
        //div.style.position = "absolute";
        //div.style.top = "450px";
        //div.style.left = "134px";
        //div.style.width = "500px";
        div.style.textAlign = "center";
        // Attach the error container to inner wrapper.
        var parent = document.getElementById(container);
        parent.appendChild(div);
        
        // Create error message element.
        var p = document.createElement("p");
        p.setAttribute("id", "error");

        // Set the error message text.
        var text = "";
        switch (DAMICO.ErrorHandler.error)
        {
            case 100:
                //text = document.createTextNode("100 Error");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 101:
                //text = document.createTextNode("101 Invalid Input");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 200:
                //text = document.createTextNode("200 Cart Error");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 201:
                //text = document.createTextNode("201 Empty Cart");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 300:
                //text = document.createTextNode("300 Amount Error");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 301:
                //text = document.createTextNode("301 Empty Amount");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 302:
                //text = document.createTextNode("302 Invalid Amount");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 303:
                //text = document.createTextNode("303 Out Of Range Amount");
                text = document.createTextNode("Please select an amount between $1 and $1000.");
                break;
            case 400:
                //text = document.createTextNode("400 Quantity Error");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 401:
                //text = document.createTextNode("401 Empty Quantity");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 402:
                //text = document.createTextNode("402 Invalid Quantity");
                text = document.createTextNode("Error. Please try again.");
                break;
            case 403:
                //text = document.createTextNode("403 Out Of Range Quantity");
                text = document.createTextNode("Please select a quantity between 0 and 100.");
                break;
            default:
                //text = document.createTextNode("100 Error");
                text = document.createTextNode("Error. Please try again.");
                break;
        }
        p.appendChild(text);
        
        // Style the error message.
        p.style.fontFamily = "Arial, Sans-Serif";
        p.style.fontSize = "10pt";
        p.style.fontWeight = "bold";
        p.style.padding = "8px";
        p.style.border = "2px solid #f00";
        p.style.backgroundColor = "#fcc";
        p.style.color = "#f00";
        // Attach error message to error container.
        document.getElementById("error-container").appendChild(p);
    },
    
    /**
     * Hides the current error message.
     *
     * @return void
     */
    hideError: function()
    {
        // Remove the error message elements (if present).
        if (document.getElementById("error-container"))
        {
            var target = document.getElementById("error-container");
            target.parentNode.removeChild(target);
        }
    }
}

/**
 * Ready event - Executes when the document is loaded.
 */
$(document).ready(function(){
    DAMICO.init();
});
