

//////////FAVORITES PROCESSING - PRIMARILY CLIENT SIDE, PAGE DOES NOT CHANGE 


////UPDATE FAVORITE - CALL FROM SCREEN WITH CHECKBOX...IF CHECKED, ADDS TO FAVORITE, IF NOT IT IS REMOVED

function UpdateFavorite( favId , ItemId , iNumFavLists , strCatNum  ) { 
	
		
		if ( favId.checked == true ) {  
			//var numfavlists = Form1.NumFavoritesLists.value ; 
			if ( iNumFavLists > 1 ) 
				window.open( "../Order/PickFavoritesList.aspx?ItemId=" + ItemId + "&strCatNum=" + strCatNum   , "FavPopup" , "width=400 , height=400, scrollbars=yes , resizable=yes " ) ; 
			else 
			    PageMethods.AddFavorite(ItemId,0,null,OnError);
				//parent.frames["hidden"].location.href="../AppCode/ClientSQL.aspx?Action=AddFavorite&ItemId=" + ItemId  + "&CatId=0" ; 
			}
		else { 	
			    PageMethods.RemoveFavorite(ItemId,null,OnError);
			    //parent.frames["hidden"].location.href="../AppCode/ClientSQL.aspx?Action=RemoveFavorite&ItemId=" + ItemId ; 
			}
		} //UpdateFavorite
		
	
///FAVORITES MAINTENANCE FUNCTIONS HERE AS WELL....	
////MOVE FAVORITE - CALL FROM MAINTENANCE SCREEN...MOVE FROM ONE LIST TO ANOTHER

function MoveFavorite( ItemId , strCatNum , iOldCatId ) { 
	
		window.open( "../Order/PickFavoritesList.aspx?ItemId=" + ItemId + "&strCatNum=" + strCatNum  + "&iOldCatId=" + iOldCatId   , "FavPopup" , "width=400 , height=400, scrollbars=yes , resizable=yes " ) ; 
			
		} //UpdateFavorite		
		

function UpdateFavListName( iCatId , objListName ) { 

	var strListName ;
	var Form1 = document.forms[0];
	strListName = Form1[objListName].value; 
	
    PageMethods.UpdateFavListName(iCatId,strListName,OnUpdateFavListNameComplete,OnError);
	//parent.frames["hidden"].location.href="../AppCode/ClientSQL.aspx?Action=UpdateFavListName&CatId=" + iCatId + "&strListName=" + strListName ; 	
	} //Update Favorite List Name
		
function OnUpdateFavListNameComplete(result, userContext) {
    alert("Name Updated.");
    window.location = "../Order/FavoritesMaintain.aspx";    //TC 2009 Q4
    }

	
function DeleteFavList( iCatId ) { 
    PageMethods.RemoveFavoritesList(iCatId,OnDeleteFavListComplete,OnError);
	//parent.frames["hidden"].location.href="../AppCode/ClientSQL.aspx?Action=RemoveFavoritesList&CatId=" + iCatId ; 
	}

function OnDeleteFavListComplete(result, userContext) {
    window.location ="../Order/FavoritesMaintain.aspx";
    }

/////////////////////////////// ITEM QUANTITY UPDATES ////////////////////////////////


/////UPDATE ITEM - CALLED WHEN Quantity changes...Can update calling screen quantity, price, and ext amount
///KEY DIFFERENTIATORS TO MAKE CALL
///objQtyID MUST be a valid Text Box where Qty is being updated
///objExtAmtDiv is used to pass updated Ext Amt to the page....These options are possible:
    ////(1) - "N" - There is no place for Ext Amount, so leave it alone
    ////(2) - "RELOAD" - The whole page ( cart page for example ) needs to be reloaded to re-display cart totals and messages
    ////(3) - The name of the Ext Amt Div...It will be dynamically updated on the page when this is run
////objPriceDiv - Label holding Price display on the page...If changed on update, it will be changed on the screen
////objFlyer - Flyer value
	
function UpdateItem( objQtyID , iItemId ,sCatalogNum, iCartId , iMin , iMult , dblPrice , strContractItem , strPrompted , objExtAmtDiv , objPriceDiv , objFlyer , strNextURL  ){  
	
	
		var iNewQty = objQtyID.value ; 
		var clientID = objQtyID.name ; 
		var Form1 = document.forms[0];
		var sExtAmtDiv ="";
		var strNextPage = "";
		var sDC = "";//TC 2009 Q3
		
		///extAmtDiv is used to identify "next page" 
		    ///Can come from Form ( Cart page ) , or passed as parameter (pop-ups ) 
		///objextAmtDiv is used to update an object on the existing page
        ///strNextPage is not really used....Except with prompts....


		if (strNextURL != null && strNextURL.toString() > "")
		    sExtAmtDiv = strNextURL; 
		else if (Form1["extAmtDiv"] != null) 
		    sExtAmtDiv = Form1["extAmtDiv"].value;

		if (Form1["strNextPage"] != null)
		    strNextPage = Form1["strNextPage"].value;

		var ctx = [sExtAmtDiv, iCartId, sCatalogNum, objExtAmtDiv, objPriceDiv, objFlyer, strNextPage, dblPrice, strPrompted, iNewQty]; //TC 2009 Q4: Added iNewQty

        //Validate Quantity
        if (isNaN(iNewQty)) { 
			alert( "A NUMBER MUST BE ENTERED" ) ; 
			Form1[ clientID ].value = "" ; 
			Form1[ clientID ].focus() ; 
			return; 
			}

		if (iNewQty == "") {
		    alert("A QUANTITY MUST BE ENTERED");
		    Form1[clientID].value = "";
		    Form1[clientID].focus();
		    return;
		}

		//TC 2009 Q3
		if (Number(iNewQty) < 0) {
		    iNewQty = 0;
		}

		if (iNewQty == 0 && Form1[clientID] != null) {
		    Form1[clientID].value = "";
		}
		//TC 2009 Q3
		
		if ( Number( iNewQty ) < Number( iMin )  && iNewQty  > 0 ) { 
		if ( confirm( "Entered quantity is less than the minimum order quantity of " + iMin + ". Do you want to order minimum qty? "  ) )  {
			iNewQty = iMin ;
			if (Form1[clientID] != null) { //TC: 2009 Q3
			    Form1[clientID].value = iMin;
			}
			}
		else {
		    Form1[clientID].value = ""; 
			Form1[ clientID ].focus() ; 
			return; 
			}
		} 

		else if ( iMult > 1 ) { 
		if ( iNewQty % iMult != 0 ) {
			alert( "This item must be ordered in multiples of " + iMult + ". Your order qty will be rounded up to next multiple." ) ; 
			
			if (Form1[clientID] != null) { //TC: 2009 Q3
			
			    Form1[ clientID ].value = Math.ceil( iNewQty / iMult ) * iMult  ;
			}
			iNewQty = Math.ceil( iNewQty / iMult ) * iMult  ;
			}	
		}
		
		//Get Flyer Code
		var flyerID 
		var strFlyer ; 
			
		if ( objFlyer > "" ) { 
			flyerID = objFlyer.name ; 
			strFlyer = Form1[ flyerID ].value ; 
			}
		else 
			strFlyer = "" ; 
			
		
		///GET OPTIONS IF THEY EXIST 
		var promptlist = "";
		var hasOptions = "N" ; 
		
		for ( i = 0 ; i < Form1.length ; i++ ) { 
			if ( Form1.elements[i].name == "iNumPrompts" ) 	
				hasOptions = "Y" ; 
			}
			
        
		if ( hasOptions == "Y" ) 	{ 
			var x , pn , itemchecked ; 		
			var selOpt ; 
			
	
			//Only pass as many prompts as necessary
			for ( x = 1 ; x <= Form1.iNumPrompts.value ; x++ ) { 
				pn = "category" + x ; 
				itemchecked = false ; 
			
				//If only ONE option, there is no array of elements...
				//Need to look at the value and selection of the radio box itself 
				//These most likely are "yes or no", so allow an unchecked box here...

				numopts = Form1.elements[pn].length ;	
		
				if ( isNaN( numopts )  )  {
				    if (Form1.elements[pn].checked) {
				        promptlist += String(Form1.elements[pn].value) + "||";
				        continue;
				        }
					}  
		
				 
				//Find selected option and pass to update program
  				for ( y = 0 ; y < numopts ; y++ ) {
  					if ( Form1.elements[pn][y].checked ) { 
						promptlist += Form1.elements[pn][y].value + "||" ; 
						itemchecked = true ; 					
						} //item checked
					}   //loop through options for prompt 

 				///Not mandatory from this screen:
 					//if ( itemchecked == false ) { 
					//alert( "You have not selected one option for each category. You must do so before you can add this item to the cart. " ) ; 
					//return ;
					//}  

				}  //loop through prompts	
				
			} //Has Options

            //Do UPseell is done...( now integrated into screens...
            //if (strDoUpsell == null)
			//    strDoUpsell = "";

			//TC 2009 Q3
			//Check if qty > inventory, if yes, display replacement/substitute item
			//if no, use the original item and pass the DC
			var objhiddenMaxQty = document.getElementById("hiddenMaxQty");
			var objhiddenMaxQtyDC = document.getElementById("hiddenMaxQtyDC");
			if (objhiddenMaxQty != null && objhiddenMaxQty.value != null && objhiddenMaxQty.value != "") {

			    if (objhiddenMaxQty.value * 1 < iNewQty) {
			        // Need to go back to the replacement item info
			        // replace the links and labels with stored values
			        var objhiddenlblDescription = document.getElementById("hiddenlblDescription");
			        if (objhiddenlblDescription != null) {
			            var objlblDescription = document.getElementById("lblDescription");

			            if (objlblDescription != null) {
			                objlblDescription.innerHTML = objhiddenlblDescription.value;
			            }

			        }

			        var objhiddenlblSKU = document.getElementById("hiddenlblSKU");
			        if (objhiddenlblSKU != null) {
			            var objlblSKU = document.getElementById("lblSKU");
			            if (objlblSKU != null) {
			                objlblSKU.innerHTML = objhiddenlblSKU.value;
			            }
			        }

			        var objhiddenlblUOM = document.getElementById("hiddenlblUOM");
			        if (objhiddenlblUOM != null) {
			            var objlblUOM = document.getElementById("lblUOM");
			            if (objlblUOM != null) {
			                objlblUOM.innerHTML = objhiddenlblUOM.value;
			            }
			        }

			        var objhiddenPriceBreakQty = document.getElementById("hiddenPriceBreakQty");
			        if (objhiddenPriceBreakQty != null) {
			            objhiddenPriceBreakQty.value = iNewQty.toString(); //Update Qty
			            var objPriceBreakQty = document.getElementById("PriceBreakQty");
			            if (objPriceBreakQty != null) {
			                objPriceBreakQty.innerText = objhiddenPriceBreakQty.value;
			            }
			        }

			        var objhiddenlbllcp = document.getElementById("hiddenlbllcp");
			        if (objhiddenlbllcp != null) {
			            var objlbllcp = document.getElementById("lbllcp");
			            if (objlbllcp != null) {
			                objlbllcp.innerHTML = objhiddenlbllcp.value;
			            }
			        }

			        var objhiddenlnkProductDetail = document.getElementById("hiddenlnkProductDetail");
			        if (objhiddenlnkProductDetail != null) {
			            var objlnkProductDetail = document.getElementById("lnkProductDetail");
			            if (objlnkProductDetail != null) {
			                objlnkProductDetail.href = objhiddenlnkProductDetail.value;
			            }
			        }

			        var objhiddenlnkQuickFacts = document.getElementById("hiddenlnkQuickFacts");
			        if (objhiddenlnkQuickFacts != null) {
			            var objlnkQuickFacts = document.getElementById("lnkQuickFacts");
			            if (objlnkQuickFacts != null) {
			                objlnkQuickFacts.href = objhiddenlnkQuickFacts.value;
			            }
			        }

			        var objhiddenhlAddToCart = document.getElementById("hiddenhlAddToCart");
			        if (objhiddenhlAddToCart != null) {
			            var objhlAddToCart = document.getElementById("hlAddToCart");
			            if (objhlAddToCart != null) {
			                objhlAddToCart.href = objhiddenhlAddToCart.value;
			            }
			        }

			        var objhiddenlblPrice = document.getElementById("hiddenlblPrice");
			        if (objhiddenlblPrice != null) {
			            var objlblPrice = document.getElementById("lblPrice");
			            if (objlblPrice != null) {
			                objlblPrice.innerHTML = objhiddenlblPrice.value;
			            }
			        }

			        //Clear stored values
			        objhiddenMaxQty.value = "";
			        if (objhiddenMaxQtyDC != null) objhiddenMaxQtyDC.value = "";

			        objhiddenlblDescription.value = "";
			        objhiddenlblSKU.value = "";
			        objhiddenlblUOM.value = "";
			        objhiddenPriceBreakQty.value = "";
			        objhiddenlbllcp.value = "";
			        objhiddenlnkProductDetail.value = "";
			        objhiddenlnkQuickFacts.value = "";
			        objhiddenhlAddToCart.value = "";
			        objhiddenlblPrice.value = "";

			        return;
			    }
			    else {

			        objhiddenMaxQty.value = "";
			        if (objhiddenMaxQtyDC != null) {
			            sDC = objhiddenMaxQtyDC.value;
			            objhiddenMaxQtyDC.value = "";
			        }
			    }
			}

			//TC 2009 Q3
            
			//Make SQL update call in hidden frame
			if (iCartId == 0)  
			{
				//var updSQL = "../AppCode/ClientSQL.aspx?Action=AddCartItem&iItemId=" + iItemId  + "&sCatalogNumber=" + sCatalogNum  + "&iNewQty=" + iNewQty  + "&dblPrice=" + dblPrice  + "&strContractItem=" + strContractItem + "&extAmtDiv=" + objExtAmtDiv + "&priceDiv=" + objPriceDiv + "&strFlyer=" + strFlyer + "&promptlist=" + promptlist + "&strDoUpsell=" + strDoUpsell ;
			    PageMethods.AddCartItem(iItemId, sCatalogNum, dblPrice, strContractItem, strFlyer, iNewQty, promptlist, "" ,  sDC, OnAddItemComplete, OnError, ctx);
			}
			else 
			{
				//PageMethods.UpdateCartItem(iCartId,sCatalogNum,iNewQty,dblPrice,strFlyer,promptlist, OnUpdateItemComplete,OnError,ctx);//TC 2009 Q3
				//TC 2009 Q3
			    if (sExtAmtDiv == "FAVORITE" || sExtAmtDiv == "ORDERGUIDE")
				{
				    if (iNewQty <= 0) 
				    {
				            PageMethods.UpdateCartItem(iCartId, sCatalogNum, 0, dblPrice, strFlyer, promptlist, OnUpdateItemComplete, OnError, ctx);
				    }
				    else 
				     {
				            PageMethods.UpdateCartItem(iCartId, sCatalogNum, 0, dblPrice, strFlyer, promptlist, null, OnError, ctx);
				            PageMethods.AddCartItem(iItemId, sCatalogNum, dblPrice, strContractItem, strFlyer, iNewQty, promptlist, "", sDC, OnAddItemComplete, OnError, ctx);
				     }
				 } 
				 else 				 
				 {
				    PageMethods.UpdateCartItem(iCartId,sCatalogNum,iNewQty,dblPrice,strFlyer,promptlist, OnUpdateItemComplete, OnError, ctx);
				 }
				//TC 2009 Q3
				//var updSQL = "../AppCode/ClientSQL.aspx?Action=UpdateCartItem&iCartId=" + iCartId + "&sCatalogNumber=" + sCatalogNum  +  "&iNewQty=" + iNewQty + "&dblPrice=" + dblPrice  + "&extAmtDiv=" + objExtAmtDiv + "&priceDiv=" + objPriceDiv + "&strFlyer=" + strFlyer + "&promptlist=" + promptlist  ; 
			}


		    if (strNextURL == null || strNextURL == "ORDER") 
                  return false;				
		}

        //function GetQuantity(productID, elemToUpdate, productLabelElem, buttonElem) {
        //   var userContext = [productID, elemToUpdate, productLabelElem, buttonElem];
        //   Samples.ProductQueryService.GetProductQuantity(productID, OnSucceeded, null, userContext, null);
        //   $get(buttonElem).value = "Retrieving value...";
        //}
        //function OnSucceeded(result, userContext) {
        //   var productID = userContext[0];
        //   var elemToUpdate = userContext[1];
        //   var productLabelElem = userContext[2];
        //   var buttonElem = userContext[3];
        //   $get(buttonElem).value = "Get Quantity from Web Service";
        //   if ($get(elemToUpdate) !== null && $get(productLabelElem).innerHTML == productID) {
        //     $get(elemToUpdate).value = result;		

    function OnAddItemComplete(result, userContext,methodName)
        {
        
        var sExtAmtDiv =  userContext[0];
        var iItemId = userContext[1];
        var sCatalogNum = userContext[2];
        var objExtAmtDiv = userContext[3];
        var objPriceDiv = userContext[4];
        var objFlyer = userContext[5];
        var strNextPage = userContext[6];
        var dblPrice = userContext[7];
        var strPrompted = userContext[8];
        var iNewQty = userContext[9]; //TC 2009 Q4
        //alert(result);  
        //alert("Method Name is " + methodName);
        
        var aResults = String(result).split("||");
        var iCartId = aResults[0];
 
        //TC 2009 Q4
        //Display Price Change Message
        var sPriceChangeMsg = aResults[6]; //Price Change Message
         
        if ( sPriceChangeMsg != "") 
                alert(sPriceChangeMsg);
        //TC 2009 Q4
        
       //for (var i = 0; i < aResults.length; i++) {
       //    alert(aResults[i]);
       //    }
       
           
        if (sCatalogNum  != null && sCatalogNum.substr(0,4) == "3495")
            {
            var sNextPage = "";
            
            if (sExtAmtDiv == "CART")
                sNextPage = "Cart/ReviewCart.aspx";
            else if (sExtAmtDiv == "FAVORITE")
                sNextPage = "Order/FavoritesOrder.aspx";
            else if (sExtAmtDiv == "ORDERGUIDE")
                sNextPage = "Order/OrderGuide.aspx";

             window.location ="../Cart/SelectUrnType.aspx?ItemId=" + iItemId + "&CartId=" + iCartId + "&CatNum=" + sCatalogNum + "&Next=" + sNextPage;
            }
       else if ( sExtAmtDiv == "CART")
            {
            //Option here to open it up with prompts...
            //lblSQLMessage.Text += "parent.frames['main'].location.href='../Cart/ReviewCart.aspx?PCart=" + oparam_cart_id.Value.ToString() + "#XOptions'" ;

                window.location = "../Cart/ReviewCart.aspx";
            
            }
         //else if ($(objExtAmtDiv) == "FAVORITE")
            else if (sExtAmtDiv == "FAVORITE" || (sExtAmtDiv == "FAVORITE_CHECK" && sPriceChangeMsg != "")) //TC 2009 Q4
            {
              
             if ( strPrompted == "Y" )
                 window.location = "../Order/FavoritesOrder.aspx?PCart=" + iCartId + "#XOptions";
             else
                 window.location = "../Order/FavoritesOrder.aspx";
                 
                
            }
            else if (sExtAmtDiv == "REORDER" || (sExtAmtDiv == "REORDER_CHECK" && sPriceChangeMsg != "")) //TC 2009 Q4
            {
            
                if ( strPrompted == "Y" )
                        window.location ="../Order/ReOrder.aspx?PCart=" + iCartId + "#XOptions";
                else 
                        window.location ="../Order/ReOrder.aspx" ;     
            }
            //else if (sExtAmtDiv == "ORDERGUIDE")
            else if (sExtAmtDiv == "ORDERGUIDE" || (sExtAmtDiv == "ORDERGUIDE_CHECK" && sPriceChangeMsg != "")) //TC 2009 Q4
   
            {
                if ( strPrompted == "Y" )
                        window.location ="../Order/OrderGuide.aspx?PCart=" + iCartId + "#XOptions";
                else 
                     window.location ="../Order/OrderGuide.aspx" ;

             }
             else if (sExtAmtDiv == "ORDER")
        {
                window.location = "../Order/ReviewOrder.aspx";
                }
        else
        {
                //lblSQLMessage.Text += "parent.frames['main'].top_nav_lblCartItems.innerHTML='" + HttpContext.Current.Session["CartItems"].ToString() + " Items in Cart" + "';";
                //lblSQLMessage.Text += "parent.frames['main'].top_nav_lblCartValue.innerHTML='" + "Subtotal: " + double.Parse(HttpContext.Current.Session["CartValue"].ToString()).ToString("C") + "';";

            try {
                var objCartItems = document.getElementById("ctl00_TopNavContentId_TopNav_lblCartItems");
                objCartItems.innerHTML = aResults[2];

                var objCartValue = document.getElementById("ctl00_TopNavContentId_TopNav_lblCartValue");
                objCartValue.innerHTML = aResults[3];

                if ($(objPriceDiv) != null)
                    $(objPriceDiv).innerHTML = aResults[4]; //TC: New Price (Cart Price)

                if ($(objExtAmtDiv) != null)
                    $(objExtAmtDiv).innerHTML = aResults[5];
                    

//                var objAmt = document.getElementById(objExtAmtDiv);
//                objAmt.innerHTML = aResults[3];

//                var objPrice = document.getElementById(objPriceDiv);
                //                objPrice.innerHTML = aResults[4];
//              DIsplay price alert
            }
            catch (oErr) {
                alert("Following error occured :" + oErr.description);
            }
                                        

                    //lblSQLMessage.Text += "parent.frames['main']." + Request["extAmtDiv"] + ".innerHTML='" + dblExtAmt.ToString("C") + "';";

                //UPDATE CALLING SCREEN WITH NEW PRICE

                //if (Math.Round(dblNewPrice, 2) != Math.Round(dblPrice, 2))
                //    {
                //    lblSQLMessage.Text += "parent.frames['main']." + Request["PriceDiv"] + ".innerHTML='" + dblNewPrice.ToString("C") + "';";
                //    lblSQLMessage.Text += "alert( 'Price has changed due to change in quantity' );";
                //    } //Price Has changed 
        }  //ExtAmt NOT passed as "CART" 
			
        
        //window.location.href("/Cart/ReviewCart.aspx");        
        } //OnAddItemComplete


    function OnUpdateItemComplete(result, userContext,methodName)
        {

            var sExtAmtDiv = userContext[0];
            var iItemId = userContext[1];
            var sCatalogNum = userContext[2];
            var objExtAmtDiv = userContext[3];
            var objPriceDiv = userContext[4];
            var objFlyer = userContext[5];
            var strNextPage = userContext[6];
            var dblPrice = userContext[7];
            var strPrompted = userContext[8];
            var iNewQty = userContext[9];
            
            //alert( result ) ; 
        
            var aResults = String(result).split("||");

            var sPriceChangeMsg = aResults[0];
            var sMediaCodeMsg = aResults[1];
        
            if ( sPriceChangeMsg != "") 
                alert(sPriceChangeMsg);
                
            if ( sMediaCodeMsg != "") 
                alert(sMediaCodeMsg);


            if (sExtAmtDiv == "CART") {
                //Option here to open it up with prompts...
                //lblSQLMessage.Text += "parent.frames['main'].location.href='../Cart/ReviewCart.aspx?PCart=" + oparam_cart_id.Value.ToString() + "#XOptions'" ;

                window.location = "../Cart/ReviewCart.aspx";

            }

            //else if ($(objExtAmtDiv) == "FAVORITE")
            ///If Item Added, option to do prompt-pop-is used
            ///Here, the quantity is just updated..Refresh screen if called here...

            else if (sExtAmtDiv  == "FAVORITE" || (sExtAmtDiv == "FAVORITE_CHECK" && (sPriceChangeMsg != "" || (iNewQty * 1) == 0))) //TC 2009 Q4
                window.location = "../Order/FavoritesOrder.aspx";
            else if (sExtAmtDiv == "REORDER" || (sExtAmtDiv == "REORDER_CHECK" && (sPriceChangeMsg != "" || (iNewQty * 1) == 0))) //TC 2009 Q4
                window.location = "../Order/ReOrder.aspx";
            //else if (sExtAmtDiv == "ORDERGUIDE")
            else if (sExtAmtDiv == "ORDERGUIDE" || (sExtAmtDiv == "ORDERGUIDE_CHECK" && (sPriceChangeMsg != "" || (iNewQty * 1) == 0))) //TC 2009 Q4
                window.location = "../Order/OrderGuide.aspx";
            //TC: 2009 Q3
            else if (sExtAmtDiv == "ORDER") {
                window.location = "../Order/ReviewOrder.aspx";
            }
            //TC: 2009 Q3
            else {

                try {
                    var objCartItems = document.getElementById("ctl00_TopNavContentId_TopNav_lblCartItems");
                    objCartItems.innerHTML = aResults[2];

                    var objCartValue = document.getElementById("ctl00_TopNavContentId_TopNav_lblCartValue");
                    objCartValue.innerHTML = aResults[3];

                    if ($(objPriceDiv) != null)
                        $(objPriceDiv).innerHTML = aResults[4];

                    if ($(objExtAmtDiv) != null)
                        $(objExtAmtDiv).innerHTML = aResults[5];

                }
                catch (oErr) {
                    alert("Following error occured :" + oErr.description);
                }

            }  //Cart not passed as next page..update page elements in-line///


        } //OnUpdateItemComplete

        function OnUpdatePromptsComplete(results, userContext, methodName) {

            ///Once prompts are done, the prompts should be removed from the page
            ///Refresh the page ( it should have passed 'strNextPage' to do so ) 
            ///Worst case, open cart page....

            var strNextPage = userContext[0];

            if (strNextPage == "")
                window.location = "/Cart/ReviewCart.aspx";
            else
                window.location = "/" + strNextPage;       


        }    

    function OnError(error, userContext,methodName) {

        if (error != null) {
            alert(error.get_message());
            }
        }


        function OnAddGraingerItemComplete(result, userContext, methodName) {

            //alert(result);
            //alert(methodName);

//        var strNextPage = userContext[6];

//        var aResults = String(result).split("||");

//        var sPriceChangeMsg = aResults[0];
//        var sMediaCodeMsg = aResults[1];

//        if (sPriceChangeMsg != "")
//            alert(sPriceChangeMsg);

//        if (sMediaCodeMsg != "")
//            alert(sMediaCodeMsg);


        //if (strNextPage == "")
            window.location = "/Cart/ReviewCart.aspx";
        //else
        //    window.location = "/" + strNextPage;
    }
	
///////////////////////////  PROMPT PROCESSING /////////////////////////////////////////


///UPDATE PROMPTS...PAGE NEEDS TO OPEN SECTION WITH PROMPTS AND SUBMITS TO HERE...
//THIS ROUTINE VALIDATES THAT ALL PROMPTS ARE SELECTED, THEN SUBMITS TO HIDDEN FRAME FOR SQL PROCESSING

function UpdatePrompts() { 
	
	var x , pn , itemchecked ; 		
	var selOpt ; 
	var promptlist = "";
	var Form1 = document.forms[0];

	
	//Only pass as many prompts as necessary
	for ( x = 1 ; x <= Form1.iNumPrompts.value ; x++ ) { 
		pn = "category" + x ; 
		itemchecked = false ; 

		//If only ONE option, there is no array of elements...
		//Need to look at the value and selection of the radio box itself 
		//These most likely are "yes or no", so allow an unchecked box here...

		numopts = Form1.elements[pn].length ;	
		
		if ( isNaN( numopts )  )  {
		    if (Form1.elements[pn].checked) {
		        promptlist += String(Form1.elements[pn].value) + "||";
		        continue;
		        }
			}  
		
				 
		//Find selected option and pass to update program
  		for ( y = 0 ; y < numopts ; y++ ) {
  			if ( Form1.elements[pn][y].checked ) { 
				promptlist += Form1.elements[pn][y].value + "||" ; 
				itemchecked = true ; 					
				} //item checked
			}   //loop through options for prompt 

 		if ( itemchecked == false ) { 
			alert( "You have not selected one option for each category. You must do so before you can add this item to the cart. " ) ; 
			return ;
			}  

		}  //loop through prompts

      var strNextPage = "";
      
      if (Form1["strNextPage"] != null) 
        strNextPage = Form1["strNextPage"].value;

      var ctx = [strNextPage];	                

     //alert( "Cart Value is : " + Form1.iCartId.value + "; promptlist:" + promptlist);			
	  //parent.frames["hidden"].location.href="../AppCode/ClientSQL.aspx?Action=UpdateCartPrompts&iCartId=" + Form1.iCartId.value + "&promptlist=" +  promptlist + "&strNextPage=" + Form1.strNextPage.value  ; 
      PageMethods.UpdateCartPrompts(Form1.iCartId.value,promptlist,OnUpdatePromptsComplete,OnError,ctx);
 
	}
	
function CancelPrompts() { 

	var Form1 = document.forms[0];

	  //Just Takes calling page and refreshes it..Takes out the prompt box	
	   window.location = "../" +  Form1.strNextPage.value   ; 
	  
	    
    	}

    function OnAddGraingerItemComplete(result, userContext)
        {
        
        var objExtAmtDiv =  userContext;

        
        var aResults = String(result).split("||");
        
        var iReturn = aResults[0];
        var sMsg = aResults[1];
        
       // for (var i = 0; i < aResults.length; i++) {
       //     alert(aResults[i]);
       //     }
        
        //document.getElementById(destCtrl);
        //alert("sExtAmtDiv: " + sExtAmtDiv);
        //alert("objExtAmtDiv: " + objExtAmtDiv);
        
        if (iReturn == "0") {
            window.location = "/Cart/ReviewCart.aspx";
        }
        else {
            alert( "There is a problem adding this item. " + sMsg ) ;
            }                                 

        //window.location.href("/Cart/ReviewCart.aspx");        
        }

function AddGraingerItem( objQtyID , sSKU ,sShortDescription, sLongDescription , sUOM , iMin , iMult , dblPrice , sImageUrl , sCountry , objExtAmtDiv  ){  
		
		var iNewQty = objQtyID.value ; 
		var clientID = objQtyID.name ; 
					
		
		//Validate Quantity
		if ( isNaN( iNewQty ) )  { 
			alert( "A NUMBER MUST BE ENTERED" ) ; 
			Form1[ clientID ].value = "" ; 
			Form1[ clientID ].focus() ; 
			return; 
			}
	
		if( iNewQty == "" ){ 
			alert( "A QUANTITY MUST BE ENTERED" ) ; 
			Form1[ clientID ].value = "" ; 
			Form1[ clientID ].focus() ; 
			return; 
			}
				
		if ( Number( iNewQty ) < Number( iMin )  && iNewQty  > 0 ) { 
		if ( confirm( "Entered quantity is less than the minimum order quantity of " + iMin + ". Do you want to order minimum qty? "  ) )  {
			iNewQty = iMin ; 
			Form1[ clientID ].value = iMin ; 
			}
		else { 
			Form1[ clientID ].value = "" ; 
			Form1[ clientID ].focus() ; 
			return; 
			}
		} 

		else if ( iMult > 1 ) { 
		if ( iNewQty % iMult != 0 ) {
			alert( "This item must be ordered in multiples of " + iMult + ". Your order qty will be rounded up to next multiple." ) ; 
			Form1[ clientID ].value = Math.ceil( iNewQty / iMult ) * iMult  ;
			iNewQty = Math.ceil( iNewQty / iMult ) * iMult  ;
			}	
		}
		
		if ( ! objExtAmtDiv > "" ) 
			objExtAmtDiv = "N"; 
		
		var ctx = objExtAmtDiv;
        
        PageMethods.AddGraingerCartItem(sSKU,iNewQty,sShortDescription,sLongDescription,	iMin,iMult,dblPrice,sCountry,sImageUrl,OnAddGraingerItemComplete,OnError,ctx);

        /*        
		var updSQL = "../AppCode/ClientSQL.aspx?Action=AddGraingerCartItem&SKU=" + escape(sSKU) 
					+ "&short_description=" + escape(sShortDescription)  
					+ "&long_description=" + escape(sLongDescription)
					+ "&unit_of_measure=" + sUOM 
					+ "&minimum_quantity=" + iMin
					+ "&items_in_box=" + iMult
					+ "&case_pack=1" 
					+ "&price=" + dblPrice  
					+ "&ord_qty=" + iNewQty 
					+ "&image_url=" + escape(sImageUrl)  
					+ "&country=" + sCountry 
					+ "&extAmtDiv=" + objExtAmtDiv ;  
					
		parent.frames["hidden"].location.href=updSQL ; 
		*/		
		} //Add Grainger Item

		function AddGraingerItemFmList(QtyId, sSKU, sShortDescription, sLongDescription, sUOM, iMin, iMult, dblPrice, sImageUrl, sCountry, objExtAmtDiv) {

		var txtQty = document.getElementById(QtyId);
		var iNewQty = txtQty.value;
		var clientID = txtQty.name;
		var Form1 = document.forms[0];
		
										
		//Validate Quantity
		if ( isNaN( iNewQty ) )  { 
			alert( "A NUMBER MUST BE ENTERED" ) ; 
			Form1[ clientID ].value = "" ; 
			Form1[ clientID ].focus() ; 
			return; 
			}
	
		if( iNewQty == "" ){ 
			alert( "A QUANTITY MUST BE ENTERED" ) ; 
			Form1[ clientID ].value = "" ; 
			Form1[ clientID ].focus() ; 
			return; 
			}
				
		if ( Number( iNewQty ) < Number( iMin )  && iNewQty  > 0 ) { 
		if ( confirm( "Entered quantity is less than the minimum order quantity of " + iMin + ". Do you want to order minimum qty? "  ) )  {
			iNewQty = iMin ; 
			Form1[ clientID ].value = iMin ; 
			}
		else { 
			Form1[ clientID ].value = "" ; 
			Form1[ clientID ].focus() ; 
			return; 
			}
		} 

		else if ( iMult > 1 ) { 
		if ( iNewQty % iMult != 0 ) {
			alert( "This item must be ordered in multiples of " + iMult + ". Your order qty will be rounded up to next multiple." ) ; 
			Form1[ clientID ].value = Math.ceil( iNewQty / iMult ) * iMult  ;
			iNewQty = Math.ceil( iNewQty / iMult ) * iMult  ;
			}	
		}
		
		if ( ! objExtAmtDiv > "" ) 
			objExtAmtDiv = "N"; 
		
		var ctx = objExtAmtDiv;
		// Omniture Code
        QtyId= "A" + QtyId;
        _numeric_.omni.sendAddToCart_byID(QtyId,sSKU,'Grainger','Grainger - Item');   

        //ClientSQL2.AddGraingerCartItem(sSKU,iNewQty,sShortDescription,sLongDescription,	iMin,iMult,dblPrice,sCountry,sImageUrl,OnAddGraingerItemComplete,OnError,ctx);
        PageMethods.AddGraingerCartItem(sSKU,iNewQty,sShortDescription,sLongDescription,	iMin,iMult,dblPrice,sCountry,sImageUrl,OnAddGraingerItemComplete,OnError,ctx);
        /*
		var updSQL = "../AppCode/ClientSQL.aspx?Action=AddGraingerCartItem&SKU=" + escape(sSKU) 
					+ "&short_description=" + escape(sShortDescription)  
					+ "&long_description=" + escape(sLongDescription)
					+ "&unit_of_measure=" + sUOM 
					+ "&minimum_quantity=" + iMin
					+ "&items_in_box=" + iMult
					+ "&case_pack=1" 
					+ "&price=" + dblPrice  
					+ "&ord_qty=" + iNewQty 
					+ "&image_url=" + escape(sImageUrl)  
					+ "&country=" + sCountry 
					+ "&extAmtDiv=" + objExtAmtDiv ;  
				
		parent.frames["hidden"].location.href=updSQL ; 
		*/		
		} //Add Grainger Item	

function AddGraingerItemNoQty( sSKU ,sShortDescription, sLongDescription , sUOM , iMin , iMult,   dblPrice , sImageUrl , sCountry  ){  
	
		var ctx = "N";

        PageMethods.AddGraingerCartItem(sSKU,iMin,sShortDescription,sLongDescription,	iMin,iMult,dblPrice,sCountry,sImageUrl,OnAddGraingerItemComplete,OnError,ctx);
        /*
				var updSQL = "../AppCode/ClientSQL.aspx?Action=AddGraingerCartItem&SKU=" + escape(sSKU) 
					+ "&short_description=" + escape(sShortDescription)  
					+ "&long_description=" + escape(sLongDescription)
					+ "&unit_of_measure=" + sUOM 
					+ "&minimum_quantity=" + iMin
					+ "&items_in_box=" + iMult
					+ "&case_pack=1" 
					+ "&price=" + dblPrice  
					+ "&ord_qty=" + iMin  
					+ "&image_url=" + escape(sImageUrl)  
					+ "&country=" + sCountry ;  
		
		parent.frames["hidden"].location.href=updSQL ; 
		*/
    } //Add Grainger Item

    function UpdateOrderPrompts() {

        var x, pn, itemchecked;
        var selOpt;
        var promptlist = "";
        var Form1 = document.forms[0];


        //Only pass as many prompts as necessary
        for (x = 1; x <= Form1.iNumPrompts.value; x++) {
            pn = "category" + x;
            itemchecked = false;

            //If only ONE option, there is no array of elements...
            //Need to look at the value and selection of the radio box itself 
            //These most likely are "yes or no", so allow an unchecked box here...

            numopts = Form1.elements[pn].length;

            if (isNaN(numopts)) {
                if (Form1.elements[pn].checked)
                    promptlist += String(Form1.elements[pn].value) + "||";
                continue;
            }

            //Find selected option and pass to update program
            for (y = 0; y < numopts; y++) {
                if (Form1.elements[pn][y].checked) {
                    promptlist += Form1.elements[pn][y].value + "||";
                    itemchecked = true;
                } //item checked
            }   //loop through options for prompt 

            if (itemchecked == false) {
                alert("You have not selected one option for each category. You must do so before you can add this item to the cart. ");
                return;
            }

        }  //loop through prompts

        var strNextPage = "";

        if (Form1["strNextPage"] != null)
            strNextPage = Form1["strNextPage"].value;

        var ctx = [strNextPage];

        //alert("Order Value is : " + Form1.iOrderId.value + "; Parent Item ID = " + Form1.iParentItemId.value + "; promptlist:" + promptlist);
        PageMethods.UpdateOrderPrompts(Form1.iOrderId.value, Form1.iParentItemId.value, Form1.iLineNumber.value, promptlist, OnUpdatePromptsComplete, OnError, ctx);

    }

    ///TC: fnFormatCurrency was created for multi currency 03/06/2009
    function fnFormatCurrency(dblAmount, sCurrency)
    {
        //Rounding 
        var amount = dblAmount.toString();
        var f = parseFloat(amount);
        if (isNaN(f)) { f = 0.00; }
        var minus = '';
        if (f < 0) { minus = '-'; }
        f = Math.abs(f);
        f = parseInt((f + .005) * 100);
        f = f / 100;
        s = new String(f);
        if (s.indexOf('.') < 0) { s += '.00'; }
        if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
        s = minus + s;

        //Add Currency Symbol
        if (sCurrency == "CAD") {
            //Add Comma
            s = fnCommaFormatted(s)
            s = "CDN$ " + s;
        }
        else if (sCurrency == "USD") {
            //Add Comma
            s = fnCommaFormatted(s)
            s = "$" + s;
        }
        else //for other currency later
        {
            s = "$" + s;
        }
        return s;
    }
    //end of fnFormatCurrency()

    ///TC: fnCommaFormatted was created for multi currency 03/06/2009
    function fnCommaFormatted(amount) 
    {
        var delimiter = ","; // replace comma if desired
        var a = amount.split('.', 2)
        var d = a[1];
        var f = parseInt(a[0]);
        if (isNaN(f)) { return ''; }
        var minus = '';
        if (f < 0) { minus = '-'; }
        f = Math.abs(f);
        var n = new String(f);
        var a = [];
        while (n.length > 3) {
            var nn = n.substr(n.length - 3);
            a.unshift(nn);
            n = n.substr(0, n.length - 3);
        }
        if (n.length > 0) { a.unshift(n); }
        n = a.join(delimiter);
        if (d.length < 1) { amount = n; }
        else { amount = n + '.' + d; }
        amount = minus + amount;
        return amount;
    }
    // end of function fnCommaFormatted()