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

//DOJO Dependencies
//Tabs
dojo.require("dojo.widget.TabContainer");
dojo.require("dojo.widget.Tooltip");
dojo.require("dojo.widget.LinkPane");
dojo.require("dojo.widget.ContentPane");
dojo.require("dojo.widget.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;
	}		  
	if(!busy && checkAttribute(form))
	{
    	busy = true;
        if (freeItem == 'true') 
        {
        	form.action='BECFreeItemAdd';
            form.redirectURL.value='BECUnconfirmedAddressCheck';
            form.URL.value='BECUnconfirmedAddressCheck';
                        
            form.submit();
		}
        else 
        {
       		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("recipSelect").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
//

/**
 * opens the catalog quick order popup.
 * - used when the 'openCQOFrame' is set in the request.
 */
function showZoomDialog()
{
	var dialog = getZoomFrame();
	dialog.show();
}

var zoomElement;
/**
 * lazy creation and display of the scene7 image popup.
 */
function getZoomFrame()
{
	var zoomFrame = dojo.widget.byId(ZoomWindowID);
	if(!zoomFrame)
	{	//lazy create - only do one time.
		zoomFrame = dojo.widget.createWidget("ModalFloatingPane", // widgetType
     		{	widgetId: ZoomWindowID,
     			bgColor: "white",
     			bgOpacity: "0.4",
     			toggleDuration: 0,
     			closeOnBackgroundClick: true,
     			displayCloseAction: true,
     			resizable: false,
     			titleBarDisplay: true,
     			title: "Zoom Image",
				hasShadow: true,
     			templateCssPath: eSiteStyleDir + "/dojo/widget/templates/FloatingPane.css",
     			loadingMessage: LOADING_MESSAGE
     		}, // widget attributes, for example {title: "Some Title"}
     		dojo.byId(POPUP_PLACEHOLDER_ID), // reference to a DOM node that 
        	"after"	// new widget will be placed after
    	);	

    	//set the content and size
    	// Note: only get once and save into global element to be use again
    	// some reason this code does not work the 2nd time
    	if (!zoomElement)
    	{
			zoomElement = document.getElementById("zoomDialog");
			if (!dojo.render.html.ie)	// firefox wants a copy, ie wants the original
			{
				zoomElement = zoomElement.cloneNode(true);				
			}
	
			// try to find the zoom object, if not found just use the 'zoomDialog' div
			for (var i = 0; i < zoomElement.childNodes.length; i ++)
			{
				if (zoomElement.childNodes[i].id == "ZoomMX")
				{		
					zoomElement = zoomElement.childNodes[i];
					break;
				}
			}
		}
		zoomFrame.setContent(zoomElement.innerHTML);
		zoomFrame.resizeTo(zoomDialogWidth, zoomDialogHeight);	// too small will cause scroll bars
	}

    return zoomFrame;	
}

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){}
}
