﻿var cName = "randSet";
var cartDisplay = true;
//*** Variables sent from server ***//
var cartTotal = 0;
var utTax = 0;
var shipPrice = 0;
//var multidisc = 0;
//*********************************//
var tempCartTotal = 0;

$(document).ready(function() {
    // If the add to cart button on the category or product pages is clicked then start the add to cart process
    $("#cartButton").click(function(event) {
        confirmVersion();
    });

    // If the number in the cart icon at the top-right of the page is clicked then show the fancybox rendition of the cart
    $("#cartAmount").click(function() {
        showCart();
    });

    // If the text "cart" at the top-right of the page is clicked then show the fancybox rendition of the cart
    $("#cartText").click(function() {
        showCart();
    });

    // if the compatibility link is clicked show the chart of compatible programs
    $("#compatLink").click(function() {
        showCompatibility();
    });

    $('.couponTextbox').bind('keypress', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            processCoupon();
            return false;
        }
    });

    // each time the page loads get the cart cookie and update the displayed number of items in the cart
    updateCartNum();

    //**********CART.ASPX SPECIFIC CODE****************//
    var pageLocation = location.pathname.split("/");
    if (pageLocation[pageLocation.length - 1] == "cart.aspx") {
        // hide the cart icon when on the cart.aspx page
        $("#cartInfo").css({ 'display': 'none' });

        // show the cart total
        if ($(".shippingCheckbox").length) {
            cartOptionsAdd();
            cartOptionsAdd();
        }
    }

    $(window).unload(function() {
        $.fancybox.hideActivity();
    });
});

// Custom object to store entire cart as array
function cartObj(item_numberVar, priceVar, item_nameVar, categoryVar) {
    this.cart = new Array();
    this.cart[this.cart.length] = { item_number: item_numberVar, price: Number(priceVar), item_name: item_nameVar, category: categoryVar };
}

//*******ADD PRODUCT TO CART**********//
function captureCartClick() {
    var tempHashTable = getCookie(cName);
    deleteCookie(cName);
    if ((tempHashTable == null) || (tempHashTable == "null") || (tempHashTable == "")) {
        newCartObject = new cartObj(prodVar, priceVar, prodName, categoryVar);
    } else {
        var newCartObject = JSON.parse(tempHashTable);
        var blnDuplicate = false;
        for (var p = 0; p < newCartObject.cart.length; p++) {
            if (newCartObject.cart[p].item_number == prodVar) {
                blnDuplicate = true;
            }
        }
        if (blnDuplicate) {
            $.fancybox(prodName + " is already in your cart. You cannot add the same item to your cart twice.");
        } else {
            newCartObject.cart[newCartObject.cart.length] = { item_number: prodVar, price: Number(priceVar), item_name: prodName, category: categoryVar };
        }
    }
    
    setCookie(cName, JSON.stringify(newCartObject), 7);
    updateCartNum();
    showCart();
}

function confirmVersion() {
    var showSection = "";
    var compatibilityChart = generateCompatUL();

    (categoryVar.toUpperCase() != "PRESETS") ? showSection = categoryVar: showSection = "";

    $.fancybox({
        'content' : "<strong>The " + prodName + " " + showSection + " are compatible with:</strong>" + compatibilityChart + "<p style='margin: 6px 0px 10px 0px; font-weight: bold;'>Please verify that you have the correct programs to use this product.</p> <input type=\"button\" id=\"continueButton\" value=\"Continue\" onclick=\"captureCartClick()\" />",
        'modal' : true
    });

    $(".compatUL li:even").addClass("stripeRow");
}

//*************************************************//
//**                                             **//
//**          Display Cart Contents              **//
//**                                             **//
//*************************************************//
function updateCartNum() {
    var cartCount;
    var tempHashTable = getCookie(cName);
    var hashObj = JSON.parse(tempHashTable);
    ((hashObj != null) && (hashObj.cart.length > 0)) ? cartCount = hashObj.cart.length : cartCount = "";
    $("#cartAmount").html(cartCount);
}

function showCart() {
    var cartTable;
    var cartRows = "";
    var jsCartTotal = 0;
    var preAmble = "<div id=\"cartPreamble\">Shopping Cart</div>";

    var hashTable = getCookie(cName);
    if (hashTable == null) {
        emptyCart(preAmble);
    } else {
        var hashObj = JSON.parse(hashTable);

        if ((hashObj.cart.length > 0) && (hashObj.cart != "") && (hashObj.cart != null) && (hashObj.cart != "null")) {
            cartTable = "<table id=\"cartTable\">" +
            "<thead><tr>" +
                "<th>Product</th><th>Price</th><th></th>" +
            "</tr></thead>";

//            hashObj.cart = multiOrderDisc(hashObj.cart);

            for (var i = 0; i < hashObj.cart.length; i++) {
                cartRows += "<tr id=\"cartRow" + i + "\"><td>" + hashObj.cart[i].item_name + "</td><td>" + Number(hashObj.cart[i].price).toFixed(2) + "</td><td><a href=\"#\" onclick=\"cartPop(" + i + "); return false;\" class=\"removeCart\">X</a></td></tr>";
                jsCartTotal += Number(hashObj.cart[i].price);
            }

            jsCartTotal = jsCartTotal.toFixed(2);

            cartTable += "<tfoot><tr id=\"cartFooter\"><td>Total</td><td colspan=\"2\" id=\"cartTotalRow\">" + jsCartTotal + "</td></tr></tfoot>" +
            "<tbody>" + cartRows + "</tbody>" +
            "</table>";

            var postAmble = "<p style=\"font-size: smaller; font-style: italic; margin-bottom: 5px; max-width: 250px;\">Please Note: the multi-product discount will be applied on the checkout page. To see the discount please click the \"Check Out\" button below.</p>" +
            "<div id=\"cartPostamble\"><a href=\"#\" onclick=\"$.fancybox.close(); return false;\">Continue Shopping</a>" +
            " or <input type=\"button\" id=\"checkoutButton\" value=\"Check Out\" onclick=\"window.location='cart.aspx';$.fancybox.close();$.fancybox.showActivity();\" />";

            $.fancybox({
                'content': preAmble + cartTable + postAmble
            });

            $("#cartTable tr:gt(0):even").addClass("stripeRow");
            $("#cartFooter").removeClass("stripeRow");
            $("#cartTable").data('cartArray', hashObj);
        } else {
            emptyCart(preAmble);
        }
    }
}

function cartPop(rowVal) {
    var currentCart = $("#cartTable").data('cartArray');
    currentCart.cart.splice(rowVal, 1);
    if (currentCart.cart.length < 1) {
        deleteCookie(cName);
    } else {
        setCookie(cName, JSON.stringify(currentCart), 7);
    }
    showCart();
    updateCartNum();
}

function emptyCart(preAmble) {
    var noCart = "There are no items in your cart";
    $.fancybox({
        'content': preAmble + noCart
    });
}

//function multiOrderDisc(sentObj) {
//    var discCount = 0;
//    var discAmount = 0;

//    for (var d = 0; d < sentObj.length; d++) {
//        if (sentObj[d].groupdisc === 1) {
//            discCount++;
//        }
//    }

//    (discCount == 2) ? discAmount = .10 : (discCount == 3) ? discAmount = .15 : (discCount == 4) ? discAmount = .20 : (discCount > 4) ? discAmount = .25 : discAmount = 0;

//    if (discAmount > 0) {
//        for (var e = 0; e < sentObj.length; e++) {
//            if (sentObj[e].groupdisc == 1) {
//                sentObj[e].price -= Math.round((sentObj[e].price * discAmount) * Math.pow(10, 2) / Math.pow(10, 2));
//                sentObj[e].item_name += " (w/multi-product discount)";
//            }
//        }
//    }

//    return sentObj;
//}
////*************************************************//
//**                                             **//
//**          Compatibililty Stuff               **//
//**                                             **//
//*************************************************//
function showCompatibility() {
    var preAmble = "<div id=\"compatPreamble\">Product Compatibility</div>";

    $.fancybox({
        'content': preAmble + generateCompatUL()
    });

    $(".compatUL li:odd").addClass("stripeRow");
}

function generateCompatUL() {
    var compatTable;
    var compatRows = "";

    compatTable = "<ul class=\"compatUL\">";

    for (var j = 0; j < compatArray.length; j++) {
        compatRows += "<li>" + compatArray[j] + "</li>";
    }

    compatTable += compatRows + "</ul>";

    return compatTable;
}


//*************************************************//
//**                                             **//
//**          Cart.aspx Page Code                **//
//**                                             **//
//*************************************************//
function cartOptionsAdd() {
    var tempShipping = 0;
    var tempTax = 0;
    var currentTotal = (tempCartTotal > 0) ? (tempCartTotal == 0.00001) ? 0 : tempCartTotal : cartTotal;
    var cartFooterShipping = $("#cartFooterShipping");
    var cartFooterSalestax = $("#cartFooterSalestax");
    var cartFooterTotal = $("#cartFooterTotal");
    if ($(".shippingCheckbox input").get(0).checked) {
        cartFooterShipping.html("shipped CD: + $" + shipPrice.toFixed(2));
        //$("#tblShip").css('display', 'table');
        cartFooterShipping.css('display', 'table');
        tempShipping = shipPrice;
    } else {
        //$("#tblShip").css('display', 'none');
        cartFooterShipping.css('display', 'none');
        tempShipping = 0;
    }

    if ($(".salestaxCheckbox input").get(0).checked) {
        tempTax = Math.round((currentTotal * utTax) * Math.pow(10, 2)) / Math.pow(10, 2);
        cartFooterSalestax.html("UT sales tax: + $" + Number(tempTax).toFixed(2));
        cartFooterSalestax.css('display', 'table');
    } else {
        cartFooterSalestax.css('display', 'none');
        tempTax = 0;
    }
    cartFooterTotal.html("Total: $" + Number(parseFloat(currentTotal) + tempShipping + tempTax).toFixed(2));
}

function processCoupon(oElm) {
    var couponValue = $(".couponTextbox").val();
    $("#couponMessaging").html("Validating coupon, please wait...");
    $.ajax({
        type: "POST",
        url: "CouponService.asmx/verifyCoupon",
        data: "{'code': '" + couponValue + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            couponRetrieved(msg);
        },
        error: couponError
    });
}

function couponRetrieved(result) {
    var tempCouponValue = $(".couponTextbox");
    // returned results: result,ID, amount, ispercentage, conditions
    var resultSet = JSON.parse(result.d);
    if (resultSet.result == "valid") {
        $("#couponMessaging").html("Coupon \"" + tempCouponValue.val() + "\" Successfully Applied");
        tempCouponValue.val("");
        internalApplyCoupon(resultSet);
    } else {
        couponErrorHandling("Invalid Coupon");
    }
}

function couponError(result) {
    couponErrorHandling("Coupon Error. Please try again or <a href=\"contact.aspx\">contact us</a> for assistance.");
}

function couponErrorHandling(message) {
    $("#cartFooterDiscount").css('display', 'none');
    $("#couponMessaging").html(message);
    tempCartTotal = 0;
    cartOptionsAdd();
}

// TODO: figure out why coupon that matches total dollar amount doesn't apply
function internalApplyCoupon(resultSet) {
    var totalDiscount = 0;
    tempCartTotal = 0;
    totalDiscount = (resultSet.ispercentage == 1) ? (cartTotal * resultSet.discountAmount) : ((resultSet.discountAmount != 0) ? resultSet.amount : 0);
    tempCartTotal = cartTotal - totalDiscount;
    tempCartTotal = parseFloat(((tempCartTotal * Math.pow(10, 2)) / Math.pow(10, 2)).toFixed(2));
    tempCartTotal = (tempCartTotal < 0) ? 0.00001 : tempCartTotal;
    $("#cartFooterDiscount").html("Coupon: - $" + ((totalDiscount * Math.pow(10, 2)) / Math.pow(10, 2)).toFixed(2)).css('display', 'table');
    cartOptionsAdd();
}

//*************************************************************************************************//
//**                                                                                             **//
//**       Cookie Functions                                                                      **//
//**       http://jquery-howto.blogspot.com/2010/09/jquery-cookies-getsetdelete-plugin.html      **//
//**                                                                                             **//
//*************************************************************************************************//
function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + escape(value) + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name, "", -1);
}

