/***************************************
****** This file is dependent on  ******
****** OrderPad.ex, products.ex   ******
****** and ShoppingCart.ex        ******
***************************************/

//-----( @OrderPad )-------------------------------------------
var OrderPad = {
  array : new Object(),
  obj : new Object(),
  
  init: function() {    
    OrderPad.obj["sku"] = $("fastSku");    
    OrderPad.obj["qty"] = $("fastQty");    
    OrderPad.obj["description"] = $("fastDescription");    
    OrderPad.obj["qtyPkg"] = $("fastQtyPkg");    
    OrderPad.obj["price"] = $("fastPrice");
    
    OrderPad.resetArray();
    
    var fop = getParameter("fop");
    
    if (fop) {
      fastenal.toggle('fastOrderPadContainer',document.getElementById('fastToggle')); setInitialFocus();
    }
  },
  
  checkArray: function() {
    for (var i in OrderPad.array)
      if (OrderPad.array[i] == null)
        return true;

    return false;
  },
  
  resetArray: function () {
    for (var i in OrderPad.array)
      OrderPad.array[i] = null;
    
    for (var i in OrderPad.obj)
      OrderPad.obj[i].value = "";
  },
  
  partFound: function (part, qtypkg, price, prodid, unk2) {
    OrderPad.array['description'] = part;
    OrderPad.array['qtyPkg'] = qtypkg;
    OrderPad.array['price'] = price;
    OrderPad.array['prodId'] = prodid;
    OrderPad.array['partId'] = 1 + "|" + OrderPad.array["prodId"] + "|" + OrderPad.array["sku"];

    OrderPad.obj["description"].value = OrderPad.array["description"];
    OrderPad.obj["qtyPkg"].value = OrderPad.array["qtyPkg"];
    
    if (OrderPad.array['price'].indexOf(".") + 2 >= OrderPad.array['price'].length) {
        OrderPad.obj["price"].value = parseFloat(OrderPad.array['price']).toFixed(2);
    } else {
        OrderPad.obj["price"].value = OrderPad.array['price'];
    }
  },
  
  partNotFound: function () {
    togglePopup('divFastOrderPadPopup',false);
  },
  
  setInitialFocus: function () {
    if ((OrderPad.obj["sku"]) && (isVisible(OrderPad.obj["sku"])))
      OrderPad.obj["sku"].focus();
  },
  
  // TODO Cleanup below
  
  togglePopup: function (obj,cancel) {
    var obj = obj || $(obj);
      
    var fastSku = $("fastSku");
    var fastQty = $("fastQty");
    var submit = $("fastSubmit");
      
    if (obj.style.display != 'none') {
      obj.style.display = 'none';
      
      if (cancel) {
        fastQty.setAttribute("disabled","disabled");
        submit.setAttribute("disabled","disabled");
        fastSku.value = "";
        fastSku.focus();
      }
    } else { 
      obj.style.display = '';
      $('popupFastenal').focus();
    }
  },
  
  formToggle: function (e, element) {
    e = e || window.keyup;
    var code = e.keyCode || e.which;
    
    if ((code == 1) || (e.type == 'click')) code = 13; // Checks to see if user clicks, then changes code to 13
  
    var fastSku = document.getElementById("fastSku");
    var fastQty = document.getElementById("fastQty");
    var fastDesc = document.getElementById("fastDescription");
    
    if ( code == 13 ) {
      if (element.id == 'fastSku') {
        if (fastSku.value != '') {
          fastAdd.sku = fastSku.value;
          ajaxGetProdDescription();
        } else {
          alert("You must enter a SKU");
          fastSku.focus();
        }
      } else {
        fastAdd.qty = fastQty.value;
        fastSku.focus();
        
        if (trim(fastAdd.qty) == '' || (fastAdd.qty) < 1) {
          fastQty.value = '';
          fastAdd.qty = null;
          alert("You must enter a quantity");
          fastQty.focus();
        } 
      }
      
      if (fastAdd.sku != null && fastAdd.qty != null) {
        if (fastAdd.partId == null) {
          alert("Wait for the description to load, then add the item to the cart.");
        } else {
          ajaxAddProdToCart();
        }
      }
      
      return false;
    }
    
    return true;
  },
  
  addFastenalPart: function () {
    fastAdd.qtyPkg = "1";
    fastAdd.description = "Custom Fastenal Part Number";
    fastAdd.price = "0";
    fastAdd.partId = "";
    
    var fastQty = document.getElementById("fastQty");
    var submit = document.getElementById("fastSubmit");
    
    fastQty.removeAttribute("disabled");
    submit.removeAttribute("disabled");
    fastQty.focus();
    
    document.getElementById("fastDescription").value = fastAdd.description;
    document.getElementById("fastQtyPkg").value = "NA";
    document.getElementById("fastPrice").value = "NA";
  },

  addCustomerPart: function () {
    fastAdd.qtyPkg = "1";
    fastAdd.description = "Customer Part Number";
    fastAdd.price = "0";
    fastAdd.partId = "";
    
    var fastQty = document.getElementById("fastQty");
    var submit = document.getElementById("fastSubmit");
    
    fastQty.removeAttribute("disabled");
    submit.removeAttribute("disabled");
    fastQty.focus();
    
    document.getElementById("fastDescription").value = fastAdd.description;
    document.getElementById("fastQtyPkg").value = "NA";
    document.getElementById("fastPrice").value = "NA";
  },

  cancelPart: function () {
    resetArray();
    setInitialFocus();
  },

  ajaxGetProdDescription: function () {
    var sExec = "OrderPad.ex";
    var sParam = "action=lookup";
    
    var path = setPath( sExec, sParam );
    var params = "add=NO&Sku=" + fastAdd.sku;
    
    var fastQty = document.getElementById("fastQty");
    var submit = document.getElementById("fastSubmit");
    
    dojo.xhrGet( {
        url: path + "&" + params,
        handleAs: "text",
        timeout: 60000,
        load: function(response, ioArgs) {
            eval(response);
            fastQty.removeAttribute("disabled");
            submit.removeAttribute("disabled");
            fastQty.focus();
            return response;
        },
        error: function(response, ioArgs) {
            dojo.byId("fastResponse").innerHTML = "Sorry, there has been an error.";
            console.error("HTTP status code", ioArgs.xhr.status);
            return response;
        }
    } );
  },

  ajaxAddProdToCart: function () {
    if (fastAdd.description == "Custom Fastenal Part Number") {
        var sExec = "OrderPad.ex";
        var sParam = "action=add";
        var path = setPath( sExec, sParam );
        var params = "add=YES&Sku=" + fastAdd.sku + "&Quantity=" + fastAdd.qty + "&CustomType=Fastenal";
    } else if (fastAdd.description == "Customer Part Number") {
        var sExec = "OrderPad.ex";
        var sParam = "action=add";
        var path = setPath( sExec, sParam );
        var params = "add=YES&Sku=" + fastAdd.sku + "&Quantity=" + fastAdd.qty + "&CustomType=Customer";
    } else {
        var sExec = "products.ex";
        var sParam = "dispatch=addToCart";
        var path = setPath( sExec, sParam );
        var params = "productDetailId=" + fastAdd.partId + "&qty=" + fastAdd.qty;
    }
    
    var fastQty = document.getElementById("fastQty");
    var submit = document.getElementById("fastSubmit");
    
    dojo.xhrGet( {
      url: path + "&" + params,
      handleAs: "text",
      timeout: 60000,
      load: function(response, ioArgs) {
        resetArray();
        ajaxUpdateCart();
        fastQty.setAttribute("disabled","disabled");
        submit.setAttribute("disabled","disabled");
        return response;
      },
      error: function(response, ioArgs) {
        dojo.byId("fastResult").innerHTML = "<font style='color:red;'>An error occurred updating your shopping cart.  Try again.</font>";
        console.error("HTTP status code", ioArgs.xhr.status);
        return response;  
      }
    } );
  },

  ajaxUpdateCart: function () {
    var sExec = "ShoppingCart.ex";
    var sParam = "printable=true";
    var path = setPath( sExec, sParam );

    dojo.xhrGet( {
      url: path,
      handleAs: "text",
      timeout: 60000,
      load: function(response, ioArgs) {
              dojo.byId("shoppingCartContainer").innerHTML = response;
              updateCartPopup(SITE_ROOT + 'ShoppingCart.ex?type=display');
              return response;
            },
      error: function(response, ioArgs) {
        alert(response);
               dojo.byId("fastResponse").innerHTML = "<font style='color:red;'>An error occurred updating your shopping cart.  Try again.</font>";
               console.error("HTTP status code", ioArgs.xhr.status);
               return response;  
             }
    } );
  },

  getParameter: function ( name ){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
      return "";
    else
      return results[1];
  }
};

addLoadEvent(function () { OrderPad.init(); });
//-----( END )-------------------------------------------------

// TODO - Remove the code below after testing...

// Global Variables for adding something
var fastAdd = new Object();
fastAdd.sku = null;
fastAdd.qty = null;
fastAdd.qtyPkg = null;
fastAdd.description = null;
fastAdd.price = null;
fastAdd.prodId = null;
fastAdd.partId = null;

function checkArray() {
    for (var i in fastAdd) {
        if (fastAdd[i] == null) {
            return true;
        }
    }

    return false;
}

function resetArray() {
    for (var i in fastAdd) {
      fastAdd[i] = null;
    }

    document.getElementById("fastSku").value = '';
    document.getElementById("fastQty").value = '';

    document.getElementById("fastDescription").value = '';
    document.getElementById("fastQtyPkg").value = '';
    document.getElementById("fastPrice").value = '';
}

function partFound(part, qtypkg, price, prodid, unk2) {
    fastAdd['description'] = part;
    fastAdd['qtyPkg'] = qtypkg;
    fastAdd['price'] = price;
    fastAdd['prodId'] = prodid;
    fastAdd['partId'] = 1 + "|" + fastAdd.prodId + "|" + fastAdd.sku; // 1 used to be 'fastAdd.qtyPkg'

    document.getElementById("fastDescription").value = fastAdd['description'];
    document.getElementById("fastQtyPkg").value = fastAdd['qtyPkg'];
    
    if (fastAdd['price'].indexOf(".") + 2 >= fastAdd['price'].length) {
        document.getElementById("fastPrice").value = parseFloat(fastAdd['price']).toFixed(2);
    } else {
        document.getElementById("fastPrice").value = fastAdd['price'];
    }
}

function partNotFound() {
    togglePopup('divFastOrderPadPopup',false);
}

function promoFound() {

}

function promoNotFound() {
    
}

function setInitialFocus() {
  if (document.getElementById && document.getElementById("fastSku") != null) {
    if (isVisible('fastSku')) {
      document.getElementById("fastSku").focus();
    }
  }
}


function togglePopup(obj,cancel) {
  obj = document.getElementById(obj);
    
  var fastSku = document.getElementById("fastSku");
  var fastQty = document.getElementById("fastQty");
  var submit = document.getElementById("fastSubmit");
    
  if (obj.style.display != 'none') {
    obj.style.display = 'none';
    
    if (cancel) {
      fastQty.setAttribute("disabled","disabled");
      submit.setAttribute("disabled","disabled");
      fastSku.value = "";
      fastSku.focus();
    }
  } else { 
    FAST.popupObject("newPopupWindow","framework_popup error", obj.innerHTML,null,325);
    document.getElementById('popupFastenal').focus();
  }
}

function formToggle(e, element) {
  e = e || window.keyup;
  var code = e.keyCode || e.which;
  
  if ((code == 1) || (e.type == 'click')) code = 13; // Checks to see if user clicks, then changes code to 13

  var fastSku = document.getElementById("fastSku");
  var fastQty = document.getElementById("fastQty");
  var fastDesc = document.getElementById("fastDescription");
  
  if ( code == 13 ) {
    if (element.id == 'fastSku') {
      if (fastSku.value != '') {
        fastAdd.sku = fastSku.value;
        ajaxGetProdDescription();
      } else {
        alert("You must enter a SKU");
        fastSku.focus();
      }
    } else {
      fastAdd.qty = fastQty.value;
      fastSku.focus();
      
      if (trim(fastAdd.qty) == '' || (fastAdd.qty) < 1) {
        fastQty.value = '';
        fastAdd.qty = null;
        alert("You must enter a quantity");
        fastQty.focus();
      } 
    }
    
    if (fastAdd.sku != null && fastAdd.qty != null) {
      if (fastAdd.partId == null) {
        alert("Wait for the description to load, then add the item to the cart.");
      } else {
        ajaxAddProdToCart();
      }
    }
    
    return false;
  }
  
  return true;
}

function addFastenalPart() {
  fastAdd.qtyPkg = "1";
  fastAdd.description = "Custom Fastenal Part Number";
  fastAdd.price = "0";
  fastAdd.partId = "";
  
  var fastQty = document.getElementById("fastQty");
  var submit = document.getElementById("fastSubmit");
  
  fastQty.removeAttribute("disabled");
  submit.removeAttribute("disabled");
  fastQty.focus();
  
  document.getElementById("fastDescription").value = fastAdd.description;
  document.getElementById("fastQtyPkg").value = "NA";
  document.getElementById("fastPrice").value = "NA";
}

function addCustomerPart() {
  fastAdd.qtyPkg = "1";
  fastAdd.description = "Customer Part Number";
  fastAdd.price = "0";
  fastAdd.partId = "";
  
  var fastQty = document.getElementById("fastQty");
  var submit = document.getElementById("fastSubmit");
  
  fastQty.removeAttribute("disabled");
  submit.removeAttribute("disabled");
  fastQty.focus();
  
  document.getElementById("fastDescription").value = fastAdd.description;
  document.getElementById("fastQtyPkg").value = "NA";
  document.getElementById("fastPrice").value = "NA";
}

function cancelPart() {
  resetArray();
  setInitialFocus();
}

function ajaxGetProdDescription() {
    var sExec = "OrderPad.ex";
    var sParam = "action=lookup";
    
    var path = setPath( sExec, sParam );
    var params = "add=NO&Sku=" + fastAdd.sku;
    
    var fastQty = document.getElementById("fastQty");
    var submit = document.getElementById("fastSubmit");
    
    dojo.xhrGet( {
        url: path + "&" + params,
        handleAs: "text",
        timeout: 60000,
        load: function(response, ioArgs) {
            eval(response);
            fastQty.removeAttribute("disabled");
            submit.removeAttribute("disabled");
            fastQty.focus();
            return response;
        },
        error: function(response, ioArgs) {
            dojo.byId("fastResponse").innerHTML = "Sorry, there has been an error.";
            console.error("HTTP status code", ioArgs.xhr.status);
            return response;
        }
    } );
}

function ajaxAddProdToCart() {
    if (fastAdd.description == "Custom Fastenal Part Number") {
        var sExec = "OrderPad.ex";
        var sParam = "action=add";
        var path = setPath( sExec, sParam );
        var params = "add=YES&Sku=" + fastAdd.sku + "&Quantity=" + fastAdd.qty + "&CustomType=Fastenal";
    } else if (fastAdd.description == "Customer Part Number") {
        var sExec = "OrderPad.ex";
        var sParam = "action=add";
        var path = setPath( sExec, sParam );
        var params = "add=YES&Sku=" + fastAdd.sku + "&Quantity=" + fastAdd.qty + "&CustomType=Customer";
    } else {
        var sExec = "products.ex";
        var sParam = "dispatch=addToCart";
        var path = setPath( sExec, sParam );
        var params = "productDetailId=" + fastAdd.partId + "&qty" + fastAdd.partId + "=" + fastAdd.qty;
    }
    
    var fastQty = document.getElementById("fastQty");
    var submit = document.getElementById("fastSubmit");
    
    dojo.xhrGet( {
      url: path + "&" + params,
      handleAs: "text",
      timeout: 60000,
      load: function(response, ioArgs) {
        resetArray();
        ajaxUpdateCart();
        fastQty.setAttribute("disabled","disabled");
        submit.setAttribute("disabled","disabled");
        return response;
      },
      error: function(response, ioArgs) {
        dojo.byId("fastResult").innerHTML = "<font style='color:red;'>An error occurred updating your shopping cart.  Try again.</font>";
        console.error("HTTP status code", ioArgs.xhr.status);
        return response;  
      }
    } );
}

function ajaxUpdateCart() {
    var sExec = "ShoppingCart.ex";
    var sParam = "printable=true";
    var path = setPath( sExec, sParam );

    dojo.xhrGet( {
      url: path,
      handleAs: "text",
      timeout: 60000,
      load: function(response, ioArgs) {
              dojo.byId("shoppingCartContainer").innerHTML = response;
              updateCartPopup(SITE_ROOT + 'ShoppingCart.ex?type=display');
              return response;
            },
      error: function(response, ioArgs) {
        alert(response);
               dojo.byId("fastResponse").innerHTML = "<font style='color:red;'>An error occurred updating your shopping cart.  Try again.</font>";
               console.error("HTTP status code", ioArgs.xhr.status);
               return response;  
             }
    } );
}