/******************** Scripts related to Single Add to Bag ***********************/

//global var to hold all variants (one per product)
var variants_list = new Array();

//global var for variant ItemIndex
var varItemIndex = 0;

//global var to store the variant code of the product added
var selectedVarCode = "";

//global var to store the qty of the product added
var selectedQty = 0;

//Add to bag Item  Class
function AddToBagItem()
{  
  this.varCode = "";  //product variant code
  this.qty = "";   //the qty to add to bag
}

//Intializes the page
function PSCInitializeOnPageLoad()
{    
    var tempProducts=new Array();    
    tempProducts=variants_list;
    
    //hide shopping cart bubble and reset error message
    PSCHideShowSingleShoppingCartBubble(false);
    PSCHideShowSingleShoppingCartBubbleErrorMsg("",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 or Show the Shopping Cart Bubble
function PSCHideShowSingleShoppingCartBubble(display)
{
    var SingleShoppingCartBubble   = $get("ShoppingCartBubble_Div"); 
    
    if(SingleShoppingCartBubble != null)
    { 
                  
         if(display==true)
         {
            SingleShoppingCartBubble.style.display="";
            SingleShoppingCartBubble.style.visibility="visible";
         }
         else
         {
            SingleShoppingCartBubble.style.display="none";
            SingleShoppingCartBubble.style.visibility="hidden";         
         }
    }
}
 
//Hide or show the Single Shopping Cart Error Messages 
function PSCHideShowSingleShoppingCartBubbleErrorMsg(errorMsg,display)
{
    var SingleShoppingCartBubble_ErrorMsg_Div   = $get("SingleShoppingCartBubble_ErrorMsg_Div"); 
    var SingleShoppingCartBubble_ErrorMsg_Text  = $get("SingleShoppingCartBubble_ErrorMsg_Text"); 
  
    if(SingleShoppingCartBubble_ErrorMsg_Div != null)
    { 
                  
        if(display == true)
        {
           SingleShoppingCartBubble_ErrorMsg_Div.style.display="";
           SingleShoppingCartBubble_ErrorMsg_Div.style.visibility="visible";               
        }
        else
        {
           SingleShoppingCartBubble_ErrorMsg_Div.style.display="none";
           SingleShoppingCartBubble_ErrorMsg_Div.style.visibility="hidden";
        }
        if(SingleShoppingCartBubble_ErrorMsg_Text!=null)
        { 
            SingleShoppingCartBubble_ErrorMsg_Text.innerHTML=errorMsg;
        }
    }
}

//Hide or show the "Added To Bag" section
function PSCHideShowSingleShoppingCartAddedToBagSection(display)
{
    var  SingleShoppingCartBubble_AddedToBagSection_Div   = $get("ShoppingCartBubble_AddedToBagSection_Div"); 
      
    if(SingleShoppingCartBubble_AddedToBagSection_Div != null)
    {                   
        if(display == true)
        {
           SingleShoppingCartBubble_AddedToBagSection_Div.style.display="";
           SingleShoppingCartBubble_AddedToBagSection_Div.style.visibility="visible";               
        }
        else
        {
           SingleShoppingCartBubble_AddedToBagSection_Div.style.display="none";
           SingleShoppingCartBubble_AddedToBagSection_Div.style.visibility="hidden";
        }        
    }
}

//Hide or Show Added ShoppingCartItem in the shopping cart bubble
function PSCHideShowShoppingBubbleCartAddedItem(variantCode, display)
{
    var productDivID = variantCode+"_SingleShoppingCartBubbleProduct_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";
         }
     }
     
}

//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;
     }
}

function PSCAddSelectedProductToBag(varCode)
{   
    var selectedVarSKU = new Array();
    var selectedVarQty = new Array();           
                
    selectedVarSKU[0] = varCode;
    selectedVarQty[0] = PSCGetSelectedProductQty(varCode);  //Default Qty =  1     
        
    if(selectedVarQty[0] != '-')
    {
        //Set the global var to store selected product and selected qty
        //This will be used by the AJAX callback function: PSCAddCollectionProductOnComplete
        //to retrieve the variant added to bag    
        selectedVarCode = varCode;
        selectedQty = selectedVarQty[0];
    
        //add product to bag
        _WebServiceAPI.AddMultipleProductsToCart(GetCurrentCustomerID(), selectedVarSKU, selectedVarQty, PSCAddSingleProductOnComplete);                   
    }
    else
    {
         alert("Please select the quantity to add to bag");
    }
}

//update shopping cart bubble's product price and variant name
function PSCUpdateShoppingCartProductInfo(variantCode)
{ 
   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 = PSCGetSelectedProductQty(variantCode);   
      
   if(ShoppingCartBubble_ItemQuantityObj != null)
   { 
        ShoppingCartBubble_ItemQuantityObj.innerHTML = prdQty; 
   }                                    

}

//Display Shopping bag bubble div. 
//allProductErrorMessagesArray is an array of ProductErrorMessage Objs
function PSCDisplayShoppingCartBubble(selectedAddToBagItems, productJSONErrorMessages)
{
   var productsWithErrorStr = ""; 
   var allProductErrorMessagesArrayStr = "";   
     
   //Hide all shopping cart bubble items
   for(var i=0;i<variants_list.length;i++)
   {       
        PSCHideShowShoppingBubbleCartAddedItem(variants_list[i], false);
   }
    
   //Hide the "Added to Bag" section
   PSCHideShowSingleShoppingCartAddedToBagSection(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 += productJSONErrorMessages.ErrorMessages[x].PrdParentName+variantName + "<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);
             PSCHideShowShoppingBubbleCartAddedItem(varCode, true);
             PSCHideShowSingleShoppingCartAddedToBagSection(true);
             
             //Increment cartItems
             cartItems++;
         }        
    } 
    
    //display error message is any exists
    if(productsWithErrorStr.length > 1)
    { 
        PSCHideShowSingleShoppingCartBubbleErrorMsg(productsWithErrorStr, true);
    }
    else
    {
        PSCHideShowSingleShoppingCartBubbleErrorMsg("", false);
    }
         
    //now show the shopping cart bubble
    PSCHideShowSingleShoppingCartBubble(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;}
}

//AddSingleProductOnComplete Handler
function PSCAddSingleProductOnComplete(result) 
{   
   DoDefault();
   try 
   {          
        //  if(result.ActivityStatus!=null && result.ActivityStatus==false){}
        //    alert("Status:"+result.ActivityStatus+"\nError:"+result.ErrorString);
        var  productJSONErrorMessages =  PSCGetErrorMessagesForProducts(result.ErrorString);
        
        if ( result != null && result.ActivityStatus == false )
        {
            if (productJSONErrorMessages.ErrorMessages[0].ErrorCode == "OutOfStock")
                alert("Please accept our apologies - this item is currently out of stock.\r\nFor questions, call Customer Service at 877-254-9949.");
            else if ( productJSONErrorMessages.ErrorMessages[0].ErrorCode == "ExceedBasketMaxAmount" )
                alert(productJSONErrorMessages.ErrorMessages[0].ErrorMessage);
            else
                alert("The product cannot be added to your cart at this time, please try latter");
            // Don't add the product to add below and return from function.
            return;    
                
        }
        var  selectedAddToBagItems = new Array();
        
        var itemAddedToBag = new AddToBagItem();
        itemAddedToBag.varCode = selectedVarCode;
        itemAddedToBag.qty = selectedQty;
        
        selectedAddToBagItems[0] = itemAddedToBag;
        PSCDisplayShoppingCartBubble(selectedAddToBagItems, productJSONErrorMessages, true)
        
        if (result != null) 
        {
          
          //display the shopping cart totals
           _WebServiceAPI.RetrieveShoppingCart(GetCurrentCustomerID(),_ShoppingCartBubble_Class.RetrieveShoppingCartResultHandler);
        }
        //reset value            
         
    }
    catch (err) 
    { 
        alert(err);
    }
                 
}

/*********************************/
