// quick order form validation
function validateQuickOrder(form) {
    if ((form.ProductNumber.value == "") || (form.ProductNumber.value == "Enter Product #")) {
        alert("Please enter an item number.");
        form.ProductNumber.focus();
        return false;
    }
    return true;
}

function validateMultiQuickOrder() {
    if ($("input:text[name^='p'][value!='']").length == 0) {
        alert("Please enter at least one product number");
        $("input:text[name^='p']").first().focus().select();
        return false;
    }
}


// Update purchase order on click value 
function onclickPurchaseOrder(form) {
    if (form.PurchaseOrder.checked) {
        alert(form.PurchaseOrder.value);
        form.PurchaseOrder.value = "yes";
    } else {
        form.PurchaseOrder.value = "no";
    }
}

// used on one-page check out to populate the shipping address from the billing address
/*function UseBillingAsShipping(form) {
    if (form.ship_to_bill_address.checked) {
        form.FName_SHIP.value = form.FirstName.value;
        form.LName_Ship.value = form.LastName.value;
        form.Company_Ship.value = form.Company.value;
        form.Address1_Ship.value = form.Address1.value;
        form.Address2_Ship.value = form.Address2.value;
        form.City_Ship.value = form.City.value;
        form.State_SHIP.value = form.State.value;
        form.Country_SHIP.value = form.Country.value;
        form.PostalCode_SHIP.value = form.PostalCode.value;
        form.Phone_Ship.value = form.Phone.value;
        populateCartTotal();
    } else {
        form.Company_Ship.value = '';
        form.Address1_Ship.value = '';
        form.Address2_Ship.value = '';
        form.City_Ship.value = '';
        form.State_SHIP.value = '';
        form.PostalCode_SHIP.value = '';
        form.FName_SHIP.value = '';
        form.LName_Ship.value = '';
        form.Phone_Ship.value = '';
        populateCartTotal();
    }
}*/

// used on one-page checkout(multiship) to populate the shipping address from the billing address
function UseBillingAsShippingMS(form) {
    if (form.ship_to_bill_address.checked) {
        form.FName_SHIP.value = form.FirstName.value;
        $("#CheckOut").validate().element("#FName_SHIP");
        form.LName_SHIP.value = form.LastName.value;
        $("#CheckOut").validate().element("#LName_SHIP");
        form.Company_SHIP.value = form.Company.value;
        form.Address1_SHIP.value = form.Address1.value;
        $("#CheckOut").validate().element("#Address1_SHIP");
        form.Address2_SHIP.value = form.Address2.value;
        form.City_SHIP.value = form.City.value;
        $("#CheckOut").validate().element("#City_SHIP");
        form.State_SHIP.value = form.State.value;
        $("#CheckOut").validate().element("#State_SHIP");
        form.Country_SHIP.value = form.Country.value;
        $("#CheckOut").validate().element("#Country_SHIP");
        form.PostalCode_SHIP.value = form.PostalCode.value;
        $("#CheckOut").validate().element("#PostalCode_SHIP");
        form.Phone_SHIP.value = form.Phone.value;
        $("#CheckOut").validate().element("#Phone_SHIP");
        //    populateCartTotal();
    } else {
        form.Address1_SHIP.value = '';
        form.Address2_SHIP.value = '';
        form.City_SHIP.value = '';
        form.State_SHIP.value = '';
        form.PostalCode_SHIP.value = '';
        form.FName_SHIP.value = '';
        form.LName_SHIP.value = '';
        form.Phone_SHIP.value = '';
        //    populateCartTotal();
    }
}

// used on one-page check out to update order total (for example after state, country, or shipping method change)
function populateCartTotal() {
    var state_ship = document.getElementsByName("State_SHIP")[0].value;
    var country_ship = document.getElementsByName("Country_SHIP")[0].value;
    var zip_ship = document.getElementsByName("PostalCode_SHIP")[0].value;
    if (state_ship != " - Select - " && country_ship != " - Select - " && document.getElementById("shipping_method") != null) {
        //shipping_method dropdown wont exist if page portion is being refreshed by AJAX call
        var ship_method = document.getElementsByName("shipping_method")[0].value;
        DmiAjaxFetch('CheckoutCartTotalContentMS', 'DmiAjaxSecure.aspx', 'request=CheckoutCartTotalContentMS&state_ship=' + state_ship + '&country_ship=' + country_ship + '&zip_ship=' + zip_ship + '&shipping_method=' + ship_method + debugFlag() + '&extra=', rnd());
    }
}

//global variable
var giftCertificateCount = 0;

// used on one-page check out to apply the promo code the customer provides
function applyKeyCodeRefresh() {
    var keycode = document.getElementsByName("keycode")[0].value;
    //var giftcert1 = document.getElementsByName("giftcert1")[0].value;
    var giftcert1 = '';
    // alert("giftcert1:"+giftcert1);
    DmiAjaxFetch('CheckOutCartItemsContent', 'DmiAjaxSecure.aspx', 'request=CheckOutCartItemsContent&keycode=' + keycode + '&giftcert1=' + giftcert1 + '&extra=', rnd());
}

// used on one-page check out to apply the promo code the customer provides
function applyKeyCode() {
    var keycode = document.getElementsByName("keycode")[0].value;
    //var giftcert1 = document.getElementsByName("giftcert1")[0].value;
    var giftcert1 = '';
    DmiAjaxFetch('CheckOutCartItemsContent', 'DmiAjaxSecure.aspx', 'request=CheckOutCartItemsContent&keycode=' + keycode + '&giftcert1=' + giftcert1 + debugFlag() + '&extra=', rnd());
    if (giftCertificateCount <= 0 && keycode == '') {
        setTimeout("applyKeyCodeRefresh()", 1000); //repaint with new cart object
    }
    if (keycode == '') giftCertificateCount = giftCertificateCount + 1;
    return false;
}

// used on one-page checkout(multiship) to apply the promo code the customer provides
function applyKeyCodeCheckout() {
    var keycode = document.getElementsByName("keycode")[0].value;
    // var giftcert1 = document.getElementsByName("giftcert1")[0].value;
    var giftcert1 = "";
    //alert('DEBUG: gift cert:'+ giftcert1);
    DmiAjaxFetch('CheckOutCartItemsContentMS', 'DmiAjaxSecure.aspx', 'request=CheckOutCartItemsContentMS&keycode=' + keycode + '&giftcert1=' + giftcert1 + '&extra=', rnd());
    if (giftCertificateCount <= 0 && keycode == '') {
        //alert('DEBUG: ct = '+ giftCertificateCount );
        setTimeout("applyKeyCodeRefresh()", 1000); //repaint with new cart object
    }
    if (keycode == '') giftCertificateCount = giftCertificateCount + 1;
    return false;
}

// used to generate random string that will be appended to AJAX requests to avoid getting cached response
function rnd() {
    return String((new Date()).getTime()).replace(/\D/gi, '')
}

// used to retrieve the debug flag
function debugFlag() {
    if (null != document.getElementsByName("debug")[0]) return String('&dminsite=' + document.getElementsByName("debug")[0].value);
    else
        return '';
}

// used on one-page check out to update billing state or country and order total
function updateBillingInfo() {
    var state_bill = document.getElementsByName("State")[0].value;
    var country_bill = document.getElementsByName("COUNTRY")[0].value;
    var zip_bill = document.getElementsByName("PostalCode")[0].value;
    if (state_bill != " - Select - " && country_bill != " - Select - ") {
        DmiAjaxFetch('CheckoutCartTotalContent', 'DmiAjaxSecure.aspx', 'request=CheckoutCartTotalContent&state_bill=' + state_bill + '&country_bill=' + country_bill + '&zip_bill=' + zip_bill + debugFlag() + '&extra=', rnd());
    }
}

// used on one-page multi-ship check out to update billing state or country and order total
function updateBillingInfoMS() {
    var state_bill = document.getElementsByName("State")[0].value;
    var country_bill = document.getElementsByName("COUNTRY")[0].value;
    var zip_bill = document.getElementsByName("PostalCode")[0].value;
    if (state_bill != " - Select - " && country_bill != " - Select - ") {
        DmiAjaxFetch('CheckoutCartTotalContentMS', 'DmiAjaxSecure.aspx', 'request=CheckoutCartTotalContentMS&state_bill=' + state_bill + '&country_bill=' + country_bill + '&zip_bill=' + zip_bill + debugFlag() + '&extra=', rnd());
    }
}

// used on one-page check out to update order total (for example after state, country, or shipping method change)
function populateCartTotalCheckout() {
    DmiAjaxFetch('CheckoutCartTotalContentMS', 'DmiAjaxSecure.aspx', 'request=CheckoutCartTotalContentMS' + debugFlag() + '&extra=', rnd());
}

function populateShippingMethods(recipientId) {
    populateShippingMethods(recipientId, '', '');
}

function populateShippingMethods(recipientId, giftAction, po_boxAction) {
    //assumes "State_SHIP_RECIPIENT" or "Country_SHIP_RECIPIENT", parse out the actual recipient name.  Need to figure out how to pass the nickname within the select control
    var recipient = '';
    var recipientNamePart = '';
    var tempRecipient = '';
    //sanity check
    if (recipientId == null || recipientId == 'undefined') tempRecipient = 'Default';
    else
        tempRecipient = recipientId;
    //parse only if it's not the default, assume empty is default
    if (tempRecipient.indexOf('State_SHIP') == 0) tempRecipient = tempRecipient.substring(11);
    else if (tempRecipient.indexOf('Country_SHIP') == 0) tempRecipient = tempRecipient.substring(13);
    else if (tempRecipient == '') tempRecipient = 'Default';
    recipient = tempRecipient;
    if (po_boxAction == null) po_boxAction = '';
    if (giftAction == null) giftAction = '';
    //if not the default, add the name part to retrieve specific recipient form elements
    if (recipient != 'Default' && recipient != '') recipientNamePart = '_' + recipient;
    var state_ship = '';
    var country_ship = '';
    var zip_ship = '';
    state_ship = document.getElementsByName("State_SHIP" + recipientNamePart)[0].value;
    country_ship = document.getElementsByName("Country_SHIP" + recipientNamePart)[0].value;
    zip_ship = document.getElementsByName("PostalCode_SHIP" + recipientNamePart)[0].value;
    //alert('S:' + state_ship + ' C:' + country_ship + ' Z:' + zip_ship);
    if (state_ship != " - Select - " && country_ship != " - Select - ") {
        var ship_method;
        if (document.getElementById("shipping_method" + recipientNamePart) != null) {
            //shipping_method dropdown wont exist if page portion is being refreshed by AJAX call
            ship_method = document.getElementsByName("shipping_method" + recipientNamePart)[0].value;
        } else
            ship_method = ""; //won't get set on call, but will use existing or default
        var isPO_selected;
        if (document.getElementById("PO_SHIP" + recipientNamePart) != null) {
            isPO_selected = document.getElementsByName("PO_SHIP" + recipientNamePart)[0].checked;
            //alert('PO=' + isPO_selected);
        } else
            isPO_selected = "";
        //must pass recipient or else the built section will not be able to resend the recipient
        DmiAjaxFetch('CheckoutShippingMethods' + recipientNamePart, 'DmiAjaxSecure.aspx', 'request=' + 'CheckoutShippingMethods' + recipientNamePart + '&state_ship=' + state_ship + '&country_ship=' + country_ship + '&zip_ship=' + zip_ship + '&shipping_method=' + ship_method + '&recipient=' + recipient + '&gift=' + giftAction + '&po_box=' + po_boxAction + '&po_box_checked=' + isPO_selected + debugFlag() + '&extra=', rnd());
        setTimeout("populateCartTotalCheckout()", 2000);
    }
}


/*  
Bill added
*/

function updateCartShippingAddress(name, value, cguid) {
    DmiAjaxFetch('CartShippingAddressUpdateContent', 'DmiAjaxSecure.aspx', 'request=CartShippingAddressUpdate&field=' + name + '&name=' + name + '&' + name + '=' + value + '&cguid=' + cguid + '&extra=', rnd());
    populateCartTotal();
}


function ShoppingCartAddAJAX( formElement )
{
    formElement = $( formElement );
    
    $.ajax( {
        type: "POST",
        url: "dmiajax.aspx?request=ShoppingCartAddAJAX",
        data: formElement.serialize(),
        dataType: "json",
        success: function( response )
        {
            if ( response.Status == "Success" )
            {
                $.ajax( {
                    type: "GET",
                    url: "dmiajax.aspx?request=FloatingCart&extra=" + rnd(),
                    dataType: "html",
                    success: function( response )
                    {
                        var floatingCart = $( "#floating-cart" );

                        if ( floatingCart.length == 0 )
                        {
                            floatingCart = $( '<div id="floating-cart"></div>' ).appendTo( "#header" );
                           
                            floatingCart.hoverIntent( {
                                over: function() {},
                                timeout: 200,
                                out: function() { $( this ).stop( true, true ).filter( ":visible" ).hide( "drop", { direction: "down" } ); }
                            } );

                            floatingCart.click( function( event ) {
                                event.stopPropagation();
                            } );
                        }
                        
                        floatingCart.html( response );

                        $( "html, body" ).scrollTop( 0 );
                        
                        floatingCart.stop( true, true ).show( "drop", { direction: "up" }, 800, function() {
                            var floatingCartTbody = floatingCart.find( "tbody" );
                            floatingCartTbody.scrollTop( floatingCartTbody.get( 0 ).scrollHeight );
                            floatingCartTbody.find( "tr" ).filter( ":last" ).effect( "highlight", { color : "#fff669" }, 3500 );
                        } );
                    }
                } );
                
                if ( response.CartItemCount ) {
                    $( "#header li.cart a" ).html( "Shopping Cart (" + response.CartItemCount + " Items)" );
                }
                
                formElement.find( "select option" ).attr( "selected", false );
                formElement.find( "input:radio" ).attr( "checked", false );
                formElement.find( "input:checkbox" ).attr( "checked", false );
                formElement.find( "input:text" ).val( "" );
                formElement.find( "input:text.qty" ).val( "1" );
                formElement.find( "span[id^='ProductInventoryViewSingleSku']" ).html( "<span>Make a selection to view status</span>" );
            }
            else if ( response.Error ) {
                alert( response.Error );
            }
        }
    } );
}

