// function to show the contents of the basket on successful addition of a product.
function rollDown()
{	
	$('html, body').animate({scrollTop:0});
	$("div#slidingCart").slideDown("slow");  
	settimerlong();
}

// function to support the Ajax add to Basket.
// gets called for the product submit form. doesn't use the intermediate confirmation popup.
// form is renamed to support cross sell logic on the product cell page.
function UpdateBasket()
{	
    var dataString = $('form#addToReq').serialize();     
	var url = "/on/demandware.store/Sites-Gardeners-Site/default/Cart-AjaxAddProduct?" + dataString;
	 
	$.ajax({
	        url: url,
	        type: "GET",
	        dataType: "xml",
	        success: function(res)
	        {   
				getBasket();
				$("div#emptyBasket").remove();
				$("div#roloverLink").empty().append('<a style="text-decoration: none;" id="carttotal"><span id="productstotal"></span><span id="merchtotal"></span></a>');									
				$('html, body').animate({scrollTop:0});
				$("div#slidingCart").slideDown("slow");
				settimerlong();								  
		    },
	        error: function(res)
	        {
		        var status = res.statusText;
		        // sometimes the successful add to basket is treated as an error, but the statusText is 
		        // actually an "OK". so this part will ensure the correct notification is shown to the customer.		        		        
			    if (status == 'OK')
			    {
			    	var text =  "Success!";
					getBasket();
					$("div#emptyBasket").remove();
					$("div#roloverLink").empty().append('<a style="text-decoration: none;" id="carttotal"><span id="productstotal"></span><span id="merchtotal"></span></a>');									
					$('html, body').animate({scrollTop:0});
					$("div#slidingCart").slideDown("slow");
					settimerlong();			    	 
			    }
			    else
			    {
	        		 var text = "Product was not added!"; 			     
	        	}			    		    
		    }
	        	
	});
	getBasket();
   
}

// this function is used by productcellunit and needs id and name parameters to show them in the intermediate confirmation popup.
// also the logic for 'success' and 'error' is quite different than one in updateBasket(). 
// this function needs to exist.
function updateBasket(id, name)
{
	   var lastAddedProductName = name; 
	   var productID = id;
	   var qty = $('input[name=Quantity_' + id + ']').val();
	   pageTracker._trackEvent('QuickView', 'View and Add to Basket (ajax)', id, qty);
		
    var dataString = $('form#addToRequisition').serialize();
    Boxy.get('.addNow').hide(); 
       
	var url = "/on/demandware.store/Sites-Gardeners-Site/default/Cart-AjaxAddProduct?" + dataString;
      
	$.ajax({
	        url: url,
	        type: "GET",
	        dataType: "xml",
	        success: function(res)
	        { 
				 var url = '/on/demandware.store/Sites-Gardeners-Site/default/Cart-ConfirmSuccessfulProductAdd?ID=' + id  + "&productName=" + name;
				 Boxy.load(url, {modal: true, draggable:true});	
				 getBasket();			 			  
		    },
	        error: function(res)
	        {	        
		        var status = res.statusText;
		        // sometimes the successful add to basket is treated as an error, but the statusText is 
		        // actually an "OK". so this part will ensure the correct notification is shown to the customer.
			     if (status == 'OK')
			     {		    	 
			    	 var url = '/on/demandware.store/Sites-Gardeners-Site/default/Cart-ConfirmSuccessfulProductAdd?ID=' + productID  + "&productName=" + lastAddedProductName;
					 Boxy.load(url, {modal: true, draggable:true});	
			     }
			     else
			     {
			    	 var url = '/on/demandware.store/Sites-Gardeners-Site/default/Cart-ErrorOnProductAdd?ID=' + productID  + "&productName=" + lastAddedProductName;
					 Boxy.load(url, {modal: true, draggable:true});	 	     
	        	 }
		          
		        }
	        	
	        });
	getBasket();			
}

// this function adds quantity of 1 of the product via Ajax call.
// this function is somewhat a simpler version of the updateBasket(id, name).
// updateBasket(id, name) can be modified to have the 3rd input of 'qty',
// but since the qty of 1 is really used and for the rest of the cases the whole 
// form will be serialized and sent, qty of '0' need to be passed for other calls (which doesn't make sense). 
function addProduct(id,name)
{   
	pageTracker._trackEvent('QuickView', 'Direct Add to basket (ajax)', id, '1');
	//alert(" trackEvent: 'QuickView', 'Direct Add to basket (ajax)', " + id + ", 1");

	var lastAddedProductName = name;
	var productID = id;
    var ADDITEMS = "Add to Cart";
    var QUANTITY = "Quantity_" + productID + "=1";

    var url = "/on/demandware.store/Sites-Gardeners-Site/default/Cart-AjaxAddProduct?" + QUANTITY + "&addItems=" + ADDITEMS + "&INTERACTION=no";  
	$.ajax({
	        url: url,
	        type: "GET",
	        dataType: "xml",
	        success: function(res)
	        {	
								               
				 getBasket();
				 $("div#emptyBasket").remove();				 	 														 			  
				 var url = '/on/demandware.store/Sites-Gardeners-Site/default/Cart-ConfirmSuccessfulProductAdd?ID=' + productID  + "&productName=" + lastAddedProductName;
				 Boxy.load(url, {modal: true, fixed: false, unloadOnHide: true, cache: false});
		     },
	        error: function(xhr)
	        {
		    
		    	 var status = res.statusText;
		         // sometimes the successful add to basket is treated as an error, but the statusText is 
		         // actually an "OK". so this part will ensure the correct notification is shown to the customer.
			     if (status == 'OK')
			     {		    	 
			    	 var url = '/on/demandware.store/Sites-Gardeners-Site/default/Cart-ConfirmSuccessfulProductAdd?ID=' + productID  + "&productName=" + lastAddedProductName;
					 Boxy.load(url, {modal: true, draggable:true});		     
			     }
			     else
			     {
			    	 var url = '/on/demandware.store/Sites-Gardeners-Site/default/Cart-ErrorOnProductAdd?ID=' + productID  + "&productName=" + lastAddedProductName;
					 Boxy.load(url, {modal: true, draggable:true});	     
	        	 }		     	        	 
		    }	        	
	        });		
	
}

//Load dynamic fields with current basket products data.
function getBasket()
{
	var url = "/on/demandware.store/Sites-Gardeners-Site/default/Cart-CartXML";
	$.ajax({
	        url: url,
	        type: "GET",
	        dataType: "xml",
	        success: function(res){
		
	        	    var xmldoc = res.documentElement; 
	        	    // the totals table
					var totalMerch = xmldoc.getElementsByTagName('merchandizetotal')[0].firstChild.nodeValue;
					var totalShip =  xmldoc.getElementsByTagName('shiptotal')[0].firstChild.nodeValue;
					var totalOrder = xmldoc.getElementsByTagName('ordertotal')[0].firstChild.nodeValue;
					var totalTax   = xmldoc.getElementsByTagName('taxtotal')[0].firstChild.nodeValue;
					var totalItems   = xmldoc.getElementsByTagName('totalproducts')[0].firstChild.nodeValue;
					var promocallout = "";
					promocallout = $(res).find('promocallout').text()
					var promodetails = "";
					promodetails = $(res).find('promodetails').text()
					var itemsTotal = 0;
					if (promocallout != "" && promocallout != null) {
						$(".ajaxCartPromoDetailsMessage").html(promocallout);
						promocallout = promocallout.replace("<br>","");
						promocallout = promocallout.replace("&lt;br&gt;","");
						promocallout = promocallout.replace("&amp;lt;br&amp;gt;","");
						$("#tickerpromomessage").html(promocallout);
						$(".tickerPromoDetails").html(promodetails);
						
					}
					
					if (totalItems > 1)
					{
						itemsTotal ="Basket: " + totalItems + " items. $" + totalMerch;
					}
					else if (totalItems == 1)
					{
						itemsTotal = "Basket: 1 item $" + totalMerch;
					}
					else
					{
						itemsTotal = "Your Shopping Basket is Empty.";
						$('#firstCartLink').css({'text-decoration': 'none'});
					}
					if(totalItems > 0 )
					{ 				
					$( "#productstotal").bind( "hover", { speed:50, delay:100 },
					//$("#productstotal").hover(
						function () {						
								openelement = $(this);								
								navopen();							
						},
						function () {						
						});					
										
					$('#slidingDiv').hover( 
							function () {
							navopen();
							openelement = $(this);							
							},
							function () {								
							});
					}
					else
					{
						$('#firstCartLink').css({'text-decoration': 'none'});
					} 

					
					$('#ajaxCartTotal').empty().append(" $" + totalMerch);
					$('#ordertotal').empty().append(" $" + totalOrder);
					if(totalItems > 0)
					{
						$('#emptyBasketArea').empty();
						$('#productstotal').empty().append(itemsTotal).append(" ");
					}
					else
					{
						$('#productstotal').empty();
                        $('#emptyBasketArea').empty().append(itemsTotal).append(" ");
					}
					
					$('div#slidingDiv').empty();
					var productCount = 0;
					if($(res).find('product').length > 0)
					{
					$(res).find('product').each(function(){
						var currentProduct = $(this);					
						productCount += 1;
						var varattr = $(this).find('variationAttr').length;
						var variationsPrintOut = "";
						if(varattr)
						{
							$(this).find('attribute').each(function(){
								var attributeName = $(this).attr('id');
								var attributeValue = $(this).text();
								variationsPrintOut += "<br/>" + attributeName + ": <span style='font-weight: normal;'>" + attributeValue + '</span>';
							});		
						}										
					$('<table id="productInfo" cellpadding="0" cellspacing="0" ><tr height="68" border="1"><td width="57" valign="top" style="padding: 8px 1px 8px 4px;" ><img style="border: 1px solid #C07445;" width="49" height="61" src=' + currentProduct.find('thumbSrc').text() + '></td><td style="vertical-align: top; padding: 8px 3px 8px 0px;" ><div style="color: #1A6C57; line-height: 13px;">'  + currentProduct.find('name').text()+'<span class="productInfoGrey">' + variationsPrintOut + '</span></div><div style="line-height: 13px;"><span class="productInfoGrey">Availability: '  + currentProduct.find('availability').text() + '</span></div><div style="float: right; margin-right: 20px; margin-top: 10px;">                QTY: ' + currentProduct.find('quantity').text() +  ' &nbsp; | &nbsp; $' + currentProduct.find('totalprice').text() + '</div></td></tr></table>').prependTo('div#slidingDiv');   		//($" + currentProduct.find('baseprice').text() + 'ea.)		+ currentProduct.find('sku').text() + ''	
						});

					// when the cart has more than 3 products it gets the scroll bar.
					if(productCount > 3)
					{
						$('div#slidingDiv').css({'height':'278px','overflow-y':'scroll'}); 
						$("productInfo").css({'width':'220px'});								
					}
	} // end of check for products in the basket != null
		        	},
	        	error: function(xhr){
	        	 $('#pageErrors').empty().show().append('We encoutered a problem processing your request. Please try again later.').fadeOut(3000);
		        	}
	        	
	        });

}

var productsavailable = true;
function trim(string)
{
	return string.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function checkQuantity()
{
	var hasValue = false;
	var elements = document.getElementById("addToReq").elements;
	for (var i = 0; i < elements.length; i++)
	{
        var element = elements[i];
		if (element.name && element.name.match(/^Quantity_/) && trim(element.value) != "" && trim(element.value) != "0")
		{
			hasValue = true;
			break;
		}
	}
	return hasValue;
}

function setQuantityText(text)
{
	var quantitymsg = document.getElementById("quantitymsg");
	if (quantitymsg.firstChild == null)
	{
		quantitymsg.appendChild(document.createTextNode(text));
	}
	else
	{
		quantitymsg.firstChild.data = text;
	}
}

function checkBasketQuantity()
{
	var text = "";
	if (checkQuantity()) {
		if (productsavailable == true) {				
			UpdateBasket();
    		setQuantityText('');
		}else {
			text = " This option is not in stock.  Please choose another.";
			setQuantityText(text);
		}
	}else {
		text = "Please select a quantity and click 'Add to Shopping Basket'.";
		setQuantityText(text);
	}
	
}

// do the form client side validation.
// for regular products: check that the qty input is filled and valid.
// for gift cards: validate the input fields.
function ValidateAddToReqForm()
{
	//check if this is a e-gift card and validate all input fields.
	if ($('input[name=dwfrm_giftcard_amount]').length > 0)
	{
    	//alert("this page has email input field");
    	var validInputs = true;
    	var giftCardSKU = $('input[name=GiftCardPid]').attr('value');
    	//alert(" this GC is : " + giftCardSKU);
    	var ecard = false;
    	if(giftCardSKU  == '01-136EC')
    	{ 
        	ecard = true;
    	}
   	
    	var amount = $('input[name=dwfrm_giftcard_amount]').val();
    	amount = amount.replace(/^\s*/g,'');
    	var recipient = $('input[name=dwfrm_giftcard_recipient]').val();
    	var message = $('textarea[name=dwfrm_giftcard_message]').val();

    	if(ecard)
    	{
    		var email = $('input[name=dwfrm_giftcard_email]').val();
       		var from = $('input[name=dwfrm_giftcard_from]').val();
    	}
    	
    	if(amount <= 1 || amount =="" || isNaN(amount))
    	{
    		validInputs = false;
    		document.getElementById('amountmsg').innerHTML='Please enter a dollar amount greater than $1.00';
    		$('#amountmsg').css({'color':'red'});
    		$('input[name=dwfrm_giftcard_amount]').attr('class', 'errorbox'); 
    		
    	}
    	else
    	{
        	// just in case if has empty spaces
    		amount = amount.replace(/^\s*/g,'');
        	//remove the error messaging for this input.
    		document.getElementById('amountmsg').innerHTML='';
    		$('input[name=dwfrm_giftcard_amount]').attr('class', '');
    	}

    	// validate the gift message textarea.
    	if(message != "" && message.length > 114 && ecard)
    	{
    		validInputs = false;
    		$('textarea[name=dwfrm_giftcard_message]').attr('class', 'errorbox');
    		var text = "Please limit your message to 114 characters.";
    		setQuantityText(text);
    		$('#quantitymsg').css({'color':'red'});
    	}
    	else if(message != "" && message.length > 54 && !ecard)
    	{
    		validInputs = false;
    		$('textarea[name=dwfrm_giftcard_message]').attr('class', 'errorbox');
    		var text = "Please limit your message to 54 characters.";
    		setQuantityText(text);
    		$('#quantitymsg').css({'color':'red'});
    	}
    	else
    	{ // remove the error messaging  for this textarea.      	
    		$('textarea[name=dwfrm_giftcard_message]').attr('class', '');
    		setQuantityText('');
    	}

		// validate the recipint input field.
		if(recipient == "")
		{
			validInputs = false; 	   
    		document.getElementById('recipientmsg').innerHTML="Please fill in the 'Recipient Name' field.<br/>";
    		$('#recipientmsg').css({'color':'red'});
    		$('input[name=dwfrm_giftcard_recipient]').attr('class', 'errorbox'); 
		}
		else
		{   //remove the error messaging for this input.
			document.getElementById('recipientmsg').innerHTML='';
    		$('input[name=dwfrm_giftcard_recipient]').attr('class', '');
		}

    	// validate the 'email' input field and 'from' field (only for e-gift cards).
    	if(ecard){
	    	var emailValid = false;
	    	emailValid = ValidateEmail(email);
	    	if(!emailValid)
	    	{		
	    		validInputs = false; 	   
	    		document.getElementById('emailmsg').innerHTML='Please enter a valid email address.<br/>';
	    		$('#emailmsg').css({'color':'red'});
	    		$('input[name=dwfrm_giftcard_email]').attr('class', 'errorbox');   
	    	}
	    	else
	    	{   //remove the error messaging for this input.
	    		document.getElementById('emailmsg').innerHTML='';
	    		$('input[name=dwfrm_giftcard_email]').attr('class', '');   
	    	}

	    	// validate the from input field.
			if(from == "")
			{
				validInputs = false; 	   
	    		document.getElementById('frommsg').innerHTML="Please fill in the 'From' field.<br/>";
	    		$('#frommsg').css({'color':'red'});
	    		$('input[name=dwfrm_giftcard_from]').attr('class', 'errorbox'); 
			}
			else
			{   //remove the error messaging for this input.
				document.getElementById('frommsg').innerHTML='';
	    		$('input[name=dwfrm_giftcard_from]').attr('class', '');
			}
	
	    } // end of condition for e-gift cards.
    	
    	// add Gift Card to the cart only if all fields have validated.	
    	if(validInputs)
    	{
    		UpdateBasket();
    		// clear the gift card fields
    		$('input[name=dwfrm_giftcard_amount]').val("");
    		if( $('input[name=dwfrm_giftcard_email]').length > 0) 
        	{
        		$('input[name=dwfrm_giftcard_email]').val("");
        	}
    		if( $('input[name=dwfrm_giftcard_from]').length > 0) 
        	{
    			$('input[name=dwfrm_giftcard_from]').val("");
        	}
    		$('input[name=dwfrm_giftcard_recipient]').val("");
       		$('textarea[name=dwfrm_giftcard_message]').val("");
    	}
    }
	else
	{
		checkBasketQuantity();
	}
	
}



