
/*
 * Mechanism to assign window.onload a dynamic list of functions.
 *
 * Adding a new function (e.g. myNewFunction()) to the list:
 * window.onload = makeDoubleDelegate(window.onload, myNewFunction );
 *
 * Borrowed (by serdioue) from
 * http://blog.roberthahn.ca/articles/2007/02/02/how-to-use-window-onload-the-right-way/
 *
 */
function makeDoubleDelegate(function1, function2) {
    return function() {
        if (function1)
            function1();
        if (function2)
            function2();
    }
}

window.onload = makeDoubleDelegate(window.onload, shoppingBagHandler);
 
//************shopping bag functionality*******************
function shoppingBagHandler() {
var pageUrl = window.location.href
//    if(!window.navigator.cookieEnabled && pageUrl.indexOf("cookieError")==-1){           
//    window.location.href = "/agshop/html/cookieError.jsf"    
//    return false;
//    }
  setNumItemsInBagMsg();
  renderAddToWithListOrGCRegistryLink();
  if(!document.getElementById("fragment:shoppingBag:bagConfirmation")) return  
  if(!readCookie("addedAGshop")) return //if cookie is not present, don't show drawer  
  findContent()
	myFadeSize = new fx.FadeSize('fragment:shoppingBag:bagConfirmation', {duration: 400})
	myHeight = new fx.Height('fragment:shoppingBag:bagConfirmation', {duration: 500})
	myFadeSize.hide()
	myHeight.hide()
	positionBag()
	myFadeSize.toggle("height")
  eraseCookie("addedAGshop") //delete cookie to prevent showing drawer more than once  
  if(window.clearFieldValues){
  window.clearFieldValues();
  }
}

document.documentElement.onclick = function(){hideCart()}

function hideCart(){
  if(!document.getElementById("fragment:shoppingBag:bagConfirmation")) return
	if(document.getElementById("fragment:shoppingBag:bagConfirmation").style.visibility == "visible"){
		myFadeSize.toggle('height');
    setTimeout("pageDisplay(10,'visible')",200)//reset content display; delay to sync up with bag
	}
}
function positionBag(){
	var shopStatus = document.getElementById("shopStatus")
	var bagConfirm = document.getElementById("fragment:shoppingBag:bagConfirmation")
	var shopHeight = parseInt(shopStatus.offsetHeight)
	var confirmTop = shopHeight - 1 
	bagConfirm.style.top = confirmTop + "px"
	pageDisplay(24,'hidden')//set content display to avoid image overlap and hide pesky dropdowns
}


function pageDisplay(margin,toggle){ 
  if(brandContent || !isIndex) return //only modify page display if branding content is not present on index page
  if(document.getElementById("ThumbnailDetails")){//hide pesky dropdowns
  	var filterForm = document.getElementById("ThumbnailDetails")
    filterForm.style.visibility = toggle
  }
  content.style.marginTop = margin + "px" //shift content to avoid image overlap issue
}


var brandContent = null 
var content = null
var isIndex = false
function findContent(){//determine relevant elements needed for modifying page display
	var pageType = document.body.className
  if(pageType != "indexPage" && pageType != "indexMultiPage") return //only necessary for index pages
  isIndex = true
  var divElements = document.getElementsByTagName("div")
  for(var i=0;i < divElements.length;i++){
  	if(divElements[i].className == "content") content = divElements[i]
    if(divElements[i].className == "brandContent") brandContent = divElements[i]
    if(brandContent && content) break
  }
}


//generic cookie functions (create, read, delete)
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


//************popups*******************
function openAgeGrade(){//delegate to generic popup management
	openSupplPop("/static/popups/ageGrade.html")
}

var supplPop = null //store supplemental window handle
function openSupplPop(URL,w,h){
	if (supplPop && !supplPop.closed){//close existing window first
    closeSupplPop();
  }
  //if width and height are not explicit, use default values
  var width
  var height
  if(w) width = w
  else width = "400"
  if(h) height = h
  else height = "400"
  
  //open new popup, store in handle variable and set focus
  supplPop=window.open(URL,"supplPop","scrollbars=yes,resizable=yes,width="+width+",height="+height+",left=0,top=0");
  supplPop.focus();
}

function closeSupplPop() {
	//close existing window
  if(supplPop && !supplPop.closed) {
    supplPop.close()
    supplPop = null
  }
}

/* Uses the value of the BAG_COUNT cookie to
 * set the text contained within
 * the <span id="numItemsInBagSpan"></span>
 * This function is meant to be run as a part of the
 * onload() function chain.
 */
function setNumItemsInBagMsg() {
  var bagCount = readCookie("BAG_COUNT");
  if (bagCount == null) {
      bagCount = 0;	
  }
    if( !/^[0-9]+$/.test(bagCount)){   // This condition for shopping bagcount vulnerability
      bagCount = 0;	
  }
  var itemLabel = null;
  if (bagCount == 1) {
     itemLabel = "item";	
  } else {
     itemLabel = "items";
  }
  
  var numItemsInBagMsg = bagCount + " " + itemLabel;
  var numItemsInBagSpan = document.getElementById("numItemsInBagSpan");
  if (numItemsInBagSpan != null) {
    numItemsInBagSpan.innerHTML = numItemsInBagMsg;
  }
}

function renderAddToWithListOrGCRegistryLink() {
  var wishListOrGCRegistrySpan = document.getElementById("wishListOrGCRegistrySpan");
  if (wishListOrGCRegistrySpan == null) {
    //
    // Don't do anything unless <span id="wishListOrGCRegistrySpan"> is found.
    //
    return;
  }
  if (readCookie("LOGGEDIN")) {
    //
    // If logged-in, show "Add to Gift Registry" unless addToGCRegistryLink element
    // is found.
    //
    if (document.getElementById("addToGCRegistryLink") == null) {
        wishListOrGCRegistrySpan.innerHTML = "<li class=\"giftReg\"><a href=\"#\" onclick=\"getSelectedItemsSPP('giftregistry',event)\">Add to Gift Registry</a></li>";
    }
  } else {
    //
    // If not logged-in, show "Add to With List" unless addToWishListLink element
    // is found.
    //
    if (document.getElementById("addToWishListLink") == null) {
        wishListOrGCRegistrySpan.innerHTML = "<li class=\"wish\"><a href=\"#\" onclick=\"getSelectedItemsSPP('wishlist',event)\">Add to Wish List</a></li>";
    }
  }
}