﻿var cName = "randSet";
var cartDisplay = true;
//*** Variables sent from server ***//
var cartTotal = 0;
var utTax = 0;
var taxableTotal = 0;
var shipPrice = 0;
var depositAmount = 400;
//*********************************//
var tempCartTotal = 0;
var tempDiscountPercent = 0;
var rdoSelected;
var newProdVar;

$(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();
    });

    $('.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();
    });

    if (window.location.pathname.indexOf("cart.aspx") != -1) cartOptionsAdd(); // After page postback check for tax options
});

// 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() {
    if (rdoSelected == "noval") {
        alert("Please select an option before continuing");
    } else {
        rdoSelected ? newProdVar = prodVar + rdoSelected : newProdVar = prodVar;

        var tempHashTable = getCookie(cName);
        deleteCookie(cName);
        if ((tempHashTable == null) || (tempHashTable == "null") || (tempHashTable == "")) {
            newCartObject = new cartObj(newProdVar, 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 == newProdVar) {
                    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: newProdVar, price: Number(priceVar), item_name: prodName, category: categoryVar };
            }
        }

        setCookie(cName, JSON.stringify(newCartObject), 7);
        updateCartNum();
        showCart();
    }
}

function confirmVersion() {
    if (deposit == 1) {
        rdoSelected = "noval";
        $.fancybox({
            'content': "<strong>Please select a payment option:</strong><div><input type=\"radio\" name=\"paytype\" id=\"paytype1\" onclick=\"rdoSelected='-full';\" /> <label for=\"paytype1\">Pay in full and receive a $50 discount</label><br /><input type=\"radio\" name=\"paytype\" id=\"paytype2\" onclick=\"rdoSelected='-dep';\" /> <label for=\"paytype2\">Pay a $400 deposit</label></div> <input type=\"button\" id=\"continueButton\" value=\"Continue\" onclick=\"captureCartClick()\" />",
            'modal': true
        });
    } else if (deposit == 2) {
        rdoSelected = "noval";
        $.fancybox({
            'content': "<strong>Please select your shipping type:</strong><div><input type=\"radio\" name=\"shiptype\" id=\"ship1\" onclick=\"rdoSelected='-dom';\" /> <label for=\"ship1\">Shipping <em>within</em> the U.S.</label><br /><input type=\"radio\" name=\"shiptype\" id=\"ship2\" onclick=\"rdoSelected='-int';\" /> <label for=\"ship2\">Shipping <em>outside</em> of the U.S. ($25 surcharge required)</label></div> <input type=\"button\" id=\"continueButton\" value=\"Continue\" onclick=\"captureCartClick()\" />",
            'modal': true
        });
    } else if (deposit == 3) {
        rdoSelected = "noval";
        $.fancybox({
            'content': "<strong>Please select your shipping type:</strong><div><input type=\"radio\" name=\"shiptype\" id=\"ship1\" onclick=\"rdoSelected='-dom';\" /> <label for=\"ship1\">Shipping <em>within</em> the U.S.</label><br /><input type=\"radio\" name=\"shiptype\" id=\"ship2\" onclick=\"rdoSelected='-int';\" /> <label for=\"ship2\">Shipping <em>outside</em> of the U.S. ($50 surcharge required)</label></div> <input type=\"button\" id=\"continueButton\" value=\"Continue\" onclick=\"captureCartClick()\" />",
            'modal': true
        });
    } else if (deposit == 4) {
        rdoSelected = "noval";
        $.fancybox({
        'content': "<strong>Please select your mentoring session length:</strong><div><input type=\"radio\" name=\"shiptype\" id=\"ship1\" onclick=\"rdoSelected='_2hr';\" /> <label for=\"ship1\">2 hours: $375</label><br /><input type=\"radio\" name=\"shiptype\" id=\"ship2\" onclick=\"rdoSelected='_4hr';\" /> <label for=\"ship2\">4 hours: $625</label><br /><input type=\"radio\" name=\"shiptype\" id=\"ship3\" onclick=\"rdoSelected='_8hr';\" /> <label for=\"ship3\">8 hours $995</label></div> <input type=\"button\" id=\"continueButton\" value=\"Continue\" onclick=\"captureCartClick()\" />",
        'modal': true
        });
    } else {
        captureCartClick();
    }
}

//*************************************************//
//**                                             **//
//**          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")) {
            window.location = 'cart.aspx';
            $.fancybox.close();
            $.fancybox.showActivity();
        } 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
    });
}

////*************************************************//
//**                                             **//
//**          Compatibililty Stuff               **//
//**                                             **//
//*************************************************//
function showCompatibility() {
    var preAmble = "<div id=\"compatPreamble\">Product Compatibility</div>";

    $.fancybox({
        'content': preAmble + generateCompatUL()
    });

    $(".compatUL li:odd").addClass("stripeRow");
}

//*************************************************//
//**                                             **//
//**          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");
    cartFooterShipping.css('display', 'none');

    if ($(".salestaxCheckbox input").get(0).checked) {
        tempTax = Math.round((taxableTotal * utTax) * Math.pow(10, 2)) / Math.pow(10, 2);
        tempTax = tempTax - (tempTax * tempDiscountPercent);
        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');
    tempDiscountPercent = totalDiscount / cartTotal;
    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);
}

