/*
	CatalogQuickOrder.js
	Javascript used for the Catalog Quick Order popup Form.
*/

/* -----[ BEGIN: module initialization ]------------------------------------- */
var com;
if (!com) com = {};
else if (typeof com != "object")
    throw new Error("com already exists and is not an object");
	
if (!com.bec) com.bec = {}
else if (typeof com.bec != "object")
    throw new Error("com.bec already exists and is not an object");
	
if (!com.bec.order) com.bec.order = {}
else if (typeof com.bec.order != "object")
    throw new Error("com.bec.order already exists and is not an object");
	
if (com.bec.order.CatalogQuickOrder)
    throw new Error("com.bec.order.CatalogQuickOrder already exists");
/* -----[ END: module initialization ]--------------------------------------- */

com.bec.order.CatalogQuickOrder = function() {};

/////////////    
//attributes
com.bec.order.CatalogQuickOrder.ID = "cqoFrame";
com.bec.order.CatalogQuickOrder.productDisplayURL = "";
com.bec.order.CatalogQuickOrder.emptyErrorMessage = "";
com.bec.order.CatalogQuickOrder.missingRecipMessage = "";
com.bec.order.CatalogQuickOrder.unavailableErrorMessage = "";
com.bec.order.CatalogQuickOrder.reOpen = "true";

/**
 * initialization 
 */
com.bec.order.CatalogQuickOrder.init = function(e) 
{
    //should we start opened?
    if(getRequestParameter("openCQOFrame") == "true")
    {
        com.bec.order.CatalogQuickOrder.openCQOFrame();
    }
}
dojo.addOnLoad(com.bec.order.CatalogQuickOrder.init); 

/////////////    
//setters
/**
 * @param url string url used as base for redirecting to product page.
 */
com.bec.order.CatalogQuickOrder.setProductDisplayUrl = function(url)
{
	this.productDisplayURL = url;
}
/**
 * set the error message displayed when the input is empty.
 * @param msg string error message.
 */
com.bec.order.CatalogQuickOrder.setEmptyErrorMessage = function(msg)
{
	this.emptyErrorMessage = msg;
}
/**
 * set the error message displayed when the input is empty.
 * @param msg string error message.
 */
com.bec.order.CatalogQuickOrder.setMissingRecipMessage = function(msg)
{
	this.missingRecipMessage = msg;
}
/**
 * set the error message displayed when the input item is unavailable.
 * @param msg string error message.
 */
com.bec.order.CatalogQuickOrder.setUnavailableErrorMessage = function(msg)
{
	this.unavailableErrorMessage = msg;
}

/////////////    
//behavior
/**
 * Execute add to cart from Catalog Quick Order form
 * TODO: need to have error message set outside of here.
 */
com.bec.order.CatalogQuickOrder.add2Cart = function()
{
	var doSubmit = true;
	var cqoEntry = document.getElementById("cqoPartNum").value;
	var cqoRecip = document.getElementById("cqoRecipient");
	if (cqoEntry == '')
	{
		doSubmit = false;
		this.setCatalogErrorMessage(this.emptyErrorMessage);
	}
	else if(cqoRecip && cqoRecip.value == '')
	{	//check if recip input is set.
		var cqoRecipInput = document.getElementById("cqoRecipientInput").value;
		if(cqoRecipInput == '')
		{
			doSubmit = false;
			this.setCatalogErrorMessage(this.missingRecipMessage);	//TODO: need diff error message
		}
		else
		{
			cqoRecip.value = cqoRecipInput;
		}
	}

	if(doSubmit)
	{
		this.setCatalogErrorMessage("");	
		document.getElementById("quickOrderPartNumber").value = cqoEntry;	
		this.defineService();
		wc.service.invoke("AjaxCatalogQuickShop");	
		cursor_wait();	
	}
}

/**
 * Lazy definition of service
 */
com.bec.order.CatalogQuickOrder.serviceDefined = false;
com.bec.order.CatalogQuickOrder.defineService = function()
{
	if(this.serviceDefined == false)
	{
		wc.service.declare(
		{
			id: "AjaxCatalogQuickShop",
			actionId: "BECOrderItemAddCatalogQuickOrder",
			url: "AjaxBECOrderItemAddCatalogQuickOrder",
			formId: "cqoForm"		
			,successHandler: function(serviceResponse) 
			{
				cursor_clear();	
				document.location = "BECOrderItemDisplay?openCQOFrame=" + com.bec.order.CatalogQuickOrder.reOpen + "&storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId;
			}		
			,failureHandler: function(serviceResponse) 
			{
				cursor_clear();
		  		if(serviceResponse.errorMessageKey && serviceResponse.errorMessageKey == '_ERR_GETTING_SKU') 
		  		{
					document.location = com.bec.order.CatalogQuickOrder.productDisplayURL + serviceResponse.exceptionData.catEntryId;
				}
				else
				{	//TODO: this should be coming from the error response as serviceResponse.errorMessage
					com.bec.order.CatalogQuickOrder.setCatalogErrorMessage(com.bec.order.CatalogQuickOrder.unavailableErrorMessage);
				}
			}		
		});
				
		this.serviceDefined = true;
	}
}

/**
 * update the recipient input field.
 */
com.bec.order.CatalogQuickOrder.changeAddress = function()
{
	var cqoRecip = document.getElementById("cqoRecipient");
	var cqoRecipSelect = document.getElementById("cqoRecipientSelect");	
	var cqoRecipInput = document.getElementById("cqoRecipientInput");
	//clear the previous selection 
	cqoRecip.value = '';
	
	var recipSelected = cqoRecipSelect.options[cqoRecipSelect.selectedIndex].value;
	if (recipSelected == 'add')
    {
    	toggleBox('cqoNewName',1);
    	cqoRecipInput.focus();
    }
    else
    {
    	if(cqoRecipInput)
    	{
    		toggleBox('cqoNewName',0);
    		cqoRecipInput.value = '';
    	}
    	cqoRecip.value = recipSelected;
    }
}

/**
 * set the error message on the popup
 * @param dialogErrorMessages string error message.
 */
com.bec.order.CatalogQuickOrder.setCatalogErrorMessage = function(dialogErrorMessages)
{
	document.getElementById("cqoError").innerHTML = dialogErrorMessages;
	if(dialogErrorMessages == '')
	{
		toggleBox('cqoError',0);
	}
	else
	{
		toggleBox('cqoError',1);
	}
}

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

/**
 * lazy creation and display of the cqo popup.
 */
com.bec.order.CatalogQuickOrder.getCQOFrame = function()
{
	var cqoFrame = dojo.widget.byId(com.bec.order.CatalogQuickOrder.ID);
	if(!cqoFrame)
	{	//lazy create - only do one time.
		cqoFrame = dojo.widget.createWidget("ModalFloatingPane", // widgetType
     		{	widgetId: com.bec.order.CatalogQuickOrder.ID,
     			bgColor: "white",
     			bgOpacity: "0.4",
     			toggleDuration: 0,
     			closeOnBackgroundClick: true,
     			resizable: false,
     			title: "Catalog Quick Shop",
     			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
    	);	
    	
		//connect events
		dojo.event.connect(cqoFrame, "onLoad", function () 
			{ 
				focusElement = dojo.byId("cqoPartNum");
				if(focusElement && !dojo.lang.isUndefined(focusElement))
				{
					if(focusElement.type != "hidden" && focusElement.style.display != "none"  && !focusElement.disabled) 
					{
						try
						{
							//focusElement.focus();	//set focus on item number entry field
							setTimeout("com.bec.order.CatalogQuickOrder.setCQOFocus()",100);
						}
						catch(e)
						{
							//not much to do, just can't set focus (this was happening in IE on 2nd display)
						}
					}
				}
			dojo.event.connect(this, "onKey", function (/*Event*/ evt) 
				{ 
					if(evt.key)
					{
						if(evt.key == evt.KEY_ENTER)
						{ 	//allow enter key to submit cqo form.
							com.bec.order.CatalogQuickOrder.add2Cart();
							dojo.event.browser.stopEvent(evt);	//don't let it go any further.
						}
					}
				});
			});		

    	//set the content and size
    	cqoFrame.setUrl("BECCatalogQuickOrderView?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId);
		cqoFrame.resizeTo(570, 260);
		
	   	//add onShow event to set focus on the partnum field. 
	   	//(onload not called after content loaded so 2nd time popup shown we need this)
		dojo.event.connect(cqoFrame, "onShow", function () 
			{ 
			//dojo.byId(com.bec.order.CatalogQuickOrder.ID).focus();
			//if(cqoFrame.isLoaded)alert('loaded'); else alert('not loaded');
			//if(cqoFrame.isShowing())alert('showing'); else alert('not showing');

				focusElement = dojo.byId("cqoPartNum");
				if(focusElement && !dojo.lang.isUndefined(focusElement))
				{
					if(focusElement.type != "hidden" && focusElement.style.display != "none"  && !focusElement.disabled) 
					{
						try
						{
							//focusElement.focus();	//set focus on item number entry field
							setTimeout("com.bec.order.CatalogQuickOrder.setCQOFocus()",100);
						}
						catch(e)
						{
							//not much to do, just can't set focus (this was happening in IE on 2nd display)
						}
					}
				}
				
				// remove and hide the error element
				errorElement = dojo.byId("cqoError");
				if(errorElement && !dojo.lang.isUndefined(errorElement))
				{
					if(errorElement.type != "hidden" && errorElement.style.display != "none"  && !errorElement.disabled) 
					{
						try
						{
							errorElement.innerHTML = "";	//reset the error element on show
							errorElement.style.display = "none"; // hide the error div
						}
						catch(err)
						{
							//not much to do, just can't set focus (this was happening in IE on 2nd display)
						}
					}
				}
			});		
    } 
	//connect events
    return cqoFrame;	
}

/**
 * set the focus to the partnumber
 */
com.bec.order.CatalogQuickOrder.setCQOFocus = function()
{
	try
	{
		dojo.byId('cqoPartNum').focus();
	}
	catch(e)
	{
		//not much to do, just can't set focus (this was happening in IE on 2nd display)
	}
}