﻿//----------------------------
//Start Product Form Functions 
//----------------------------

function changeStockLevel() {
    var ddForm = $("#VariantDD").val();
    DDArray = ddForm.split(' _ ');
    $("#defaultvariantid").val(DDArray[0])  
    $("#availability_value").html(DDArray[1]);
}

function swapVariantImage() {
    var ddForm = $("#VariantDD").val()
    DDArray = ddForm.split(' _ ');
    $("#product-full").attr("src","http://images.buyitsellit.com/" + DDArray[2] + "_290.jpg");
}

function setOptions() {

    if (trackinventory == true) {
        var sOpt1, sOpt2, sOpt3, sOpt4, sOpt5;
 
        if ($("#opt1").val() != undefined) { sOpt1 = unescape($("#opt1").val()) } else { sOpt1 = 'null' };
        if ($("#opt2").val() != undefined) { sOpt2 = unescape($("#opt2").val()) } else { sOpt2 = 'null' };
        if ($("#opt3").val() != undefined) { sOpt3 = unescape($("#opt3").val()) } else { sOpt3 = 'null' };
        if ($("#opt4").val() != undefined) { sOpt4 = unescape($("#opt4").val()) } else { sOpt4 = 'null' };
        if ($("#opt5").val() != undefined) { sOpt5 = unescape($("#opt5").val()) } else { sOpt5 = 'null' };

        var hasmatch = false
        var variantid = '-1;'
        var stocklevel = 'Not in stock'
        var price = ''
        var saleprice = 'null'
        var assignedimageid = 'null'

        for (var i = 0; i < VariationList.length; i++) {

            if (sOpt1 == VariationList[i].opt1.replace("&amp;", "&") && sOpt2 == VariationList[i].opt2.replace("&amp;", "&") && sOpt3 == VariationList[i].opt3.replace("&amp;", "&") && sOpt4 == VariationList[i].opt4.replace("&amp;", "&") && sOpt5 == VariationList[i].opt5.replace("&amp;", "&") && VariationList[i].id != '-1') {

                hasmatch = true
                variantid = VariationList[i].id;
                stocklevel = VariationList[i].stocklevel;
                price = VariationList[i].price;
                saleprice = VariationList[i].saleprice;
                assignedimageid = VariationList[i].assignedimageid;
            }

        }
        if (hasmatch == true) {
            if (stocklevel == null || stocklevel <= 0) {
                
                $("#availability_value").html("not in stock");
                if ($("#btn_addtocart") != null) {
                    $("#btn_addtocart").attr("disabled", true);
                    $("#btn_addtocart").val("not in stock");
                    $("#btn_addtocart").html("not in stock"); 
                };
                $("#defaultvariantid").val(variantid);

            } else {
            if (stocklevel == 'unlimited') {
                stocklevel = '';
            }
            
                if ($("#product-full") != null && assignedimageid != '0') {
                    $("#product-full").attr("src","http://images.buyitsellit.com/" + assignedimageid + "_290.jpg");
                }
                if ($("#zoom") != null && assignedimageid != '0') {
                    $("#zoom div a").css("background", "url('http://images.buyitsellit.com/" + assignedimageid + "_290.jpg')");
                }                
                $("#availability_value").html(stocklevel + " in stock");
                //Set The Variant ID
                $("#defaultvariantid").val(variantid);

                //Set The Price
                if (saleprice != 'null') {
                    $("#optionprice").html("<s>" + price + "</s> " + saleprice);
                }
                else {
                    $("#optionprice").html(price);
                }
                $("#btn_addtocart").val('add to cart');
                $("#btn_addtocart").html('add to cart');
                $("#btn_addtocart").removeAttr("disabled");
 
            }

        }
        else {
            $("#availability_value").html("not in stock");
            $("#btn_addtocart").attr("disabled", true);
            $("#btn_addtocart").val("not in stock");
            $("#btn_addtocart").html("not in stock");
            $("#defaultvariantid").val(variantid);
        }
    }
    else {
        price = VariationList[0].price;
        saleprice = VariationList[0].saleprice;
        //Set The Price
        if (saleprice != 'null') {
            $("#optionprice").html("<s>" + price + "</s> " + saleprice);
        }
        else {
            $("#optionprice").html(price);
        }

        $("#availability_value").html("in stock");
        $("#defaultvariantid").val(defaultvariantid);
        $("#btn_addtocart").attr("disabled", false);
    }
};
//----------------------------
//End Product Form Functions 
//----------------------------


//Ajax request to submit newsletter signup.
function emailSubscribe() {
    var sEmail;
    var sStoreID;
    sEmail = $("#emailsub_emailaddress").val();
    sStoreID = $("#emailsub_storeid").val();

    $.ajax({
       type: "GET",
       dataType: "html",
       url: '/ajaxresponses/emailSubscribe.aspx?email=' + sEmail + '&storeid=' + sStoreID,
       success: function(msg){
         $("#emailsub_wrapper").html('<br/>Thank you for subscribing!');
       },
       error: function(msg) {
        alert('Unable to subscribe');
       }
     });
};

//Add to cart function from outside product page.
function addToCart(formid) {
    window.status = 'Add product to cart.';
    $('#productform_' + formid).submit()

}

//Changes the page from the drop down list.
function changePage(page) {
    var pageArray
    pageArray = page.split(' _ ');
    location = pageArray[0] + '&pagesize=' + pageArray[1];
}

//shows the product review form
function showReviewForm() {
    $("#writereviewbutton").hide();
    $("#reviewlist").hide();
    $("#reviewform").show();
}

//hides the product review form
function hideReviewForm() {
    $("#writereviewbutton").show();
    $("#reviewlist").show();
    $("#reviewform").hide();
}

//submits the product review form
function submitReviewForm() {
    var isValid = true;
    if (isValid && $("#revrating").val() == '') { isValid = false; alert('Please select a rating.'); };
    if (isValid && $("#revtitle").val() == '') { isValid = false; alert('Please enter a title for your review.'); };
    if (isValid && $("#revtext").val() == '') { isValid = false; alert('Please enter some text for your review'); };
    if (isValid && $("#recaptcha_response_field") == '') { isValid = false; alert('Please enter the code shown!'); };

    if (isValid) {

        $.ajax({
            type: "POST",
            url: "/product/submitreview",
            data: $("#reviewform").serialize(),
            success: function(msg) {
                $("#reviewcomplete").show();
                $("#reviewform").hide();
            },
            error: function(msg) {
                alert("You've entered an invalid code.");
                return false;
            }
        });

    }
}

//----------------------------
//Start Cart Form Functions 
//----------------------------

//prompts the user to ensure they want to clear the entire cart contents.
function confirmClearCart() {
    if (confirm("Are you sure you want to clear your cart?")) {
        clearCart();
    }
}

//Changes the total price when rate drop-down is selected.
function updateTotal(cartTotal) {
    var OldShippingFee = new String();
    OldShippingFee = $("#shippingrates").val();
    var NewShippingFee = OldShippingFee.replace(currencyPrefix, "");
    var ShippingFee = parseFloat(NewShippingFee)

    cartTotal = parseFloat(cartTotal)
    if (ShippingFee != 0) {
        var aTotal = (ShippingFee) + (cartTotal);
        var newTotal = aTotal.toFixed(2);
        $("#CartTotalHolder").html("<strong>" + currencyPrefix + newTotal + "</strong>");
        $("#excludingfees")("(excluding taxes)");
    }

    else {
        $("#CartTotalHolder").html("<strong>" + currencyPrefix + cartTotal.toFixed(2) + "</strong>");
        $("#excludingfees").html("(excluding taxes & shipping)");
    }
}

//Removes a specified item from a cart.
function deleteCartItem(itemID) {
    $("#cartitemid").val(itemID);
    $("#actiontype").val("delete");
    $('#cartform').submit()
}

//Cleares the entire shopping cart
function clearCart() {
    $("#cartitemid").val('all');
    $("#actiontype").val('clearall');
    $('#cartform').submit()
}

//Update the all of the quantities in the cart
function updateCart() {
    if($('[name=cartform]').eq(1).length == 0){
        $("#cartitemid").val('all');
        $("#actiontype").val('updateall');
        $('#cartform').submit()
    } else {
        $('[name=cartitemid]').eq(1).val('all');
        $('[name=actiontype]').eq(1).val('updateall');
        $('[name=cartform]').eq(1).submit()
    }
    
}

//generates calculated shipping rates specified in DestZip form
function getShippingRates() {
    
    $("#actiontype").val('getshippingrates');
    $("#cc_code").val($("#CountryCode").val());
    $("#zippostal").val($("#destzippostal").val());
    $('#cartform').submit()
}

//Post the cart to Google Checkout
function postCartToGoogle() {
    $("#actiontype").val('gccheckout');
    $('#cartform').submit()    
}

//Post the cart with normal checkout
function checkout() {
    $("#actiontype").val('checkout');
    $('#cartform').submit()     
}

//----------------------------
//End Cart Form Functions 
//----------------------------
