/* Collections Javascript v 1.0.0  */
//relocating the selAll and delSelAll click functions to the top of colections.js to fix a bug in Safari
$(document).ready(function(){
fixInfoHeight();
	// function for times where the customer has the option to select all items with one click
		$('.selAll').click(function(){
			$('.qty input.qtyNo').each(function(){						  
				if(  $(this).attr("disabled")!=true ){
					$(this).val(1);	
				}
			});
		});
	
		// de-select all items with one click
		$('.deselAll').click(function(){
			$('.qty input.qtyNo').each(function(){
			 if($(this).attr("disabled")!=true){		
					$(this).val(0);	
				 
				}
			});			  
			$('ul.attribute li').removeClass('active');
			$('span.added').remove();
		});
		$.fn.clearField = function() {
	var regExp = new RegExp("^[0-9]{1,2}$");
	return this.focus(function() {				   
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( (!this.value.length) || (!this.value.match(regExp)) ){
			this.value = this.defaultValue;
		}
	});
};	

});
var productAttrName="";
var isApple=false;
if (navigator.appVersion.indexOf('Apple') != -1){
isApple=true;
}

var INSURANCE_B2B=11201;
if(isApple){
   var partNumberCollection;
   var imagePath;
}
 var SPU_TURNED_ON=false;
var SELECTED_STORE_COOKIE=false;
if(getStoreId()=='10161') {
 	SPU_TURNED_ON=true;
 	SELECTED_STORE_COOKIE=true;
}
var omniPageName='Collections Page';
 
var omniCollectionCartPageName;
var omCollections;

var collectionProductPartNumbers= partNumberCollection+';';

var  singleSelectionMissing='<h2>Add to Cart</h2><p>Select the [specific attribute] before you add to cart.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  multipleSelectionMissing='<h2>Missing Selections</h2><p>The items you are trying to add to cart require selections. Please see individual items for details.</p><img class="cancelMod" alt="OK"src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  selectQuantity='<h2>Add to Cart</h2><p>Please specify the quantity  before adding to cart.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  selectStoreForSPU='<h2>Select Store<h2> <p>Please select the store for product pick up before adding to the cart.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';

var  diffrentArrivalMethod='<h2>Different Arrival Method</h2><p>The items you are trying to add to cart have different arrival methods.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  spuErrorMethod='<h2>Not Available For Store Pickup</h2><p>The items you are trying to add to cart are not available for pick up at selected store.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  spuOrderErrorMethod='<p>The items you are trying to add to order are not available for pick up at selected store.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';

var  outOfStockMultiple='<h2>Out Of Stock</h2><p>Sorry, the item(s) you are trying to add to the Shopping Cart are currently out of stock. Please try again later.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  genericErrorMessage='<h2>Error</h2><p>Sorry, the item(s) you are trying to add to the Shopping Cart can not be added. Please try again later.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';

var  wishListClicked='<h2>Add to Wishlist</h2><p>Please make a selection before adding to Wishlist.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  selectQuantityWishlist='<h2>Add to Wishlist</h2><p>Please specify the quantity (Qty) before adding to wishlist.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  wishlistSingleMissing='<h2>Add to Wishlist</h2><p>Select the [specific attribute] before you add to wishlist.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  wishlistMultiMissing='<h2>Missing Selections</h2><p>The items you are trying to add to wishlist require selections. Please see individual items for details.</p><img class="cancelMod" alt="OK"src="'+imagePath+'img/buttons/okay_btn.gif" />';

var  saveForLaterClicked='<h2>Add to Save for Later</h2><p>Please make a selection before adding to Add to Save for Later list.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  selectQuantitySaveForLater='<h2>Add to Save For Later</h2><p>Please specify the quantity (Qty) before adding to save for later.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
 var saveForLaterSingleMissing='<h2>Add to Save for Later</h2><p>Select the [specific attribute] before you add to save for later.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  saveForLaterMultiMissing='<h2>Missing Selections</h2><p>The items you are trying to add to save for later require selections. Please see individual items for details.</p><img class="cancelMod" alt="OK"src="'+imagePath+'img/buttons/okay_btn.gif" />';

var  giftRegistryClicked='<h2>Add to Gift Registry</h2><p>Please make a selection before adding to Gift Registry.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  selectQuantityRegistry='<h2>Add to Gift Registry</h2><p>Please specify the quantity (Qty) before adding to registry.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  registrySingleMissing='<h2>Add to Gift Registry</h2><p>Select the [specific attribute] before you add to registry.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  registryMultiMissing='<h2>Missing Selections</h2><p>The items you are trying to add to registry require selections. Please see individual items for details.</p><img class="cancelMod" alt="OK"src="'+imagePath+'img/buttons/okay_btn.gif" />';

var  giveTogetherClicked='<h2>Add to Give Together</h2><p>Please make a selection before adding to Give Together.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  selectQuantityGT='<h2>Add to Give Together</h2><p>Please specify the quantity (Qty) before adding to Give Together.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  GTSingleMissing='<h2>Add to Give Together</h2><p>Select the [specific attribute] before you add to Give Together.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  GTMultiMissing='<h2>Missing Selections</h2><p>The items you are trying to add to Give Together require selections. Please see individual items for details.</p><img class="cancelMod" alt="OK"src="'+imagePath+'img/buttons/okay_btn.gif" />';



var addToCartErrorMessageStart='<h2>Error</h2><p>The following issues are preventing your item(s) from being added to the Shopping Cart.';
var addToCartErrorMessageEnd='</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  overSizeDelivery='<div id=collOver><div class=tab>Oversized Item - Special Delivery Required</div><div class=sumMsg><p>Delivery fee charged: This item is oversized and requires delivery instead of standard shipping. The delivery fee will be determined by the delivery location and the weight and dimension of the item.</p><p>The delivery fee will be displayed after you select Add to Cart, provide your ZIP Code and proceed to the Shopping Cart.</p>	<p><strong>Save on Delivery Costs:</strong> You may be able to pick up this item in a Sears store, which would eliminate delivery fees. The Pick Up option varies by store and will only appear if it\'s available for this item.</p></div></div>';
//MyGofer change - Messages to be displayed for error condition whern 'Add to order' button is clicked -Start
var  AddToOrderSelectQuantity='<h2>Add to Order</h2><p>Please specify the quantity (Qty) before adding to order.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  AddToOrderSingleSelectionMissing='<h2>Add to Order</h2><p>Select the [specific attribute] before you add to order.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  AddToOrderMultipleSelectionMissing='<h2>Missing Selections</h2><p>The items you are trying to order require selections. Please see individual items for details.</p><img class="cancelMod" alt="OK"src="'+imagePath+'img/buttons/okay_btn.gif" />';
//MyGofer change - Messages to be displayed for error condition whern 'Add to order' button is clicked -End
//MyGofer change - Messages to be displayed for error conditions when 'Add to shopping list' button is clicked  - Start
var  selectQuantityShoppingList='<h2>Add to Shopping List</h2><p>Please specify the quantity (Qty) before adding to shopping list.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  shoppingListSingleSelectionMissing='<h2>Add to Shopping List</h2><p>Select the [specific attribute] before you add to shopping list.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
var  shoppingListMultipleSelectionMissing='<h2>Missing Selections</h2><p>The items you are trying to add to shopping list require selections. Please see individual items for details.</p><img class="cancelMod" alt="OK"src="'+imagePath+'img/buttons/okay_btn.gif" />';
var makeShoppingListSelection='<h2>Add to Shopping List</h2><p>Please select a shopping list.</p><img class="cancelMod" alt="OK" src="'+imagePath+'img/buttons/okay_btn.gif" />';
//MyGofer change - Messages to be displayed for error conditions when 'Add to shopping list' button is clicked  - End
var cartException = "3";
var cartExceptionMessage = errorMessageString;
if(errorMessageString !="")
{
    /*The exception message was picked from the errormessagescart.jspf*/
    cartException = "1";
 }
var spuError=0;
var outOfStockError=0;
var itemsAddedOffset;
var catentryError=0;
var arrivalMethodError=0;
var saveStoryArray=[];
var catEntryArray=[];
var quantityArray=[];
var parentCatEntryArray=[];
var orderItemArray=[];
var orderID;
var optionsExist=false;

var totalAddedItems=0;
var totalCartSum=0;
var totalSavings=0;

var leftVal = 0;
var topVal= 0;
var tempOrderItemID=0;
var tempCatentryID=0;
var tempQuantity=0;
var regPrice=0;
var salePrice=0;
var bundleIndicator=0;
var softlineIndicator=0;
var shipV=0 ;
var deliveryV=0  ;
var pickupV =0;
var itemOfferPrice=0;
var itemRegPrice=0;
var productCountZero=false;	



$(function(){

 

    $('.buttons .checkOut').hide();
	 
	setRegPrice();
	var tmrOpts;
	var tmrList;
	var throwErr;
	
	$(".collItm input, .upsell div.pro input, div.qView input.qv").clearField();
    $('.collItm input.qtyNo').val(0);
    $('.pro input.qtyNoC').val(0);
    if(bundleIndicator==1){
	       $('.subTot .summary .total').hide(0);
	       $('.collItm input.qtyNo').val(1);
	       var bundleTotal = $('.qty input.qtyNo').length;
	        $('.summary span.tot').html(bundleTotal);
	        getBundleTotalPrice();
       }
    
   
	var saveListCode = '<ul id="saveToOpts">\n'
		saveListCode += '<li><a href="javascript:;">Save to Wishlist</a></li>\n'
		saveListCode += '<li><a href="javascript:;">Save to Registry</a></li>\n'
		saveListCode += '<li><a href="javascript:;">Save for Later</a></li>\n'
		saveListCode += '<li><a href="javascript:;">Add to Give Together</a></li>\n'
		saveListCode += '</ul>';
	
	 
			
	$('body').append(saveListCode); 
	$('ul#saveToOpts, .collWarn').hide(0);
	
	showPopup();
	
	 $('img.saveList').click(function () {									
			var offsetList = $(this).offset();
			if($('body').hasClass('collection')){
				$('ul#saveToOpts').show().css({top:offsetList.top+20, left:offsetList.left+2});
			}else{
				$('ul#saveToOpts').show().css({top:offsetList.top+9, left:offsetList.left+0});
			}
		});
		
		var tmrList = setTimeout(function(){
			$('ul#saveToOpts').fadeOut('fast');		
		},500);	
		
		$("ul#saveToOpts, img.saveList").hover(function() {
			clearTimeout(tmrList);	
		}, function() {
			tmrList = setTimeout(function(){
				$('ul#saveToOpts').fadeOut('fast');		
			},500);	
		});	
	 
	 
 $('#saveLater').click(function(){
		var off = $(this).offset();
		var ht = $(this).height();
		var wd = $(this).width()
		var timer1 = 0;
		var dd = $('#saveToOpts');
		if(dd.length == 0){
			var code = $('\n'
			+ '<ul id="saveToOpts" style="display: none;">\n'
			+ '	<li><a href="javascript:;">Save to Wishlist</a></li>\n'
			+ '	<li><a href="javascript:;">Save to Registry</a></li>\n'
			+ '	<li><a href="javascript:;">Save for Later</a></li>\n'
			+ '	<li><a href="javascript:;">Add to Give Together</a></li>\n'
			+ '</ul> \n').appendTo('body').fadeIn(500).css({top:off.top+ht, left:off.left+3});
			code.hover(function(){
				clearTimeout(timer1)					
			},function(){
				timer1 = setTimeout(function(){
					code.fadeOut(500,function(){$(this).remove()});							
				},600)
			});
			var actions = code.find('a');
			actions.click(function(){
				if($('#quant').val() == 0){
					qe_popup.css({top:off.top, left:off.left}).find('.content').append('<h2>Save to List</h2><p>Please specify the quantity (Qty) before adding to wishlist.</p><img src="http://c.sears.com/1112/img/buttons/okay_btn.gif" alt="OK" class="cancelMod"/>')
					qe_popup.show().find('.cancelMod').click(function(){
						qe_popup.hide().find('.content').empty();										
					})
				}				   
			});
		}else{
			if(dd.is(':visible')){
				dd.fadeOut(500);	
			}else{
				dd.fadeIn(500);	
			}	
		}
		return false;
	});
 
  
		$('ul#saveToOpts li').click(function(){	
		  _global = $(this).offset();
		var typeOfAction=$(this);
		var actionValue= $(this).find("a").text();
		if(actionValue=='Save for Later'){
		saveForLater();
		}
		if(actionValue=='Save to Wishlist'){
		addToWishList();
		}
		 if(actionValue=='Save to Registry'){
		   addToRegistry();
		}
		 if(actionValue=='Add to Give Together'){
		   addToRegistry("gt");
		}
		 									  
	});
	 
	 $('.productTitle').click(function(){
	    seteVar41();			
    });	 

	 
		
	 $('.productImage > .thumbWidget img').each(function(){
			if($(this).hasClass('video')){
			$(this).parent().append('<img alt="video icon" src="'+imagePath+'img/icons/product_video_icon.gif" height="10" width="10" class="icon"/>');
			}
		});


	// size selction start
	if( $("body").hasClass('attributes') ){	
		$('ul.sizeDisplay li.small, ul.sizeDisplay li.medium, ul.sizeDisplay li.large, ul.sizeDisplay li.xlarge').hide(0);
		$('ul.attribute li').click(function() {
			$(this).parent().children().removeClass('active');
			$(this).parent().children().find('a').css('background','#d8d8d8');
			$(this).addClass('active');
			$(this).find('a').css('background','#fff');
			var $buttonClass = $(this).find('a').attr('class');
			$(this).parent().prev().find('span').html( $buttonClass );
			$('body').children('.attError').add('.glAttErr').add('.glAttErrBack').remove();
		});
		// checking for multiple attributes
		var checkAllAttr = function(){
			$("ul.attribute").each(function(){
				if( $(this).children().size() == 1 ){
					$(this).prev().find('span').html( $(this).children('li').find('a').attr('class') );
					$(this).children('li').addClass('active').find('a').css('background','#fff');
				}
			});
		}
		checkAllAttr();
	}
 
	//MyGofer change - Method invoked when 'Add to shopping list' button is clicked  - Start
	$('div.subTot img.shoppingListBtn').unbind().click(function() {
		  _global = $(this).offset();
		   callAddtoShoppingList();
        
	});	 
	//MyGofer change - Method invoked when 'Add to shopping list' button is clicked  - End 
	 
	 
	// trigger for when the customer actually clicks on the "Add to Cart" button
	$('div.subTot img.btnAdd').unbind().click(function() {
		  _global = $(this).offset();
		   
		   if(bundleIndicator==1){
		   
		     $('.summary a.itemsAdded').html('Items Added:');
              $(".subTot .tot").html('0');
             }
		   callAddtoCart();
        
	});
	
	// invoke the "Items Added" summary DHTML 'modal'
	$('.itemsAdded').unbind().click(function(){
	 
	itemsAddedOffset=$(this).offset();
	
	var htmlContent=$(this).html();
	 
	 	 
	 	if(totalAddedItems!=null&& totalAddedItems!='' && totalAddedItems>0 && htmlContent!='Bundle Items:'){
	          displayCartSummary();
	   }
	 
	});

   	  $('.oversizedMsg').dynamicPopup({filename:dynamicPopup+'&vName=OversizeDeliveryPopup',contentname:'#collOver',windowWidth:'350px',windowHeight:'235px'});
	 
     var qvImgDim = 248;
	var qvThmbDim = 40;
	var qvThmbDim2 = 100;
	var jspStoreImgDir='';
	
	var itmWgts = $('.productImage');	
	var nonZoom = $('.scrollWsmall');
	var slider = $(itmWgts).find('.slider');
	var slider2 = $(itmWgts).find('.slider2');
	var sliderThumbs = $(slider2).children('img');
	                          	 
	$(slider2).find('img').eq(0).addClass('selected');

	var scrlWgt = $('.scrollWidget');
	var clickIndx=0, clickIndx2=0;
	var curImg = imgArr[clickIndx];
var imgArrLength=imgArr.length;
	 
	if(imgArrLength==1){
	 $('.thumbWidget').hide(0);
	 $('.pImg').hide(0);
	 $('.nImg').hide(0);
	 $('.c_pImg').hide(0);
	 $('.c_nImg').hide(0);
	}
	$(slider).children('img').each(function(i){
		var zImgTemp = imgArr[i];  
		if(zImgTemp.w>2000){zImgTemp.w=2000};
		if(zImgTemp.h>2000){zImgTemp.h=2000};
		/* ========================================================================
		
			For the imgZoom function to work at its best, the maximum zoomed
			image dimension should vary depending on the maximum size of the
			full-resolution image on the Scene7 system. In this EXAMPLE, we
			are passing a hard-coded dimension, because the images are not
			being served from a JSON string. JSON is the preferred method of
			populating the image gallery interface for QuickView and all
			Product pages.
		
		======================================================================== */
		$(this).imgZoomV2({container:'.ztBucket', src:"http://s.sears.com/is/image/Sears/"+zImgTemp+"?hei="+1600+"&wid="+1600+"&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0", hideIt:true});
	});
	
	if($('div#summary').length){
		$('div.ztBucket').css({width:$('div.specs').width(),right:$('div#summary').width()+20});
	}else if($('div#logoHelp').length){
		$('div.ztBucket').css({width:$('div.specs').width(),left:0});
	};
	$(window).resize(function(){
		if($('div#summary').length){
			$('div.ztBucket').css({width:$('div.specs').width(),right:$('div#summary').width()+20});
		}else if($('div#logoHelp').length){
			$('div.ztBucket').css({width:$('div.specs').width(),left:0});
		};
	});
	
	// the following code contains the controls for the image slide show / viewer

	highlightThumb = function(){
		$(sliderThumbs).each(function(){
			$(this).removeClass('selected');
		});
		$(sliderThumbs[clickIndx]).addClass('selected');
	};
	$(".pImg").click(function(){
		clickIndx--;
		if(clickIndx < 0){clickIndx = 0; return false};
		$(slider).animate({left:"-"+(clickIndx*qvImgDim)},250);
		highlightThumb();
		return false;
	});
	$(".nImg").click(function(){
		clickIndx++;
		if(clickIndx >= imgArr.length){clickIndx--; return false};
		$(slider).animate({left:"-"+(clickIndx*qvImgDim)},250);
		highlightThumb();
		return false;
	});
	$(".c_pImg").click(function(){
		clickIndx2--;
		if(clickIndx2 < 0){clickIndx2 = 0; return false};
		$(slider2).animate({left:"-"+(clickIndx2*qvThmbDim)},250);
		return false;
	});
	$(".c_nImg").click(function(){
		clickIndx2++;
		if(clickIndx2 >= (imgArr.length-3)){clickIndx2--; return false};
		$(slider2).animate({left:"-"+(clickIndx2*qvThmbDim)},250);
		return false;
	});
	$(sliderThumbs).each(function(i){
		$(this).click(function(){
			clickIndx = i;
			$(this).siblings().removeClass('selected');
			$(this).addClass('selected');
			$(slider).animate({left:"-"+(clickIndx*qvImgDim)},250);
			return false;
		})
	}); 
});

 function getTotalQuantity(){
  var totalQuantity = 0; 
     $('.collItm input.qtyNo, .pro input.qtyNoC').each(function(){
 		  	if($(this).val()>0 && $(this).attr("disabled")!=true){
		       totalQuantity=totalQuantity+$(this).val();
			}
		});
	 return totalQuantity;
}

	function createFormValues(){
		 
		 catEntryArray=[];
		 quantityArray=[];
		 parentCatEntryArray=[];
		  $('.attError').remove(); 
		 $('.collItm input.qtyNo').each(function(){
		 	if($(this).val()>0 && $(this).attr("disabled")!=true){
					var outOfStock=false; 
					var spuCheck=false;
				 
			  
		 		         quantityArray.push($(this).val());
		 		  	      var y=$(this).parents('.collItm').find("form input") ; 
		 		  	     var currentCatEntryId=y[0].value
		 		   
		 		  	     catEntryArray.push(currentCatEntryId);
		 		  	      var inStock=y[1].value ;
						   
						  if(inStock=='false'){
						 
						  outOfStock=true;
						  
						  }
		 		  	     var storePickUpEligible=y[2].value ;
		 		  	     var options=y[3].value ;
		 		  	     if(options=='true'){
		 		  	         optionsExist=true;
		 		  	     }
		 		  	     var parentCatentryVal=y[5].value ;
		 		  	     parentCatEntryArray.push(parentCatentryVal);
		 		  	    
			 		  	 if(currentCatEntryId==0 || currentCatEntryId=='undefined' || currentCatEntryId==undefined  ){

			 		       // $(this).after('<span class="attError">Make selections</span>');
      							productAttrName=getAttrNames(parentCatentryVal);
                                productAttrName = productAttrName.replace ("Overall ", " ");
                                $(this).after('<span class="attError">Please Select:'+productAttrName+'</span>');
			 		    
			 		        catentryError++;
			 		  	  }
		 		  	     
	 	                if(currentCatEntryId > 0 && (document.addToCart.IndicatorA.value=='ship' || document.addToCart.IndicatorA.value=='delivery' ) && outOfStock==true ){		
                             $(this).after('<span class="attError">Make selections</span>');
  					       outOfStockError++;
			          }		  
		 		  	 if(SPU_TURNED_ON && currentCatEntryId > 0 && arrivalMethodError<=0 && storePickUpEligible=='true' &&  document.addToCart.IndicatorA.value=='pickup' ){
		 		  	    
                             if(storeId=='10161'){
                                  var childPickUpAvl="";
                                  if(typeof itemBeanArray[currentCatEntryId]!='undefined'){
                                    childPickUpAvl=itemBeanArray[currentCatEntryId].pickAvail;
                                  }
                                 
                                 if(childPickUpAvl=="" || childPickUpAvl=="N"){
		 		  	        spuError++;
		 		  	           $(this).after('<span class="attError">This product is not available at the selected store</span>');
		 		  	        // $(this).after('<span class="attError">Make selections</span>');
		 		  	         spuCheck=true;
		 		  	     }
                            }else if(!checkEligForSPUItem(currentCatEntryId,parentCatentryVal) ){
                                spuError++;
                                   $(this).after('<span class="attError">This product is not available at the selected store</span>');
                                // $(this).after('<span class="attError">Make selections</span>');
                                 spuCheck=true;
		 		  	    }
                        }
		 		  	   
		 		  	      if( spuError<= 0 && currentCatEntryId > 0 && outOfStock!=true && !checkfullFilmentChannel(document.addToCart.IndicatorA.value ,inStock,storePickUpEligible)){
		 		  	        $(this).after('<span class="attError">Make selections</span>');
		 		  	       arrivalMethodError++;
		 		  	     
		 		  	    }
		 		  	
		 		  	
		 		  	  
		 		  	    
					 }
					
				}); 
				$('.pro input.qtyNoC').each(function(){
		 		  	if($(this).val()>0 && $(this).attr("disabled")!=true){
		           		    quantityArray.push($(this).val());
		 		    		var y=$(this).parents('.pro').find("form input") ; 
		 		  	        var currentCatEntryId=y[0].value
		 		  	        catEntryArray.push(currentCatEntryId);
		 		  	        var inStock=y[1].value ;
		 		  	        var storePickUpEligible=y[2].value ;
		 		  	        var options=y[3].value ;
			 		  	     if(options=='true'){
			 		  	         optionsExist=true;
			 		  	     }
			 		  	    var parentCatentryVal=y[4].value ;
		 		  	     	parentCatEntryArray.push(parentCatentryVal);
		 		  	       if(currentCatEntryId==0 ){
			 		         $(this).after('<span class="attError">Make selections</span>');
			 		         catentryError++;
			 		  	  }
		 		  	      if(currentCatEntryId!=0 && !checkfullFilmentChannel(document.addToCart.IndicatorA.value ,inStock,storePickUpEligible)){
		 		  	        $(this).after('<span class="attError">Make selections</span>');
		 		  	       arrivalMethodError++;
		 		  	    }
		 		  	    
					 }
					
				}); 
				 
		}
	
function displayErrorMessage(errorMessage){

              $('body').append('<div class="glAttErr">'+errorMessage+'</div>').append('<div class="glAttErrBack"/>');
			  $('.glAttErr').css({top:_global.top,left:_global.left});
			  $('.glAttErrBack').css({width:$('.glAttErr').width()+40,height:$('.glAttErr').height()+41,top:_global.top-10,left:_global.left-10}).bgiframe();
			    $('.glAttErr').click(function(){
			      	$('.glAttErr').remove();
				    $('.glAttErrBack').remove();
				    return false
			     });
}
 
function displayAddToCartPostErrors(failedOrders){
var outOfStockArray=[];
var offlineArray=[];
var noDefaultFulArray=[];
var noPriceArray=[];
var quantityMaxArray=[];
var genericArray=[];
var errorDetail="";
for(var i=0;i<failedOrders.length;i++){  
   if(failedOrders[i].errorCode == '_ERR_OUTOFSTOCK'){
       outOfStockArray.push(failedOrders[i].parentCatentryID);
   }
   else if(failedOrders[i].errorCode=='_ERR_OFFLINE'){
     offlineArray.push(failedOrders[i].parentCatentryID);
   }
    else if(failedOrders[i].errorCode=='_ERR_NO_DEFAULT_FULFILMENT'){
       noDefaultFulArray.push(failedOrders[i].parentCatentryID);
   }
    else if(failedOrders[i].errorCode=='_ERR_NO_PRICE'){
       noPriceArray.push(failedOrders[i].parentCatentryID);
   }
    else if(failedOrders[i].errorCode=='_ERR_QUANTITY'){
       quantityMaxArray.push(failedOrders[i].parentCatentryID);
   }
   else{
   
     if(failedOrders[i].parentCatentryID!=null){
           genericArray.push(failedOrders[i].parentCatentryID);
       } 
   }
}
 
//Out of Stock
var counter=1;
var errorCounter=0;
 
if(outOfStockArray.length >=1){
		errorDetail="<p><b>Following products are out of stock.</b></p>"
             	for(var i=0;i<outOfStockArray.length;i++){
	             var title=  $("input[value="+outOfStockArray[i]+"]").parents().find(" .productTitle").html();  
	        
			     errorDetail=errorDetail+"<p> Item "+counter+"  "+title+" </p>"; 
			     errorCounter++;
			     counter++;
  
		 }
 }
 
 if( offlineArray.length >=1){
 
		errorDetail=errorDetail+"<p><b>Following products are Offline.</b></p>"
		counter=1;
		for(var i=0;i<offlineArray.length;i++){
		 var title=  $("input[value="+offlineArray[i]+"]").parents().find(" .productTitle").html();  
		     errorDetail=errorDetail+"<p> Item "+counter+"  "+title+" </p>"; 
		     counter++;    errorCounter++;
		 }
		      
 }
 if(noPriceArray.length >=1){
		errorDetail=errorDetail+"<p><b>Price is not available for the following products.</b></p>"
		counter=1;
		for(var i=0;i<noPriceArray.length;i++){
		 var title=  $("input[value="+noPriceArray[i]+"]").parents().find(" .productTitle").html();  
		     errorDetail=errorDetail+"<p> Item "+counter+"  "+title+" </p>"; 
		     counter++;    errorCounter++;
		 }  
 }
  if(noDefaultFulArray.length >=1){
			errorDetail=errorDetail+"<p>Default fullfilment is not available for following products.</p>"
			counter=1;
			for(var i=0;i<noDefaultFulArray.length;i++){
			 var title=  $("input[value="+noDefaultFulArray[i]+"]").parents().find(" .productTitle").html();  
			     errorDetail=errorDetail+"<p> Item "+counter+": "+title+" </p>"; 
			     counter++;    errorCounter++;
			 } 
  }
if( quantityMaxArray.length >=1){
		errorDetail=errorDetail+"<p>Quantity > 999 for the following products in the shopping cart.</p>"
		counter=1;
		for(var i=0;i<quantityMaxArray.length;i++){
		 var title=  $("input[value="+quantityMaxArray[i]+"]").parents().find(" .productTitle").html();  
		     errorDetail=errorDetail+"<p> Item "+counter+": "+title+" </p>"; 
		     counter++;    errorCounter++;
		 } 
 }
if(genericArray.length >=1 ){
		errorDetail=errorDetail+"<p>Following prouducts can not be added to cart. Please try againg later. </p>"
		counter=1;
		for(var i=0;i<genericArray.length;i++){
		 var title=  $("input[value="+genericArray[i]+"]").parents().find(" .productTitle").html();  
		     errorDetail=errorDetail+"<p> Item "+counter+":  "+title+" </p>"; 
		     counter++;    errorCounter++;
		 } 
}
 
  
 if(errorCounter>=1){ 
      displayErrorMessage(addToCartErrorMessageStart+errorDetail+addToCartErrorMessageEnd);
    }
}
 

  
 

function removeOrderItemFromArray(orderItemID){
   
var index=orderItemArray.indexOf(orderItemID);
orderItemArray.splice(index,1);
					                  	 
}
 

 
  
 
  //MyGofer change - Method to add items to the shopping list - Start
  function callAddtoShoppingList(checkDiv,type){
  		var ffmt;
	  	 if(type == 'order'){
	  	  	ffmt=document.addToCart.IndicatorA.value;
   			document.addToCart.IndicatorA.value="pickup";
	  	 
	  	 }
		 catentryError=0;
		 createFormValues();
		 if(type == 'order'){
   			document.addToCart.IndicatorA.value=ffmt;	  	 
	  	 }
	  	 var divIdCollectionAddToList=checkDiv;
	  	 var msg;
	  	 if(type=='list')
	  	 {
	  	 	_global = $("a[@id=AddToList_"+checkDiv+"]").offset()
	  	 }
	  	 else
	  	 {
	  	 	_global = $("a[@id=AddToOrder_"+checkDiv+"]").offset()
	  	 }
		
	   	 if(getTotalQuantity()==0){
	   	 	if(type=='list')
	   	 	{
	         displayErrorMessage(selectQuantityShoppingList);
	        }
	        else
	        {
	        	displayErrorMessage(AddToOrderSelectQuantity);
	        }
	 	     return false;
	      }	    
	     else if(catentryError==1){
	     	if(type=='list')
			{	     
	 	      displayErrorMessage(shoppingListSingleSelectionMissing);
	 	    }
	 	    else
	 	    {
	 	    	displayErrorMessage(AddToOrderSingleSelectionMissing);
	 	    }
	 	      return false;
		 }
		 else if(catentryError>=2){
		 	
		 	if(type=='list')
			{
		    	displayErrorMessage(shoppingListMultipleSelectionMissing);
		    }
		    else
		    {
		    	displayErrorMessage(AddToOrderMultipleSelectionMissing);
		    }
		     return false;
		 }else if(spuError>=1){
			  if(type == 'order'){ 
			      displayErrorMessage(spuOrderErrorMethod);
			      spuError=0
			      return false;
			   }
		 }
	 	 var catentryList="";
 		 var quantityList="";
 		 var num=catEntryArray.length;
 	
  		if(type=='list')
  		{
	  	 for (var i=0; i<catEntryArray.length; i++) {
	  		catentryList=catentryList+catEntryArray[i]+"/";
	  		quantityList=quantityList+quantityArray[i]+"/";			
	  	 }
	  	}
		 else
		 {
		 	 for (var i=0; i<catEntryArray.length; i++) {
		 	catentryList=catentryList+catEntryArray[i]+",";
	  		quantityList=quantityList+quantityArray[i]+",";	
	  		}
		 }
		 document.getElementById("quantity_"+checkDiv).value = quantityList;
		 document.getElementById("catentryId_"+checkDiv).value = catentryList;	
		 return true;
		 
  }
  
   
 function callAddtoCart(){
   var errorDisplayed=false;
               if(getTotalQuantity()==0){
                  displayErrorMessage(selectQuantity);
         	       errorDisplayed=true;
         	       return errorDisplayed;
                }
             
               
			if(errorDisplayed==false && SPU_TURNED_ON && !SELECTED_STORE_COOKIE && document.addToCart.IndicatorA.value=='pickup'){
  	         displayErrorMessage(selectStoreForSPU);
         	       errorDisplayed=true;
  	 			   return true;
  	      
  	      }  
                
                
                
                
         createFormValues();	
          if(catentryError==1 && errorDisplayed==false){
         	     // displayErrorMessage(singleSelectionMissing);
 displayErrorMessage(getAddToCartErrorMessageForSoftline(productAttrName));
         	      errorDisplayed=true;
	     }
			    if(catentryError>=2 && errorDisplayed==false){
			     displayErrorMessage(multipleSelectionMissing);
			     errorDisplayed=true;
			    }
            if(outOfStockError>=1 && errorDisplayed==false){
			       displayErrorMessage(outOfStockMultiple);
			        errorDisplayed=true;
			   }
				if(arrivalMethodError>=1 && errorDisplayed==false){
			       displayErrorMessage(diffrentArrivalMethod);
			        errorDisplayed=true;
			   }
	       if(spuError>=1 && errorDisplayed==false){
			       displayErrorMessage(spuErrorMethod);
			        errorDisplayed=true;
			   }
		    catentryError=0;
            outOfStockError=0;			  
			arrivalMethodError=0;
			spuError=0;
		        
			if(!errorDisplayed){
			    //Create form paramters for Either AJAX or Normal Form Submit
				createOmniturepartNumbers();
						    if(optionsExist){
						    createFormParemtersWithOptions();
						    return;
						    // do form submit
						    }
						    else{
						    //call ajax
						      createFormForAjax();
						      return;
						    }
						    
		     
			    }
 
 
 }
 function  createOmniturepartNumbers(){
 
 for (var i=0; i<catEntryArray.length; i++) { 
    var partNumber=  $("input[value="+catEntryArray[i]+"]").parents().find(" .partNumberCollproduct").html();  
	partNumber=jQuery.trim(partNumber);
    collectionProductPartNumbers=collectionProductPartNumbers+partNumber+';';
	}
  trackCollectionProducts(collectionProductPartNumbers);
 }
 
function checkfullFilmentChannel(collectionMethod, inStock, storePickup){
 
		if((collectionMethod=='ship'||collectionMethod=='delivery')&& inStock=='true'){
		return true;
		}
		if((collectionMethod=='pickup')&& storePickup=='true'){
		return true;
		}
		else 
		return false;

}		

function createFormParemtersWithOptions(){
	var catEntryIndex = 1;
	if(document.getElementById('addedItems')){
 	var addHere=document.getElementById('addedItems');
	var newdiv = document.createElement('div');

   for (var i=0; i<catEntryArray.length; i++) { 

      newdiv.innerHTML+="<input id=\"catEntryHidden_" + catEntryIndex + "\" type=\"hidden\" name=\"catEntryId_" + catEntryIndex + "\" value=\"" + catEntryArray[i] + "\" />\n";
	 newdiv.innerHTML+="<input id=\"quantityHidden_" + catEntryIndex + "\" type=\"hidden\" name=\"quantity_" + catEntryIndex + "\" value=\"" + quantityArray[i] + "\" />\n";
	catEntryIndex++;
	}
	 
    addHere.appendChild(newdiv);
	document.addToCart.submit();
	}
 
}


function createFormForAjax(){
		 var catEntryIndex = 1;
		 var parameters="";
		  for (var i=0; i<catEntryArray.length; i++) {
		  parameters=parameters+"&catEntryId_"+catEntryIndex+"="+catEntryArray[i]+"&quantity_"+catEntryIndex+"="+quantityArray[i]+"&parent_catEntryId_"+catEntryIndex+"="+parentCatEntryArray[i];
		  if(storeId=='10161'){
			  var ffm="";
			  var sresDays="";
			  var childCatId=catEntryArray[i];
			  if(typeof itemBeanArray[childCatId]!='undefined'){
			  	ffm=itemBeanArray[childCatId].resFFM;
			  	sresDays=itemBeanArray[childCatId].ldTime;
			  }
			  parameters=parameters+"&ffm_"+catEntryIndex+"="+ffm+"&sresDays_"+catEntryIndex+"="+sresDays;		  
		  }
		 catEntryIndex++;
        }
  
 
var queryString="URL=AJAXResponseView&langId=-1&storeId="+storeId+"&catalogId="+catalogId+parameters+"&IndicatorA="+document.addToCart.IndicatorA.value ;
 
  $.ajax({
  url: "/shc/s/MultipleOrderItemAddCmd",
  data:queryString,
  success: function(msg){
   
     postCartFlow(msg);
   }
 });
   
}

function postCartFlow(msg){
 
   
  
  if(msg!=null && msg!=''&& msg!=' '){
    var myJSONObject= "(" + msg + ")";
    if (!_gc) {
	   var _gc = new Object();
     }  
   _gc.prod = eval(myJSONObject);
    
    var  totalFailure=_gc.prod.totalFailure;
     if(totalFailure=='false'){
         orderID=_gc.prod.addedOrders
		  
         setOrders(_gc.prod.addedOrders);
	 
         setFailedOrders(_gc.prod.failedOrders);
		  
         displayCheckoutButton();
		 	  
         addedSummaryDisplayed();
		   
         //MyGofer change - To display the smartcart animation after adding item(s) to the cart  - Start
         if(document.getElementById("mygofercollection")!=null && document.getElementById("mygofercollection").value== "true"){
         	
         	smartCartAnimation();
         	
         }
         //MyGofer change - To display the smartcart animation after adding item(s) to the cart  - End
        
		if(_gc.prod.totalQuantity!=null && _gc.prod.totalQuantity!=''  && _gc.prod.totalPrice!=null && _gc.prod.totalPrice!='' && storeId!=INSURANCE_B2B){
              updateMiniCartDisplayLink(_gc.prod.totalQuantity,_gc.prod.totalPrice);
         }
	 
	   if(_gc.prod.failedOrders!=null && _gc.prod.failedOrders.length >=1){
	             displayAddToCartPostErrors(_gc.prod.failedOrders);
	         }
       
     }
      if(totalFailure=='true'){
         displayErrorMessage(genericErrorMessage);
     }

   
  }  
}
 

function displayCheckoutButton(){
  
	      $('.subTot .buttons .checkOut').css('display','block');
	      
	   
}


function addedSummaryDisplayed(){

$('.collItm input.qtyNo, .pro input.qtyNoC').each(function() {	
			var  $addedSec = $(this).parent().parent().find('.added');
			var qty = $(this).val(); 
			if(  $(this).attr("disabled")!=true){ 
			 $addedSec.remove();
			 
			if( (this.value == '') || (this.value == 0) ){	
			 
				 $addedSec.remove();
			}else{
				 
					if( $(this).parent().parent().hasClass('upsell') ){
						var bkColor = '#f8f8f8'						
					}else{
						var bkColor = '#ffffff'
					}
					  
					$(this).after('<span class="added"><p>'+qty+' Added</p></span>');	
					 if(!isApple){
                       //$('div.summary').animate({ backgroundColor: "#eff2f5" }, 100).animate({ backgroundColor: "#fff" }, 3000)					   
					   //$(this).parent().parent().animate({ backgroundColor: "#eff2f5" }, 100).animate({ backgroundColor: ""+bkColor+"" }, 3000);	
	               }				 
				}
			}	
			 				
		});
		 
		 getTotalPrice();
		 	 
 }
 
 // function to calculate total price based on an item's qty field being filled in
	 function getTotalPrice(){
    
	  $('.subTot .summary .total').css('display','block');
	 
	    var savings=0;
		var subtot = 0;
		var counter1 = 0;
		var counter2 = 0; 
		  
		 
		$(".collItm").each(function(){
		   
		   var qty = $(this).find("input.qtyNo").val();
		  
		 if( qty!=undefined && qty >0  && $(this).find("input.qtyNo").attr("disabled")!=true){
           var catentry=$(this).find("input[name=currentCatEntryId]").val(); 
	     if(catentry!='undefined' && catentry >0 ){	      		 
				   getPrice(catentry);
				   var offerPrice =itemOfferPrice;
				   offerPrice = parseFloat(offerPrice).toFixed(2);
		           var listPrice= itemRegPrice ;
		           if(listPrice!=null && listPrice!='' ){ 
				            listPrice=parseFloat(listPrice).toFixed(2);
					         if(  Number(listPrice) > Number(offerPrice)){
							 
			                        var diff=listPrice-offerPrice;
								   savings= savings+ Number(qty) * Number(diff) ;
								  
								 
			                }
							
		            }
					subtot += Number(qty)*Number(offerPrice);
				counter1 += Number(qty);
				$(this).find("input.qtyNo").val(0);
				}
			 }
		});
	 
		$(".pro").each(function(){
			var qty = $(this).find("input.qtyNoC").val();
		   
			if(qty!=undefined && qty>0 && $(this).find("input.qtyNoC").attr("disabled")!=true){
		     var catentry=$(this).find("input[name=currentCatEntryId]").val(); 
				    var oqvId = $(this).find("div.qty input").attr('id');
					getPrice(catentry);
				    var offerPrice =itemOfferPrice;
				 	 offerPrice = parseFloat(offerPrice).toFixed(2);
                     var listPrice= itemRegPrice ;
                     listPrice = jQuery.trim(listPrice);
    				if(listPrice!=null && listPrice!=''){ 
			      	  
			            listPrice=parseFloat(listPrice).toFixed(2);
			          
	               if(  Number(listPrice) > Number (offerPrice)){
	                        var diff=listPrice-offerPrice;
						   savings= savings+ Number(qty) * Number(diff) ;
	                }
            }
			subtot += Number(qty)*Number(offerPrice);
			counter1 += Number(qty);
		 
			if( (qty == '') || (qty == 0) ){
				$('#'+oqvId).next().hide();
			}
			}
			  $(this).find("input.qtyNoC").val(0);
		});
		
		if(isI18NConvReq()){
				subtot = Number(fnConSSaving(subtot));
				savings = Number(fnConSSaving(savings));
		}   
	 	 
		totalAddedItems=totalAddedItems+counter1+counter2;
		  
		totalCartSum=totalCartSum+subtot;
			 
		totalSavings=totalSavings+savings;
				
		 		 
				
		$(".subTot .tot").html(totalAddedItems);
		$(".subTot .summary .total .price").html(totalCartSum.toFixed(2));
		
		if(isI18NConvReq()){
			$(".subTot .savings ").hide();
			$(".subTot .savings ").html("your savings: "+i18nCookieData.currencyCode);
			$(".subTot .savings ").show();
			$(".subTot .savings ").append("<span class='price'></span>");
		}
		$(".subTot .savings span.price").html(totalSavings.toFixed(2));
				
				   
	} 

 
// function to calculate total price based on an item's qty field being filled in
function getBundleTotalPrice(){
	    var savings=0;
		var subtot = 0;
	    var totalBundleSum=0;
	    var totalSavings=0;
	$(".collItm").each(function(){
			var qty = $(this).find("input.qtyNo").val();
		 
			 if( qty!='undefined' &&  qty >0  && $(this).find("input.qtyNo").attr("disabled")!=true){
					var catentry=$(this).find("input[name=currentCatEntryId]").val(); 
				  if(catentry==0){
				  
				    catentry=$(this).find("input[name=parentCatentryVal]").val();
				  }
			  
					getPrice(catentry);
					var offerPrice =itemOfferPrice;
					offerPrice = parseFloat(offerPrice).toFixed(2);
						  
					var listPrice= itemRegPrice ;
				  
		           if(listPrice!=null && listPrice!='' && listPrice!=0 ){ 
								            listPrice=parseFloat(listPrice).toFixed(2);
									         if(  Number(listPrice) > Number(offerPrice)){
							                        var diff=listPrice-offerPrice;
												   savings+= Number(diff) ;
							                }
			            }
			       subtot +=  Number(offerPrice);
				   }
             
	});
	
		if(isI18NConvReq()){
					subtot = Number(fnConSSaving(subtot));
					savings = Number(fnConSSaving(savings));
		} 
	
 
	   $(".subTot .summary .bundle .price").html(subtot.toFixed(2));
	   if(isI18NConvReq()){
	   			$(".subTot .savings ").hide();
	   			$(".subTot .savings ").html("your savings: "+i18nCookieData.currencyCode);
	   			$(".subTot .savings ").show();
	   			$(".subTot .savings ").append("<span class='price'></span>");
		}
	   $(".subTot .savings span.price").html(savings.toFixed(2));
	}  

function setOrders( addedOrders){
       for (var x = 0; x <  addedOrders.length ; x++){
              orderItemArray.push(addedOrders[x].orderItemID);
        }
		 
     
      }
function setFailedOrders( failedOrders){
 
       for (var x = 0; x <  failedOrders.length ; x++){
             setQuantityToZero(failedOrders[x].catentryID);
        } 
      }
function setQuantityToZero(catEntryID){
     // 	var b=$("input[value="+catEntryID+"]").parent().parent().parent().animate({ backgroundColor: "#eff2f5" }, 100).animate({ backgroundColor: "#fff" }, 30000); 
	    //var qty = $("input[value="+catEntryID+"]").parent().parent().find("input.qtyNo,input.qtyNoC").val();
	  
	    $("input[value="+catEntryID+"]").parent().parent().find("input.qtyNoC").val(0);
	 	$("input[value="+catEntryID+"]").parent().parent().find("input.qtyNo").val(0);
	}
	
/*
 * Function called when the user is guest and had clicked on add to wishlist. This function is
 * is called after the first ajax call is made. We pass a parameter guest=1 which differentiates a 
 * a user who has already regsitered and is browsing and the guest user who had just clicked on
 * add to wishlist button.
 */
function showLogonForm() {  
    
    
    var logonUrl = "LogonForm?langId=-1&storeId="+storeId+"&catalogId="+catalogId+"&URL=";
    var addToWishlistUrl = "AddToWishlist?langId=-1&storeId="+storeId+"&&catalogId="+catalogId+"&partNumber="+partNumberCollection+"&productURL="+collectionProductURL+"&guest=1&";
    var vertical = gup('vName');
    var category = gup('cName');
    var subcategory = gup('sName');
    var grUserType = getCookie('GiftRegApp'+storeId);
    
    if(grUserType != "")
        addToWishlistUrl = addToWishlistUrl + '&grUserType='+grUserType;
    if(vertical !="")
        addToWishlistUrl = addToWishlistUrl + '&vName='+vertical;
    if(category !="")
        addToWishlistUrl = addToWishlistUrl + '&cName='+category;
    if(subcategory !="")
        addToWishlistUrl = addToWishlistUrl + '&sName='+subcategory;
    
    
    var catEntryIds = createURL();
        addToWishlistUrl = addToWishlistUrl+catEntryIds;
        addToWishlistUrl = enCodeUrl(addToWishlistUrl);
        window.location = logonUrl+addToWishlistUrl;
    
}
function enCodeUrl(url){
    
    var strValue = "";
    var urlLen = url.length;
    
     for(var i=0;i<urlLen;i++){         
        var ch = url.charAt(i);
        if(ch=="="){
            strValue = strValue + "%3d";
        }
        else if(ch=="&")
        {
            strValue = strValue + "%26";
        }
        else{
            strValue =  strValue + ch;
        }
    }
    
    return strValue;
}
function fnAjaxReturnSaveForLater(value)
{
    
    object = document.getElementById("saveToListButton"); 
        flag = '';
    if(value == "Success")
    {
        if(document.getElementById("remembered")!=null)
         {
           var remem = document.getElementById("remembered").value;
            if(remem=="yes")
                flag = 'error8';
         }
        else        
          flag = 'error6';
        
        showErrorPopUpBox(object,flag);
        savedCart();
    }else if(value == "Redirect")
    {
        showLogonForm();
    }
    else
    {
        wishlistExceptionMessage = value;
        showErrorPopUpBox(object,flag);
    }
}	
function saveForLater(){
                catentryError=0;
                var errorDisplayed=false;
                createFormValues();	
				if(getTotalQuantity()==0 && !errorDisplayed){
                  displayErrorMessage(selectQuantitySaveForLater);
                  errorDisplayed=true;
                  }
				  
                 if(catEntryArray.length==0 && !errorDisplayed){
         	        displayErrorMessage(saveForLaterClicked);
         	         errorDisplayed=true;
         	     }
				 if(catentryError==1 && !errorDisplayed){
         	                  displayErrorMessage(saveForLaterSingleMissing);
         	                  errorDisplayed=true;
	                     }
			     if(catentryError>=2 && !errorDisplayed){
			                displayErrorMessage(saveForLaterSingleMissing);
			             errorDisplayed=true;
			     }
         	    
         	 if(!errorDisplayed){
         	   var url="AddToWishlist?langId=-1&storeId="+storeId+"&catalogId="+catalogId+"&partNumber="+partNumberCollection+"&URL=AddToWishListSuccessView&errorViewName=AddToWishListErrorView&redirectView=AddToWishListRedirectView";

			    var grUserType = getCookie('GiftRegApp'+storeId);
			    var catEntryIds=createURL();
			    
			    if(grUserType != ""){
			        url = url + '&grUserType='+grUserType;
			    }
			    ajaxCall(url + catEntryIds,'fnAjaxReturnSaveForLater','','');
            }			     

}
 
 
 function createURL(){
 
	 var catEntryIndex = 1;
	 var parameters="";
	  for (var i=0; i<catEntryArray.length; i++) {
	  parameters=parameters+"&catEntryId_"+catEntryIndex+"="+catEntryArray[i]+"&quantity_"+catEntryIndex+"="+quantityArray[i]+"&parent_catEntryId_"+catEntryIndex+"="+parentCatEntryArray[i];
	    catEntryIndex++;
	  }
	 return parameters;
 }
 
 
 function createOrderItemIdURL(){
	   var Index = 1;
	 var orderItemIdURL="";
	  for (var i=0; i<orderItemArray.length; i++) {
	       orderItemIdURL=orderItemIdURL+"&orderItemId_"+Index+"="+orderItemArray[i];
	    Index++;
	  }
	  return orderItemIdURL;
  }
 function createRemoveItemURL(orderId,orderItemId,catentryId){
     var url = "langId=-1&updatePrices=1&calculationUsageId=-1&URL=AJAXResponseView&storeId="+storeId+"&catalogId="+catalogId+"&"+"&orderId="+orderId+"&orderItemId="+orderItemId+"&productId="+catentryId;
     return url;
 }
 
 
function savedCart(){		
		$('.collItm input.qtyNo, .pro input.qtyNoC').each(function() {
			var $addedSec = $(this).parent().parent().find('.added');
			var qty = $(this).val(); 
			$addedSec.remove();
			if( (this.value == '') || (this.value == 0) ){	
				$addedSec.remove();
			}else{
				if( $("body").hasClass('attributes') ){	
				
					var actCount = 0;
					$(this).parent().parent().find('.attrHolder').each(function() {
						if( $(this).find('li').hasClass('active') ) {				
							actCount += 0;
						}else{
							actCount += 1;								
						}
					});
					
					if( actCount != 0 ){
						throwErr = true;
						$(this).after('<span class="attError">Make selections</span>');
						//$(this).next().fadeOut(1400);
					}else{
						$(this).after('<span class="added">Saved</span>');
						if(!isApple){
					     //	$(this).parent().parent().animate({ backgroundColor: "#eff2f5" }, 100).animate({ backgroundColor: "#fff" }, 3000);
						}
					}
				}else{
					if( $(this).parent().parent().hasClass('upsell') ){
						var bkColor = '#f8f8f8';						
					}else{
						var bkColor = '#ffffff';
					}
					
					$(this).after('<span class="added"><p>Saved</p></span>');	
					if(!isApple){
			     		//$(this).parent().parent().animate({ backgroundColor: "#eff2f5" }, 100).animate({ backgroundColor: ""+bkColor+"" }, 3000);
						}
				}
			}				
		});
	};
function displayCartSummary(){
   
var queryString=createOrderItemIdURL();
  
  
   $.ajax({
  url: "/shc/s/DisplayCollectionOrderSummaryCmd",
  data:queryString,
  success: function(msg){
   displayAddCartSummary(msg);
   }
 });
    
}
var rowIndicator;

function clickRemove(){
 
  var smry = $('#collSummary');
  $(smry).hide(0);
  $(smry).remove();
  $('.summaryBack').remove();
   

}
function adjustHeight(){
 var smry = $('#collSummary');
 $('.summaryBack').height($(smry).height()+35);
 return false;
  

}
 
		function executeDeleteCartItem(value){		
 
	if(value!=null && value!='' && INSURANCE_B2B!=storeId){
	 	value=jQuery.trim(value);
	 	 
				    var myJSONObject= "(" + value + ")";
				    if (!_cs) {
					   var _cs = new Object();
				     }  
				   _cs.prod = eval(myJSONObject);
					
					 if(_cs.prod.totalQuantity!=null && _cs.prod.totalQuantity!=''  && _cs.prod.totalPrice!=null && _cs.prod.totalPrice!='' ){
                        updateMiniCartDisplay(_cs.prod.totalQuantity,_cs.prod.totalPrice);
                       }
				 	 
						 
					
				         if(totalAddedItems!=null && totalAddedItems!='' && totalAddedItems > 0){ 
							            totalAddedItems= parseInt(totalAddedItems);
				                        totalAddedItems= totalAddedItems-tempQuantity;
	                              if(totalAddedItems==0){
				                         $('.buttons .checkOut').hide();
										  totalSavings=0;
										 $(".subTot .savings span.price").html(totalSavings.toFixed(2));
				                        }				    
                                       $(".subTot .tot").html(totalAddedItems);
				                       $(rowIndicator).parent().remove();
				                    
										if(totalAddedItems==0){
										  clickRemove();
				                        }
				                        
										 removeOrderItemFromArray(tempOrderItemID);
					                 	 
										 totalCartSum=totalCartSum - (tempQuantity*salePrice);
										 	  
										 
				                   		 adjustHeight();
										 
										 
				                     if(totalCartSum>0){
									 $(".subTot .summary .total .price").html(totalCartSum.toFixed(2));
									 }
									 else{
									   
									 	 $(".subTot .summary .total .price").html("0.00");
									 }
									 regPrice=parseFloat(regPrice).toFixed(2);
									 salePrice=parseFloat(salePrice).toFixed(2);
										 
				                        if(totalSavings!=null && totalSavings !='' && totalSavings > 0){
				               
				                            if( regPrice> 0 && salePrice!=null && salePrice!='' && salePrice > 0 &&( (regPrice - salePrice)>0 ) ){
				                                
 
											    totalSavings=totalSavings-(tempQuantity*(regPrice-salePrice));
												   
				                              $(".subTot .savings span.price").html(totalSavings.toFixed(2));
										 
				                             }                       
				                         
				                       }
				             }
				             
				     } 
          if(INSURANCE_B2B==storeId){
		             if(totalAddedItems!=null && totalAddedItems!='' && totalAddedItems > 0){ 
							            totalAddedItems= parseInt(totalAddedItems);
				                        totalAddedItems= totalAddedItems-tempQuantity;
	                              if(totalAddedItems==0){
				                         $('.buttons .checkOut').hide();
										 totalSavings=0;
										   $(".subTot .savings span.price").html(totalSavings.toFixed(2));
				                        }				    
                                       $(".subTot .tot").html(totalAddedItems);
				                       $(rowIndicator).parent().remove();
								      if(totalAddedItems==0){
										  clickRemove();
				                        }
										 removeOrderItemFromArray(tempOrderItemID);
					                 	
				                   		totalCartSum=totalCartSum-(tempQuantity*salePrice);
										 adjustHeight();
										 
				                     
									 $(".subTot .summary .total .price").html(totalCartSum.toFixed(2));
									  
										  
				                        if(totalSavings!=null && totalSavings !='' && totalSavings > 0){
				              
				                           if(regPrice!=null && regPrice!='' && regPrice> 0 && salePrice!=null && salePrice!='' && salePrice > 0 &&  ( (regPrice - salePrice)>0 ) && totalAddedItems!=0){
				                               
											  totalSavings=totalSavings-(tempQuantity*(regPrice-salePrice));
												 
				                              $(".subTot .savings span.price").html(totalSavings.toFixed(2));
										 
				                             }                       
				                         
				                       }
				             }
		  
		  
		  
		  
		  
		  }					 
		}
		
		
function removeOrderItem(removeQueryString,orderItemId,catentryID,quantity){
		
		setOdrCatIDs(orderItemId,catentryID,quantity);
		var queryString= removeQueryString;
		 $.ajax({
			url: "/shc/s/OrderItemDelete",
			data:removeQueryString,
			success: function(msg){
			  		executeDeleteCartItem(msg);
					}
 });
}

function setOdrCatIDs(orderItemId,catentryID,quantity){
		          tempOrderItemID=orderItemId;
                  tempCatentryID=catentryID;
                  tempQuantity=quantity;
				   getPrice(catentryID);
                   salePrice=itemOfferPrice; 
				   regPrice=itemRegPrice;
                   if(salePrice!=null && salePrice!=''& salePrice!=0){ 
                   salePrice = parseFloat(salePrice).toFixed(2);
                   
                   }
    	 if(regPrice!=null && regPrice!=''& regPrice!=0){ 
                       regPrice=   parseFloat(regPrice).toFixed(2);
                      
                   
                   }
                   
		}
		
function displayAddCartSummary(msg){
  
   
  if(msg!=null && msg!=''&& msg!=' '){
    var myJSONObject= "(" + msg + ")";
     
    if (!_cs) {
	   var _cs = new Object();
     }  
   _cs.prod = eval(myJSONObject);
	    
	   var appCollSum  = '<div id="collSummary"  style="font-size: 13px; position: absolute;">'
	     	appCollSum += '<div class="tab"><p>Items Added Summary</p> <a href="javascript:;" class="clSummary">close</a></div><div class="clear"></div>'
	 	  
	 	    for(var x=0;x<_cs.prod.orderItems.length;x++){
            var title=" ";
	        if(_cs.prod.orderItems[x].title!=null){
	         
	       
	           title=_cs.prod.orderItems[x].title;
                } 
	        if(title=='null' || title ==null ){
	           title=" ";
	        
	        }
	        var attributes="";
			var attrText='';
	         attributes= _cs.prod.orderItems[x].attributes;
	         
	        if(attributes == 'null' || attributes == null ){
	         attributes=" ";
			attrText= '<span class="attr"></span>';
	        }
			if(attributes!=null && attributes!=''){
			
			  attributes = attributes.split(",");
			   for(var y=0;y<attributes.length;y++){
			   attrText=attrText+'<span class="attr">'+attributes[y]+'</span>';
			   
			   }
			  
			}
			
			
	        var divClass;
			if(x%2==0){divClass="sumMsg";}
			else{divClass="sumMsg stripe";}
			
	             appCollSum += '<div class="'+divClass+'"><span class="name">'+title+'</span>'+attrText +' <span class="qty">&nbsp;Qty: '+_cs.prod.orderItems[x].quantity+'</span>';
	              var deleteURL= createRemoveItemURL(_cs.prod.orderItems[x].orderId,_cs.prod.orderItems[x].orderItemId,_cs.prod.orderItems[x].catEntryId);
	              appCollSum += '<a  class="remove" onclick="rowIndicator=jQuery(this);removeOrderItem(\''+deleteURL+'\',\''+_cs.prod.orderItems[x].orderItemId+'\',\''+_cs.prod.orderItems[x].catEntryId+'\',\''+_cs.prod.orderItems[x].quantity+'\');" title="remove">Remove</a>';
	             appCollSum += '</div>';
	         }
	 	     
		appCollSum += '</div>';
	if(_cs.prod.orderItems.length >=1){
          $('body').append(appCollSum);
	   }
       
	  //var itemOffset= ('.itemsAdded');
	//  var itemOffset=itemsAddedOffset;
    //   var offsetSum = $(itemOffset).offset();
	var offsetSum=itemsAddedOffset
	 
       var smry = $('#collSummary');
		 $(smry).show().bgiframe().css({ top: offsetSum.top +25, left: offsetSum.left -255 });
		$('<div class="summaryBack"/>').height($(smry).height()+35).width($(smry).width()+20).css({top:offsetSum.top+15,left:offsetSum.left -265}).appendTo($('body'));
		$('.clSummary').click(function(){ $(smry).hide(0);$('.summaryBack').remove() ;$(smry).remove();});
  }  
}	
function hideSelectAll(){
	    $('.deSel').hide(0);
 }

 
	
/*************************************************************************************************************************************
/******************************************  GIFT REGISTRY/ WISHLIST /SAVE FOR LATER FUNCTIONS****************************************
**************************************************************************************************************************************
*/
function getCatEntryIdForScim() {
    var catEntId = "";
    var gty_GR='';
     catEntId = catEntryArray[catEntryArray.length-1];
     if(catEntId != null && catEntId != '' && catEntId != "undefined" &&  catEntId != 0){
         catEntId= catEntId+'&gty_GR='+gty_GR;
      }
      else{
      catEntId="undefined";
      
      }
    return catEntId;
}

function createWishListURL(){
        var catEntryIndex = 1;
		 var parameters="";
		  for (var i=0; i<catEntryArray.length; i++) {
		  parameters=parameters+"&catEntryId_"+catEntryIndex+"="+catEntryArray[i]+"&quantity_"+catEntryIndex+"=1&parent_catEntryId_"+catEntryIndex+"="+parentCatEntryArray[i];
		    catEntryIndex++;
		  }
 return parameters;
 }

function getProductStatus(value,isGT){
   
    var qty_GR='';
    var actionStatus=value.substring(0,8);
        
    if((actionStatus == "registry")||(actionStatus == "wishlist"))
    {
    var RegistryType=value.substring(0,8);
    createFormValues();	
    var catEntryIdScim='';
         for(var x=0;x<catEntryArray.length;x++){
                        catEntryIdScim = catEntryIdScim+catEntryArray[x] +'N';
         }        
   
        
   if (isGT =="gt")
      {
        	location.href = "GiveTogetherSignOnView?storeId="+storeIdReq+"&catalogId="+catalogId+"&URL=ProductDisplay&partNumber="+partnumber+"&catEntryIdScim="+catEntryIdScim+"&RegistryType="+RegistryType+"&fromCreate=productPage&qty_GR="+qty_GR;
      }
   if (isGT =="wishlist")
      {
        	location.href = "GiftRegistryWishlistSignOnView?storeId="+storeIdReq+"&catalogId="+catalogId+"&URL=ProductDisplay&partNumber="+partnumber+"&catEntryIdScim="+catEntryIdScim+"&RegistryType="+RegistryType+"&fromCreate=productPage&qty_GR="+qty_GR;
      }
   else
     {
        location.href = "GiftRegistrySignOnView?storeId="+storeIdReq+"&catalogId="+catalogId+"&URL=ProductDisplay&partNumber="+partnumber+"&catEntryIdScim="+catEntryIdScim+"&RegistryType="+RegistryType+"&fromCreate=productPage&qty_GR="+qty_GR;
     }
    }else{
 
       flag = value;
	    newDiv=document.createElement('div');
        newDiv.className='errorPop';
        newDiv.id='errorBox';
        if (value.substring(0,6) == 'error7' || value.substring(0,6) == 'error9')
	        {
	          newDiv.innerHTML=getErrorStatus(value);
	        }
	        else{
	          newDiv.innerHTML=value;
	        }
        document.body.appendChild(newDiv);
        var errBox=document.getElementById('errorBox');
        var ox = leftVal;
        var oy = topVal;
		
		if(browser=="Internet Explorer"){
	        var docWidth=document.body.scrollWidth;
	        var docHeight=(document.body.scrollHeight);
	        var boxH=errBox.offsetHeight;
	        var boxW=errBox.offsetWidth;
			if ((ox-100)<0)
				{
			 
				errBox.style.top=(oy-100)+"px";
				errBox.style.left=(ox)+"px";
				document.getElementById('errorBox').focus();
				} 
			else if ((ox-100)>(docWidth-boxW))
				{
			 
				errBox.style.top=(oy-100)+"px";
				errBox.style.left=(ox)+"px";
				document.getElementById('errorBox').focus();
				} 
			else 
				{
		   
		        errBox.style.top=(oy-100)+"px";
		        errBox.style.left=(ox-75)+"px";
		        document.getElementById('errorBox').focus();
				}
		} else {
	        var docWidth=document.documentElement.clientWidth;
	        var docHeight=document.documentElement.clientHeight;
	        var boxH=errBox.offsetHeight;
	        var boxW=errBox.offsetWidth;
			if ((ox-100)<0)
				{
			 	errBox.style.top=(oy-100)+"px";
				errBox.style.left=(ox)+"px";
				document.getElementById('errorBox').focus();
				} 
			else if ((ox-100)>(docWidth-boxW))
				{
				 
				errBox.style.top=(oy-100)+"px";
				errBox.style.left=(docWidth-boxW-10)+"px";
				document.getElementById('errorBox').focus();
				} 
			else 
				{
		       
		        errBox.style.top=(oy-100)+"px";
		        errBox.style.left=(ox-165)+"px";
		        document.getElementById('errorBox').focus();
				}
			}
 }  
	
}

function popupWishlistSubmit(){
             
              var storeId = document.getElementById("storeId").value;
              var langId = document.getElementById("langId").value;
              var catalogId = document.getElementById("catalogId").value;
              for (i=0;i<document.GRForm.registry.length;i++) 
              {
                if (document.GRForm.registry[i].checked) 
                { 
                    var extId = document.GRForm.registry[i].value;
                    if (extId == 'create'){
                      var cattId = createURL();
					    if(cattId==''){
                           cattId=getCatEntryIDFromURL();
                            }
                      var rew = "~";
                      cattId = cattId.replace(/&/g,rew);
                      mainUrl = mainUrl.replace(/&/g,rew);
                      if(document.getElementById("remembered")!=null)
                      {
                        var remem = document.getElementById("remembered").value;
                        if(remem=="yes")
                            location.href = "LogonForm?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId+'&URL=WeddingWishListCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&cattId='+cattId+'&mainUrl='+mainUrl;
                        else
                            location.href = "WeddingWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                      }
                      else
                          location.href = "WeddingWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                    }
                    else{
                      onWishlist(extId);
                    }
                }
              }
              
              if (document.GRForm.registry.checked)
              {
                if (document.getElementById("registry").value == 'create') 
                  {
                     var cattId = createURL();
					   if(cattId==''){
                           cattId=getCatEntryIDFromURL();
                            }
                     var rew = "~";
                     cattId = cattId.replace(/&/g,rew);
                     mainUrl = mainUrl.replace(/&/g,rew);
                     if(document.getElementById("remembered")!=null)
                      {
                        var remem = document.getElementById("remembered").value;
                        if(remem=="yes")
                            location.href = "LogonForm?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId+'&URL=WeddingWishListCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&cattId='+cattId+'&mainUrl='+mainUrl;
                        else
                            location.href = "WeddingWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                      }
                      else
                          location.href = "WeddingWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                  }
              }
     }
     
     
     
function onWishlist(value)
{
    
    var url = "";  
    var grUserType = getCookie('GiftRegApp'+storeId);
    var catEntryIds = createURL();
    if(catEntryIds==''){
        catEntryIds=getCatEntryIDFromURL();
    }
    var externalId = value;
    url = 'AddToGiftRegistry?storeId='+storeId+'&catalogId='+catalogId+'&grUserType='+grUserType+'&externalId='+ externalId;
    ajaxCall(url + catEntryIds ,'getAddToNewWishListCollection','',''); 
    
}


function getAddToNewWishListCollection(value)
{
    object = document.getElementById("saveToListButton");
    flag = '';    
   if(value.substring(7,value.length) == 'ItemsExceeded'){
    
    flag = value.substring(7,value.length);
    
    }
     else {
    
    if(value.substring(0,7) == "Success")
    {    savedCart();
        if(document.getElementById("remembered")!=null)
        {
           var remem = document.getElementById("remembered").value;
           if(remem=="yes")
                flag = 'error12'+value.substring(7,value.length);
           else
                flag = 'error9'+value.substring(7,value.length);
        }
        else
            flag = 'error9'+value.substring(7,value.length);

    }
   }
    showErrorPopUpBox(object,flag);
   
}

////

function popupSubmit(isGT){
          //Load.style.display = "block";
              var storeId = document.getElementById("storeId").value;
              var langId = document.getElementById("langId").value;
              var catalogId = document.getElementById("catalogId").value;
              for (i=0;i<document.GRForm.registry.length;i++) 
              {
                if (document.GRForm.registry[i].checked) 
                { 
                    var extId = document.GRForm.registry[i].value; 
                    if (extId == 'create'){
                     
                      var cattId = createURL();
                       
                       if(cattId==''){
                           cattId=getCatEntryIDFromURL();
                            }
                      
                      var rew = "~";
                      cattId = cattId.replace(/&/g,rew);
                     
                      mainUrl = mainUrl.replace(/&/g,rew);
                      if(document.getElementById("remembered")!=null)
                      {
                           var remem = document.getElementById("remembered").value;
                            if(remem=="yes"){
                                location.href = "LogonForm?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId+'&URL=WeddingRegistryCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&cattId='+cattId+'&mainUrl='+mainUrl;                           
                               
                                }
                                  else{
                                location.href = "WeddingRegistryCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                                 
                                }
                      }
                      else{
						if (isGT =="gt") {
		                  location.href = "GiveTogether?nextView=GTCreateListView&storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
		                } else {
                          location.href = "WeddingRegistryCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                        }
                          }
                    }
                    else{
                      onRegistry(extId);   
                    }
                }
              }              
              if (document.GRForm.registry.checked)
              {
                if (document.getElementById("registry").value == 'create')
                  {
                     var cattId = createURL();
                     if(cattId==''){
                           cattId=getCatEntryIDFromURL();
                            }
                            
                     var rew = "~";
                     cattId = cattId.replace(/&/g,rew);
                    
                     mainUrl = mainUrl.replace(/&/g,rew);
                     if(document.getElementById("remembered")!=null)
                     {
                        var remem = document.getElementById("remembered").value;
                        if(remem=="yes")
                            location.href = "LogonForm?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId+'&URL=WeddingRegistryCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&cattId='+cattId+'&mainUrl='+mainUrl;                           
                                //location.href = "WeddingRegistryCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                        else
                            location.href = "WeddingRegistryCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                      }
                      else{
						if (isGT =="gt") {
	                  		location.href = "GiveTogether?nextView=GTCreateListView&storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
	                 	 } else {
                          location.href = "WeddingRegistryCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                  }
              }
     }
	}
 } 


function onRegistry(value){
     var url = "";  
    var grUserType = getCookie('GiftRegApp'+storeId);
    var catEntryIds = createURL();
   if(catEntryIds==''){
        catEntryIds=getCatEntryIDFromURL();
    }
    var externalId = value;
    url = 'AddToGiftRegistry?storeId='+storeId+'&catalogId='+catalogId+'&grUserType='+grUserType+'&externalId='+ externalId;
    ajaxCall(url + catEntryIds ,'getAddToRegistryStatusCollection','','');
    
}


function getCatEntryIDFromURL(){
			var strURL = document.location.search;
			var catId="";
			var url="";																	
				if (strURL.search("catEntryIdScim") != -1)
				{
				    
				    var temp=new Array();
				    temp=strURL.split("&");
				    for(var i=0;i<temp.length;i++)
				    {
				        if(temp[i].search("catEntryIdScim") != -1)
				        {
				        catId=temp[i].substring(temp[i].indexOf("=")+1,temp[i].length);
				    }
				    }
				
				}
                var str = catId;
                var counter = 1;
                var temp = '';
                while(str.indexOf('N')!=-1)
                {
                    temp = str.substring(0,str.indexOf('N'));
                    url = url + '&catEntryId_' + counter + '='+temp+'&quantity_' + counter + '=1';
                    str = str.substring(str.indexOf('N')+1,str.length);
                    counter++;
                  
                }

return url;
 
}

function getAddToRegistryStatusCollection(value){
    
    object = document.getElementById("saveToListButton");
    flag = '';
    
    if(value.substring(7,value.length) == 'ItemsExceeded'){
    
    flag = value.substring(7,value.length);
    
    }
     else {
    if(value.substring(0,7) == "Success")
    {  savedCart();
        if(document.getElementById("remembered")!=null)
        {
           var remem = document.getElementById("remembered").value;
           if(remem=="yes")
                flag = 'error11'+value.substring(7,value.length);
           else
                flag = 'error7'+value.substring(7,value.length);
        }
        else
            flag = 'error7'+value.substring(7,value.length);
    }
   }
    showErrorPopUpBox(object,flag);

}

addLoadEvent(showPopup);
addLoadEvent(displayErrorPopUp_CartCollection);
addLoadEvent(trackPageName);
function showPopup(){
 
var varRegistryType = "";
/*To check whether the user clicked registry or wishlist*/
var strURL = document.location.search;
if (strURL.search("RegistryType=registry") != -1)
{
    varRegistryType = "registry";
}
else if (strURL.search("RegistryType=wishlist") != -1)
{
     varRegistryType = "wishlist";
}    
else{
      varRegistryType = ""; 
}

if(varRegistryType == "registry")
{
 
addToRegistry();

}
if(varRegistryType == "wishlist")
{
 
addToWishList();
}

}

function addToRegistry(objImg){
          catentryError=0;
          var errorDisplayed=false; 
               createFormValues();	
               var catEntryIdScim = getCatEntryIdForScim();
              
					  if(catEntryIdScim == '' || catEntryIdScim == 'undefined' || catEntryIdScim == 0) {
					            var strURL = document.location.search;
							if (strURL.search("catEntryIdScim") != -1){
					             	var temp=new Array();
					  			temp=strURL.split("&");
					    			for(var i=0;i<temp.length;i++) {
					        					if(temp[i].search("catEntryIdScim") != -1){
					        				      	catEntryIdScim=temp[i].substring(temp[i].indexOf("=")+1,temp[i].length);
					                                       }
					                     }
					
					           }
					
					}           
        
         	   		 object = document.getElementById("saveToListButton"); 
	   					findPos(object);
						leftVal = xPos;
		 				topVal  = yPos;
		   			    var grUserType = getCookie('GiftRegApp'+storeId);
			            var catEntryIds=createURL();
			 	      mainUrl="partNumber="+partNumberCollection;
		              if(grUserType != ""){
				            mainUrl = mainUrl + '&grUserType='+grUserType;
				        }
				     if(catEntryIdScim != '' && catEntryIdScim != "undefined"){
		                mainUrl = mainUrl + catEntryIds;
		             }
			         var ProductUrl="";
			        //var ProductUrl = 'SHCGiftRegistryProductDetailsCmd?storeId='+storeId+'&catalogId='+catalogId+'&URL=ProductDisplay&partNumber='+partNumberCollection+'&catEntryIdScim='+catEntryIdScim; 
		          if (objImg == "gt" )
                 	 {
        	        	 ProductUrl = 'SHCGiftRegistryProductDetailsCmd?isGiveTogether=true&storeId='+storeIdReq+'&catalogId='+catalogId+'&URL=ProductDisplay&partNumber='+partnumber+'&catEntryIdScim='+catEntryIdScim; 
        	         }
		         else
		       		 {
						ProductUrl = 'SHCGiftRegistryProductDetailsCmd?isGiveTogether=false&storeId='+storeIdReq+'&catalogId='+catalogId+'&URL=ProductDisplay&partNumber='+partnumber+'&catEntryIdScim='+catEntryIdScim; 
					}
		             
		            if(catEntryIdScim != '' && catEntryIdScim !=  "undefined" && catEntryIdScim != 0)
		            {
		          
		                 //ajaxCall(ProductUrl,'getProductStatus');   
		                  ajaxCall(ProductUrl,'getProductStatus','',objImg); 
		            }
		 else{
				       
	          	if(getTotalQuantity()==0 && !errorDisplayed)
	          		{
				 	 if(objImg == 'gt')
				 	   {
				     	  displayErrorMessage(selectQuantityGT);
						  errorDisplayed=true;  
				       }
                    else
                      {
                         displayErrorMessage(selectQuantityRegistry);
		                 errorDisplayed=true;
		              }		             
		           }
				if(catEntryArray.length==0 && !errorDisplayed)
				   {
				    if(objImg == 'gt')
				      {
					    displayErrorMessage(giveTogetherClicked);
		         	    errorDisplayed=true;
					   }
					else
					  {
					     displayErrorMessage(giftRegistryClicked);
		         	     errorDisplayed=true;
		         	  }
		         }
		       if(catentryError==1 && !errorDisplayed)
		         {
		           if(objImg == 'gt')
		           {
		         	 displayErrorMessage(GTSingleMissing);
         	         errorDisplayed=true;
		           }
		          else
		           {
		         	   displayErrorMessage(registrySingleMissing);
         	           errorDisplayed=true;
	                }
	            }
			  if(catentryError>=2 && !errorDisplayed)
			    {
			     if(objImg == 'gt')
			       {
			          displayErrorMessage(GTMultiMissing);
			          errorDisplayed=true;
			       }
			     else
			       {
			           displayErrorMessage(registryMultiMissing);
			           errorDisplayed=true;
			       }
			   }
		                  
	     } 
         

}
/**
*
*/
function addToWishList(){
 catentryError=0;
            var errorDisplayed=false; 
               createFormValues();	
               var catEntryIdScim = getCatEntryIdForScim();
              
					  if(catEntryIdScim == '' || catEntryIdScim == 'undefined' || catEntryIdScim == 0) {
					            var strURL = document.location.search;
							if (strURL.search("catEntryIdScim") != -1){
					             	var temp=new Array();
					  			temp=strURL.split("&");
					    			for(var i=0;i<temp.length;i++) {
					        					if(temp[i].search("catEntryIdScim") != -1){
					        				      	catEntryIdScim=temp[i].substring(temp[i].indexOf("=")+1,temp[i].length);
					                                       }
					                     }
					
					           }
					
					}           
        
         	   		 object = document.getElementById("saveToListButton"); 
	   					findPos(object);
						leftVal = xPos;
		 				topVal  = yPos;
		   			    var grUserType = getCookie('GiftRegApp'+storeId);
			            var catEntryIds=createURL();
			 	      mainUrl="partNumber="+partNumberCollection;
		              if(grUserType != ""){
				            mainUrl = mainUrl + '&grUserType='+grUserType;
				        }
				     if(catEntryIdScim != '' && catEntryIdScim != "undefined"){
		                mainUrl = mainUrl + catEntryIds;
		             }
			    
			    var ProductUrl = 'SHCGiftRegistryProductDetailsCmd?storeId='+storeId+'&catalogId='+catalogId+'&wishListId=1&URL=ProductDisplay&partNumber='+partNumberCollection+'&catEntryIdScim='+catEntryIdScim; 
            
		              
		            if(catEntryIdScim != '' && catEntryIdScim !=  "undefined" && catEntryIdScim != 0)
		            {
		          
		                 ajaxCall(ProductUrl,'getProductStatus');   
		            }
				   else{
				        
		         	     if(getTotalQuantity()==0 && !errorDisplayed){
		                 displayErrorMessage(selectQuantityWishlist );
		                 errorDisplayed=true;
		                  }
						   if(catEntryArray.length==0 && !errorDisplayed){
		         	        displayErrorMessage(wishListClicked);
		         	         errorDisplayed=true;
		         	     }
						 if(catentryError==1 && !errorDisplayed){
         	                  displayErrorMessage(wishlistSingleMissing);
         	                  errorDisplayed=true;
	                     }
			            if(catentryError>=2 && !errorDisplayed){
			                displayErrorMessage(wishlistSingleMissing);
			             errorDisplayed=true;
			            }
						 
		            
		            } 
         
      
      
      
      
}
function checkRadioButtons(name)
{

  
    var radioLen = document.actionsForm.pd.length;

    /* If there is only one element in the radio buttons group*/
    if(radioLen == undefined)
    {
         document.actionsForm.pd.checked = true;
         document.addToCart.IndicatorA.value = document.actionsForm.pd.value;
    }
    else
    {
        for (i=0;i<document.actionsForm.pd.length;i++)
        {
            if(document.actionsForm.pd[i].value == name)
            {
                document.actionsForm.pd[i].checked = true;
                  document.addToCart.IndicatorA.value = document.actionsForm.pd[i].value;
                return;
            }
        }
    }
}
function getRadioButtonValue(){
  
    var len = document.actionsForm.pd.length;
    if(len == undefined)
    {
        
        document.addToCart.IndicatorA.value = document.actionsForm.pd.value;
               
       
        return;
    }
    else
    {
    for(var i = 0; i < len ;i++)
    {
        if(document.actionsForm.pd[i].checked)
        {
            document.addToCart.IndicatorA.value = document.actionsForm.pd[i].value;
                 
                 $(document).ready(function(){
                  document.actionsForm1.pd1[i].checked = true;
                  });
           
            return;
        }
    }
    }
}
function displayErrorPopUp_CartCollection()
{

    //Setting an empty to string to type of error message
    var value = "";
    if(cartException != "3")
    {
        //The add to cart button had been clicked
        if(cartException == "1")
        {
                 //An exception had occured
            	object = document.getElementById("addToCartButton");
            	showErrorPopUpBox(object,value); 
        }
    }
}
function checkRadioButtons1(name)
{

  
    var radioLen = document.actionsForm1.pd1.length;

    /* If there is only one element in the radio buttons group*/
    if(radioLen == undefined)
    {
        document.actionsForm1.pd1.checked = true;
         document.addToCart.IndicatorA.value = document.actionsForm1.pd1.value;
    }
    else
    {
        for (i=0;i<document.actionsForm1.pd1.length;i++)
        {
            if(document.actionsForm1.pd1[i].value == name)
            {
                document.actionsForm1.pd1[i].checked = true;
                  document.addToCart.IndicatorA.value = document.actionsForm1.pd1[i].value;
                return;
            }
        }
    }
}
function getRadioButtonValue1(){
  
    var len = document.actionsForm1.pd1.length;
    if(len == undefined)
    {
        
        document.addToCart.IndicatorA.value = document.actionsForm1.pd1.value;
     
       
        return;
    }
    else
    {
    for(var i = 0; i < len ;i++)
    {
        if(document.actionsForm1.pd1[i].checked)
        {
            document.addToCart.IndicatorA.value = document.actionsForm1.pd1[i].value;
                   document.actionsForm.pd[i].checked = true;
            return;
        }
    }
    }
}
function checkProductActions()
{

   
    
    if((shipV == 1) && (pickupV == 0))
    {
         checkRadioButtons('ship');
        
    }
    else if((deliveryV == 1)&& (pickupV == 0))
    {
         
        checkRadioButtons('delivery');
    }
   if((shipV == 1) && (pickupV == 1))
    {
    	if(storeId == '10152'){
    		checkRadioButtons('pickup');
    		getRadioButtonValue();    	
    	}else{
         	checkRadioButtons('ship');
        }
        
    } 
   if((deliveryV == 1) && (pickupV == 1))
    {
         checkRadioButtons('delivery');
        
    } 
	  if((shipV == 0) && (deliveryV == 0) && (pickupV == 1)){
	  
	  checkRadioButtons('pickup');
	  }
    
}
function checkProductActions1()
{
  
    
    if((shipV == 1) && (pickupV == 0))
    {
         checkRadioButtons1('ship');
        
    }
    else if((deliveryV == 1)&& (pickupV == 0))
    {
         
        checkRadioButtons1('delivery');
    }
   if((shipV == 1) && (pickupV == 1))
    {
         if(storeId == '10152'){
    		checkRadioButtons1('pickup');
    		getRadioButtonValue1();    	
    	}else{
         	checkRadioButtons1('ship');
        }
        
    } 
 if((deliveryV == 1) && (pickupV == 1))
    {
         checkRadioButtons1('delivery');
        
    } 
   if((shipV == 0) && (deliveryV == 0) && (pickupV == 1)){
	  
	 
	   checkRadioButtons1('pickup');
	  }
    
}

function getPrice(catentryId){
itemOfferPrice=0;
itemRegPrice=0;
itemOfferPrice=regPriceArray[catentryId].nPrice;
itemRegPrice=regPriceArray[catentryId].rPrice;
if(itemRegPrice=='undefined' || itemRegPrice==''){itemRegPrice=0;}
			 
			 
			 
 }
 function setPrice(catentry_id,regPrice){
 
 if(catentry_id!=null && catentry_id!='undefined' && catentry_id!='' && 
    regPrice!=null && regPrice!='undefined' && regPrice!='' && 	regPriceArray[catentry_id]!='undefined'){
				regPriceArray[catentry_id].nPrice=regPrice;
				regPriceArray[catentry_id].rPrice=regPrice;
			}
 }
 
 var regPriceArray=[];
 function setRegPrice(){
  
 	for(var i=0;i<jsonSaveStory.itemBeanSaveStory.length;i++){  
		var regObject=new Object();
		regObject.catEntryId=jsonSaveStory.itemBeanSaveStory[i].catEntryId;
	    regObject.nPrice=jsonSaveStory.itemBeanSaveStory[i].offerPrice;
		regObject.rPrice=jsonSaveStory.itemBeanSaveStory[i].regPrice;
		regPriceArray[jsonSaveStory.itemBeanSaveStory[i].catEntryId]=regObject;
		
  }
 
 }
//Omniture Functions for  Collections Page
function trackPageName(){
if (typeof omPrefix != 'undefined') {
		omPrefix=omniPageName;
	}
if (typeof s != 'undefined') {

   s.t();
  
}
}
function trackCollectionProducts(productIDS){

if (typeof s != 'undefined' && productIDS!='undefined') {
       s.events='scAdd';
       s.products=productIDS 
	   omniCollectionCartPageName=omniPageName;
     
	s.tl();
   }
}
function seteVar41(){
if (typeof s != 'undefined') {
			   omCollections=omniPageName;
			   	s.tl();
			 
             }
 }

 function getAttrNames(catentryId){
 

	for(var jj=0;jj<_Pd.prod.prodList.length;jj++){
	var jsonCatId=_Pd.prod.prodList[jj].pCId;
	var attrName="";
	if(jsonCatId!=null && jsonCatId!='undefined'&& jsonCatId!='' && jsonCatId==catentryId){
        	attrName=_Pd.prod.prodList[jj].attNames.join(', ');
        	return attrName;

	}
	
	
	
	}
 }
 function getAddToCartErrorMessageForSoftline(attrName){
 
  var   singleSelectAddToCartMissing="<h2>Add to Cart</h2><p>Select the [ "+attrName+" ]before you add to cart.</p><img class=\"cancelMod\" alt=\"OK\" src=\""+imagePath+"img/buttons/okay_btn.gif\"/>";
 return singleSelectAddToCartMissing;
 }
 function fixInfoHeight(){
		if($.browser.msie && /6.0/.test(navigator.userAgent)){
			if(($('div.productName').height()+$('div#summary').height())>$('div.productImage').height()){
				$('div.mainInfo').css({height:($('div.productName').height()+$('div#summary').height())+45});
			}else{
				$('div.mainInfo').css({height:$('div.productImage').height()});
			}
		}else{
			if(($('div.productName').height()+$('div#summary').height())>$('div.productImage').height()){
				$('div.mainInfo').css({minHeight:($('div.productName').height()+$('div#summary').height())+45});
			}else{
				$('div.mainInfo').css({minHeight:$('div.productImage').height()});
			}
		}
	}

//Function to hide the corresponding DIV's for the International Shippping flow.	
function fnIntlColPageHide(){
	var cokkieVal = $.cookie("IntnlShip");
    if(cokkieVal !='undefined' || cokkieVal !=null ){	
		intnlShippingValue = cokkieVal.split('|');
		countryCode = intnlShippingValue[0];
	}
	if(collectionstoreId == '10153'){
			if(intShipJspChk == 'true'){
				fnIntHideCollections();
		    }
		    if(intShipJspChk == 'false'){
				if(collintlShipElgCol != 'YES'){
					$('li.unvIntShipCol').hide();	
					$('li.intShipCol').hide();
				}else if (collintlShipElgCol == 'YES'){
					$('li.intShipCol').show();
					$('li.unvIntShipCol').hide();
			   }
		    }
	 }
}
