/******************** Scripts related to Mutiple Add to Bag ***********************/

//global var to hold all variants (one per product)
var variants_list = new Array();

//global var to hold all Topic collection products
var topic_collections = new Array();

//global var for variant ItemIndex
var varItemIndex = 0;

//global var for topic ItemIndex (all topics under Haircare_Collection)
var topicItemIndex = 0;

//global var to store the Topic Code for selected Collection
var selectedTopicCode = "";

//global var to store the variant code of the product added from "Complete the Collection"
var selectedCollectionVarCode = "";

//Add to bag Item  Class
function AddToBagItem()
{  
  this.varCode = "";  //product variant code
  this.qty = "";   //the qty to add to bag
}

//Products Arranged by Topic Class
//Each Product will always have only 1 variant
function ProductsByTopic()
{
  this.topicCode = ""; //Topic Code
  this.variantsList = new Array(); //List of variants associated with the Topic
}

//Intializes the page
function PSCInitializeOnPageLoad()
{
    
    var tempProducts=new Array();
    var selectedAddToCartProducts= new Array();
    tempProducts=variants_list;
    
    //hide shopping cart bubble and reset error message
    PSCHideShowMultiShoppingCartBubble(false);
    PSCHideShowMultiShoppingCartBubbleErrorMsg("",false);
    //Hide the "Complete the Collection" section
    PSCHideShowMultiShoppingCartCompleteCollection(false);

    for(var i=0;i<tempProducts.length;i++)
    {   
        //alert('HIDING :' + tempProducts[i]); 
        //Hide all the ADDED TO BAG section shopping cart bubble items
        PSCHideShowShoppingBubbleCartAddedItem(tempProducts[i], false); 
        //Hide all the COMPLETE THE COLLECTION section shopping cart bubble items
        PSCHideShowShoppingBubbleCartCollectionItem(tempProducts[i],false);  
        //Hide all the Product Line Dividers in bubble
        PSCHideShowShoppingBubbleCartAddedItemLineDivider(tempProducts[i],false); 
        //Hide all the Product Plus seperators in bubble
        PSCHideShowShoppingBubbleCartItemPlusSeperator(tempProducts[i],false); 
    }   
}

//Hide or Show the Multi Shopping Cart Bubble
function PSCHideShowMultiShoppingCartBubble(display)
{
    var MultiShoppingCartBubble   = $get("ShoppingCartBubble_Div"); 
    
    if(MultiShoppingCartBubble != null)
    { 
                  
         if(display==true)
         {
            MultiShoppingCartBubble.style.display="";
            MultiShoppingCartBubble.style.visibility="visible";
         }
         else
         {
            MultiShoppingCartBubble.style.display="none";
            MultiShoppingCartBubble.style.visibility="hidden";         
         }
    }
}
 
// Custom Handle CORE Error Messages as Necessary
function PCSStringReplace(strValue) {
  
  arrStrings = new Array();
  arrNewStrings = new Array();
  var intIndex;
  var strTemp;
  arrStrings.push("The Maximum Amount of the Shopping Cart is Reach : ");
  arrNewStrings.push("The Maximum Amount of the Shopping Bag allowed is $");
  
  for (x=0; x<arrStrings.length; x++) {
    intIndex = strValue.toString().toLowerCase().indexOf(arrStrings[x].toString().toLowerCase());
    if (intIndex > -1) {
      strTemp = strValue.toString().substr(0, intIndex);
      strTemp = strTemp + arrNewStrings[x].toString();
      strTemp = strTemp + strValue.toString().substr(intIndex + arrStrings[x].toString().length, strValue.toString().length);
      return strTemp;
    }
  }
  return strValue
}

//Hide or show the Multi Shopping Cart Error Messages 
function PSCHideShowMultiShoppingCartBubbleErrorMsg(errorMsg,display)
{
    var MultiShoppingCartBubble_ErrorMsg_Div   = $get("MultiShoppingCartBubble_ErrorMsg_Div"); 
    var MultiShoppingCartBubble_ErrorMsg_Text  = $get("MultiShoppingCartBubble_ErrorMsg_Text"); 
  
    if(MultiShoppingCartBubble_ErrorMsg_Div != null)
    { 
                  
        if(display == true)
        {
           MultiShoppingCartBubble_ErrorMsg_Div.style.display="";
           MultiShoppingCartBubble_ErrorMsg_Div.style.visibility="visible";               
        }
        else
        {
           MultiShoppingCartBubble_ErrorMsg_Div.style.display="none";
           MultiShoppingCartBubble_ErrorMsg_Div.style.visibility="hidden";
        }
        if(MultiShoppingCartBubble_ErrorMsg_Text!=null)
        { 
            MultiShoppingCartBubble_ErrorMsg_Text.innerHTML=PCSStringReplace(errorMsg);
        }
    }
}

//Hide or show the "Complete the Collection" section
function PSCHideShowMultiShoppingCartCompleteCollection(display)
{
    var  MultiShoppingCartBubble_CompleteCollection_Div   = $get("ShoppingCartBubble_CompleteCollection_Div"); 
      
    if(MultiShoppingCartBubble_CompleteCollection_Div != null)
    {                   
        if(display == true)
        {
           MultiShoppingCartBubble_CompleteCollection_Div.style.display="";
           MultiShoppingCartBubble_CompleteCollection_Div.style.visibility="visible";               
        }
        else
        {
           MultiShoppingCartBubble_CompleteCollection_Div.style.display="none";
           MultiShoppingCartBubble_CompleteCollection_Div.style.visibility="hidden";
        }        
    }
}

//Hide or show the "Added To Bag" section
function PSCHideShowMultiShoppingCartAddedToBagSection(display)
{
    var  MultiShoppingCartBubble_AddedToBagSection_Div   = $get("ShoppingCartBubble_AddedToBagSection_Div"); 
      
    if(MultiShoppingCartBubble_AddedToBagSection_Div != null)
    {                   
        if(display == true)
        {
           MultiShoppingCartBubble_AddedToBagSection_Div.style.display="";
           MultiShoppingCartBubble_AddedToBagSection_Div.style.visibility="visible";               
        }
        else
        {
           MultiShoppingCartBubble_AddedToBagSection_Div.style.display="none";
           MultiShoppingCartBubble_AddedToBagSection_Div.style.visibility="hidden";
        }        
    }
}

//Hide or Show Added ShoppingCartItem in the shopping cart bubble
function PSCHideShowShoppingBubbleCartAddedItem(variantCode, display)
{
    var productDivID = variantCode+"_MultiShoppingCartBubbleProduct_AddedDisplay_DIV";
    var productDivObj = $get(productDivID);
     if (productDivObj != null) 
     {  
         if(display==true)
         {
            productDivObj.style.display="";
            productDivObj.style.visibility="visible";
         }
         else
         {
            productDivObj.style.display="none";
            productDivObj.style.visibility="hidden";
         }
     }
     
}

//Hide or Show "Complete the Collection" ShoppingCartItem in the shopping cart bubble
function PSCHideShowShoppingBubbleCartCollectionItem(variantCode,display)
{
    var productDivID = variantCode+"_MultiShoppingCartBubbleProduct_CollectionDisplay_DIV";
    var productDivObj = $get(productDivID);
     if (productDivObj != null) 
     {  
         if(display==true)
         {
            productDivObj.style.display="";
            productDivObj.style.visibility="visible";
         }
         else
         {
            productDivObj.style.display="none";
            productDivObj.style.visibility="hidden";
         }
     }
     
}

//Hides or Show ShoppingCartItem Line Divider in the shopping cart bubble
function PSCHideShowShoppingBubbleCartAddedItemLineDivider(variantCode,display)
{
    var productDivLineDividerID = variantCode+"_line_divider";
    var productDivLineDividerObj = $get(productDivLineDividerID);
     if (productDivLineDividerObj != null) 
     {  
         if(display==true)
         {
            productDivLineDividerObj.style.display="";
            productDivLineDividerObj.style.visibility="visible";
         }
         else
         {
            productDivLineDividerObj.style.display="none";
            productDivLineDividerObj.style.visibility="hidden";
         }
     }
     
}

//Hides or Show ShoppingCartItem Plus Seperator in the shopping cart bubble
function PSCHideShowShoppingBubbleCartItemPlusSeperator(variantCode,display)
{
    var productDivPlusSeperatorID = variantCode+"_plus_seperator";
    var productDivPlusSeperatorObj = $get(productDivPlusSeperatorID);
     if (productDivPlusSeperatorObj != null) 
     {  
         if(display==true)
         {
            productDivPlusSeperatorObj.style.display="";
            productDivPlusSeperatorObj.style.visibility="visible";
         }
         else
         {
            productDivPlusSeperatorObj.style.display="none";
            productDivPlusSeperatorObj.style.visibility="hidden";
         }
     }

}

 //This function either disables the Qty dropdown for 'out of stock' or enables it for 'add to cart'
function PSCManagePrdAddToCartDropdown(variantCode,stockQty) 
{    
    var addToCartDropdown = document.getElementById(variantCode+"_QtyList");  
  
    if (PSCIsVariantInStock(stockQty)) 
    {       
        addToCartDropdown.disabled=false;           
    }
    else 
    {          
        addToCartDropdown.disabled=true;        
    }   
}

//This function returns true if variant is in stock and false if it is out of stock
function PSCIsVariantInStock(stockQty) 
{
  
     if (AJAX_ENABLE_OUTOFSTOCK==false) return true; //if not enabled return true so treats everything in stock
     var _IsInStock = false; 
     var StockTresHold = AJAX_GetTresHoldNumber();
     if (stockQty!=null) 
     {  
        if (parseInt(stockQty)>StockTresHold) 
        { 
            _IsInStock = true;  
        }
                     
     }
           
      return  _IsInStock;
}

//returns the selected product qty
function PSCGetSelectedProductQty(variantCode) 
{
    var prdQtyIDStr = variantCode + "_QtyList";	
	
	 var objdrp = $get(prdQtyIDStr);
	 
     if (objdrp != null) 
     {
        var _prdQty = objdrp.value;         
        return _prdQty;                 
     }
     else 
     { 
        return 1;
     }
}

//Gets add to bag variant codes
function PSCGetAddToBasketItems()
{
    var tempProducts = new Array();
    var selectedAddToCartProducts = new Array();  

    var selectedAddToBagItems = new Array();//to be returned
    tempProducts = variants_list;    
        
    var addToCartCount=0;
    
    for(var i=0;i<tempProducts.length;i++)
    {
          //alert('Variant : ' + tempProducts[i]);
          var prdAddToCartDropdown = document.getElementById(tempProducts[i]+"_QtyList");//$get(tempProducts[i]+"_QtyList");
           
          //alert(prdAddToCartDropdown + ' : ' + prdAddToCartDropdown.value);   
          if(prdAddToCartDropdown!=null)
          {
             if(prdAddToCartDropdown.value != '-')
             {
                //alert(tempProducts[i] + ': ' + prdAddToCartDropdown.value);
                //get selected variant
                selectedAddToCartProducts[addToCartCount] = tempProducts[i];
                addToCartCount++; 
             }
          }
     }  
    
    for(var i=0;i<selectedAddToCartProducts.length;i++)
    {        
        var varCode = selectedAddToCartProducts[i];     //variant code
        var varQty = PSCGetSelectedProductQty(varCode);   //qty
        var   addtoBagItem = new AddToBagItem();
        
        //alert('Selected Items : ' + varCode + ' : ' + varQty);
                        
        addtoBagItem.varCode = varCode;
        addtoBagItem.qty = varQty;
        selectedAddToBagItems[i] = addtoBagItem;
        
    }
      
    return selectedAddToBagItems;     
}

function PSCAddSelectedProductsToBag(topicCode)
{   
    //Set the global var to store selected Topic Code 
    //This will be used by the AJAX callback function: PSCAddMultipleProductOnComplete
    //The call back function internally calls: PSCDisplayShoppingCartBubble which uses this for "Complete the Collection" section
    selectedTopicCode = topicCode;    
    
    var selectedAddToBagItems= new Array();//to be returned
    selectedAddToBagItems=PSCGetAddToBasketItems();
        
    var selectedVarSKU = new Array();
    var selectedVarQty = new Array();           
            
    if(selectedAddToBagItems.length > 0)
    {            
        for(var i=0; i<selectedAddToBagItems.length; i++)
        {            
            var addToBagItems=selectedAddToBagItems[i]; 
           
            selectedVarSKU[i]=addToBagItems.varCode;
            selectedVarQty[i]=addToBagItems.qty;       
        }                 

        //add to bag
        _WebServiceAPI.AddMultipleProductsToCart(GetCurrentCustomerID(), selectedVarSKU, selectedVarQty, PSCAddMultipleProductOnComplete);         
    }
    else
    {
         alert("Please select a product to add to bag");
    }
}

function PSCAddSelectedProductToBagFromCollection(varCode, varQty)
{   
    //Set the global var to store selected product from "Complete the Collection"
    //This will be used by the AJAX callback function: PSCAddCollectionProductOnComplete
    //to retrieve the variant added to bag    
    selectedCollectionVarCode = varCode;
    
    //Set the global var to store selected Topic Code 
    //This will be used by the AJAX callback function: PSCAddMultipleProductOnComplete
    //The call back function internally calls: PSCDisplayShoppingCartBubble which uses this for "Complete the Collection" section
    //selectedTopicCode = topicCode;    
   
    var selectedVarSKU = new Array();
    var selectedVarQty = new Array();           
                
    selectedVarSKU[0] = varCode;
    selectedVarQty[0] = varQty;  //Default Qty =  1     
    
    //add colleciton product to bag
    _WebServiceAPI.AddMultipleProductsToCart(GetCurrentCustomerID(), selectedVarSKU, selectedVarQty, PSCAddCollectionProductOnComplete);                   
    
}

//update shopping cart bubble's product price and variant name
function PSCUpdateShoppingCartProductInfo(variantCode, isCollection)
{  
  
   var ShoppingCartBubble_VariantNameStr =  variantCode + "_ShoppingCartBubble_VariantName";
   var ShoppingCartBubble_ItemQuantityStr = variantCode + "_ShoppingCartBubble_ItemQuantity";
   
   var ShoppingCartBubble_VariantNameObj  = $get(ShoppingCartBubble_VariantNameStr);
   var ShoppingCartBubble_ItemQuantityObj = $get(ShoppingCartBubble_ItemQuantityStr);   
  
   //We do not have to set the Variant Name as SHU has only 1 variant per Product
   /*if(ShoppingCartBubble_VariantNameObj != null)
   { 
        ShoppingCartBubble_VariantNameObj.innerHTML = selectedShadeName; 
   }*/
     
   var prdQty = 0;
   
   //If Variant was not added from "Complete the Collection", then get the Qty added from the dropdownlist
   //Else Qty added = 1
   if(isCollection == false) 
        prdQty = PSCGetSelectedProductQty(variantCode);   
   else
        prdQty = 1;
   
   if(ShoppingCartBubble_ItemQuantityObj != null)
   { 
        ShoppingCartBubble_ItemQuantityObj.innerHTML = prdQty; 
   }                                    

}

//Display Shopping bag bubble div. 
//allProductErrorMessagesArray is an array of ProductErrorMessage Objs
//Display "Complete the Collection" section if complete collection products did not get added to Cart
function PSCDisplayShoppingCartBubble(selectedAddToBagItems, productJSONErrorMessages, isCollection)
{
   var productsWithErrorStr = ""; 
   var allProductErrorMessagesArrayStr = "";   
     
   //Hide all shopping cart bubble items, line dividers and plus seperators
   for(var i=0;i<variants_list.length;i++)
   {       
        PSCHideShowShoppingBubbleCartAddedItem(variants_list[i], false);
        PSCHideShowShoppingBubbleCartCollectionItem(variants_list[i], false);
        PSCHideShowShoppingBubbleCartAddedItemLineDivider(variants_list[i],false);        
        PSCHideShowShoppingBubbleCartItemPlusSeperator(variants_list[i],false);
   }
    
   //Hide the "Added to Bag" and "Complete the Collection" sections
   PSCHideShowMultiShoppingCartAddedToBagSection(false);
   PSCHideShowMultiShoppingCartCompleteCollection(false);
 
   if(productJSONErrorMessages!=null )
   {
       for(var x=0;x<productJSONErrorMessages.ErrorMessages.length;x++)
       { 
           try
           {
                allProductErrorMessagesArrayStr += productJSONErrorMessages.ErrorMessages[x].VariantCode + " "; 
                //Product   is 
                //alert(productJSONErrorMessages.ErrorMessages[x].VariantName.length+" "+productJSONErrorMessages.ErrorMessages[x].VariantName);
                var variantName = productJSONErrorMessages.ErrorMessages[x].VariantName.length > 1 ? "&nbsp;&nbsp;&nbsp;" + productJSONErrorMessages.ErrorMessages[x].VariantName + "" : "";
                productsWithErrorStr += "<span class='AMedGREY11_BTT'>" + productJSONErrorMessages.ErrorMessages[x].PrdParentName+variantName + "</span><br>" + productJSONErrorMessages.ErrorMessages[x].ErrorMessage + "<br><br>";         
             } 
             catch(err){}                
          }  
    }     
 
    //Variable to count #items actually added to cart via AJAX
    var cartItems = 0;
    
    for(var i=0;i<selectedAddToBagItems.length;i++)
    { 
         var  varCode = selectedAddToBagItems[i].varCode;
         var searchKey = varCode;
         var searchResult = allProductErrorMessagesArrayStr.search(searchKey);     
        
         if(searchResult == -1)           
         {   
             //alert('ADDED VAR :' + varCode);     
             PSCUpdateShoppingCartProductInfo(varCode, isCollection);
             PSCHideShowShoppingBubbleCartAddedItem(varCode, true);
             PSCHideShowMultiShoppingCartAddedToBagSection(true);
             
             //Increment cartItems
             cartItems++;
                
             //Except for the last item added to bag, show the product line line divider.
             if(i != (selectedAddToBagItems.length - 1))
             {                
                PSCHideShowShoppingBubbleCartAddedItemLineDivider(varCode, true);    
             }
         }        
    } 
    
    //BEGIN: "Complete the Collection" section
    //Check if any item of the Topic Collection did not get added to cart
    //Display the selected Topic Code
    //alert(selectedTopicCode);
    
    //Retrieve all the products in the selected Topic collection
    var variantsList = new Array();
    
    if(topic_collections.length > 0)
    {
        for(var i=0; i<topic_collections.length; i++)
        {   
            var topicProducts = topic_collections[i];
            //If a matching Topic Code is found, break out of the loop
            if(topicProducts.topicCode == selectedTopicCode)
            {   
                variantsList = topicProducts.variantsList;
                
                /*for(var j=0; j<variantsList.length; j++)
                {
                    alert(variantsList[j]);
                }*/
                
                break;
            }           
        }   
    }
    
    //User can only add products of ONE collection at a time and not add products across collections
    //(The dropdowns are reset everytime user closes a collection carousel)
    //Therefore it is sufficient to check if the max #products inside the selected Topic matches
    //the #products user tried to add to cart.
    //If they do not match and ATLEAST 1 ITEM WAS ADDED TO CART VIA AJAX, then display the "Complete the Collection" section    
    if(cartItems > 0 && (variantsList.length !=  selectedAddToBagItems.length))
    {
        var productsToCompleteCollection = new Array();
        var itemIndex = 0;
        var productAdded = false;
        
        for(var i=0; i<variantsList.length; i++)
        {      
            productAdded = false;
                                 
            for(var j=0; j<selectedAddToBagItems.length; j++)
            {
                if(variantsList[i] == selectedAddToBagItems[j].varCode)
                {
                    //If there's a match, then this product has been added to cart already...
                    //We need to skip to next product in Topic Collection                    
                    productAdded = true;
                    break;
                }                
            }            
            
            //If variantsList[i] is in Cart, skip to next product in Topic Collection
            if(productAdded == true)
            {   
                continue;
            }
            else
            {
                //variantsList[i] is not added to Cart but is part of the Collection.                
                //Add item to "Complete Collection" array.
                productsToCompleteCollection[itemIndex++] = variantsList[i]
             }
         }
        
         //Now we have the list of variants that complete the collection
         if(productsToCompleteCollection.length > 0)
         {
            for(var i=0; i<productsToCompleteCollection.length; i++)
            {
                //Display the product to complete the collection
                PSCHideShowShoppingBubbleCartCollectionItem(productsToCompleteCollection[i], true);   
                //Display the LINE divider for the last product added to cart                
                PSCHideShowShoppingBubbleCartAddedItemLineDivider(selectedAddToBagItems[selectedAddToBagItems.length - 1].varCode, true);             
                //Display "Complete the Collection" section
                PSCHideShowMultiShoppingCartCompleteCollection(true);
                
                //Display the PLUS seperator if it's NOT the last product that completes the collection
                if(i != (productsToCompleteCollection.length - 1))
                {                
                    PSCHideShowShoppingBubbleCartItemPlusSeperator(productsToCompleteCollection[i], true);    
                }
            }
         }
    }
    else
    {
        //Complete collection is in BAG...Hide "Complete the Collection" DIV
        PSCHideShowMultiShoppingCartCompleteCollection(false);
    }        
   
    //END: "Complete the Collection" section
    
    //display error message is any exists
    if(productsWithErrorStr.length > 1)
    { 
        PSCHideShowMultiShoppingCartBubbleErrorMsg(productsWithErrorStr, true);
    }
    else
    {
        PSCHideShowMultiShoppingCartBubbleErrorMsg("", false);
    }
         
    //now show the shopping cart bubble
    PSCHideShowMultiShoppingCartBubble(true);
        
}

//Parses an error message string and returns a JSON object of ErrorMessages 
//Received from WebService in the format {"ErrorMessages":[ {"PrdParentCode": "", "PrdParentName": "", "VariantCode": "", "VariantName": "", "VariantDescription": "", "ErrorCode": "", "ErrorMessage": "" }]}
function PSCGetErrorMessagesForProducts(errorString)
{
    //Construct JSON Object. 
    if(errorString!=null  )
    {
        try
        {
            var jsonErrorMessages = eval('(' + errorString + ')');
            return jsonErrorMessages;
        }
        catch(err)
        {}
    }
     else {return null;}
}


//AddMultipleProductOnComplete Handler
function PSCAddMultipleProductOnComplete(result) 
{   
   DoDefault();
   try 
   {          
        //  if(result.ActivityStatus!=null && result.ActivityStatus==false){}
        //    alert("Status:"+result.ActivityStatus+"\nError:"+result.ErrorString);
        var  productJSONErrorMessages =  PSCGetErrorMessagesForProducts(result.ErrorString);
               
        var  selectedAddToBagItems = PSCGetAddToBasketItems();
        PSCDisplayShoppingCartBubble(selectedAddToBagItems, productJSONErrorMessages, false)
        
        if (result != null) 
        {
          
          //display the shopping cart totals
           _WebServiceAPI.RetrieveShoppingCart(GetCurrentCustomerID(),_ShoppingCartBubble_Class.RetrieveShoppingCartResultHandler);
        }
        //reset value            
         
    }
    catch (err) 
    { 
        alert(err);
    }
                 
}

//AddMultipleProductOnComplete Handler
function PSCAddCollectionProductOnComplete(result) 
{   
   DoDefault();
   try 
   {          
        //  if(result.ActivityStatus!=null && result.ActivityStatus==false){}
        //    alert("Status:"+result.ActivityStatus+"\nError:"+result.ErrorString);
        var  productJSONErrorMessages =  PSCGetErrorMessagesForProducts(result.ErrorString);
               
        var  selectedAddToBagItems = new Array();
        
        var collectionItemAddedToBag = new AddToBagItem();
        collectionItemAddedToBag.varCode = selectedCollectionVarCode;
        collectionItemAddedToBag.qty = 1;
        
        selectedAddToBagItems[0] = collectionItemAddedToBag;
        PSCDisplayShoppingCartBubble(selectedAddToBagItems, productJSONErrorMessages, true)
        
        if (result != null) 
        {
          
          //display the shopping cart totals
           _WebServiceAPI.RetrieveShoppingCart(GetCurrentCustomerID(),_ShoppingCartBubble_Class.RetrieveShoppingCartResultHandler);
        }
        //reset value            
         
    }
    catch (err) 
    { 
        alert(err);
    }
                 
}

/*********************************/
