// Cart.js
//-----( @ShoppingCart )---------------------------------------
var ShoppingCart = {
        showLocationAndSublocation : false,
	form: Object,
	init: function() {
		ShoppingCart.form = $("updateCart");
		if (ShoppingCart.form) {
			Event.observe(ShoppingCart.form, "submit", ShoppingCart.updateCart, false);
		}
		if($('showLocations') != null && $('showLocations').value == "true")
                {
                    ShoppingCart.showHideLocations();
                }
	},
  updateCart: function(ev) {
  		//alert("cart update function");
		var allNodes = document.getElementsByClassName("cartQtyTextBox");
    for (i=0; i<allNodes.length; i++) {
			qty = allNodes[i].value;
			var num = parseInt(qty);
	    
			if (isNaN(qty) || qty < 0) {
				alert("Enter a valid value for quantity.");
				allNodes[i].focus();
				Event.stop(ev);
			}
    }
  },
  empty: function(url) {
		var alertMsg = "Are you sure you want to empty your cart?";
		if (confirm(alertMsg)) { gotoUrl(url); updateCartPopup(SITE_ROOT + 'ShoppingCart.ex?type=display') }
  },
  remove: function(url) {
		var alertMsg = "Are you sure you want to remove this line item?";
		if (confirm(alertMsg)) { gotoUrl(url); updateCartPopup(SITE_ROOT + 'ShoppingCart.ex?type=display'); }
  },
    addLocations: function() {
      var classes = document.getElementsByClassName("cartLocation");
      for(i=0;i<classes.length;i++) {
        classes[i].style.display = "block";
      }
    },
    showHideLocations: function() {
      if(ShoppingCart.showLocationAndSublocation) {
        var classes = document.getElementsByClassName("cartLocation");
        for(i=0;i<classes.length;i++) {
          classes[i].style.display = "none";
        }
  
        if(document.getElementById('showHideLocations') != null){
          document.getElementById('showHideLocations').value = "Show Locations";
          ShoppingCart.showLocationAndSublocation = false;
        }
      }
      else {
        var classes = document.getElementsByClassName("cartLocation");
        for(i=0;i<classes.length;i++) {
          classes[i].style.display = "block";
        }
        
        if(document.getElementById('showHideLocations') != null) {
          document.getElementById('showHideLocations').value = "Hide Locations";
          ShoppingCart.showLocationAndSublocation = true;
        }             
      }        
    }    
};

// go to a location
function gotoUrl(url) {
	window.location.href = url;
}

function setCart(aForm) {
    var valid = false;

    for(i = 0; i < document.forms.length; i++) {
        if (document.forms[i].addThis) {
            if ((parseFloat(document.forms[i].fldQty.value) > "0") && (document.forms[i].fldQty.value.length != 0)) {
                valid = true;
                updateCart(document.forms[i]);
            }
            else {
                if (!valid)
                    valid = false;
            }
        }    
    }
    
    if (!valid) {
        document.getElementById(aForm.hidDivResult.value).innerHTML = "<font style='color:red;'>You must enter a quantity to add to the cart.</font>";
    } else {
        document.getElementById(aForm.hidDivResult.value).innerHTML = "<font style='color:green;'>Items successfully added to cart.</font>";
    }
}

function updateCart( aForm) {
  //alert("Ajax update cart");
  var sProductDetailId = aForm.hidProdDet.value;
  var sQty = aForm.fldQty.value;
  var sQtyPerPkg = aForm.hidQtyPerPkg.value;
  var sIsAvailableOnline = aForm.hidIsAvailable.value;
 
   if (document.getElementById) {
    var cartErrors = document.getElementById(aForm.hidCartErrorId.value);
    
    if (cartErrors != null && sQty != null) {
    
      if (isNaN(parseInt(sQty))) {
	  cartErrors.innerHTML = "<ul><h4>The following errors occurred</h4><li>Quantity must be numeric</li><ul>";
	  cartErrors.style.display = "block";
          fixSubmit(aForm);
	  
	  return false;
      } else if ((sQty % 1) != 0) {
	  cartErrors.innerHTML = "<ul><h4>The following errors occurred</h4><li>Quantity must be an integer</li><ul>";
	  cartErrors.style.display = "block";
           fixSubmit(aForm);
	  
	  return false;
      }else if (sQty <= 0) {
	  cartErrors.innerHTML = "<ul><h4>The following errors occurred</h4><li>Quantity must be greater than zero</li><ul>";
	  cartErrors.style.display = "block";
           fixSubmit(aForm);
	  
	  return false;
      }
      
    }   
    cartErrors.style.display = "none";
    }

  var sExec = "products.ex";
  var sParam = "dispatch=addToCartSingleSku";
  var path = setPath( sExec, sParam );
  var params = "productDetailId=" + sProductDetailId + "&qty=" + sQty + "&qtyperpkg=" + sQtyPerPkg + "&isAvailableOnline=" + sIsAvailableOnline;
  
  //alert("final path: " + path + "&" + params);

  dojo.xhrGet( {
      url: path + "&" + params,
      handleAs: "text",
      timeout: 60000,
      load: function(response, ioArgs) {
              updateCartPopup(SITE_ROOT + 'ShoppingCart.ex?type=display');     //update the cart popup as well
              Popup.hide('linkdiv' + aForm.name,'div' + aForm.name);
              fixSubmit(aForm)
              return response;
            },
      error: function(response, ioArgs) {
               dojo.byId(sDivResult).innerHTML = "<font style='color:red;'>An error occurred updating your shopping cart.  Try again.</font>";
               console.error("HTTP status code", ioArgs.xhr.status);
               showDiv(sDivResult);
               return response;  
             }
  } );
  
   
    
} //end updateCart

function clearErrorDisplay(cartErrorId){
 if (document.getElementById) {
    var cartErrors = document.getElementById(cartErrorId);
    cartErrors.style.display = "none";
    
}
}

function showDiv( p_sDivName ) {
  var aDiv = document.getElementById(p_sDivName);
  aDiv.style.display = "block";
}

function hideDiv( p_sDivName ) {
  var aDiv = document.getElementById(p_sDivName);
  aDiv.style.display = "none";
}

function fixSubmit(aForm) {
  for (var i=0;i<aForm.length;i++) {
    if (aForm[i].type == 'submit') {
        if (aForm[i].disabled == true)
            aForm[i].disabled = false;
        else 
            aForm[i].disabled = true;
    }
  }
}

/******************************
****** Cart Summary Code ******
******************************/

var globalCurrent;
var globalRelated;

// Update shopping cart popup after user updates the cart
function updateCartPopup(file) {
  dojo.xhrGet({url:file,
	       handleAs: "text",
	       load: function(response, ioArgs) {
		    //console.log(response);
		    var test = document.getElementById("cartContainer");

		     var cartContainer = document.getElementById("cartContainer");
		     var cartPopup = document.getElementById("cartPopup");
		     var separator = "-------separator------";
		     var l1 = response.indexOf(separator);
		     var content1 = response.substring(0, l1);
		     var content2 = response.substring(l1 + separator.length);
		     cartPopup.innerHTML = content2;
		     cartContainer.setAttribute("class","cartFull");
    
		     var myNode = document.createElement("div");
		     myNode.innerHTML = content1;
		    
		     /*if (!document.all) {
				cartContainer.innerHTML = content1;	
		     } else {
				// for ie do not change the replace the li item directly, but rather change its content and the id
				cartContainer.childNodes[0].innerHTML = myNode.childNodes[0].innerHTML;
				cartContainer.childNodes[0].setAttribute("id", myNode.childNodes[0].getAttribute("id"));
		     }*/
		     cartContainer.innerHTML = content1;
			
		     if (document.getElementById("cartEmpty") != null) {
		      var emptyIcon = document.getElementById("cartEmpty");
		      emptyIcon.id = "cartFull";
		    }
		    
		    document.getElementById("mainCartContainer").onmouseout = hideCartPopup;
		    document.getElementById("cartPopup").onmouseout = hideCartPopup;
	}
    });
}

// Clear cart popup content
function clearCartPopup() {
    
    if (document.getElementById("cartPopup") != null) {
        var cartPop = document.getElementById("cartPopup");
        
        cartPop.innerHTML = "Your Shopping Cart is empty.";
        
        var count = document.getElementById("cartIconCount");
        count.innerHTML = "";
    }
}

// Determine if cart summary should be shown after brief delay
function showCartPopup(event) {
    if (!preventCartState) {	    
	    document.onmousemove = determineCurrent;
    
	    timer = setTimeout("displayCartPopup()", 500);
    }
}

// Update global mouseover element reference and 
function determineCurrent(event) {
    
    if (window.event) {
	globalCurrent = this;
	globalRelated = window.event.toElement;
	
	if (globalCurrent != null && globalRelated != null) 
	  console.log("Current: " + globalCurrent.id + " Related: " + globalRelated.id + "/n");
    } else {
	globalCurrent = event.currentTarget;
	globalRelated = event.relatedTarget;
	
	if (globalCurrent != null && globalRelated != null)
	  console.log("Current: " + globalCurrent.id + " Related: " + globalRelated.id + "/n");
    }
    
    if (window.event) {
        current = this;
        related = window.event.toElement;
    } else {
        current = event.currentTarget;
        related = event.relatedTarget;
    }
}

// Show the cart summay popup
function displayCartPopup(event) {
    document.onmousemove = null;
    
    if ( (globalCurrent.id == "cartPopup" || globalCurrent.id == "cartContainer")
		|| contains(globalCurrent, document.getElementById("cartContainer"))
		   || (current.id == "cartContainer") || contains(current, document.getElementById("cartContainer")) ) {	
	
	if (document.getElementById("cartPopup") != null
		&& document.getElementById("cartContainer") != null
		    && document.getElementById("iconCartLink") != null
			&& document.getElementById("header") != null) {
      
        var cartContainer = document.getElementById("cartContainer");
          
          var bgImage = getStyle(document.getElementById('cartContainer'),'backgroundImage');
          Popup.Dropdown('cartContainer','cartPopup',false,true);
          cartContainer.style.backgroundImage = bgImage;
	}
    }
    
    setTimeout("checkCurrentElement", 1000);
}

// Determine if mouse is not over cart summay containers then hide the cart summary if so
function checkCurrentElement() {
    document.onmousemove = determineCurrent;
    
    if (document.getElementById("cartPopup") != null
	    && document.getElementById("cartContainer") != null
		&& document.getElementById("cartPopTopBorder") != null) {
		
		    var cartPop = document.getElementById("cartPopup");
		    var cartContainer = document.getElementById("cartContainer");
		    //var cartSummaryBack = document.getElementById("cartPopTopBorder");
		    
		    if (globalCurrent != cartPop 
			    && globalCurrent != cartContainer 
				&& globalCurrent != document.getElementById("mainCartContainer") ) {
				
			cartPop.className = 'hideCart';
			cartContainer.className = 'cartContainerOff';
			//cartSummaryBack.style.display = "none";
		    } else {
			displayCartPopup();
		    }
    }
    
    document.onmousemove = null;
}

// Hide the cart popup if mouse is not in the popup after given amount of time
function hideCartPopup(event) {
    clearTimeout(timer);
    
    if (window.event) {
        current = this;
        related = window.event.toElement;
    } else {
        current = event.currentTarget;
        related = event.relatedTarget;
    }
    
    if (document.getElementById("cartPopup") != null 
	    && document.getElementById("cartContainer") != null 
		&& document.getElementById("mainCartContainer") != null ) {
			    
		    var cartPop = document.getElementById("cartPopup");
		    var cartPopBar = document.getElementById("cartContainer-hide-me");
		    var cartContainer = document.getElementById("cartContainer");
		    var cartHolder = document.getElementById("mainCartContainer");
        
		    if ( (related != cartHolder && related != cartPop) 
			    && related != cartContainer && related != cartPopBar
				&& ( !contains(cartHolder, related) && !contains(cartContainer, related) && !contains(cartPop, related) ) ) {
		    
          var bgImage = getStyle(document.getElementById('cartContainer'),'backgroundImage');
          Popup.Dropdown('cartContainer','cartPopup',false,false);
          cartContainer.style.backgroundImage = bgImage;
		    }
    }
}

// Return true if node a contains node b
function contains(a, b) {

    if (a != null & b != null) {
  
        while (b.parentNode) {
    
            if ((b = b.parentNode) == a) {
                return true;
            }
        }
    }
    return false;
}
