/* Minification failed. Returning unminified contents.
(389,73-74): run-time error JS1009: Expected '}': [
(389,93-94): run-time error JS1006: Expected ')': :
(389,93): run-time error JS1004: Expected ';'
(389,105-106): run-time error JS1195: Expected expression: )
(436,1-2): run-time error JS1002: Syntax error: }
(447,140-141): run-time error JS1010: Expected identifier: .
(447,140-141): run-time error JS1195: Expected expression: .
 */
var csx = (function ($) {
  var cart = {
    get: function () {
      return $.get('/api/cart/getcart');
    },

    getSummary: function () {
      return $.get('/api/cart/getsummary');
    },

    add: function (items) {
      return $.post('/api/cart/addproducts', {
        products: items
      });
    },	
      add: function (items,warehouse) {
          return $.post('/api/cart/addproducts', {
              products: items,
              warehouseCode:warehouse
          });
      },
    addByPartNumber: function (items) {
      return $.post('/api/cart/addproductsbypartnumber', {
        products: items
      });
    },
    addUploadByPartNumber: function (items,warehouse) {
          return $.post('/api/cart/addproductsbypartnumber', {
              products: items,
              WarehouseCode:warehouse
          });
      },
    addCoupon: function(couponCode) {
      return $.post('/api/cart/addcoupon', {
        couponCode: couponCode
      });
    },

    remove: function (cartItemId) {
      return $.post('/api/cart/removeitem/' + cartItemId);
    },

    removeCoupon: function (couponCode) {
      return $.post('/api/cart/removecoupon', {
        couponCode: couponCode
      });
    },

    updateQuantity: function (cartItemId, quantity) {
      return $.post('/api/cart/updateitemquantity/' + cartItemId, {
        quantity: quantity
      });
    },

    updateNote: function (cartItemId, note) {
      return $.post('/api/cart/updateitemnote/' + cartItemId, {
        note: note
      });
    },
    
    changeWarehouse: function (warehouseCode) {
      return $.post('/api/cart/changeorderwarehouse', {
        WarehouseCode: warehouseCode
      });
    },
      
    updateUOM: function (cartItemId, UOM) {
      return $.post('/api/cart/updateUOM/' + cartItemId, {
        UOM: UOM
      });
    }
  };

  var common = {
    updateCartSummary: function () {
      return cart.getSummary()
        .then(function (summary) {
          $(".c-total").text(summary.Total);
          $(".c-items").text(summary.NumberOfItems);
            $(".c-warehousename").text(summary.CartTitle);
        });
    }
  };

  var products = {
    getChildProduct: function (variantID) {
      return $.post('/api/products/GetChildProduct', {
          //partNumber: partNumber
          variantid: variantID
      });
      },
    getProductsInformation: function (partNumbers) {
        return $.post('/api/products/RetrieveProducts', {
            PartNumbers: partNumbers
          });
    }
  };

  return {
    cart: cart,
    common: common,
    products: products
  };
})($);
;
var partnumberfieldname;
var test;
var form; 

function CreateJSONFromSelections(elementnumber, partnumberfield, tilenumber, mThis) {
    var selectedItems = [];
	if (tilenumber === undefined) tilenumber = '';
	if (partnumberfield === undefined) partnumberfield = '';
	
	partnumberfieldname = partnumberfield;
	form = $(mThis.target).closest('form');
	if (form[0].name == '' && form[0].id == 'product-grid-form' )
	{
		form = $(mThis.target).closest('.tile--product');
	}
	var pkid = form.find('input[name^=pkid]').val();
	var selections = form.find('[name^="ParentChildOptions"]').toArray();

    for (i = 0; i < selections.length; i++) {
        var item = new Object();
        item.Name = selections[i].id.replace(tilenumber,'');
        item.Value = selections[i].value;
        selectedItems.push(item);
    }

	return GetSKU(pkid, selectedItems, mThis.target);
}

function GetSKU(spkid, parentchildoptions, target) {
    $.ajax({
        type: "POST",
        url: "/WebService.asmx/GetProductFromParentChildOptions",
		data: "{spkid: '" + spkid + "',sParentChildOptions: '" + JSON.stringify(parentchildoptions) + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
		success: function (data, e) {
			parentchildsuccess(data, target);
		},
        error: parentchilderror
    });
}

function parentchilderror(response) {
    console.log(response.d);
}

function cartEnabled(target) {
    var bOptionsSelected = true;
	var selections = form.find('[name^="ParentChildOptions"]').toArray();

    
    for (i = 0; i < selections.length; i++) {
        if (selections[i].value == '') {
            bOptionsSelected = false;
        }
    }
    if (bOptionsSelected == true) {
		form.find('.btn-addtocart').prop( "disabled", false );
		if (form.name == 'form1')
{
			try {
			form.find("[name^=productrow]").attr("style", "");
		} catch (err) {

}

}
        

		if (partnumberfieldname != '') {
			form.find('#' + partnumberfieldname).val(form.find("[name^=SKU]").val());
        }  
    }
}

function parentchildsuccess(response, target) {
	const formatter = new Intl.NumberFormat('en-US', {
		style: 'currency',
		currency: 'USD',
		minimumFractionDigits: 2
	});
	var product = JSON.parse(response.d);
    var pricelabel;
	var breadcrumbpart;

	if (product.ValidProduct == true) {
		if (partnumberfieldname != '') {
			form.find('#' + partnumberfieldname).html(product.PartNumber);
		}

		form.find('[name^=pricetext]').html(product.PriceText);
		form.find('[name^=pricetext]').attr('style', '');

		if (product.VariantId !== 0) {
			form.find('input[name^=variantid]').val(product.VariantId);
		}

		form.find("[name^=ProductNumber]").html(product.PartNumber);
		form.find('input[name^=SKU]').val(product.PartNumber);
		form.find('[id^="Network Quantity"]').html(product.NetworkQuantity);
		form.find('[id^="Quantity On Hand"]').html(product.QuantityOnHand);
		form.find('input[name^=price]').val(product.Price);
		form.find('.priceholder').html(formatter.format(product.Price));

		//priceholder
		pricelabel = document.getElementById('productdetailprice');


		if (form[0].name == 'form1')
		{
			if (pricelabel != null) {
				document.getElementById('productdetailprice').style.display='';
			}

			breadcrumbpart = document.getElementById('breadcrumbpart');

			if (document.getElementById('breadcrumbpart') != null) {
				document.getElementById('breadcrumbpart').innerHTML=product.PartNumber;
			}
		}

		cartEnabled(target);
	}
    
    console.log(response.d);
}

;
function enableVariations (variants, formPrefix) {
    var formPrefixEscaped = $.escapeSelector(formPrefix);
    var cartButton = $(document.getElementById(formPrefix + '.cart-btn'));
    var variantInput = $(document.getElementById(formPrefix + '.variant.id'));

    var selectors = {
        selectedVariationInput: function (index) {
            return $('input[name="' + formPrefixEscaped + '\\.variations[' + index + ']"]:checked');
        },

        variationGroupNameInput: function (index) {
            return $('#' + formPrefixEscaped + '\\.variations\\[' + index + '\\]\\.name');
        },

        variationInputs: function (index) {
            return $('input[name="' + formPrefixEscaped + '\\.variations[' + index + ']"]');
        },

        allvariationInputs: function () {
            return $('input[name^="' + formPrefixEscaped + '\\.variations"]');
        }
    };

    // Gets the name of the variation group at a given index. E.g. Color, Size, Shape.
    function getVariationGroupName(index) {
        var variationGroupNameInput = selectors.variationGroupNameInput(index);
        var value = variationGroupNameInput.val();

        if (value === undefined) {
            throw 'No variation group name found at index ' + index;
        }

        return value;
    }

    // Gets the value of the selected variation at a given index. Returns null if undefined.
    function getSelectedVariation(index) {
        var selectedVariationInput = selectors.selectedVariationInput(index);
        var value = selectedVariationInput.val();

        if (value === undefined) {
            return null;
        }

        return value;
    }

    // Gets the currently selected variation values.
    function getSelectedVariations() {
        var variationGroupCount = getVariationGroupCount();
        var variations = {};

        for (var i = 0; i < variationGroupCount; i++) {
            var variationGroupName = getVariationGroupName(i);
            var selectedVariation = getSelectedVariation(i);

            variations[variationGroupName] = selectedVariation;
        }

        return variations;
    }

    // Determines if the variant is an orderable product.
    function isValidVariant(variant) {
        return variant !== null && variant.PartNumber !== '' && variant.PartNumber !== null;
    }

    // Checks if an array of variations matches a variant's variations array.
    function variationsMatchVariant(variations, variant) {
        var variantVariations = Object.keys(variant.Variations);

        for (var i = 0; i < variantVariations.length; i++) {
            var variantVariationName = variantVariations[i];

            if (variations[variantVariationName] !== variant.Variations[variantVariationName]) {
                return false;
            }
        }

        return true;
    }

    // Returns the form's currently selected product variant. Null if none exists.
    function getSelectedVariant() {
        var variations = getSelectedVariations();        

        for (var i = 0; i < variants.length; i++) {
            var variant = variants[i];

            if (variationsMatchVariant(variations, variant)) {
                return variant;
            }
        }

        return null;
    }

    // Returns how many variation groups exist for the product.
    function getVariationGroupCount() {
        if (variants.length === 0) {
            return 0;
        }

        return Object.keys(variants[0].Variations).length;
    }

    // Determines whether or not the list of variations has a possible matching variant.
    // Any null values in the list is considered a wildcard.
    function hasPossibleMatchingValidVariant(variations) {
        for (var i = 0; i < variants.length; i++) {
            var variant = variants[i];
            var variantVariationNames = Object.keys(variant.Variations);
            var matches = true;

            if (!isValidVariant(variant)) {
                continue;
            }

            for (var j = 0; j < variantVariationNames.length; j++) {
                var variation = variations[variantVariationNames[j]];
                var variantVariation = variant.Variations[variantVariationNames[j]];

                if (variation === null) {
                    continue;
                }

                if (variation === variantVariation) {
                    continue;
                }

                matches = false;
            }

            if (matches) {
                return true;
            }
        }

        return false;
    }

    // Iterates through all variation inputs and enables or disables them based off of
    // whether or not a possible valid variant exists for the variation given the currently selected
    // variations.
    function checkVariationsValidity() {
        var variationGroupCount = getVariationGroupCount();
        var selectedVariations = getSelectedVariations();

        for (var i = 0; i < variationGroupCount; i++) {
            var variationInputs = selectors.variationInputs(i);

            for (var j = 0; j < variationInputs.length; j++) {
                var variationGroupName = getVariationGroupName(i);
                var variationInput = $(variationInputs[j]);
                var variation = variationInput.val();
                var variations = Object.assign({}, selectedVariations, {[variationGroupName]: variation});
                var variationHasPossibleMatchingVariant = hasPossibleMatchingValidVariant(variations);

                if (variationHasPossibleMatchingVariant) {
                    variationInput.prop('disabled', false);
                } else {
                    variationInput.prop('disabled', true);
                }
            }
        }
    }
    
    selectors.allvariationInputs().change(function (event) {
        var selectedVariant = getSelectedVariant();        
        console.log(selectedVariant);
        checkVariationsValidity();

        if (!isValidVariant(selectedVariant)) {
            variantInput.val(null);
            cartButton.prop('disabled', true);
            cartButton.data('disabled', true);
            return;
        }

        csx.products.getChildProduct(selectedVariant.Id)
            .then(function (response) {
                cartButton.prop('disabled', false);
                cartButton.data('disabled', false);
                variantInput.val(selectedVariant.Id);
                document.dispatchEvent(new CustomEvent('onVariantDataReceived', {
                    detail: {
                        data: response.Data,
                        prefix: formPrefix
                    }
                }))
            })
            .catch(function (response) {
                console.error(response);
                toastr.error('Failed to retrieve product variant information.');
            });
    });

    // Start out cart button as disabled until a valid variant is selected.
    cartButton.data('disabled', true);

    // Variation inputs start out disabled.
    checkVariationsValidity();    
};
;
/*!
  SerializeJSON jQuery plugin.
  https://github.com/marioizquierdo/jquery.serializeJSON
  version 2.9.0 (Jan, 2018)

  Copyright (c) 2012-2018 Mario Izquierdo
  Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
  and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*/
!function(e){if("function"==typeof define&&define.amd)define(["jquery"],e);else if("object"==typeof exports){var n=require("jquery");module.exports=e(n)}else e(window.jQuery||window.Zepto||window.$)}(function(e){"use strict";e.fn.serializeJSON=function(n){var r,s,t,i,a,u,l,o,p,c,d,f,y;return r=e.serializeJSON,s=this,t=r.setupOpts(n),i=s.serializeArray(),r.readCheckboxUncheckedValues(i,t,s),a={},e.each(i,function(e,n){u=n.name,l=n.value,p=r.extractTypeAndNameWithNoType(u),c=p.nameWithNoType,(d=p.type)||(d=r.attrFromInputWithName(s,u,"data-value-type")),r.validateType(u,d,t),"skip"!==d&&(f=r.splitInputNameIntoKeysArray(c),o=r.parseValue(l,u,d,t),(y=!o&&r.shouldSkipFalsy(s,u,c,d,t))||r.deepSet(a,f,o,t))}),a},e.serializeJSON={defaultOptions:{checkboxUncheckedValue:void 0,parseNumbers:!1,parseBooleans:!1,parseNulls:!1,parseAll:!1,parseWithFunction:null,skipFalsyValuesForTypes:[],skipFalsyValuesForFields:[],customTypes:{},defaultTypes:{string:function(e){return String(e)},number:function(e){return Number(e)},boolean:function(e){return-1===["false","null","undefined","","0"].indexOf(e)},null:function(e){return-1===["false","null","undefined","","0"].indexOf(e)?e:null},array:function(e){return JSON.parse(e)},object:function(e){return JSON.parse(e)},auto:function(n){return e.serializeJSON.parseValue(n,null,null,{parseNumbers:!0,parseBooleans:!0,parseNulls:!0})},skip:null},useIntKeysAsArrayIndex:!1},setupOpts:function(n){var r,s,t,i,a,u;u=e.serializeJSON,null==n&&(n={}),t=u.defaultOptions||{},s=["checkboxUncheckedValue","parseNumbers","parseBooleans","parseNulls","parseAll","parseWithFunction","skipFalsyValuesForTypes","skipFalsyValuesForFields","customTypes","defaultTypes","useIntKeysAsArrayIndex"];for(r in n)if(-1===s.indexOf(r))throw new Error("serializeJSON ERROR: invalid option '"+r+"'. Please use one of "+s.join(", "));return i=function(e){return!1!==n[e]&&""!==n[e]&&(n[e]||t[e])},a=i("parseAll"),{checkboxUncheckedValue:i("checkboxUncheckedValue"),parseNumbers:a||i("parseNumbers"),parseBooleans:a||i("parseBooleans"),parseNulls:a||i("parseNulls"),parseWithFunction:i("parseWithFunction"),skipFalsyValuesForTypes:i("skipFalsyValuesForTypes"),skipFalsyValuesForFields:i("skipFalsyValuesForFields"),typeFunctions:e.extend({},i("defaultTypes"),i("customTypes")),useIntKeysAsArrayIndex:i("useIntKeysAsArrayIndex")}},parseValue:function(n,r,s,t){var i,a;return i=e.serializeJSON,a=n,t.typeFunctions&&s&&t.typeFunctions[s]?a=t.typeFunctions[s](n):t.parseNumbers&&i.isNumeric(n)?a=Number(n):!t.parseBooleans||"true"!==n&&"false"!==n?t.parseNulls&&"null"==n?a=null:t.typeFunctions&&t.typeFunctions.string&&(a=t.typeFunctions.string(n)):a="true"===n,t.parseWithFunction&&!s&&(a=t.parseWithFunction(a,r)),a},isObject:function(e){return e===Object(e)},isUndefined:function(e){return void 0===e},isValidArrayIndex:function(e){return/^[0-9]+$/.test(String(e))},isNumeric:function(e){return e-parseFloat(e)>=0},optionKeys:function(e){if(Object.keys)return Object.keys(e);var n,r=[];for(n in e)r.push(n);return r},readCheckboxUncheckedValues:function(n,r,s){var t,i,a;null==r&&(r={}),e.serializeJSON,t="input[type=checkbox][name]:not(:checked):not([disabled])",s.find(t).add(s.filter(t)).each(function(s,t){if(i=e(t),null==(a=i.attr("data-unchecked-value"))&&(a=r.checkboxUncheckedValue),null!=a){if(t.name&&-1!==t.name.indexOf("[]["))throw new Error("serializeJSON ERROR: checkbox unchecked values are not supported on nested arrays of objects like '"+t.name+"'. See https://github.com/marioizquierdo/jquery.serializeJSON/issues/67");n.push({name:t.name,value:a})}})},extractTypeAndNameWithNoType:function(e){var n;return(n=e.match(/(.*):([^:]+)$/))?{nameWithNoType:n[1],type:n[2]}:{nameWithNoType:e,type:null}},shouldSkipFalsy:function(n,r,s,t,i){var a=e.serializeJSON.attrFromInputWithName(n,r,"data-skip-falsy");if(null!=a)return"false"!==a;var u=i.skipFalsyValuesForFields;if(u&&(-1!==u.indexOf(s)||-1!==u.indexOf(r)))return!0;var l=i.skipFalsyValuesForTypes;return null==t&&(t="string"),!(!l||-1===l.indexOf(t))},attrFromInputWithName:function(e,n,r){var s,t;return s=n.replace(/(:|\.|\[|\]|\s)/g,"\\$1"),t='[name="'+s+'"]',e.find(t).add(e.filter(t)).attr(r)},validateType:function(n,r,s){var t,i;if(i=e.serializeJSON,t=i.optionKeys(s?s.typeFunctions:i.defaultOptions.defaultTypes),r&&-1===t.indexOf(r))throw new Error("serializeJSON ERROR: Invalid type "+r+" found in input name '"+n+"', please use one of "+t.join(", "));return!0},splitInputNameIntoKeysArray:function(n){var r;return e.serializeJSON,r=n.split("["),""===(r=e.map(r,function(e){return e.replace(/\]/g,"")}))[0]&&r.shift(),r},deepSet:function(n,r,s,t){var i,a,u,l,o,p;if(null==t&&(t={}),(p=e.serializeJSON).isUndefined(n))throw new Error("ArgumentError: param 'o' expected to be an object or array, found undefined");if(!r||0===r.length)throw new Error("ArgumentError: param 'keys' expected to be an array with least one element");i=r[0],1===r.length?""===i?n.push(s):n[i]=s:(a=r[1],""===i&&(o=n[l=n.length-1],i=p.isObject(o)&&(p.isUndefined(o[a])||r.length>2)?l:l+1),""===a?!p.isUndefined(n[i])&&e.isArray(n[i])||(n[i]=[]):t.useIntKeysAsArrayIndex&&p.isValidArrayIndex(a)?!p.isUndefined(n[i])&&e.isArray(n[i])||(n[i]=[]):!p.isUndefined(n[i])&&p.isObject(n[i])||(n[i]={}),u=r.slice(1),p.deepSet(n[i],u,s,t))}}});;
/*
	jQuery Zoom v1.7.1 - 2013-03-12
	(c) 2013 Jack Moore - jacklmoore.com/zoom
	license: http://www.opensource.org/licenses/mit-license.php
*/
(function(o){var t={url:!1,callback:!1,target:!1,duration:120,on:"mouseover"};o.zoom=function(t,n,e){var i,u,a,c,r,m=o(t).css("position");return o(t).css({position:/(absolute|fixed)/.test()?m:"relative",overflow:"hidden"}),o(e).addClass("zoomImg").css({position:"absolute",top:0,left:0,opacity:0,width:e.width,height:e.height,border:"none",maxWidth:"none"}).appendTo(t),{init:function(){i=o(t).outerWidth(),u=o(t).outerHeight(),a=(e.width-i)/o(n).outerWidth(),c=(e.height-u)/o(n).outerHeight(),r=o(n).offset()},move:function(o){var t=o.pageX-r.left,n=o.pageY-r.top;n=Math.max(Math.min(n,u),0),t=Math.max(Math.min(t,i),0),e.style.left=t*-a+"px",e.style.top=n*-c+"px"}}},o.fn.zoom=function(n){return this.each(function(){var e=o.extend({},t,n||{}),i=e.target||this,u=this,a=new Image,c=o(a),r="mousemove",m=!1;(e.url||(e.url=o(u).find("img").attr("src"),e.url))&&(a.onload=function(){function t(t){s.init(),s.move(t),c.stop().fadeTo(o.support.opacity?e.duration:0,1)}function n(){c.stop().fadeTo(e.duration,0)}var s=o.zoom(i,u,a);"grab"===e.on?o(u).on("mousedown",function(e){o(document).one("mouseup",function(){n(),o(document).off(r,s.move)}),t(e),o(document).on(r,s.move),e.preventDefault()}):"click"===e.on?o(u).on("click",function(e){return m?void 0:(m=!0,t(e),o(document).on(r,s.move),o(document).one("click",function(){n(),m=!1,o(document).off(r,s.move)}),!1)}):"toggle"===e.on?o(u).on("click",function(o){m?n():t(o),m=!m}):(s.init(),o(u).on("mouseenter",t).on("mouseleave",n).on(r,s.move)),o.isFunction(e.callback)&&e.callback.call(a)},a.src=e.url)})},o.fn.zoom.defaults=t})(window.jQuery);;
var mouseX, mouseY;
var isIE = document.all;
document.onmousemove = getMousePos;
function SetSXNotes() {
    document.getElementById('sxText2').value = document.getElementById('SXNotes').value
}
function getMousePos(e){
if (!e) e = window.event;
if (e)
        {try{
  mouseX = isIE ? (e.clientX + document.body.scrollLeft) : e.pageX;
  mouseY = isIE ? (e.clientY + document.body.scrollTop) : e.pageY;
        }catch(err){}}
}
function doClear(theText) 
{
    if (theText.value == theText.defaultValue) {
        theText.value = '';
    }
 }
function numbersonly(myfield, e, w, dec)
{
    var key;
    var keychar;
    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    // control keys
    if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
    {
        return true;
    }
    // numbers
    else if ((("0123456789").indexOf(keychar) > -1))
    {
        return true;
    }
    // decimal point jump
    else if (dec && (keychar == "."))
    {
        myfield.form.elements[dec].focus();
        return false;
    }
    else
        return false;
}
function submitform()
{
    try {
        document.form1.Compareme.value="compare";
        document.form1.submit();
    }
    catch (err) {
        var txt = 'There was an error in function SubmitForm.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}
function submitdateform()
{
    document.datefilter.submit();
}
function PrintPdf()
{
   window.open('SampleCatalog.aspx');
   return false;
}
function PrintPdfDetail()
{
   var id = document.getElementById().value;
   window.open('SampleCatalog.aspx?typeAndpartno=detail,' + id);
   return false;
}
function submitpageform(Request)
{
    try {
        document.form1.Compareme.value="pagequery";
        document.form1.CompRequest.value=Request;
        document.form1.submit();
    }
    catch (err) {
        var txt = 'There was an error in function SubmitPageForm.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}
function LoadGallery(pictureName,imageFile,ActualWidth,ActualHeight)
{
  var picture = document.getElementById(pictureName);
  picture.src = imageFile;
  var picture = document.getElementById('PopupImage1');
  picture.href = pictureName + '?js_imagepath=' + imageFile + '&js_width=' + ActualWidth + '&js_height=' + ActualHeight;
  picture = document.getElementsByClassName('zoomImg')[0];
  if(picture){
     picture.src = imageFile;
     picture.href = pictureName + '?js_imagepath=' + imageFile + '&js_width=' + ActualWidth + '&js_height=' + ActualHeight;
  }
}
function DisplayImage()
  {
  var ActualWidth;
  var ActualHeight;
  var ImagePath;
  var picture = document.getElementById('PopupImage1');
  var parameterString = picture.href.replace(/.*\?(.*)/, "$1");
  var parameterTokens = parameterString.split("&");
  var parameterList = new Array();
  for (i = 0; i < parameterTokens.length; i++)
      {
      var parameterName = parameterTokens[i].replace(/(.*)=.*/, "$1");
      var parameterValue = parameterTokens[i].replace(/.*=(.*)/, "$1");
      parameterList[parameterName] = parameterValue;
      }
  ImagePath = parameterList["js_imagepath"]; 
  ActualWidth = parameterList["js_width"]; 
  ActualHeight = parameterList["js_height"]; 
  windowparams='menuBar=0,resizable=1,width=' + ActualWidth + ',height=' + ActualHeight;
  window.open(ImagePath,'popup',windowparams)
  }
function SubmitSpecForm() {
    document.formSpec.submit();
}
function TLReQuerySpecs(Reset, SpecTextCount, FormID) {
    try {
        var i, j, k, txt, form;
        var bGo = true;
        ToggleDisplay('busybox', 'on', '');
        form = document.getElementById(FormID);
        txt = null;
        //if all SpecSearchText inputs blank then reset; o/w run spec search
        for (i = 1; i <= SpecTextCount; i++) {
            for (j = 0; j < form.elements.length; j++) {
                if (form.elements[j].name == 'SpecSearchText' + i) {
                    txt = form.elements[j];
                    break;
                }
            }
            if (txt != null && txt.value != '') {
                bGo = false;
                break;
            }
        }
        if (Reset || bGo) {
            $('#' + form.id + ' :input').val('');
            if (!event.currentTarget.id === "TiledLayoutSort") form.RunSpecSearch.value = 'reset'; //BCM 4-13-17 Added logic to prevent reset if this comes from the sort dropdown
            form.TopSpecSearch.value = '';
     if (form.Compareme) {
            form.Compareme.value = '';
     }
        }
        else {
            for (i = 1; i < 12; i++) {
                try {
                    form('Compare' + i).value = '';
                } catch (err) {}; //on error resume next
            }
            form.RunSpecSearch.value = 'yes';
            form.TopSpecSearch.value = (FormID == 1) ? 'TL' : 'MD';
        }
        form.submit();
    }
    catch (err) {
        var txt = 'There was an error in function TLReQuerySpecs.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
} //TLReQuerySpecs
function CorrectQuantity(dQuantity) {
    try {
       var dTotalQuantity = 1;  
       if(String(dQuantity) == 'true')
          {
          dTotalQuantity = 1;
          }
       else if(dQuantity > 0)
          {
          dTotalQuantity = dQuantity;
          }
       else if(String(dQuantity) == 'false')
          {
          dTotalQuantity = '';
          }
       else 
          {
          }
        } catch (e) {};
    return String(dTotalQuantity);
} 
function TLSortChanged(CompareCount) {
    try {
        document.form1.Compareme.value = 'nocompare';
        document.form1.TLSort.value = 'true';
        for (var i = 0; i <= CompareCount; i++) {
            document.form1('Compare' + i).value = '';
        }
    } catch (e) {};
    document.form1.submit();
}
function TLCompare(SpecTextCount) {
    if ($( '.tilecompare:checked' ).length > 1) {
      var action = $('#compare').attr('action');
    try {
        document.form1.Compareme.value = 'compare';
        for (var i = 0; i < $( '.tilecompare:checked' ).length; i++) {
            action = action + '&Compare' + i + '=' + $( 'input:checked' )[i].value;
        }
        $('#compare').attr('action', action)
    }
    catch (err) {
        var txt = 'There was an error in function TLCompare.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    };
    document.form1.submit();
}
else {alert('Select more checkboxes to compare'); return false;}
}
function submitformShopping()
{
    document.form1.Shopping.value= 'Shopping';
    document.form1.submit();
}
function isIE()
{
return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
 }
function ToggleDisplay(DivName, State, KillDivIDs) {
    if (KillDivIDs != '') {
        var aryIDs = KillDivIDs.split('|');
        for (var i = 0; i < aryIDs.length; i++) {
            //alert('TiledDetailDiv' + aryIDs[i]);
            the_style = getStyleObject('TiledDetailDiv' + aryIDs[i]);
            the_style.visibility = 'hidden';
        }
    }
    var the_style = getStyleObject(DivName);
    var tempX = 0;
    var tempY = 0;
    var offset = -50;
    var offsetX = 150;
    tempX = mouseX;
    tempY = mouseY;
    tempY += offset;
    // step 4
    if (tempX < 0){tempX = 0;}
    if (tempY < 0){tempY = 0;}
    if (State == 'on') {
        the_style.zindex = 10;
        the_style.visibility = 'visible';
        //the_style.position = 'relative';
        if (tempX > (document.body.clientWidth / 2)){tempX -= (the_style.width).replace('px','');}
        the_style.pixelTop = tempY;
        the_style.pixelLeft = tempX;
        the_style.left = tempX + 'px';
        the_style.top = tempY + 'px';
        //alert(the_style.left);
        //}
    }
    else {
        the_style.visibility = 'hidden';
    }
}
function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its
    if(document.getElementById && document.getElementById(objectId)) {
        // W3C DOM
        return document.getElementById(objectId).style;
    }
    else if (document.all && document.all(objectId)) {
        // MSIE 4 DOM
        return document.all(objectId).style;
    }
    else if (document.layers && document.layers[objectId]) {
        // NN 4 DOM.. note: this won't find nested layers
        return document.layers[objectId];
    }
    else {
        return false;
    }
} // getStyleObject
function OpenWindowWithHTML(myHTML)
{
    var sFeatures = "height=400,width=600,left=100,top=100,resizable=yes";
    var win = window.open("","popup_window", sFeatures);
    win.document.write(myHTML);
    win.document.close();
    win.focus();
}
function submitconfig(myScrollPos)
{
var intY = document.body.scrollTop;
document.cookie = intY;
document.cookie = "yPos=!~" + myScrollPos + "~!";
document.configform.precon.disabled=true;
document.configform.submit();
}
function sortSelect(selElem) {
//var tmpAry = new Array();
//for (var i=0;i<selElem.options.length;i++) {
//        tmpAry[i] = new Array();
//        tmpAry[i][0] = selElem.options[i].text;
//        tmpAry[i][1] = selElem.options[i].value;
//}
//tmpAry.sort();
//while (selElem.options.length > 0) {
//    selElem.options[0] = null;
//}
// for (var i=0;i<tmpAry.length;i++) {
//        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
//        selElem.options[i] = op;
// }
// return;
}
function CheckBoxValue(Quantity) {
  if (Quantity > 0)
      {
      return true;
      }
  else 
      {
      return false;
      }
  }
function setCaretPos (obj, pos) 
  {
  if (obj.selectionStart) {
  obj.focus();
  obj.setSelectionRange(obj.value.length, obj.value.length);
  } 
else if (document.selection) 
  {
  var range = obj.createTextRange();
  range.move('character', obj.value.length);
  range.select();
  }
}
function Toggle (node) 
  { 
  // Unfold the branch if it isn't visible
 var node2 = node.nextSibling
// var node2 = node
  if (node2.nextSibling.style.display == 'none')
      { 
      // Change the image (if there is an image)
      if (node.children.length > 0) 
          { 
          if (node.children.item(0).tagName == "IMG")
              { 
              node.children.item(0).src = "minus.gif";
              } 
          } 
      node2.nextSibling.style.display = '';
      }
      // Collapse the branch if it IS visible
  else
      { 
      // Change the image (if there is an image)
      if (node2.children.length > 0) 
          { 
          if (node.children.item(0).tagName == "IMG") 
              {
              node.children.item(0).src = "plus.gif"; 
              }
          } 
      node2.nextSibling.style.display = 'none';
      } 
  } 
checked = false;
function SelectAll() {
if (checked == false){checked = true}else{checked = false}
  $(':checkbox').each(function () {
    if (this.name.substring(0, 3) === "del" ) {
      this.checked = checked;
}
  })
}
function UpdateAndSubmit(theValue)
{
    if (theValue != 0) {
    document.form1.updatesubmit.value = theValue;
    document.form1.submit();
    }
}
function SelectAllAllowBackorder()
{
var totallinecount = ++document.form1.totallines.value;
if (checked == false){checked = true}else{checked = false}
for (var x=1; x<totallinecount; x++)
{
  document.getElementById('allowBackorder' + x).checked = checked;  
}
}
function OpenWindowold()
{
    var printContent = document.getElementById("mainTableBgrnd");
    var sFeatures = "height=400,width=600,status=1,toolBar=0,menuBar=1,location=1, resizable=1, scrollBars =1";
    win = window.open("","Print", sFeatures);
    win.document.write(printContent.innerHTML);
    win.document.close();
    win.focus();
    win.print();
//   win.close();
}
function CopyShippingInfo(sender) {
if (document.forms('ShowShip').elements('selectStateUS')(0) && document.forms('ShowShip').elements('selectStateUS')(1)) {
document.forms('ShowShip').elements('selectStateUS')(1).value = document.forms('ShowShip').elements('selectStateUS')(0); 
document.forms('ShowShip').elements('selectStateUS')(1).options[document.forms('ShowShip').elements('selectStateUS')(0).selectedIndex].selected = true; }
if (document.getElementById('Company') && document.getElementById('Company_billing')) {
document.getElementById('Company_billing').value = document.getElementById('Company').value; }
if (document.getElementById('ATTN') && document.getElementById('Attn_billing')) {
document.getElementById('Attn_billing').value = document.getElementById('ATTN').value; }
if (document.getElementById('Add1') && document.getElementById('Add1_billing')) {
document.getElementById('Add1_billing').value = document.getElementById('Add1').value; }
if (document.getElementById('Add2') && document.getElementById('Add2_billing')) {
document.getElementById('Add2_billing').value = document.getElementById('Add2').value; }
if (document.getElementById('City') && document.getElementById('City_billing')) {
document.getElementById('City_billing').value = document.getElementById('City').value; }
if (document.getElementById('State') && document.getElementById('State_billing')) {
document.getElementById('State_billing').value = document.getElementById('State').value; }
if (document.getElementById('Zip') && document.getElementById('Zip_billing')) {
document.getElementById('Zip_billing').value = document.getElementById('Zip').value; }
}
function verify() {
var themessage = "You are required to complete the following fields: ";
if (document.ShowShip.Company.value=="") {
themessage = themessage + " - Company";
}
if (document.ShowShip.add1.value=="") {
themessage = themessage + " -  Address line 1";
}
if (document.ShowShip.city.value=="") {
themessage = themessage + " -  City";
}
if (document.ShowShip.state.value=="") {
themessage = themessage + " -  State/Province";
}
if (document.ShowShip.zip.value=="") {
themessage = themessage + " -  Postal Code";
}
if (themessage == "You are required to complete the following fields: ") {
document.form.submit();
}
else {
alert(themessage);
return false;
   }
}
function UpdateShipping(iShip) 
{
    try {
        document.ShowShip.pos.value="1";
        document.ShowShip.SelectedShipto.value=iShip;
        document.ShowShip.submit();
    }
    catch (err) {
        var txt = 'There was an error in function SubmitForm.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}
function UpdateUPSValidateShipping(iShip) 
{
    try {
        document.ShowShip.pos.value="1";
        document.ShowShip.SelectedShipto.value=iShip;
        document.ShowShip.addressvalidate.value='on';
        document.ShowShip.submit();
    }
    catch (err) {
        var txt = 'There was an error in function UpdateUPSValidateShipping.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}
function EnableUPSAddressValidate() 
{
    try {
        document.ShowShip.pos.value="1";
        document.ShowShip.SelectedShipto.value='new';
        document.ShowShip.addressvalidate.value='on';
    }
    catch (err) {
        var txt = 'There was an error in function EnableUPSAddressValidate.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}
    function HideTD(dropdown)
    {
        var myindex  = dropdown.selectedIndex
        var SelValue = dropdown.options[myindex].value
     if(SelValue=="Other"){
showElement('hiddenTD');
        }
        else
        {
hideElement('hiddenTD');
        }
//        var baseURL  = '!!!';
//        top.location.href = baseURL;
        
        return true;
    }
        function hideElement (elementId) {
        var element;
        if (document.all)
        element = document.all[elementId];
        else if (document.getElementById)
        element = document.getElementById(elementId);
        if (element && element.style)
        element.style.display = 'none';
        }
        function showElement (elementId) {
        var element;
        if (document.all)
        element = document.all[elementId];
        else if (document.getElementById)
        element = document.getElementById(elementId);
        if (element && element.style)
        element.style.display = '';
        }       
function emailCheck (emailStr) {
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
alert("Email address seems incorrect (check @ and .'s)")
return false
}
var user=matchArray[1]
var domain=matchArray[2]
if (user.match(userPat)==null) {
alert("The username doesn't seem to be valid.")
    return false
}
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
      for (var i=1;i<=4;i++) {
        if (IPArray[i]>255) {
            alert("Destination IP address is invalid!")
        return false
        }
    }
    return true
}
var domainArray=domain.match(domainPat)
if (domainArray==null) {
alert("The domain name doesn't seem to be valid.")
    return false
}
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   alert("The address must end in a three-letter domain, or two letter country.")
   return false
}
if (len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}
return true;
}
function PopupPicker(ctl, e) {
var PopupWindow = null;
//var posX = event.clientX;
PopupWindow = window.open('PopupCalendar.aspx?Ctl=' + ctl, 
'PopupWindow', "width=266, height=215, resizable=yes");
PopupWindow.moveTo(e.clientX, e.clientY);
PopupWindow.focus();
return false;
}
function enableCOD (codCheck) 
{
if (codCheck == true)
    {
    document.getElementById('selectconfirmation').style.display = '';
    }
else {
    document.getElementById('selectconfirmation').style.display = 'none';
    }
}
function ValidateNewAddress () 
        {
        if (document.ShowShip.Add1.value != '' &&
 document.ShowShip.City.value != '' &&
 document.ShowShip.State.value != '' &&
 document.ShowShip.Zip.value != '' || document.ShowShip.CustShipAccountNum.value != '')
            {
            document.ShowShip.action='catalogwebcheckout.aspx?pos=1&SelectedShipto=new&ShippingCalculate=yes';
            document.ShowShip.submit();
            }
        else if (document.ShowShip.SelectedShipto.value != 'new')
            {
            document.ShowShip.action = 'catalogwebcheckout.aspx?pos=1&ShippingCalculate=yes';
            document.ShowShip.submit();
            }
        }
function InputNewKey (iShip) 
        {
        document.ShowShip.shipto[iShip].checked=true;
        document.getElementById('IMAGE1').style.display='none';
        }
function updatereorderhide()
{
    try {
        document.form3.reorderhide.value="updated";
        document.form3.submit();  }
    catch (err) {
        var txt = 'There was an error in function UpdateReorderHide.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}
function show_confirm(SetWareHouse)
{
    var r=confirm("Do you want to change your warehouse?");
    if (r==true)
        {
//        alert("You pressed OK!");
        document.chgwhse.action = 'account.aspx?page=changewarehouse&selectedwarehouse=' + SetWareHouse;
        document.chgwhse.submit();
        }
    else
        {
        }
}
function save_alt(altpn, altkw)
{
    document.frmaddalts.action = 'account.aspx?page=addalts&altpartnumber=' + altpn + '&altkeyword=' + altkw;
    document.frmaddalts.submit();
}
function PrintDiv(objectId)
{
    var printContent1 = document.getElementById('OrderNum_' + objectId + '_1');
    var printContent2 = document.getElementById('OrderNum_' + objectId + '_2');
    var printContent3 = document.getElementById('OrderNum_' + objectId + '_3');
//    var printContent = document.getElementById('OrderNum_' + objectId + '_11');
    var sFeatures = "height=400,width=600,status=1,toolBar=0,menuBar=1,location=1, resizable=1, scrollBars =1";
    win = window.open("","Print", sFeatures);
    win.document.write('<table border=1><tr>' + printContent1.innerHTML + '</tr><tr><br>' + printContent2.innerHTML + '</tr><tr><br>' +  printContent3.innerHTML + '</tr></table>');
    win.document.close();
    win.focus();
    win.print();
   win.close();
}
function CheckAllOnForm(boxchecked)
{
var inputboxes=document.form1.getElementsByTagName("input")
for (iCounter=0;iCounter<inputboxes.length;iCounter++)
    {
    if (inputboxes[iCounter].getAttribute('type') == 'checkbox')
       {
       if (inputboxes[iCounter].disabled == false) {
                   inputboxes[iCounter].checked = boxchecked
               }
       }
    }
}
 function changeAction() {
    document.form3.action = 'account.aspx?page=shoppinglist&action=update';
    document.form3.submit();
}
//START JOB WORKSHEET JAVASCRIPT ***********************************************
 function changeWorksheetAction(changeAction,WorkSheetName) {
    document.form3.action = 'account.aspx?page=worksheets&worksheetaction=' + changeAction + '&worksheetname=' + WorkSheetName;
    document.form3.submit();
}
 function updateWorkSheetItems() {
    document.form3.action = 'account.aspx?page=worksheets&worksheetaction=updateitems';
    document.form3.submit();
}
 function OtherToThis(OtherWorkSheetName,ThisWorkSheetName) {
    document.form3.action = 'account.aspx?page=worksheets&worksheetaction=addotherjobworksheettothisjobworksheet&otherworksheetname=' + OtherWorkSheetName + '&thisworksheetname=' + ThisWorkSheetName;
    document.form3.submit();
}
 function ItemsToOther(WorkSheetName) {
    document.form3.action = 'account.aspx?page=worksheets&worksheetaction=sendselecteditemstoother&worksheetname=' + WorkSheetName;
    document.form3.submit();
}
function TurnOn(Object)
{
    Object.previousSibling.style.display='';
    Object.style.display='none';
    var a = Object.previousSibling.children[0];
    a.setAttribute('size', a.options.length);
}
function TurnOff(Object)
{
    Object.parentNode.nextSibling.style.display='';
    Object.parentNode.style.display='none';
}
// function InsertItemIntoWorkSheet(WorkSheetName,ItemNumber,ItemQuantity) {
//    document.form3.action = 'account.aspx?page=worksheets&worksheetaction=' + changeAction + '&worksheetname=' + WorkSheetName;
//    document.form3.submit();
//}
 function ChangeJobWorkSheet(changeAction,WorkSheetName,WorkSheetComments) {
    document.form3.action = 'account.aspx?page=worksheets&worksheetaction=' + changeAction + '&worksheetname='+ WorkSheetName + '&worksheetcomments=' + WorkSheetComments;
    document.form3.submit();
}
function AddItemNumberToJobWorkSheet(WorkSheetTo)
{
    document.form3.action = 'account.aspx?Page=worksheets&worksheetaction=additemnumbertojobworksheet&ItemList=' + WorkSheetTo;
    document.form3.submit();
}
function CheckAll(CheckBoxList,status)
{
var iCounter
CheckBoxList.checked=status
for (iCounter=0;iCounter<CheckBoxList.length;iCounter++)
    {
    CheckBoxList[iCounter].checked = status 
    }
}
function AddToJobWorkSheet(WorkSheetTo,WebID,Qty)
{
    document.form1.page.value= 'worksheets';
    document.form1.worksheetaction.value= 'AddToJobWorkSheet';
    document.form1.addworksheetname.value= WorkSheetTo;
    document.form1.AddWorkSheetWebID.value= WebID;
    if (Qty>0)
      {
    document.form1.AddWorkSheetQty.value= Qty;
      }
    else
      {
      document.form1.AddWorkSheetQty.value= 1;
      }
    document.form1.action = 'account.aspx';
    document.form1.submit();
}
function submittojobworksheet(WorkSheetName)
{
    document.form1.action = 'account.aspx?page=worksheets&worksheetaction=addfromdetailgrid&worksheetname=' + WorkSheetName;
    document.form1.submit();
}
 function EMailQuestionsAndComments(QuestionsAndComments,WorkSheetName) {
    document.form3.action = 'account.aspx?page=worksheets&worksheetaction=emailquestionsandcomments&questionsandcomments=' + QuestionsAndComments + '&worksheetname=' + WorkSheetName;
    document.form3.submit();
}
//END JOB WORKSHEET JAVASCRIPT ***********************************************
//START GLOBAL FILTER JAVASCRIPT ***********************************************
function submitGlobalFilter(sQueryString)
{
    try {
//        document.formGlobalFilter.action='AdvancedWebPage.aspx' + sQueryString;
if(sQueryString != '')
        {
        document.formGlobalFilter.Compareme.value="pagequery";
        document.formGlobalFilter.CompRequest.value=sQueryString;
        }
        document.formGlobalFilter.submit();

    }
    catch (err) {
        var txt = 'There was an error in function SubmitGlobalFilter.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}
function submitGlobalNavigationFilter(sQueryString, GFName, GFValue, iCounter)
{
try {
//        document.formGlobalFilter.action='AdvancedWebPage.aspx' + sQueryString;
if(sQueryString != '')
{
document.formGlobalFilter.Compareme.value="pagequery";
document.formGlobalFilter.CompRequest.value=sQueryString;
}
filtername = document.getElementById('GlobalFilterName' + iCounter).value=GFName;
filter = document.getElementById('GlobalFilter' + iCounter).value=GFValue;
document.formGlobalFilter.submit();
}
catch (err) {
var txt = 'There was an error in function SubmitGlobalFilter.\n\n';
txt += 'Error description: ' + err.description;
if (true) alert(txt);
}
}
//END GLOBAL FILTER JAVASCRIPT ***********************************************
//START PRICING DOWNLOAD JAVASCRIPT ***********************************************
 function submitPriceDownload(incrementAmount) {
    document.formpricedownload.action = 'account.aspx?page=pricingdownload&hdDownloadFile=True';
    document.getElementById('progressContainer').style.visibility = 'visible';
    setInterval(function(){updateProgressBar(incrementAmount)}, 1000);
    document.formpricedownload.submit();
}
 function updateProgressBar(incrementAmount) {
    var progressBarDiv = document.getElementById('progressBar');
    var currentBarWidth = (parseFloat(progressBarDiv.style.width));
    var divPercent;
//    alert(incrementAmount);
    if (currentBarWidth >= 100){
        divPercent = 70;}
    else{
        divPercent = (parseFloat(progressBarDiv.style.width) + incrementAmount);}
    progressBarDiv.style.width = divPercent + '%';
}
//END PRICING DOWNLOAD JAVASCRIPT ***********************************************
//START MAILING LIST JAVASCRIPT ***********************************************
function DeleteList(ListName)
    {
    var r=confirm('Do you want to delete the mailing list ' + ListName + '?');
    if (r==true)
        {
        document.editMailingLists.action = 'account.aspx?page=editMailingLists&Delete=yes&ListName=' + ListName;
        document.editMailingLists.submit();
        }
    else
        {
        }
    }
function AddList(ListName)
    {
        document.editMailingLists.action = 'account.aspx?page=editMailingLists&Add=yes&ListName=' + ListName;
        document.editMailingLists.submit();
    }
function RemoveListSubscription(ListName, UserID)
    {
    var r=confirm('Do you want to remove the mailing list subscription ' + ListName + '?');
    if (r==true)
        {
        document.editmailinglistsubscriptions.action = 'account.aspx?page=editmailinglistsubscriptions&RemoveListSubscription=yes&ListName=' + ListName + '&UserID=' + UserID;
        document.editmailinglistsubscriptions.submit();
        }
    else
        {
        }
    }
function AssignListSubscription(ListID, UserID)
    {
        document.editmailinglistsubscriptions.action = 'account.aspx?page=editmailinglistsubscriptions&AssignListSubscription=yes&ListID=' + ListID + '&UserID=' + UserID;
        document.editmailinglistsubscriptions.submit();
    }
function ChangeReportCombo()
    {
        document.mailinglistreports.action = 'account.aspx?page=mailinglistreports';
        document.mailinglistreports.submit();
    }
function UpdateMailingList()
    {
        document.editmailinglistsubscriptions.action = 'account.aspx?page=editMailingListSubscriptions';
        document.editmailinglistsubscriptions.submit();
    }
function UpdateApprovalStatus(ListId,ApprovalValue,UserID)
    {
        document.mailinglistreports.action = 'account.aspx?page=mailinglistreports&updateapprovalstatus=yes&listid=' + ListId + '&approvalvalue=' + ApprovalValue + '&userid=' + UserID;
        document.mailinglistreports.submit();
    }
//END MAILING LIST JAVASCRIPT ***********************************************
function display(id, caller) {
    var obj = document.getElementById(id);
    if (obj.style.display == 'none') {
        obj.style.display = 'block'
    }
    else {
        obj.style.display = 'none'
    }
    if (caller == 'Approve') {
        document.getElementById('approvalSubmit').Value = 'Send Approval'
        document.getElementById('approvalSubmit').defaultValue = 'Send Approval'
    }
    if (caller == 'Deny') {
        document.getElementById('approvalSubmit').Value = 'Send Denial'
        document.getElementById('approvalSubmit').defaultValue = 'Send Denial'
    }
    return false
}
function SelectAllCompareCheckboxes()
{
var totallinecount = ++document.form1.totallines.value;
if (checked == false){checked = true}else{checked = false}
for (var x=0; x<totallinecount; x++)
{
  document.getElementById('compare' + x).checked = checked;  
}
}
function CheckAllCompareCheckboxes()
{
var totallinecount = ++document.form1.totallines.value;
for (var x=0; x<totallinecount; x++)
{
  document.getElementById('compare' + x).checked = true;  
}
}
function UncheckAllCompareCheckboxes() {
    var totallinecount = document.getElementById("totallines");
    if (totallinecount) {
        totallinecount = totallinecount.value
        for (var x = 0; x < totallinecount; x++) {
            if (document.getElementById('compare' + x)) {
                document.getElementById('compare' + x).checked = false;
            }
        }
    }
}
function DeleteSXCustomerNumber(CustomerNumber,formtouse)
{
var r=confirm('Do you want to delete the customer number ' + CustomerNumber + '?');
if (r==true)
{
formtouse.action = 'account.aspx?page=sxsettings&delete=yes&customernumber=' + CustomerNumber;
formtouse.submit();
}
Else
{
}
}
function DeleteSXCustomerLogin(UserID,formtouse)
{
var r=confirm('Do you want to delete the login ' + UserID + '?');
if (r==true)
{
formtouse.action = 'account.aspx?page=sxsettings&delete=yes&deleteuserid=' + UserID;
formtouse.submit();
}
Else
{
}
}
function UpdateCustomer(formtouse)
{
formtouse.pageaction.value = 'update';
formtouse.submit();
}
function AddValidShipTo(formtouse)
{
formtouse.pageaction.value = 'addvalidshipto';
formtouse.submit();
}
function AddValidBillTo(formtouse)
{
formtouse.pageaction.value = 'addvalidbillto';
formtouse.submit();
}
function ClearSXShipTOs(formtouse)
{
formtouse.pageaction.value = 'deleteallsxshiptos';
formtouse.submit();
}
function DeleteSXShipTo(formtouse)
{
formtouse.pageaction.value = 'deleteselectedsxshipto';
formtouse.submit();
}
function ShipTosByRep(formtouse)
{
formtouse.pageaction.value = 'shiptosbyrep';
formtouse.submit();
}
function comboInit(thelist)
{
theinput = document.getElementById(theinput);
var idx = thelist.selectedIndex;
var content = thelist.options[idx].innerHTML;
if(theinput.value == "")
theinput.value = content;
}
function combo(thelist, theinput)
{
theinput = document.getElementById(theinput);
var idx = thelist.selectedIndex;
var content = thelist.options[idx].innerHTML;
theinput.value = content;
}
function changesxcode(thelist, theinput)
{
theinput = document.getElementById(theinput);
var sxlist = document.getElementById('selCustCodes');
var idx = thelist.selectedIndex;
var content = sxlist.options[idx].innerHTML;
theinput.value = content;
}
function UpdateShippingInstructionsFromPreload(iPreload, preloadText)
{
notesTextArea = document.getElementById('eShipNotes');
var currentNotes = notesTextArea.value;
if (document.getElementById('shippinginstructions' + iPreload).checked != checked)
{
document.getElementById('eShipNotes').value = currentNotes + ' ' + preloadText
}
else
{
var m = currentNotes.indexOf(' ' + preloadText);
var n = currentNotes.indexOf(preloadText);
if (m >= 0)
{
document.getElementById('eShipNotes').value = currentNotes.replace(' ' + preloadText,'');
}
else if (n >= 0)
{
document.getElementById('eShipNotes').value = currentNotes.replace(preloadText,'');
}
}
}
function ResetCustomerSearch()
{
document.form1.page.value = 'login';
document.form1.reset.value = 'reset';
document.form1.txtFindCustomer.value = '';
document.form1.submit();
}
function DisplayPage(Page)
{
document.form1.page.value = 'login';
document.form1.reset.value = 'reset';
document.form1.pagenumber.value = Page;
document.form1.submit();
}
function ChangeCompany(Proc,formtouse){
formtouse.companychange.value = 'y';
formtouse.submit();
}
function AddToNewCompany(formtouse)
{
if (document.getElementById("CText").style.display == 'none') {
document.getElementById("CText").style.display = '';
document.getElementById("CSelect").style.display = 'none';
formtouse.newCompany.value = 'yes';
formtouse.btnNewCompany.value = 'Select Existing Company';
}
else {
document.getElementById("CText").style.display = 'none';
document.getElementById("CSelect").style.display = '';
formtouse.newCompany.value = '';
formtouse.btnNewCompany.value = 'Create New Company';
}
}
$(document).ready(function () {
    // Optimalisation: Store the references outside the event handler
    var $window = $(window);
    var $cBodyTable = $("table.cBodyTable");
    var $TiledLayoutContainer = $("div.TiledLayoutContainer");
    var $specsContainerDiv = $("div.specsContainerDiv");
    var $SideBar = $("td.SideBar");

    function resizeDivs() {
        var width
        if ($window.width() < "926") {
            width = $window.width() - $SideBar.width()
        } else {
            width = "926" - $SideBar.width()
        }
        $TiledLayoutContainer.width(width)
        $specsContainerDiv.width(width)
    }
    // Execute on load
    resizeDivs();
    // Bind event listener
    $(window).resize(resizeDivs);
});
;
function addDollarSign() {
    var rows = document.getElementsByTagName('table')[0].rows
    for (var i = 0; i < rows.length; i++) {
        var revenue = rows[i].cells[1].innerHTML;
        if (revenue) {
            revenue = '$' + revenue;
        }
    }
}
function InitNumbers()
 {
	 console.log('InitNumbers');
     $('#qty0').prop(true);
    $('#plus-btn').click(function(){
        $('#qty0').val(parseInt($('#qty0').val()) + 1 );
            });
        $('#minus-btn').click(function(){
        $('#qty0').val(parseInt($('#qty0').val()) - 1 );
        if ($('#qty0').val() == 0) {
            $('#qty0').val(1);
        }


            });
			console.log('InitNumbersEmd');
 }
function enableShipMeth() {
    var state = document.getElementById('State');
    if (state == 'WI') {
        document.getElementById('SHIPMETH').options[3].disabled = false;
    }
}

function showCartAlert() {
  var x = document.getElementById("cartalert");
  x.className = "show";
  setTimeout(function(){ x.className = x.className.replace("show", ""); }, 6000);
}


function SetPricing() {
    var selection = document.getElementById('UOM0');
    var id = selection.options[selection.selectedIndex].value;
    console.log(id);
    var pricing = document.getElementById('pricing-unit-' + id).value;
    console.log(pricing);
    document.getElementById('pricetext0').innerHTML = '$' + Number(pricing).toFixed(2);
    document.getElementById("price").value = Number(pricing).toFixed(2);
    //document.getElementById("btn-addtocart-main").setAttribute('data-uom', id);
}
function addToCart(line) {
  var cartBtns = document.getElementsByClassName("AddToCart");
  var elem = 'order' + line;
  var elem2 = 'QTY' + line;
  var oForm = document.forms["form1"];
  var formElem = oForm.elements[elem];
  var formElem2 = oForm.elements[elem2];

    
    if (formElem2 !== null) {
        formElem2.value = CorrectQuantity(formElem2.value);
    }

  for (var i = 0; i < cartBtns.length; i++) {
    cartBtns[i].disabled = "False";
  }
  document.form1.action = "/catalogwebcart.aspx"
  document.form1.submit();
}
function showMinQtyMsg(iLine, incrementalQty, event) {
    var id = "minqtymsg" + (iLine + 1);
    var x = document.getElementById(id);
    var currentInput = event.target.value;
    var keyPressed = event.which || event.keyCode;
    keyPressed = String.fromCharCode(keyPressed);
    currentInput = currentInput + keyPressed;
    if (currentInput % incrementalQty == 0) {
        x.style.display = 'none';
    } else {
        x.removeAttribute("style");
    }
}
/*jslint browser: true*/
/*global $, jQuery*/
//Item Finish Scripts
function displayFinishPrice() {
    "use strict";
    var x, y, index;
    x = document.getElementById("finishtitle");
    y = document.getElementById(x.value);
    for (index = 1; index < y.length; index += 1) {
        if (y[index].selected) {
            document.getElementById("finish" + y[index].value).hidden = false;
        } else {
            document.getElementById("finish" + y[index].value).hidden = true;
        }
    }
}
//End Item Finish Scripts

function checkPayment() {
    if (document.getElementById('terms').value == 'payp') {
        document.getElementById('PayPalMark').style.visibility = '';
    }
    else {
        //document.getElementById('PayPalMark').style.visibility = 'hidden';
    }
    if (document.getElementById('terms').value == 'payp' || document.getElementById('terms').value == '') {
        document.getElementById('CreditCardName').disabled = true;
        document.getElementById('CreditCardNum').disabled = true;
        document.getElementById('CreditCardExp').disabled = true;
        document.getElementById('CreditCardVerification').disabled = true;
        document.getElementById('CreditCardZip').disabled = true;
    }
    else {
        document.getElementById('CreditCardName').disabled = false;
        document.getElementById('CreditCardNum').disabled = false;
        document.getElementById('CreditCardExp').disabled = false;
        document.getElementById('CreditCardVerification').disabled = false;
        document.getElementById('CreditCardZip').disabled = false;
    }
    showCreditCards();
}
function showCreditCards() {
    if (document.getElementById("terms").value == 'VISA' || document.getElementById("terms").value == 'MASTERCARD' || document.getElementById("terms").value == 'AMEX' || document.getElementById("terms").value == 'DISCOVER') {
        document.getElementById("CreditCards").style.display = '';
        document.getElementById("CreditCardName").required = true;
        document.getElementById("CreditCardNum").required = true;
        document.getElementById("CreditCardExp").required = true;
        document.getElementById("CreditCardVerification").required = true;
        document.getElementById("CreditCardZip").required = true;
    }
    else {
        document.getElementById("CreditCardName").required = false;
        document.getElementById("CreditCardNum").required = false;
        document.getElementById("CreditCardExp").required = false;
        document.getElementById("CreditCardVerification").required = false;
        document.getElementById("CreditCardZip").required = false;
        document.getElementById("CreditCards").required = false;
        document.getElementById("CreditCards").style.display = 'none';
    }
}
function newShipTo(checked) {
    if (checked == true) {
        document.getElementById("company").required = true;
//        document.getElementById("attn").required = true;
        document.getElementById("Address1").required = true;
        //document.getElementById("Address2").required = true;
        document.getElementById("city").required = true;
        document.getElementById("State").required = true;
        document.getElementById("zip").required = true;
    }
    else {
        document.getElementById("company").required = false;
//        document.getElementById("attn").required = false;
        document.getElementById("Address1").required = false;
        //document.getElementById("Address2").required = false;
        document.getElementById("city").required = false;
        document.getElementById("State").required = false;
        document.getElementById("zip").required = false;
    }
}

function submitformShopping2() {
    var form1 = document.form1;
    if (document.form1.length > 1) form1 = document.form1[1];
    if (!form1.Shopping) {
        $('<input />').attr('type', 'hidden')
          .attr('name', "Shopping")
          .attr('value', "Shopping")
          .appendTo(form1);
    }
    else {
        form1.Shopping.value = 'Shopping';
    }
    form1.submit();
}

function submitToCart(Path, Qty, WebID, Catalog) {
    var URL;

    URL = Path + 'catalogwebcart.aspx?QTY0=' + Qty + '&order0=on&SKU0=' + WebID + '&WebID0=' + WebID + '&TotalLines=1&CatName=' + Catalog
    window.open(URL, '_parent');
}

function UpdatePPE() {
    try {
        document.formPPE.submit();
    }
    catch (err) {
        var txt = 'There was an error in function SubmitForm.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}

function UpdateAndSubmit2(theValue) {
    if (theValue != 0) {
        document.form1.action += "&updatesubmit=" + theValue;
        //document.form1.submit();
    }
}


function submitalltocart(Path, Catalog) {
    var myform = document.getElementById('form1')
    var inputTags = myform.getElementsByTagName('input')
    var totallines = 0
    var cart = []
    var URL = Path + 'catalogwebcart.aspx?'

    // Get all items that were checked
    for (var i = 0, length = inputTags.length; i < length; i++) {
        if (inputTags[i].type == 'checkbox') {
            if (inputTags[i].checked == true) {
                totallines += 1

                var groupNumber = inputTags[i].id.replace('order', '')
                var qty = document.getElementById('QTY' + groupNumber).value
                var webid = document.getElementById('WebID' + groupNumber).value
                cart[totallines - 1] = qty + ',' + webid + ',' + Catalog
            }
        }
    }

    // Out of all the items that were checked, build the new cart query string
    // that will be parsed on the next page
    for (var j = 0; j < cart.length; j++) {
        if (j != 0) {
            URL += '&'
        }

        var item = cart[j].split(',')

        URL += 'QTY' + j + '=' + item[0] + '&' +
				'order' + j + '=on' + '&' +
				'SKU' + j + '=' + item[1] + '&' +
				'WebID' + j + '=' + item[1]
    }
    URL += '&TotalLines=' + totallines //+ '&' + 'CatName=' + item[2]
    window.open(URL, '_parent');
}

function CenPOSForm() {
    if (document.getElementById('selectordertype').value == 'so') {
        document.getElementById('NewCenposPlugin').style.visibility = '';
        document.getElementById('NewCenposPlugin').style.display = 'inherit';
        $('#IMAGE1').click(function (e) { $("#NewCenposPlugin").submitAction(); e.preventDefault(); })
    }
    else {
        document.getElementById('NewCenposPlugin').style.visibility = 'hidden';
        document.getElementById('NewCenposPlugin').style.display = 'none';
        $('#IMAGE1').click(function () { })
    }
}

function openPleaseWaitSpinner() {
    var reqDate = document.getElementById('reqdate');
    if (reqDate) {
    if (document.getElementById("reqdate").value !== "") {
        document.getElementById('PleaseWaitSpinner').style.display = 'flex';
    }
    } else {
        document.getElementById('PleaseWaitSpinner').style.display = 'flex';
    }

}

$(function () {
    if (typeof listnav !== 'undefined' && $.isFunction(listnav)) {
        var clicks = 0;
        $('#demoOne').listnav({
            includeAll: false, noMatchText: 'There are no matching entries.', showCounts: false,
            onClick: function () { clicks++; if (clicks == 1) { $('#demoOne').show(); } }
        }).hide();
    }
});

$(".bcm01").keypress(function (event) {
    var chr = String.fromCharCode(event.which);
    if ("-".indexOf(chr) >= 0) {
        event.preventDefault();
    }
})

function printObject(divName) {
    var printContents = document.getElementById(divName).innerHTML;
    var originalContents = document.body.innerHTML;

    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}
function printDiv(divName) {
    var printContents = document.getElementById(divName).innerHTML;
    var originalContents = document.body.innerHTML;

    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}
function LoadGallery2(pictureName, imageFile, ActualWidth, ActualHeight) {
    var picture = document.getElementById(pictureName);
    picture.nextSibling.src = imageFile;
    picture.src = imageFile;
    picture = document.getElementById('PopupImage1');
    picture.href = pictureName + '?js_imagepath=' + imageFile + '&js_width=' + ActualWidth + '&js_height=' + ActualHeight;
}

function ValidateNewAddress2() {
    if (document.ShowShip.Add1.value != '' &&
document.ShowShip.City.value != '' &&
document.ShowShip.State.value != '' &&
document.ShowShip.Zip.value != '') {
        document.ShowShip.action = 'catalogwebcheckout.aspx?pos=1&SelectedShipto=new&shipto=new&ShippingCalculate=yes';
        document.ShowShip.submit();
    }
    else if (document.ShowShip.SelectedShipto.value != 'new') {
        document.ShowShip.action = 'catalogwebcheckout.aspx?pos=1&ShippingCalculate=yes';
        document.ShowShip.submit();
    }
}

function propertyFromStylesheet(selector, attribute) {
    var value;

    [].some.call(document.styleSheets, function (sheet) {
        return [].some.call(sheet.rules, function (rule) {
            if (selector === rule.selectorText) {
                return [].some.call(rule.style, function (style) {
                    if (attribute === style) {
                        value = rule.style.getPropertyValue(attribute);
                        return true;
                    }

                    return false;
                });
            }

            return false;
        });
    });

    return value;
}

function TLReQuerySpecs1(Reset, SpecTextCount, FormID) {
    try {
        var i, j, k, txt, form, count, divCount;
        var bGo = true;
        //ToggleDisplay('busybox', 'on', '');

        form = document.getElementById(FormID); //(FormID == formSpec) ? document.formSpec : document.specSearch;
        txt = null;
        //if all SpecSearchText inputs blank then reset; o/w run spec search
        for (i = 0; i <= SpecTextCount - 1; i++) {
            for (j = 0; j < form.elements.length; j++) {
                if (form.elements[j].name == 'SpecSearchText' + i) {
                    txt = form.elements[j];
                    break;
                }
            }
            if (txt != null && txt.value != '') {
                bGo = false;
                break;
            }
        }
        if (Reset || bGo) {
            for (i = 0; i <= SpecTextCount - 1; i++) {
                for (j = 0; j <= form.elements.length; j++) {
                    if (form.elements[j].name == 'SpecSearchText' + i) {
                        txt = form.elements[j];
                        break;
                    }
                }
                txt.value = '';
            }
            form.RunSpecSearch.value = 'reset';
            form.TopSpecSearch.value = '';
        }
        else {
            for (i = 1; i < 12; i++) {
                try {
                    form('Compare' + i).value = '';
                } catch (err) {}; //on error resume next
            }
            form.RunSpecSearch.value = 'yes';
            form.TopSpecSearch.value = (FormID == 1) ? 'TL' : 'MD';
        }
        form.submit();
        //Get the count of specDivs, loop through and disable them on selection
        divCount = document.querySelectorAll('.specDiv').length;
        for (count = 1; count <= divCount; count++) {
            document.getElementById("SpecSearchText" + count).disabled = true;
        }
    }
    catch (err) {
        var txt = 'There was an error in function TLReQuerySpecs.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
} //TLReQuerySpecs

function TLReQuerySpecs2(Reset, SpecTextCount, FormID) {
    try {
        var i, j, k, txt, form, count, divCount;
        var bGo = true;
        //ToggleDisplay('busybox', 'on', '');
        form = document.getElementById(FormID);
        txt = null;
        //if all SpecSearchText inputs blank then reset; o/w run spec search
        for (i = 0; i <= SpecTextCount - 1; i++) {
            for (j = 0; j < form.elements.length; j++) {
                if (form.elements[j].name == 'SpecSearchText' + i) {
                    txt = form.elements[j];
                    break;
                }
            }
            if (txt != null && txt.value != '') {
                bGo = false;
                break;
            }
        }
        if (Reset || bGo) {
            for (i = 0; i <= SpecTextCount - 1; i++) {
                for (j = 0; j <= form.elements.length; j++) {
                    if (form.elements[j].name == 'SpecSearchText' + i) {
                        txt = form.elements[j];
                        break;
                    }
                }
                txt.value = '';
            }
            if (event.currentTarget.id !== "TiledLayoutSort") form.RunSpecSearch.value = 'reset';
            form.TopSpecSearch.value = '';
            form1.Compareme.value = '';
        }
        else {
            for (i = 0; i < 11; i++) {
                try {
                    form('Compare' + i).value = '';
                } catch (err) { }; //on error resume next
            }
            form.RunSpecSearch.value = 'yes';
            form.TopSpecSearch.value = (FormID == 1) ? 'TL' : 'MD';
        }
        form.SpecSearchPageOne.value = 'yes';
        form.submit();
        //Get the count of specDivs, loop through and disable them on selection
        divCount = document.querySelectorAll('.specDiv').length;
        for (count = 1; count <= divCount; count++) {
            document.getElementById("SpecSearchText" + count).disabled = true;
        }
    }
    catch (err) {
        var txt = 'There was an error in function TLReQuerySpecs2.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
} //TLReQuerySpecs2

function TLCompare2(SpecTextCount, form) {
    //checkboxes may be selected from other pages
    if ($('input:checkbox[class=tilecompare]:checked').length > 1) {
        var action;
        if ($('#compare').attr('action')) {
            action = $('#compare').attr('action');
        } else {
            action = form.action;
        }
        try {
            //document.compare.Compareme.value = 'compare';
            if (form.RunSpecSearch) form.RunSpecSearch.value = '';

            if (action.indexOf('?') == -1) action = action + '?';
            if (action.slice(-1) != '?') action = action + '&';
            action = action + 'Compareme=compare';
            //form.Compareme.value = 'compare';

            for (var i = 0; i < $("input:checkbox[class=tilecompare]:checked").length; i++) {
                action = action + '&Compare' + i + '=' + $("input:checkbox[class=tilecompare]:checked")[i].value;
            }
            //$('#compare').attr('action', action)
            form.action = action;
        }
        catch (err) {
            var txt = 'There was an error in function TLCompare.\n\n';
            txt += 'Error description: ' + err.description;
            if (true) alert(txt);
        };
        //document.compare.submit();
        form.submit();
    }
    else { alert('Select more checkboxes to compare'); return false; }
}

function submitpageform2(Request) {
    try {
        document.form1.Compareme.value = "pagequery";
        document.form1.CompRequest.value = Request;
        document.form1.action = document.form1.action.substring(0, document.form1.action.lastIndexOf("/") + 1) + Request
        document.form1.submit();
    }
    catch (err) {
        var txt = 'There was an error in function SubmitPageForm.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}

function OpenWindow() {
    var printContent;
    if (document.getElementById("mainTableBgrnd")) {
        printContent = document.getElementById("mainTableBgrnd");
        printContent = "<link rel='stylesheet' href='main.css' type='text/css'>" + printContent.outerHTML;
    }
    else {
        printContent = document.getElementById("MS1");
        printContent = "<link rel='stylesheet' href='main.css' type='text/css'>" + printContent.outerHTML;
    }
    printContent = printContent + "<script type='text/javascript'>window.print();window.close();</script>"
    var sFeatures = "height=400,width=600,status=1,toolBar=0,menuBar=1,location=1, resizable=1, scrollBars =1";
    var win = window.open("", "Print", sFeatures);
    win.document.write(printContent);
    win.document.close();
    //win.focus();
    //win.print();
    //win.close();
}

//START JOB WORKSHEET JAVASCRIPT ***********************************************
function changeWorksheetAction2(changeAction) {
    document.form3.action = document.form3.action.substring(0, document.form3.action.lastIndexOf("/") + 1) + 'account.aspx?page=worksheets&worksheetaction=' + changeAction;
    document.form3.submit();
}
function updateWorkSheetItems2() {
    document.form3.action = document.form3.action.substring(0, document.form3.action.lastIndexOf("/") + 1) + 'account.aspx?page=worksheets&worksheetaction=updateitems';
    submitForm(document.form3);
}
function OtherToThis2() {
    document.form3.action = document.form3.action.substring(0, document.form3.action.lastIndexOf("/") + 1) + 'account.aspx?page=worksheets&worksheetaction=addotherjobworksheettothisjobworksheet';
    document.form3.submit();
}
function ItemsToOther2() {
    document.form3.action = document.form3.action.substring(0, document.form3.action.lastIndexOf("/") + 1) + 'account.aspx?page=worksheets&worksheetaction=sendselecteditemstoother';
    document.form3.submit();
}
function TurnOn2(Object) {
    Object.previousElementSibling.style.display = '';
    Object.style.display = 'none';
    var a = Object.previousElementSibling.children[0];
    a.setAttribute('size', a.options.length);
}
function TurnOff2(Object) {
    Object.parentNode.nextElementSibling.style.display = '';
    Object.parentNode.style.display = 'none';
}
// function InsertItemIntoWorkSheet(WorkSheetName,ItemNumber,ItemQuantity) {
//    document.form3.action = document.form3.action.substring(0, document.form3.action.lastIndexOf("/") + 1) + 'account.aspx?page=worksheets&worksheetaction=' + changeAction + '&worksheetname=' + WorkSheetName;
//    document.form3.submit();
//}
function ChangeJobWorkSheet2(changeAction) {
    document.form3.action = document.form3.action.substring(0, document.form3.action.lastIndexOf("/") + 1) + 'account.aspx?page=worksheets&worksheetaction=' + changeAction;
    document.form3.submit();
}
function AddItemNumberToJobWorkSheet2(WorkSheetTo) {
    document.form3.action = document.form3.action.substring(0, document.form3.action.lastIndexOf("/") + 1) + 'account.aspx?Page=worksheets&worksheetaction=additemnumbertojobworksheet&ItemList=' + WorkSheetTo;
    submitForm(document.form3)
}
function CheckAll(CheckBoxList, status) {
    var iCounter
    CheckBoxList.checked = status
    for (iCounter = 0; iCounter < CheckBoxList.length; iCounter++) {
        CheckBoxList[iCounter].checked = status
    }
}
function AddToJobWorkSheet2(WorksheetId) {
    document.form1.action = document.form1.action.substring(0, document.form1.action.lastIndexOf("/") + 1) + 'account.aspx?page=worksheets&job-worksheet-action=insert-into-job-worksheet&job-worksheet-id=' + WorksheetId;
    submitForm(document.form1);
}
function CreateWorksheet() {
    document.form1.action = '/account.aspx?page=worksheets&job-worksheet-action=create-job-worksheet&job-worksheet-action2=insert-into-job-worksheet&job-worksheet-id=new';
    submitForm(document.form1);
}
function submittojobworksheet2(WorksheetId) {
    document.form1.hdCurrentWorkSheetName.value = WorksheetId;
    document.form1.action = '/account.aspx?page=worksheets&worksheetaction=add-from-detail-grid&job-worksheet-id=' + WorksheetId;
    submitForm(document.form1);
}
function EMailQuestionsAndComments2(QuestionsAndComments, WorkSheetName) {
    document.form3.action = document.form3.action.substring(0, document.form3.action.lastIndexOf("/") + 1) + 'account.aspx?page=worksheets&worksheetaction=emailquestionsandcomments&questionsandcomments=' + QuestionsAndComments + '&worksheetname=' + WorkSheetName;
    document.form3.submit();
}
//END JOB WORKSHEET JAVASCRIPT ***********************************************

//BCM 2/14/2018 Call this instead of form.submit() method which skips the onSubmit event handlers
function submitForm(form) {
    //get the form element's document to create the input control with
    //(this way will work across windows in IE8)
    var button = form.ownerDocument.createElement('input');
    //make sure it can't be seen/disrupts layout (even momentarily)
    button.style.display = 'none';
    //make it such that it will invoke submit if clicked
    button.type = 'submit';
    //append it and click it
    form.appendChild(button).click();
    //if it was prevented, make sure we don't get a build up of buttons
    form.removeChild(button);
}

function MakeApiCalls() {
    $("input[name='localQuantity']").each(function (i) {
        var placeholder = $(this).parent();
        $.ajax({
            type: 'POST',
            url: 'WebService.asmx/GetLocalQuantityService',
            data: { webID: this.value },
            error: function (jqXHR, textStatus, errorThrown) {
                $(i).next().outerHeight('<span color="red">Sorry, an error occurred.</span>');
            },
            success: function (data) {
                $(placeholder).html(data.firstChild.innerHTML);
            }
        })
    });
    $("input[name='networkQuantity']").each(function (i) {
        var placeholder = $(this).parent();
        $.ajax({
            type: 'POST',
            url: 'WebService.asmx/GetNetworkQuantityService',
            data: { webID: this.value },
            error: function (jqXHR, textStatus, errorThrown) {
                $(i).next().outerHeight('<span color="red">Sorry, an error occurred.</span>');
            },
            success: function (data) {
                $(placeholder).html(data.firstChild.innerHTML);
            }
        })
    });
}

function ResponsiveCartTable(tableClassName) {    
    if (/Mobi/.test(navigator.userAgent)) {
        $('table.' + tableClassName).each(function () {
            var table = $(this); // cache table object
            var head = table.find('thead th');
            var rows = table.find('tbody tr').clone(); // appending afterwards does not break original table

            // create new table
            var newtable = $(
                '<table class="generated_for_mobile mobile' + tableClassName + '">' +
                '  <tbody>' +
                '  </tbody>' +
                '</table>'
            );

            // cache tbody where we'll be adding data
            var newtable_tbody = newtable.find('tbody');

            rows.each(function (i) {
                var cols = $(this).find('td');
                var classname = i % 2 ? 'even' : 'odd';
                cols.each(function (k) {
                    var new_tr = $('<tr class="' + classname + ' highlight' + k + '"></tr>').appendTo(newtable_tbody);
                    new_tr.append(head.clone().get(k));
                    new_tr.append($(this));
                });
            });

            $(this).after(newtable);

            // attach submit handler to enclosing form
            // using .parents('form:first').each() instead of .parents('form:first')[0] in case no such form exists            
            table.parents('form:first').each(function () {
                $(this).submit(function (event) {
                    ((table.css('position') == 'absolute') ? table.remove() : $('.generated_for_mobile').remove());
                });
            });
        });

        //var orderPad = $('#menufunctions_table_0').clone();
        //orderPad.attr('class', 'mobileOrderPad');
        //$('table.cartContentsTable').after(orderPad);

        //Remove select all checkboxes from each row on JW
        var child = document.getElementById("cb_jobworksheetfunctions96");
        child.parentNode.removeChild(child);
    };
};

// prefer ResponsiveCartTable
function ResponsiveTableGeneric(tableClassName) {
    if (/Mobi/.test(navigator.userAgent)) {
        $('table.' + tableClassName).each(function () {
            var table = $(this); // cache table object
            var head = table.find('thead th');
            var rows = table.find('tbody tr').clone(); // appending afterwards does not break original table

            // create new table
            var newtable = $(
                '<table class="generated_for_mobile">' +
                '  <tbody>' +
                '  </tbody>' +
                '</table>'
            );

            // cache tbody where we'll be adding data
            var newtable_tbody = newtable.find('tbody');

            rows.each(function (i) {
                var cols = $(this).find('td');
                var classname = i % 2 ? 'even' : 'odd';
                cols.each(function (k) {
                    var new_tr = $('<tr class="' + classname + '"></tr>').appendTo(newtable_tbody);
                    new_tr.append(head.clone().get(k));
                    new_tr.append($(this));
                });
            });

            $(this).after(newtable);
            $(this).remove();
        });
    }
}
function UpdateShippingCharge() {
    document.getElementById('ShowShip').action += "&pos=1&ShippingCalculate=yes";
    document.getElementById('ShowShip').submit();
}
function UpdateShippingDD(iShip) {
    try {
        document.ShowShip.pos.value = "1";
        document.ShowShip.shipto[0].value = iShip;
        document.ShowShip.SelectedShipto.value = iShip;
        document.ShowShip.submit();
    }
    catch (err) {
        var txt = 'There was an error in function SubmitForm.\n\n';
        txt += 'Error description: ' + err.description;
        if (true) alert(txt);
    }
}
function isNumberAndAvailable(myfield, e, w, dec, iLine) {
    var key;
    var keys;
    var keychar;
    var lineID;
    lineID = iLine;
    if (myfield.selectionStart > 0) {
        keys = myfield.value;
    }
    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    keys += keychar;
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27)) {
        return true;
    }
        // numbers
    else if ((("0123456789").indexOf(keychar) > -1)) {
        if (isAvailable(keys, lineID)) {
            return true;
        }
        else
            return false;
    }
        // decimal point jump
    else if (dec && (keychar == ".")) {
        myfield.form.elements[dec].focus();
        return false;
    }
    else
        return false;
}
function isAvailable(keychar, lineID) {
    var qoh;
    qoh = document.getElementById('qoh' + lineID).value

    if (parseInt(keychar) > parseInt(qoh)) {
        $('.overOrderMsg').show();
        return false;
    }
    else
        $('.overOrderMsg').hide();
    return true;
}

function TLSortChanged2(CompareCount) {
    try {
        document.form1.Compareme.value = 'nocompare';
        document.form1.TLSort.value = 'true';
        document.form1.action = removeParam('TiledLayoutSort', document.form1.action);
        document.form1.action = removeParam('TLSearch', document.form1.action);
        document.form1.action = removeParam('totallines', document.form1.action);
        document.form1.action = removeParam('TLSort', document.form1.action);
        for (var i = 0; i <= CompareCount; i++) {
            document.form1('Compare' + i).value = '';
        }
    } catch (e) { };
    document.form1.submit();
}

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

/*
  CSP 4.23.18
  This code is designed to be attached to form inputs inside tables targetted by
  the above mobile-view table generating functions. This will ensure the mobile table
  gets updated when a user changes the desktop table and vice-versa.
*/
function UpdateDuplicateInputs(obj) {
  $('input[name="' + obj.name + '"]').val(obj.value);
}

/*
 * Detect changes in the "Add To Job Worksheet" select input on the cart page. If the
 * value is the sNewJobWorkSheetGUID constant defined in CB_JobWorkSheetFunctions.aspx.vb,
 * then prompt the user with the Create New Job Worksheet modal. Otherwise, submit the form.
 */
$(document).on('change', '#ddWorkSheetSelect', function (el) {
  var target = $(el.target);

  if (target.val() === '6a7a02ec094a4a9c8f9c3e9019ee9263') {
    $('#CreateNew').modal('show');
  }
  else if (target.val()) {
    document.form1.action = '/CartPage.aspx';
    submitForm(document.form1);
  }
});

$(document).ready(function () {
    function submit() {
        document.form1.action = '/CartPage.aspx';
        submitForm(document.form1);
    }

    $('#txtworksheetname, #txtworksheetcomment').keydown(function (e) {
        if (e.key === 'Enter') {
            submit();
        }
    });

    $('#create-job-worksheet-btn').click(function () {
        submit();
    });
});

function sendQuoteRequest(quoteNumber) {
    $.ajax({
        type: "POST",
        url: "WebService.asmx/SendQuoteToOrder",
        data: "{sQuoteNumber:" + JSON.stringify(quoteNumber) + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSendQuoteSuccess,
        error: OnSendQuoteError
    });
}
function OnSendQuoteSuccess(response) {
    console.log(response.d);
    alert('A request to convert your quote(s) to order(s) has been sent to the order desk. An associate will contact you as soon as possible to review the details.');
    //    location.reload();
}
function OnSendQuoteError(response) {
    console.log(response.error);
}

function changeShippingFee(shipMethod, startDistance, endDistance) {
    var newShipFee;

    newShipFee = prompt("Please enter the new ship fee for a " + shipMethod + " with a range between " + startDistance + " and " + endDistance + " miles.")

    if (newShipFee != null) {
        $.ajax({
            type: "POST",
            url: "WebService.asmx/UpdateShippingRate",
            data: "{sShipMeth:" + JSON.stringify(shipMethod) + ",sStart: " + JSON.stringify(startDistance) + ",sEnd: " + JSON.stringify(endDistance) + ",sNewValue:" + JSON.stringify(newShipFee) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnChangeShippingFeeSuccess,
            error: OnChangeShippingFeeErrorCall
        });
    }
}
function updateShippingTable(pkid, newShipFee, startAmount, endAmount) {
    if (confirm("Do you really want to update the values?")) {
        $.ajax({
            type: "POST",
            url: "WebService.asmx/UpdateShippingTable",
            data: "{pkid:" + JSON.stringify(pkid) + ",sNewValue:" + JSON.stringify(newShipFee) + ",sStartAmount:" + JSON.stringify(startAmount) + ",sEndAmount:" + JSON.stringify(endAmount) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnUpdateShippingTablesuccess,
            error: OnUpdateShippingTableErrorCall
        });
        document.getElementById('updateshipping').submit();
    }
}

/*
function updateShippingTable(pkid, startDistance, endDistance, newShipFee, startAmount, endAmount) {
    if (confirm("Do you really want to update the values?"))
    {
        $.ajax({
            type: "POST",
            url: "WebService.asmx/UpdateShippingTable",
            data: "{pkid:" + JSON.stringify(pkid) + ",sStart: " + JSON.stringify(startDistance) + ",sEnd: " + JSON.stringify(endDistance) + ",sNewValue:" + JSON.stringify(newShipFee) + ",sNewValue:" + JSON.stringify(newShipFee) + ",sStartAmount:" + JSON.stringify(startAmount) + ",sEndAmount:" + JSON.stringify(endAmount) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnUpdateShippingTablesuccess,
            error: OnUpdateShippingTableErrorCall
        });
    }
}

*/


function OnUpdateShippingTablesuccess(response) {
    console.log(response.d);
    location.reload();
}
function OnUpdateShippingTableErrorCall(response) {
    console.log(response.error);
}


function TLPageSubmit(pageNumber) {
    document.form1.TLPage.value = pageNumber;
    document.form1.submit();
}

function SubmitCoupon() {
    document.getElementById('totallines').value = '';
    document.form1.submit();
}
function textLength(value) {
    var maxLength = 4;
    if (value.length > maxLength) return false;
    return true;
}

function UpdateFormShipping(value) {
    if (!textLength(value)) GetShippingOptions(document.ShowShip.Zip.value, document.ShowShip.State.value);
}

function CheckKey(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode
        e.preventDefault();
        return false;
    }
}

function dontSubmit(event) {
    if (event.keyCode == 13) {
        return false;
    }
}

$(document).ready(function () {
    function clearQuickOrderValidations() {
        $('#quickorder input').removeClass('is-valid').removeClass('is-invalid');
    }

    $('#qbutton').click(function (e) {        
        var partNumbers = $('#quickorder input[name=partnumber]');
        var quantities = $('#quickorder input[name=quantity]');
        var items = [];        

        for (var i = 0; i < partNumbers.length; i++) {
            var partNumber = partNumbers[i].value.trim();
            var quantity = parseInt(quantities[i].value);

            if (partNumber === '') continue;
            if (isNaN(quantity) || quantity < 1) quantity = 1;

            items.push({
                partNumber: partNumber,
                quantity: quantity
            });
        }

        if (items.length === 0) {
            toastr.warning('No products specified.');
            return;
        }
        
        e.target.disabled = true;        
        csx.cart.addByPartNumber(items)
            .then(function () {
                toastr.success('Your item(s) have been added to the cart.');                
                clearQuickOrderValidations();
                csx.common.updateCartSummary();
                $('#quickorder input[name=partnumber]').val('');
                $('#quickorder input[name=quantity]').val('');
            })
            .catch(function (e) {
                var invalidPartNumbers = e.responseJSON.invalidPartNumbers

                if (invalidPartNumbers) {
                    var partNumberInputs = $('#quickorder input[name=partnumber]');

                    clearQuickOrderValidations();
                    partNumberInputs.each(function (i, x) {
                        var input = $(x);
                        var partNumber = input.val();

                        if (partNumber.trim() === "") return;

                        if ($.inArray(partNumber, invalidPartNumbers) === -1) {
                            input.addClass('is-valid');
                        } else {
                            input.addClass('is-invalid');
                        }
                    });
                }
            })
            .then(function () {
                e.target.disabled = false;
            });
    });
});;

     
          
          
          
          
function         CBAddress(mAddress)
{          
        var address= new Object();
          
        address.sAddressID = '';
        address.sAttn = mAddress.sAttn;
        address.sCompanyName = mAddress.sCompanyName;
        address.sAddress1 = mAddress.sAddress1;
        address.sAddress2 = mAddress.sAddress2;
        address.sAddress3 = mAddress.sAddress3;
        address.sCountry = mAddress.sCountry;
        address.sCity = mAddress.sCity;
        address.sState = mAddress.sState;
        address.sCounty = mAddress.sCounty;
        address.sPhone1 = '';
        address.sPhone2 = '';
        address.sPhone3 = '';
        address.sFax = '';
        address.sZip = mAddress.sZip;
address.sNotes='';
    address.sEmail = '';
    address.sNameOnCard = '';
        address.sName = '';
        address.sTaxableFlg = '';
        address.sDeliveryMessage = '';
        address.sInvtofl = '';
        address.sShipVia = '';
          
          
    address.sUser11 = '';
    address.sUser12 = '';
    address.sUser13 = '';
    address.sUser14 = '';
    address.sUser15 = '';
    address.sPriceType = '';
    address.sPORequired = '';
    address.sWhse = '';
    return address;
}

function GetShippingOptions(ZipCode, State,OrderID) {
    $.ajax({
        type: "POST",
        url: "WebService.asmx/GetShippingOptions",
        data: "{sZipCode: " + JSON.stringify(ZipCode) + ",sState: " + JSON.stringify(State) + ",sOrderID: " + JSON.stringify(OrderID) + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnChangeShipSuccess,
        error: OnChangeShipErrorCall
    });
}
function UpdateFreeFormAddress(mAddress)
{
    $("#Address1").val(mAddress.sAddress1);
    $("#city").val(mAddress.sCity);
    $("#zip").val(mAddress.sZip);
}
function GetShippingOptionsOBJ(mAddress,OrderID) {
    //$('.loading').removeClass('hidden');
    var mRequest = new Object();
    mRequest.OrderID = OrderID;
    mRequest.ShipToAddress = CBAddress(mAddress);
    $.post('/api/shippingapi/getshipoptions', mRequest)
        .done(function (data) {
            console.log("Data Loaded: " + data);
            document.getElementById('SHIPMETH').disabled = false;
            var select = document.getElementById("SHIPMETH");
            document.getElementById('ShippingMethods').innerHTML = JSON.stringify(data);
            select.options.length = 1;

            if (data.Status.bError == true)
            {
                toastr.error(data.Status.Message);
            }
            else
            {
                for (var key in data.ValidShippingMethods)
                {
                    if (data.ValidShippingMethods[key].mShippingReturn != null)
                    {
                    select.options[select.options.length] = new Option(data.ValidShippingMethods[key].mShippingReturn.sPrice, data.ValidShippingMethods[key].sShipCode);
                    }
                    else
                    {
                        select.options[select.options.length] = new Option(data.ValidShippingMethods[key].sMethod, data.ValidShippingMethods[key].sInternalCode);
                    }
                    
                }
                UpdateFreeFormAddress(data.ValidAddress);
}
            $("#PleaseWaitSpinner").hide();
        });

}

function OnChangeShippingFeeSuccess(response) {
    console.log(response.d);
    location.reload();
}
function OnChangeShippingFeeErrorCall(response) {
    console.log(response.error);
}

function GetShippingOptionsByShippingID(ShipID,OrderID) {
    //$('.loading').removeClass('hidden');
    var mRequest = new Object();
    mRequest.OrderID = OrderID;
    mRequest.ShipID = ShipID;
    $.post('/api/shippingapi/getshipoptionsbyid', mRequest)
        .done(function (data) {
            console.log("Data Loaded: " + data);
            document.getElementById('ShippingMethods').innerHTML = JSON.stringify(data);
            document.getElementById('SHIPMETH').disabled = false;
            var select = document.getElementById("SHIPMETH");
            select.options.length = 1;
            for (var key in data.ValidShippingMethods) {
                select.options[select.options.length] = new Option(data.ValidShippingMethods[key].mShippingReturn.sPrice, data.ValidShippingMethods[key].sShipCode);
}
            $("#PleaseWaitSpinner").hide();
        });
    }
function UpdateShippingMethod(ShippingMethod,OrderID)
{
    var mRequest = new Object();
    mRequest.OrderID = OrderID;
    var methods = JSON.parse(document.getElementById('ShippingMethods').innerHTML);
    //var data = methods.ValidShippingMethods.filter(function (method) { return method.sShipCode = ShippingMethod; });
    for (var key in methods.ValidShippingMethods) {
        if (methods.ValidShippingMethods[key].sShipCode == ShippingMethod)
        {
            mRequest.Method = methods.ValidShippingMethods[key];
            $.post('/api/shippingapi/updateshippingmethod', mRequest)
                .done(function (data) {
                    console.log("Data Loaded: " + data);
                    document.getElementById('IMAGE1').disabled = false;
                    document.body.style.cursor = 'default';
    });
}
}
}
function AddShippingRateMethod()
    {
    var newShipMethod;

    newShipMethod = prompt("Please enter the name method you want to add.");
    if (newShipMethod != null)
    {


    }
}

function DeleteShippingRateMethod()
    {
    var MethodToDelete;

    MethodToDelete = prompt("Please enter the method you want to delete.");
    if (MethodToDelete != null) 
    {

    }

}

function sendQuoteRequest(quoteNumber)
{
    $.ajax({
        type: "POST",
        url: "WebService.asmx/SendQuoteToOrder",
        data: "{sQuoteNumber:" + JSON.stringify(quoteNumber) + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSendQuoteSuccess,
        error: OnSendQuoteError
    });
}
function OnSendQuoteSuccess(response) {
    console.log(response.d);
    alert('A request to convert your quote(s) to order(s) has been sent to the order desk. An associate will contact you as soon as possible to review the details.');
//    location.reload();
}
function OnSendQuoteError(response) {
    console.log(response.error);
}

function changeShippingFee(shipMethod, startDistance, endDistance)
{
    var newShipFee;

    newShipFee = prompt("Please enter the new ship fee for a " + shipMethod + " with a range between " + startDistance + " and " + endDistance + " miles.")

    if (newShipFee != null)
    {
        $.ajax({
            type: "POST",
            url: "WebService.asmx/UpdateShippingRate",
            data: "{sShipMeth:" + JSON.stringify(shipMethod) + ",sStart: " + JSON.stringify(startDistance) + ",sEnd: " + JSON.stringify(endDistance) + ",sNewValue:" + JSON.stringify(newShipFee) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnChangeShippingFeeSuccess,
            error: OnChangeShippingFeeErrorCall
        });
    }
}
function updateShippingTable(pkid, newShipFee, startAmount, endAmount) {
    if (confirm("Do you really want to update the values?"))
{
        $.ajax({
            type: "POST",
            url: "WebService.asmx/UpdateShippingTable",
            data: "{pkid:" + JSON.stringify(pkid) + ",sNewValue:" + JSON.stringify(newShipFee) + ",sStartAmount:" + JSON.stringify(startAmount) + ",sEndAmount:" + JSON.stringify(endAmount) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnUpdateShippingTablesuccess,
            error: OnUpdateShippingTableErrorCall
        });
        document.getElementById('updateshipping').submit();
    }   
}

function OnUpdateShippingTablesuccess(response) {
    console.log(response.d);
    location.reload();
}
function OnUpdateShippingTableErrorCall(response) {
    console.log(response.error);
}
;
function additemstocart(itemCount, formname, addedToCart)
{
    var index;
    var cartitemlist = new Array();

    for (index = 0; index < itemCount; index++)
    {
        var cartItem = {
            pkid: $("#" + formname + " input[id=pkid" + index + "]").val(),
            webid: $("#" + formname + " input[id=WebID" + index + "]").val(),
            price: $("#" + formname + " input[id=price" + index + "]").val(),
            sku: $("#" + formname + " input[id=SKU" + index + "]").val(),
            partnumber: $("#" + formname + " input[id=ProductNumber" + index + "]").val(),
            quantity: $("#" + formname + " input[name=QTY" + index + "]").val(),
            uom: $("#" + formname + " input[id=uom" + index + "]").val(),
        };
        if (cartItem.quantity != '')
        {
        cartitemlist.push(cartItem);
    }

    }

    $.ajax({
        type: "POST",
        url: "/Services/CartServices.asmx/UpdateCart",
        data: "{sCartItems: '" + JSON.stringify(cartitemlist) + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) { UpdateCartSuccess(response, addedToCart); },
        error: function (response) { UpdateCartError(response, addedToCart); }
    });
}




function additemtocart(index, formname, addedToCart) {
    var cartitemlist = new Array();

 
        var cartItem = {
            pkid: $("#" + formname + " input[id=pkid" + index + "]").val(),
            webid: $("#" + formname + " input[id=WebID" + index + "]").val(),
            price: $("#" + formname + " input[id=price" + index + "]").val(),
            sku: $("#" + formname + " input[id=SKU" + index + "]").val(),
            partnumber: $("#" + formname + " input[id=ProductNumber" + index + "]").val(),
            quantity: $("#" + formname + " input[name=QTY" + index + "]").val()
        };

      
        cartitemlist.push(cartItem);

    $.ajax({
        type: "POST",
        url: "/Services/CartServices.asmx/UpdateCart",
        data: "{sCartItems: '" + JSON.stringify(cartitemlist) + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) { UpdateCartSuccess(response, addedToCart);},
        error: function (response) { UpdateCartError(response, addedToCart); }
    });

}
function UpdateCartSuccess(response,addedToCart) {
    console.log(response.d);
   
    addedToCart(response);
}
function UpdateCartError(response, addedToCart) {
    console.log(response.error);
    addedToCart(response);
}

;
$(document).ready(function(){
  $('img.DetImage')
    .wrap('<span style="display:inline-block"></span>')
    .css('display', 'block')
    .parent()
    .zoom({on: 'mouseover', duration:800});
});;
