/*
	productpage.js
	Javascript used for product display pages
	TODO: need to add namespacing.
*/

//DOJO Dependencies
//Tabs
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.Tooltip");
dojo.require("dijit.layout.LinkPane");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.form.Button");

var zoomWindowID = "zoomDialogFrame";
var maxTabHeight = 0;

var busy = false;
var attrDesc = 'product';
formName = 'OrderItemAddForm';

//<%--
//ATTRIBUTES
//--%>
/**
 * check to see if an attribute has been selected
 */
function checkAttribute(form)
{
	var result = true;
	if (form.attrValue_0 && form.attrValue_0.value == '')
	{
		alert("Please specify '" + attrDesc + "' option before clicking 'Add to Cart'");
		result = false;
	}	
	return result;
} 
/**
 * Changes the currently selected gift card value for page submission
 */
function changeCurrentGiftCardValue(form)
{
	form.attrValue_0.value = form.giftCardList.options[form.giftCardList.selectedIndex].value;
}
/**
 * Changes the currently selected attribute value for page submission
 */
function changeCurrentAttributeValue(form)
{
	form.attrValue_0.value = form.attrList.options[form.attrList.selectedIndex].value;
}
/**
 * check if only one attribute for this item - if so then hide the dropdown
 */
function checkForOneAttribute(form)
{
	if(eval(form['attrList']) && form.attrList.options.length <= 1)
   	{
   		var attrStyle = form.attrList.style;
   	 	if(eval(attrStyle))
   	 	{
       	 	attrStyle.visibility="hidden";
       	 	document.getElementById("SelectProductOption").style.display = 'none';
       	}
   	}
}
//<%--
// ADD TO CART
//--%>
/**
 * Used by the 'Add to my Shopping Cart' button to set appropriate 	
 * values before the form is submitted 
 */
function Add2ShopCart(form, freeItem)
{
	if (com.bec.product.Kit && !com.bec.product.Kit.checkKit())
	{
		return;
	}
	if (!checkWine(form))
	{
		return;
	}
	
	/** Append Add "Type" to field2 for CM **/
	try 
	{
		if(form.field2.value.indexOf("ProductStandard") == -1)
		{
			form.field2.value = form.field2.value + ";ProductStandard";
		}
	}
	catch(e) 
	{
		alert('Error tracking product add');
	}	
			  
	if(!busy && checkAttribute(form))
	{
    	busy = true;
        if (freeItem == 'true') 
        {
        	form.action='BECFreeItemAdd';
            form.redirectURL.value='BECUnconfirmedAddressCheck';
            form.URL.value='BECUnconfirmedAddressCheck';
                        
            form.submit();
		}
        else 
        {
       		$(function(){AjaxAddToCart(form);});
       		//AjaxAddToCart(form);
		}
	}	  
}

/**
 * Add item to cart using ajax service
 */
function AjaxAddToCart(form)
{   
    var rtn = true;
    if (checkQuantity())
    {
	    //TODO: add busy check
		scroll(0,0);
		miniCart.set("<div class='add-item'>Adding item...</div>");
	   
		var serviceId = "AjaxAddOrderItem"
		wc.service.getServiceById(serviceId).formId = form.id;
		wc.service.invoke(serviceId);
		cursor_wait();
	}
	else
	{
		rtn = false;
	}
	
	return rtn;
}

function checkQuantity()
{
	var qtyValid = true;
	try
	{
		var hiddenQuantity = document.getElementById("quantity_0");
		
		if (hiddenQuantity && (isNaN(hiddenQuantity.value) || hiddenQuantity.value <= 0 ))
		{
			qtyValid = false;
			
			alert("Invalid quantity entered. Please try again.");
			
			hiddenQuantity.value = 1;
			
			busy = false;
		}
	}
	catch(e)
	{
	
	}
	return qtyValid;
}
/**
 * callback method used to process item added to cart display       
 */
function getItemAddCallback(text)
{
   	try
   	{
 		scroll(0,0);
   		if (text != '' && text != 'sslbug')
   		{
       		// hide the add new name input
       		toggleBox('addNewName', 0);
      		
      		// slide down the mini cart
       		miniCart.set(text);
       		miniCart.open();
       		
	       	// call coremetric function on 'add to cart' layer
	       	try
	       	{
	       		trackAddToCart();
	       	}
	       	catch(e){}
		}
	    else
	    {
   			displayAddToCartError();
	    }
   	}
   	catch(e)
   	{
   		displayAddToCartError();	
   	}
   	busy = false;
}

/**
 * display add to cart error
 */
function displayAddToCartError()
{
	miniCart.set("<div class='error'>Sorry, An error occurred while adding item to cart.<br/><br/>Please try again.</div>");
}

/**
 * reset the page after add to cart is scrolled up
 */
function resetPage()
{
	resetWineElements(true);
}
//<%--
//ADD TO GIFTLIST
//--%>
/**
 * Used by the 'Add to my Gift List' button to set appropriate values before the form is submitted
 */
function Add2GiftList(form, freeItem)
{
	if (com.bec.product.Kit && !com.bec.product.Kit.checkKit())
	{
		return;
	}
	if (!checkAttribute(form))
	{
		return;
	}
	if (!checkWine(form))
	{
		return;
	}		  
    busy = checkRecipient(form);
	if(form.recipientInput && form.recipientInput.value != null && form.recipientInput.value != '')
	{
		form.firstName.value = form.recipientInput.value;
	}

	if (!busy) 
	{
        busy = true;
        closeRecipientList = true;
				
        form.catEntryId_0.value = form.catEntryId_0.value;
        form.URL.value='BECGiftListItemDisplay?recipientNickName=-1&URL=BECGiftListEditView';
				
        // from recipient list - add item to recipient giftlist
        if(fromRecipientList)
        {
 			form.action='BECGiftListRecipientAdd?freeItem='+freeItem;
        }
       	else
       	{ 	// New Recipient - Have buyer enter new address 
			form.action='BECGiftListAddressAddView?recipientNickName=-1';
			form.refURL.value = location.href;
   		}
   		fromRecipientList = false;
	    form.submit();
	}
}
//<%--
//FREE ITEM
//--%>
/**
 * Click on no thanks for free item      
 */
function rejectFreeItem(form)
{
   	form.action="BECPromotionCodeAddRemove?URL=BECUnconfirmedAddressCheck";
    form.submit();
}
//<%--
//RECIPIENT LIST
//--%>
/**
 * Adds the new recipient as an address for the product selected
 */
function changeAddress(form)
{ 
	//clear the previous selection 
    form.recipient.value = '';
    
    var recipSelected = form.recipientSelect.options[form.recipientSelect.selectedIndex].value;
    if (recipSelected == 'add')
    {
    	toggleBox('addNewName',1);
    	form.recipientInput.focus();
    }
    else
    {
    	if (form.recipientInput)
    	{
    		toggleBox('addNewName',0);
    		form.recipientInput.value = '';
    	}
    	form.recipient.value = recipSelected;
    }
    
    //populate zip code for Wine.com zipcode check
    updateWineZip(form);  
}
/**
 *Sets the 
 */
function addNewRecipient(form)
{
	if(trim(form.recipientInput.value) != '' && trim(form.recipient.value) == '')
    {
    	form.recipient.value = form.recipientInput.value;
    }
}
/**
 * refresh recipient list
 */
function getRecipientListCallback(text)
{
	document.getElementById("recipientSelectArea").innerHTML=text;
    addNewRecipToList();
}
//<%--
//PRODUCT DETAILS
//--%>
//<%--
//IMAGE ZOOM
//--%>
/**
 * show the zoom window & create coremetric tag       
 */
function showZoomWindow(e)
{
	var obj = document.getElementById('zoomWindow');
	
	// set top of zoom window relative to scroll position
	//obj.style.top  = (document.documentElement.scrollTop + 20)+'px';
	
	toggleBox('zoomWindow', 1);
	createPageViewTag('Zoom', 'Zoom', '');		
}
//email a friend    
function popUpEmailAFriend()
{
	var win = window.open("", "emailfriend", "location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,width=380,height=375,top=200,left=150");
	document.frmState.submit();
	win.focus();
}
//close zoom layer when user clicks off
function checkZoomClose(e)
{ 
	var target = (e && e.target) || (event && event.srcElement); 
	var obj = document.getElementById('zoomWindow'); 
	if(obj && target!=obj){obj.style.display='none'} 
}

//
//WINE.COM

//Update the zip code for the wine dry zip check
function updateWineZip(form)
{
	var wineZipCodeField = document.getElementById("wineZipCode");
   	if (wineZipCodeField)
   	{	
   		if (recipientZip.length > 0 && form.recipientSelect.selectedIndex >= 2)
   		{
   			var zipCode = recipientZip[form.recipientSelect.selectedIndex-2];
   			if (zipCode && zipCode != '')
   			{
   				wineZipCodeField.value = zipCode;
   				resetWineElements(false);
   			}
   		}
   		else
   		{
   			resetWineElements(true);
   		}    	
   	}
}
//Set the wine elments back to the default
function resetWineElements(resetZip)
{
	
   	if (resetZip)
   	{
   		var zipCodeField = document.getElementById("wineZipCode");
	   	if (zipCodeField)
	   	{
	   		zipCodeField.value = '';
	   	}
	}
   	var ageVerifyCB = document.getElementById("ageVerifyChkBx");
	if (ageVerifyCB)
	{
	   	ageVerifyCB.checked = false;
  	} 
}

//For wine.com items, check to see if age has been verified and zipcode entered for leadtime
	function checkWine(form)
	{
		errorMessage= "";
            
		var zipCodeObj = document.getElementById("wineZipCode");
	   	if(zipCodeObj)
		{
			var zipCodeValue = trim(zipCodeObj.value);
			if (zipCodeValue =='')
			{
				errorMessage = "The 'Recipient Zip Code' is required.";
				zipCodeObj.focus();		
			}
			else 
			{
			 	// Checks for 5 digit zip or zip plus 4 
			 	var zipCheck  = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
			 	if (!zipCheck.test(zipCodeValue)) 
			 	{
			 		errorMessage = 'Invalid zip code. Please check the address and try again.';
	           		zipCodeObj.focus();		
	         	}
	     	}
		    if( form.ageVerifyChkBx && !form.ageVerifyChkBx.checked)
			{
				errorMessage = "To purchase wine, you must first check the box to validate that you and the recipient are at least 21 years of age.";
				form.ageVerifyChkBx.focus();	
			}
		}	     
		
		if (errorMessage != '')
		{
			alert(errorMessage);
			return false;
		}
		
		return true;
	}   
//
//END WINE.COM
//

dojo.require("bec.widget.PopupDialog");
/**
 * opens the image zoom popup window
 */
function showZoomDialog()
{
    popup.withContent(zoomWindowID, "Zoom Image", getZoomElement().innerHTML);
}

var zoomElement;
/**
 * Note: only get once and save into global element to be use again
 * some reason this code does not work the 2nd time
 */
function getZoomElement()
{
    if (!zoomElement)
    {
        zoomElement = dojo.byId("zoomDialog"); 
        //try to find the zoom object, if not found just use the 'zoomDialog' div
        var zoomEls = dojo.filter(zoomElement.childNodes, function(child) { return (child.id == "ZoomMX"); });
        if(zoomEls != null && zoomEls[0])    
        {       
            zoomElement = zoomEls[0];
        }            
    }
    return zoomElement;
}

function tabWasSelected(/*Widget*/ page, /*Widget*/ callingWidget)
{
	cmInitiateElementTag(page.label + ' tab', 'Product page');
}

function changeLeftNavHeight()
{
	try
	{
		var nav = $("#navigation");	
		
		//alert(nav.height());
		//alert($("#content").height() +   $("#breadcrumb").height());
		
		nav.height(Math.max(nav.height(), $("#content").height() +   $("#breadcrumb").height()));	
		
		//alert(nav.height());
	}
	catch(e){}
}

