﻿var maxQty = 99;
// Switches to No-Conflict mode by re-writing all '$' as 'j' to avoid conflict with other Javascript libraries.
//var j = jQuery.noConflict();

function PopupWindow(link, windowname) {
    window.open(link, windowname, "height = 830, width = 735, scrollbars=yes")
}

function CartWidget_ChangeTotal(sQtyFormID, iIncrementAmount, sSubTotalFormID, iPrice, bUpdateTotal, iAttractionID) {
    //use to calc Qty * price
  
    oInput = document.getElementById(sQtyFormID);
    iOldAmount = oInput.value.replace(/^0+/, ''); ;

    if (iOldAmount == "") iOldAmount = 0;
    if (!isNaN(iOldAmount)) {
        iNewAmount = parseInt(iOldAmount) + iIncrementAmount;
        if (iNewAmount <= 0) iNewAmount = 0;
        if (iNewAmount > maxQty) iNewAmount = maxQty;
    }
    oInput.value = iNewAmount;
    if (bUpdateTotal) {
        shoppingcart_SetProductTotal(sSubTotalFormID, iNewAmount, iPrice);
    }

    var result = sQtyFormID.search(/txtCartQty/);
    if (result != -1) {
        shoppingcart_SetCartSubTotal();
        shoppingcart_TotalQty();
        UpdateCartItems();
    }
}

function shoppingcart_SetCartSubTotal() {
    //add all items to calc subtotal
    //this function get all the values from the div 'sidebar-cart-price-subtotal-' content and sum the total
    var TotalCollection = [];
    TotalCollection = j("div[id^=sidebar-cart-price-subtotal-]");

    var iUpdatedSubTotal = 0;
    var iEachTotal;

    for (i = 0; i < TotalCollection.length; i++) { //loop each element on the price
    
        iEachTotal = j(TotalCollection[i]).text();
     
        var result = iEachTotal.indexOf("$");
        var iTotal = 0;
     
        if (result != -1) {
            iTotal = iEachTotal.replace("$", "");
        }

        iUpdatedSubTotal = iUpdatedSubTotal + parseFloat(iTotal);
    }

    //debugger;
    var sTotal = iUpdatedSubTotal.toString();
    var iSearchDecimal = sTotal.indexOf(".");
    if (iSearchDecimal > -1) {
        aTotal = sTotal.split(".");
        if (aTotal[1].length < 2) aTotal[1] = aTotal[1] + "0";
        if (aTotal[1].length < 2) aTotal[1] = aTotal[1] + "0";
        aTotal[1] = aTotal[1].substr(0, 2);
        sTotal = aTotal.join(".");
    } else {
        sTotal = sTotal + ".00";
    }
    j("#sidebar-total-amount").text("$" + sTotal);
}

function shoppingcart_SetProductTotal(sSubTotalFormID, iQty, iPrice) {
    if (iPrice > 0) {
        //debugger;
        iTotal = iQty * parseFloat(iPrice);
        sTotal =iTotal + ""

        if (sTotal.indexOf(".") > -1) {
            aTotal = sTotal.split(".");
            //if (aTotal[1].length < 2) aTotal[1] = aTotal[1] + "0";
            if (aTotal[1].length < 2) aTotal[1] = aTotal[1] + "0";
            aTotal[1] = aTotal[1].substr(0, 2);
            sTotal = "$ " + aTotal.join(".");
        } else {
            sTotal = "$ " + sTotal + ".00";
        }
    } else {
    sTotal = " N/A";
}
    var result = sSubTotalFormID.search(/_lblTotal_/);
    if (result != -1) {
        j("#" + sSubTotalFormID).text(sTotal);
   } else {
        j("#" + sSubTotalFormID).css("padding-top", "6px");
        j("#" + sSubTotalFormID).css("Height", "16px");
        j("#" + sSubTotalFormID).html("<p>" + sTotal + "<p>");
    }
}


function shoppingcart_NumbersOnly(e, el) {
    //validate keyboard input to accept number only
    var unicode = e.charCode ? e.charCode : e.keyCode;
    if (unicode == 8) { //if the key is the backspace key (which we should allow)
        return true;
    }
    if (unicode < 48 || unicode > 57) {//if not a number
        return false; //disable key press
    }
    var val = $(el).value;
    if (val.length > 0 && (val < 0 || val > 99)) {
        return false;
    }
}

function ResetQtyToZero() {
    var QtyCollection = [];
    QtyCollection = j("input[id*=_txtQty_]");
 
    var iQty = 0;
    for (i = 0; i < QtyCollection.length; i++) { //loop each element on the form
        iQty = j(QtyCollection[i]).val();
        if (iQty > 0) {
            j(QtyCollection[i]).val("0");
        }
    }

    var TotalCollection = [];
    TotalCollection = j("span[id*=_lblTotal_]");
  
    var iTotal = 0;
    for (i = 0; i < TotalCollection.length; i++) { //loop each element on the form
      
            j(TotalCollection[i]).text("$0.00");
       
    }
}

function shoppingcart_TotalQty() {
    //cal tatal tickets in the cart
    //this function get all the values from the div 'sidebar-cart-price-subtotal-' content and sum the total

    var TotalCollection = [];
    TotalCollection = j("input[id^=txtCartQty_]");
  
    var iUpdatedQty = 0;
    var iEachTotal;

    for (i = 0; i < TotalCollection.length; i++) { //loop each element on the form
        //  alert(j(TotalCollection[i]).text());
        iEachTotal = 0;
        iEachTotal = j(TotalCollection[i]).val();
        //  alert(iEachTotal);

        iUpdatedQty = iUpdatedQty + parseFloat(iEachTotal);
    }
    // alert(iUpdatedQty);
    j("#lblTicketQty").text(iUpdatedQty);
    j("#sidebar-ticket-amount-header").text("(" + iUpdatedQty + " tickets)");
    j("#sidebar-ticket-amount-body").text(iUpdatedQty);
}

//shoppingcart actions	 remove item
function DeleteCartItems() {
    var checkedvalue = [];
    j("input[id^=chkShoppingCart_]:checked").each(function (i, checked) {
        checkedvalue[i] = j(checked).val();
    });
    if (checkedvalue.length > 0) {
        sproducts = checkedvalue.join(",");
    
        var strURL = "/CartWidgetHandler.ashx?action=remove&ProductId=" + sproducts;
     
        j.ajax({
            type: "POST",
            url: strURL,
            async: false,
            success: function (data, textStatus, XMLHttpRequest) {
                var RsltElem = j("#CartDiv");
                RsltElem.html(data);
                document.getElementById('lblTicketQty').value = shoppingcart_TotalQty();

                OpenCart();
                j('#sidebar').sidebar();
                //alert("The items has been deleted");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Error occurred while loading the shopping cart. Please refresh the page again!");
            }
        });
    } else { 
    alert("No products were selected to delete from the cart.");
    }
}

//shoppingcart actions	 update item - only when user click on checkout
function UpdateCartItems(checkouturl) {
//checkout - updateDB and ChekcPassInfo and redirect to checkout.asp  

    var arrCartProductid = [];
    var arrCartProductCount = [];
    var arrCartProductAttraction = [];
    var sCartProducts = "";
    var sCartProductCounts = "";
    var sCartProductAttraction = "";

    j("input[id^=chkShoppingCart_]").each(function (i, checked) {
        arrCartProductid[i] = j(checked).val(); //return the product id and add the id to collection
        arrCartProductCount[i] = j("#txtCartQty_" + arrCartProductid[i]).val();
        arrCartProductAttraction[i] = j("#CartItemAttractionID_" + arrCartProductid[i]).val();
    });
    if (arrCartProductid.length > 0) {
        sCartProducts = arrCartProductid.join(",");
        sCartProductCounts = arrCartProductCount.join(",");
        sCartProductAttraction = arrCartProductAttraction.join(",");
    }

    if (arrCartProductCount.length > 0)
    {
        var sCartTotal =j("#sidebar-total-amount").text();
        var strURL = "/CartWidgetHandler.ashx?action=update&CartProduct=" + sCartProducts + "&CartProductCount=" + sCartProductCounts +
        "&CartProductAttraction=" + sCartProductAttraction + "&CartTotal=" + sCartTotal;
        var sResponseText;
        j.ajax({
            type: "POST",
            url: strURL,
            async: false,
            success: function (data, textStatus, XMLHttpRequest) {
                sResponseText = getResponseText(data);
                if (sResponseText != "") {
                    //if hit the max limit
                    alert(sResponseText);
                } else {
                    // alert("Your cart has been updated");
                    // checkPassInfo();
                   
                    if (checkouturl != null) {
                        window.parent.location = checkouturl;
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Error occurred while loading the shopping cart. Please refresh the page again!");
            }
        });
    } else {
    alert("No products were selected!");
}
}


var checkPassInfo = function () { //not using - Gigabit implement this function in shop area.
    //returns a result of 1 if there are additional details required for a product in the cart
    new Ajax.Request('/CheckExtraPassInfo.asp',
    {
        method: 'post',
        onSuccess: function (transport) {
            var sResult = transport.responseText;

            if (sResult == "0") {
                // no additional details are required so go straight to check out page
                loadCheckOutPage();
            }
            else if (sResult == "1") {
                //This reloads the page to show a form containing 'additional details' fields
                //Calling CheckExtraPassInfo.asp sets the session variable dctSavedPassData with required additional fields
                document.cookie = "PassData=1";
                //  var sURL = window.location.href;
                var sURL = "https://admin.staging.shop.myfun.com.au/";
                alert(sURL);
                if (sURL.indexOf("cartOpen") > -1) {
                    sURL = sURL.replace("cartOpen=1", "");
                }
                window.location.href = sURL;
            }
            else {
                alert("No Result return:" + sResult);
            }
        },
        onFailure: function (transport) {
            //			alert(transport.responseText);
        }
    });
}

var loadCheckOutPage = function () {
    window.location.href = "/default.aspx";
}


var addItemsToCart = function (f, bProceedToCheckout, iVenueProductQtyLimit, sVenueProductLimitExceedMsg) //DF added bProceedToCheckout, bValidateVenueProductQtyLimit 20100113
{
    // debugger;
    if (!testCookie()) {
        alert("You do not have cookies enabled in your browser. This shopping cart requires that cookies be enabled.");
        return;
    }

    if (iVenueProductQtyLimit) { //OMO Promo
        if (!shoppingcart_ValidateVenueProductQtyLimit(f, iVenueProductQtyLimit, sVenueProductLimitExceedMsg)) {
            return false;
        }
    }
    var aproducts = new Array();
    var aproductcounts = new Array();
    var sproductwarnings = "";
    var bfound = false;
    var icurrprodqty = 0;
    var sattractionid;
    var svenueid;
    //debugger;
    
    j("#" + f + " INPUT").each(function (i, inputbox) {
        if (j(this).attr('name') == "ProdID") {
            aproducts[aproducts.length] = j(this).val();
        } else if (j(this).attr('name') == "ProdCount") {
            icurrprodqty = j(this).val(); //add ProdCount to icurrprodqty Array
            aproductcounts[aproductcounts.length] = icurrprodqty
            if (icurrprodqty > 0) { //if icurrprodqty is greater than 0, we found the product needs to be add to shopping cart
                bfound = true;
            }
        } else if (j(this).attr('name') == "ProdCustomerWarning" && j(this).val() != "" && icurrprodqty > 0) {
            if (sproductwarnings.indexOf(j(this).val() + "<br />") == -1) {
                sproductwarnings = sproductwarnings + j(this).val() + "<br />"; //if found any error msg, append the msg
            }
        } else if (j(this).attr('name') == "AttractionID") {
            sattractionid = j(this).val();
        } else if (j(this).attr('name') == "VenueID") {
            svenueid = j(this).val();  //store the VenueID Id
        }
    });


    if (bfound) { //if found items add to cart

        sproducts = aproducts.join(","); //join the added products with ','
        sproductcounts = aproductcounts.join(","); //join the added qty with ','

        //get the new qty from the cart and add to DB
        var arrCartProductid = [];
        var arrCartProductCount = [];
        var arrCartProductAttraction = [];
        var sCartProducts = "";
        var sCartProductCounts = "";
        var sCartProductAttraction = "";
        j("input[id^=chkShoppingCart_]").each(function (i, checked) {
            arrCartProductid[i] = j(checked).val(); //return the product id and add the id to collection
            arrCartProductCount[i] = j("#txtCartQty_" + arrCartProductid[i]).val();
            arrCartProductAttraction[i] = j("#CartItemAttractionID_" + arrCartProductid[i]).val();
        });
        if (arrCartProductid.length > 0) {
            sCartProducts = arrCartProductid.join(",");
            sCartProductCounts = arrCartProductCount.join(",");
            sCartProductAttraction = arrCartProductAttraction.join(",");
        }

        var strValidateQtyURL = "/CartWidgetHandler.ashx?action=validateQty&ProductId=" +
        sproducts + "&ProductCount=" + sproductcounts + "&CartProductCount=" + sCartProductCounts +
        "&CartProduct=" + sCartProducts + "&CartProductAttraction=" + sCartProductAttraction +
        "&CustomerWarnings=" + sproductwarnings + "&VenueId=" + svenueid + "&AttractionId=" + sattractionid;
    
        var sResponseText;
        //validate the total qty of the attraction allowed by eBus
        j.ajax({
            type: "POST",
            url: strValidateQtyURL,
            async: false,
            success: function (data, textStatus, XMLHttpRequest) {
                sResponseText = getResponseText(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Error occurred while checking the shopping cart. Please refresh the page again!");
            }
        });

        if (sResponseText != "") {
            $("AttErrMsg" + sattractionid).innerHTML = "<h6>" + sResponseText + "</h6>";
            $("AttErrMsg" + sattractionid).style.display = "block";
            alert(sResponseText);
        } else {
            $("AttErrMsg" + sattractionid).style.display = "none";
           
            var strAddURL = "/CartWidgetHandler.ashx?action=add&ProductId=" +
        sproducts + "&ProductCount=" + sproductcounts + "&CartProductCount=" + sCartProductCounts +
        "&CartProduct=" + sCartProducts + "&CartProductAttraction=" + sCartProductAttraction +
        "&CustomerWarnings=" + sproductwarnings + "&VenueId=" + svenueid + "&AttractionId=" + sattractionid;
            j.ajax({
                type: "POST",
                url: strAddURL,
                async: false,
                success: function (data, textStatus, XMLHttpRequest) {
                    var RsltElem = j("#CartDiv");
                    RsltElem.html(data);
                    document.getElementById('lblTicketQty').value = shoppingcart_TotalQty();
                 
                    ResetQtyToZero();
                    OpenCart();
                    j('#sidebar').sidebar();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error occurred while loading the shopping cart. Please refresh the page again!");
                }
            });
        }


    } else {
        alert("No products were selected to add to the cart.");
    }

}


function getResponseText(transport) {
    var sResMarker = "<!--strResponseMessage=";
    var sText = transport;
    iResponseIndex = sText.indexOf(sResMarker);
    if (iResponseIndex > -1) {
        sResponseText = sText.substr(iResponseIndex + sResMarker.length);
        sResponseText = sResponseText.substr(0, sResponseText.indexOf("-->"));
        return sResponseText;
    } else {
        return "";
    }
}
function clearProductCounts(f) {
    var iform = $(f);
    for (i = 0; i < iform.elements.length; i++) {
        if (iform.elements[i].name == "ProdCount") {
            if (iform.elements[i].type == "select") {
                iform.elements[i].selectedIndex = 0;
            } else {
                iform.elements[i].value = "0";
            }
            iform.elements[i].onchange();
        }
    }
}

function shoppingcart_ValidateVenueProductQtyLimit(sVenueFormID, iQtyLimit, sMessage) {
    var oForm = $(sVenueFormID);
    var iQtyCount = 0;
    for (i = 0; i < oForm.elements.length; i++) {
        if (oForm.elements[i].name == "ProdCount") {
            iQtyCount += parseInt(oForm.elements[i].value);
        }
    }
    if (iQtyCount > iQtyLimit) {
        alert(sMessage + ', you have selected ' + iQtyCount);
        return false;
    } else {
        return true;
    }
}

function OpenCart(params) {
    var viewportWidth = j(window).width();
    var viewportHeight = j(window).height();
    params = j.extend({ open: 'myFunSidebarOpen', close: 'myFunSidebarClose', sidebar: 'sidebar', speed: '1000', openDiv: 'myFunSidebarTopRight', ticketwrapper: 'sidebar-cart-items', wrapper: 'site', topbar: '22' }, params);
    if (!j('#' + params.sidebar).is(':visible')) {
        if (j('#container').width() < 1440) {
            j('#' + params.wrapper).css('margin', '0');
        }
        j('#' + params.sidebar).css('height', viewportHeight).show("slide", { direction: "right" }, params.speed);
        j('#' + params.sidebar + " #mainBgLayer").css('height', viewportHeight);

        var ticketwrapperheight = parseInt(j("#" + params.ticketwrapper).height()) + 220;
        if (ticketwrapperheight > j(window).height()) {

            //  j("#" + params.ticketwrapper).css('height', (parseInt(j(window).height()) - 280) + "px");
            j("#" + params.ticketwrapper).css('height', (parseInt(j("#" + params.ticketwrapper).height()) + 10) + "px");
        }
        else {
            j("#" + params.ticketwrapper).css('overflow', "hidden");
        }
        return false;
    }
}


