/**
 * @author Lowe's
 * @requires Dojo library and jQuery library
 * @fileOverview This file has a mix of dojo and jQuery code. All dojo code should be considered deprecated
 * and will be replaced in the near future. In the future this file will be rewritten to adhere to the 
 * Lowe's JS framework, so the namespace will probably change to Lowes.Cart;
 */

var lowes=window.lowes || {};
lowes.cart={

	/** 
	 * Bootstraps the rest of the lowes.cart object. This technique allows for using library code
	 * (such as jQuery) before it ever gets loaded in because the init() function isn't called until
	 * after the DOM is ready via a dojo.addOnLoad(init) call later.
	 * @returns void
	 */
    init:function(){
        lowes.cart._setupReturnShopping();
        lowes.cart._setupEmptyCart();
        lowes.cart._setupEditGiftMsg();
        lowes.cart._setupCharCounter();
        lowes.cart._setupPromoCodes();
        lowes.cart._setupInvalidItem();
		lowes.cart._forceUpperCasePromo();
		lowes.cart._setupSearchZip();
        lowes.cart._setupInvalidItem();
		lowes.cart._validateGiftCardAmount();
	}, 

	/**
	 * Binds a click action to a link that shows the tooltip that the user sees when clicking the "Return to Shopping" link.
	 * @event
	 * @returns void
	 */
    _setupReturnShopping:function(){
        var ttd=null;
        dojo.query('li.return-shopping > a').forEach(function(element){
            var $li = element;
            dojo.connect(element, 'onclick',function(ev){
                ev.preventDefault();
                var $this = ev.target;
                if(!ttd){
                    var node = dojo.byId('return-to-shopping-tooltip');                
                    ttd = new dijit.TooltipDialog({
                            title:''
                    }, node);                    
                    var closeButton = dojo.byId('return-to-shopping-tooltip-close');
                    if (closeButton) {
                        ttd.connect(closeButton,'onclick',function(e){
                            dojo.style(ttd.domNode, "display", "none");
                        });
                    }
                        
                }
                dojo.style(ttd.domNode, "position", "absolute");
                dojo.style(ttd.domNode, "zIndex", 10000);
                dojo.style(ttd.domNode, "display", "block");        
                // Set up location of TooltipDialog                
                var coords = ($($this)).position();
                var ttSize = dojo.marginBox(ttd.domNode);
                // If this is a link on the bottom of the page, orient the tooltip to the top
                if(dojo.hasClass($this.parentNode, 'bottom')) {
                    ttd.domNode.className = 'dijitTooltipDialogTop';
					/* 1.0.1*/ 
                    var offsetX = -170;
					
					/* 1.2 
					var offsetX = -13;*/
                    var offsetY = (-(ttSize.h + 16));
                } else {
                    ttd.domNode.className = 'dijitTooltipDialog';
                    /* 1.0.1 */
                    var offsetX = -170;
					
					/* 1.2 
					var offsetX = -13;*/
                    var offsetY = 20;
                }
                ttd.resize({ t:coords.top+offsetY, l:coords.left+offsetX });    
                return false;
            });
        });
    },
    
    /**
     * Binds a click action to the .empty-cart links that will prompt the user to empty the cart. 
     * @event
     * @returns void
     */
    _setupEmptyCart:function(){
        var dlg = new dijit.Dialog({
            title:''
        },dojo.byId('cart-modal-dialog'));
        dojo.query('.empty-cart').forEach(function(element){
            var $this = element;
            dojo.connect($this, 'onclick', $this, function(e){
                e.preventDefault();
                dlg.show()
            });
            dojo.query("#cart-modal-dialog a.cancel").forEach(function(element){
                    dojo.connect(element,'onclick',function(ev){
                    ev.preventDefault();
                    dlg.hide();
                    return false;
                });
            });
        });
    },
    
    /** 
     * @returns void
     */
    _setupEditGiftMsg:function(){
        dojo.query('a.edit-giftcard-message').forEach(function(elm){
            dojo.connect(elm, 'onclick', elm, function(e){
                e.preventDefault();
                if(dojo.byId('gift-card-form' + elm.id)) dojo.toggleClass(dojo.byId('gift-card-form' + elm.id),'open');
                return false;
            });
            dojo.query(".gift-card-form a.update").forEach(function(element){
                    dojo.connect(element,'onclick',function(ev){
                    ev.preventDefault();
                    if (element.name == elm.id) {
                        if(dojo.byId('gift-card-form' + elm.id)) dojo.toggleClass(dojo.byId('gift-card-form' + elm.id),'open');
                    }
                    return false;
                });
            });
        });
    },
    
    /**
     * @event
     * @returns void
     */
    _setupCharCounter:function() {
        var $txtArea = dojo.byId('gift-msg-txtarea');
        if(!$txtArea) return false;
        dojo.connect($txtArea, 'onfocus', $txtArea, function(){
            if($txtArea.value == "Type your message here"){
                $txtArea.value = "";
            }
        });
        dojo.connect($txtArea, 'onblur', $txtArea, function(){
            if($txtArea.value == ""){
                    $txtArea.value = "Type your message here";
            }
            else
            {
                var strLen = e.target.value.length + 1;
                    var charRemain = 255 - strLen;
                    console.log(strLen);
                    if(charRemain <= 0) {
                     e.target.value = e.target.value.substring(0,254);
                    }
                    if(charRemain == -1) {
                            charRemain = 0;
                    }
                    if(dojo.byId('chars-rem')) dojo.byId('chars-rem').innerHTML = (charRemain);
            }
        });
        dojo.connect($txtArea, 'onkeypress', $txtArea, function(e){
            var strLen = e.target.value.length + 1;
            var charRemain = 255 - strLen;
            console.log(strLen);
            if(charRemain <= 0) {
             e.target.value = e.target.value.substring(0,254);
            }
            if(charRemain == -1) {
                charRemain = 0;
            }
            if(dojo.byId('chars-rem')) dojo.byId('chars-rem').innerHTML = (charRemain);
        dojo.style ('gift-msg-txtarea', 'color', '#000');
        });        
    }, 
    
    /**
     * @event
     * @returns void
     */
    _setupDeliveryMethodErrors:function() {
        var $shippingErrorMessage = dojo.byId('delivery-method-errors');
        var $storeNumber =     dojo.byId("store_number");
        var storeNumberFlag = $storeNumber ? $storeNumber.value : null;
        if($shippingErrorMessage){
            dojo.style($shippingErrorMessage, 'display', 'none');
            dojo.query('.js-delivery-method-error').forEach(function(el, i){
                var _content = el.innerHTML;
                var $parent = el.parentNode;
                var $inputs = dojo.query('input', $parent);
                var _coords = dojo.coords($parent);
                dojo.style(el, 'display','none');

                if(storeNumberFlag == 'true'){
                _content = "You must select a delivery method for all products in your cart in order to continue checkout.";
                }else{
                _content = "You must enter your ZIP code to view delivery options for your area.";
                }
                // Create tooltip popup
                var node = document.createElement('div');
                dojo.body().appendChild(node);
                ttd = new dijit.TooltipDialog({
                           title:''
                }, node);
                
                // Insert the content and add the close button
                var $content = document.createElement('p');
                $content.innerHTML = _content;
                ttd.setContent($content);    
                var $button = document.createElement('button');
                $button.name='close';
                ttd.containerNode.appendChild($button);
                ttd.domNode.className = 'dijitTooltipDialogLeft delivery-conf tt-index-' + i;
                // Events
                ttd.connect($button,'onclick',function(e){
                        dojo.query('.delivery-conf').forEach(function(el){
                            dojo.style(el,'display','none');
                        });
                    });                
                if($inputs) {
                    $inputs.forEach(function(el){
                        ttd.connect(el, 'onfocus',function(e) {
                            var ttRef = dojo.query('.tt-index-'+i);
                            dojo.style(ttRef[0], 'display','none');
                        });
                    })
                }        
                
                // Set up CSS of this TooltipDialog
                dojo.style(ttd.domNode, "position", "absolute");
                dojo.style(ttd.domNode, "zIndex", "10000");
                dojo.style(ttd.domNode, "top", _coords.y + 'px');
                dojo.style(ttd.domNode, "left", _coords.x + 200 + 'px');
                
                return;
            }); 
        }
    },
    
    /**
     * @returns void
     */
    _setupPromoCodes:function() {
        
        // Promo Code toggle functionality
        var $promoCodeCheckbox = dojo.byId('promo-code-checkbox');
        var $cartPromoCodes = dojo.byId('cart-promo-codes');
        var $cartPromoCodes1 = dojo.byId('cart-empty-codes');
        
        if(!$promoCodeCheckbox) return;
        
        dojo.connect($promoCodeCheckbox,'onclick',$promoCodeCheckbox, function(){
            if(this.checked) {
                if($cartPromoCodes) dojo.removeClass($cartPromoCodes, 'hidden');
                if($cartPromoCodes1) dojo.addClass($cartPromoCodes1, 'hidden');
            } else {
                if($cartPromoCodes) dojo.addClass($cartPromoCodes, 'hidden');
                if($cartPromoCodes1) dojo.removeClass($cartPromoCodes1, 'hidden');
            }
        });
        // This handles the page load state (rarely will happen, but we need this in case the page is refreshed)
        if($promoCodeCheckbox.checked) {
            if($cartPromoCodes) dojo.removeClass($cartPromoCodes, 'hidden');
            if($cartPromoCodes1) dojo.addClass($cartPromoCodes1, 'hidden');
        } else {
            if($cartPromoCodes) dojo.addClass($cartPromoCodes, 'hidden');
            if($cartPromoCodes1) dojo.removeClass($cartPromoCodes1, 'hidden');
        }

    
    },
    
    /**
     * Original comment: "Added by Paramita Das for Invalid Product Added to the cart -Defect-1652"
     * @returns void
     */
    _setupInvalidItem:function(){
        var dlg = new dijit.Dialog({title:''},dojo.byId('cart-modal-dialog-inv-prod'));        
        var $isInvalid =     dojo.byId("invalid-item");
        var isInvalid = $isInvalid ? $isInvalid.value : null;
        if(isInvalid == "true"){
            dlg.show();
            dojo.query("#cart-modal-dialog-inv-prod a.cancel").forEach(function(element){
                            dojo.connect(element,'onclick',function(ev){                            
                            ev.preventDefault();
                            dlg.hide();
                            return false;
                        }); 
                    });
        }
        
        /* for an item that can't be delivered */
        $(".page-errors").each( function(index){
            var itemNum = $(this).find("ul li:contains('restricted for shipment')").text().replace(/\D/g,'');
            var $deliveryTD = $("#my-cart-contents td.prods:contains('" + itemNum + "')").next();
            if($deliveryTD.length > 0)
            {
                if ( $(this).find("ul li:contains('ordering procedures that require assistance')").length )
                {
                    $deliveryTD.children(".delivery-options").remove();
                }
                else if( $(this).find("ul li:contains('Available for Pick Up In Store Only')").length )
                {
                    $deliveryTD.find("ul li:not(:first)").remove();
                }
            }
        });
    },

	/**
	 * A quick fix to change a promo code to uppercase for matching appropriately in the database.
	 * Should be replaced with appropriate back-end functionality in the future. 
	 * @deprecated This should not be relied upon as it needs to be done on the back-end.
	 * @returns void
	 */
	_forceUpperCasePromo:function(){
		$('#promoCode1').bind('blur', function()
		{
			//uppercase the promo before form is submitted
			var upperCasePromoCode = $('#promoCode1').val().toUpperCase();
					
			document.ShopCartForm.promoCode1.value = upperCasePromoCode;
			document.PromotionCodeForm.promoCode.value = upperCasePromoCode;
		});
	},
	
	/**
	 * The URL gets too long for IE to handle when the user goes through the interstitial/EPP page,
	 * due to some odd handling of the session variables and query string variables in the URL.
	 * So, this function originally overrode the other searchZip() function in memory to keep the URL short. 
	 * Since then, the original function was removed from the DeliveryMethod.jsp, since it is being overwritten here.
	 * It explicitly puts the searchZip() function in the window namespace to remain backwards compatible with old JSPs.
	 * @since Release 2.3
	 * @returns void 
	 */
	_setupSearchZip: function(){
		window.searchZip = function(cntr,zip){
			window.location = '/LowesStoreSearchCmd?langId=-1&storeId=10151&catalogId=10051&zipCode='+zip+'&URL=OrderItemDisplay';
		}	
	},

	/**
	 * Validates the gift card quantity and input fields by binding functions to the blur event on each.
	 * Does not currently have comparable back-end validation.
	 * @event 
	 * @returns void
	 */
	_validateGiftCardAmount: function()
	{
		var $giftCardUnitPriceInputs = $('.unitprice[name^="gcPrice"]'),
			$giftCardQuantityInputs = $giftCardUnitPriceInputs.parents('.unit').prev('.quant').find('input[name^="quantity"]'),
			$errorMessages = $('<div class="page-errors gift-card-errors" style="display:none;"><ul><li class="maximum-amount-error" style="display:none;">Gift cards are limited to a maximum of $500.</li><li class="maximum-quantity-error" style="display:none;">Gift card quantities may not exceed 10.</li></ul></div>'),
			$headerWrap = $('.header-wrap'),
			priceValidationEventData = { fieldType: 'price', errorClass: '.maximum-amount-error', upperBound: 500, lowerBound: 5 },
			quantityValidationEventData = { fieldType: 'quantity', errorClass: '.maximum-quantity-error', upperBound: 10, lowerbound: 1 };
			
		
		/* only run if there are actually gift card items on the page */
		if($giftCardUnitPriceInputs.length){
		
			$headerWrap.prepend($errorMessages);
			
			var blurEventFn = function(e){
				var $this = $(this),
					val = $this.val(),
					$updateButton = e.data.fieldType === 'price' ? $this.parents('.unit').prev('.quant').find('.button-grey') : $this.next('.button-grey');
			
				if(val < e.data.lowerBound || val > e.data.upperBound ){
				
					/* do not allow updating while this input is out of range */
					$updateButton.bind('click.preventaction', function(e){ e.preventDefault(); return false; });
				
					$this.animate({backgroundColor: 'red'}, 100, function(){ $(this).animate({backgroundColor: '#fff'}, 100, function(){ $(this).focus(); }); });
					
					$errorMessages.show().find(e.data.errorClass).show();
				}
				else {
					$errorMessages.find(e.data.errorClass).hide();
					
					if($errorMessages.children('li:visible').length < 1){
						$errorMessages.hide();
					}
					/* allow updating now that input field is within range */
					$updateButton.unbind('click.preventaction');
				}
			};
			
			$giftCardUnitPriceInputs.bind('blur.giftcardpricelimit', priceValidationEventData, blurEventFn);
		
			$giftCardQuantityInputs.bind('blur.giftcardquantitylimit', quantityValidationEventData, blurEventFn);
		}
	}
}

dojo.addOnLoad(lowes.cart.init);

/** 
 * The following functions have been put here after being removed from 
 * CurrentOrderDisplayCartSection.jsp. Any of them that involve modifying
 * or submitting a form should be fixed in re-architecting the cart JSPs.
 */

/**
 * @param {Object} Object
 * @param {Number} MaxLen
 * @deprecated
 * @returns {Boolean} 
 */
function setMaxLength(Object, MaxLen){
  return (Object.value.length <= MaxLen);
}

/**
 * @param {Object} form 
 * @param {String} orderId 
 * @returns void
 */
function checkout(form,orderId){
	form.orderId.value=orderId;
	form.URL.value='OrderDisplay';
	form.submit(); 
}  

/**
 * @param {Object} form 
 * @param {String} orderId 
 * @return void
 */		 
function checkoutLogon(form,orderId){	
	form.orderId.value=orderId;	
	form.URL.value ='CheckoutUserLogonFormView?orderId='+orderId;
	form.submit(); 
} 

/**
 * @param {Object} form 
 * @param {String} orderId 
 * @return void
 */	
function updateCart(form,orderId){
	form.orderId.value=orderId;
	form.submit();
	showScreenShadow();	
} 

/**
 * Original comment: Fixed defect 2610, added showScreenShadow function.
 * @returns void
 */
function showScreenShadow(){
	scroll(0, 0);
    if(document.all){ 
		var documentHeight = document.body.scrollHeight;
		document.getElementById('screenShadow').style.height=documentHeight;
	}
    document.getElementById('screenShadow').style.display='inline';
}	

/**
 * @param {Object} form 
 * @param {String} orderItem 
 * @return void
 */
function updateGiftCard(form,orderItem){
	form.gcOrderItemId.value = orderItem;
	form.gcMessage_i.value = document.getElementById('gcMessage_'+orderItem).value;
	form.gcOccasion_i.value = document.getElementById('gcOccasion_'+orderItem).value;
	form.gcTo_i.value = document.getElementById('gcTo_'+orderItem).value;
	form.gcFrom_i.value = document.getElementById('gcFrom_'+orderItem).value;
		
	form.submit();
}
	
function onKeyPressTxtArea(txtArea,orderItem,e) {	
	var strLen = txtArea.value.length + 1;
	var targ;				
	if (!e) {e = window.event;}
	if (e.target){ targ = e.target;}
	else if (e.srcElement) {targ = e.srcElement;}
			
	strLen = targ.value.length + 1;
	
	var charRemain = 255 - strLen;
	console.log(strLen);
	if(charRemain < 0) {
		targ.value = targ.value.substring(0,254);
	}
	if(charRemain == 0) {
		charRemain = 0;
		txtArea.value.length = 255;
	}
	document.getElementById('chars_rem_'+orderItem).innerHTML = (charRemain);	
}

function deleteItem(form,delURL){
	form.URL.value=delURL;
	form.submit();
}

function deleteAvailableItem(pOrderItemList, pDelURL){
	//split items to delete
	var orderItemIds = pOrderItemList.split(',');
	
	//create an orderItemId for each item to delete, and insert into the form
	for(var i=0; i<orderItemIds.length; ++i) {
		var inputField = document.createElement('input');
		inputField.type = 'hidden';
		inputField.name = 'orderItemId';
		inputField.id = 'orderItemId';
		inputField.value= orderItemIds[i];
		document.ItemDeleteForm.appendChild(inputField);
	}
	
	//place following URL to go
	document.ItemDeleteForm.URL.value = pDelURL;
	document.ItemDeleteForm.submit();
}
 
function NoProductThumbnail(element) {
	element.src = "${jspStoreImgDir}images/no_image_available_md.gif"
}
	
function checkoutWithoutDelOp(){ 		
	dojo.addOnCheckout(lowes.cart.initCheckOut);
}

function submitPromotion(){
	//if(document.ShopCartForm.promoCode1 && document.ShopCartForm.promoCode1.value != null && document.ShopCartForm.promoCode1.value != ""){
	 	document.PromotionCodeForm.promoCode.value=document.ShopCartForm.promoCode1.value.toUpperCase();
	 	document.PromotionCodeForm.taskType.value="A";
	 	//document.PromotionCodeForm.promoField.value="one";
	 	//document.PromotionCodeForm.promoCode1.value=document.ShopCartForm.promoCode1.value.toUpperCase();
	//}else{
	//	alert('Please enter promotion code, then click the Apply Code button');
	//	return;
	//}
	document.PromotionCodeForm.promoCodeCheckbox.value="checked";
	document.PromotionCodeForm.submit();
}

function removePromotion1(promotionCode){
	document.PromotionCodeForm.promoCode.value=promotionCode;
	document.PromotionCodeForm.taskType.value="R";
	document.PromotionCodeForm.promoCodeCheckbox.value="checked";
	document.PromotionCodeForm.submit();
}

function emptyCart(){
	document.OrderEmptyForm.submit();
}

function updateEpp(eppOrderItemId,eppCatId){	
	document.EppUpdateForm.eppOrderItemId.value=eppOrderItemId;
	document.EppUpdateForm.eppCatId.value=eppCatId;
	if(eppOrderItemId != eppCatId){
		document.EppUpdateForm.submit();
	}
}

/**
 * This is indeed an empty function pulled from CurrentOrderDisplay.jsp. 
 * The assumption is that someone created this to prevent JS errors when
 * other code tried to call the changeClass function. This should
 * eventually be removed when deeemed safe to do so.
 * @deprecated
 * @returns void
 */
function changeClass(){	}

/**
 * @returns void
 */
dojo.addOnLoad(function(){
	var dlg = new dijit.Dialog({
		title:''
	},dojo.byId('cart-modal-dialog'));
	
	dojo.query("#cart-modal-dialog a.cancel").forEach(function(element){
		dojo.connect(element,'onclick',function(ev){
			ev.preventDefault();
			dlg.show();
			
		});
	});
});

/**
 * 
 * @param {?} myfield Not in use, should be removed in future.
 * @param {Object} e The Event object passed along to determine the keycode pressed.
 * @param {?} cntr
 * @param {String} zip Zip code passed on to the searchZip function. 
 * @returns {Boolean}
 */
function submitFormWithEnter(myfield,e,cntr,zip){  
	var keycode;  
	
	if(window.event){  
		keycode = window.event.keyCode;  
	} 
	else if(e){  
		keycode = e.which;  
	}
	else {  
		return true;  
	}  
   
	if (keycode == 13){  
      searchZip(cntr,zip);
      return false;  
	}
	else {  
		return true;  
	}  
}
