//<%--
//********************************************************************
//*-------------------------------------------------------------------
//*	Common AJAX functions
//*-------------------------------------------------------------------
//********************************************************************
//--%>
//register wcs dojo library
dojo.registerModulePath("wc", "wc");

//register common bec dojo library
dojo.registerModulePath("bec.common", "../CommonAssets/javascript/bec/common");
	
dojo.require("dojo.io.*");
	
//publish and subscribe event support
dojo.require("dojo.event.*");
//Movable layer dialog
dojo.require("dojo.widget.Dialog");	

dojo.require("wc.service.*");
dojo.require("wc.render.*");
dojo.require("wc.widget.RefreshArea");
//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");*/

//Helping dojo to find the "bec" namespace
//dojo.setModulePrefix("bec", "bec");

//TODO: move to only load when necessary
//Delivery Calendar widget support
//dojo.require("bec.common.widget.DeliveryCalendar");

//---------------------------------------------------------------------------------------
//cursor functions
//---------------------------------------------------------------------------------------
var busyCount = 0;
function cursor_wait() 
{
	busyCount++;
	//alert("wait " + busyCount);
	document.body.style.cursor = 'wait';
}
function cursor_clear() 
{
	busyCount = busyCount - 1;
	if(busyCount < 1)
	{
		document.body.style.cursor = 'default';
	}
}

//---------------------------------------------------------------------------------------
//Add To Cart Service
//---------------------------------------------------------------------------------------
/** Add Order Item Service  */
wc.service.declare(
{
	id: "AjaxAddOrderItem",
	actionId: "AjaxAddOrderItem",
	url: "AjaxBECOrderItemAdd?URL=AjaxActionResponse&redirectUrl=AjaxActionErrorResponse&storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId,
	formId: ""
	,successHandler: function(serviceResponse) 
	{
		if(serviceResponse)
		{	//update the order item context with item add response properties.
			wc.render.updateContext("currentOrderItem_Context", 
				{"orderItemId" : serviceResponse.orderItemId, 
				 "productId" : serviceResponse.productId, 
				 "catEntryId" : serviceResponse.catEntryId,
				 "errorKey" : serviceResponse.errorKey,
				 "productError" : serviceResponse.productError});
		}
		else
		{	//error
			wc.render.updateContext("currentOrderItem_Context", 
				{"addOrderItemError" : "Error"});
		}
		cursor_clear();
	}
	,failureHandler: function(serviceResponse) 
	{
		if (serviceResponse.errorMessage) 
		{
        	alert("serviceResponse.errorMessage: " + serviceResponse.errorMessage);
		} 
		else 
		{
			if (serviceResponse.errorMessageKey) 
			{
            	alert("serviceResponse.errorMessageKey: " + serviceResponse.errorMessageKey);
            }
		}
    	cursor_clear();
	}
});

/** Current Order Item Context */
wc.render.declareContext("currentOrderItem_Context", {workAreaMode:"create", "storeId" : storeId, "catalogId" : catalogId, "langId" : langId}, "");

/** Item Add Area Controller */
wc.render.declareRefreshController(
{
	id: "itemAddAreaController",
	renderContext: wc.render.getContextById("currentOrderItem_Context"),
	url: "BECItemAddView",
	formId: ""
	,modelChangedHandler: function(message, widget) 
	{
		var controller = this;
		var renderContext = this.renderContext;
		if (message.actionId == "AjaxAddOrderItem") 
        {
        	if(renderContext.properties.orderItemId)
        	{
        		this.url = "BECItemAddView";	//make sure it set right.
        	}
        	else
        	{	//no order item id. set url to error
        		this.url = "ProductDisplayErrorView";
        	}
			widget.refresh(renderContext.properties);
		}
		else if(renderContext.properties.addOrderItemError)
		{	//unexpected error, try to show error page.
			this.url = "ProductDisplayErrorView";
			widget.refresh(renderContext.properties);
		}
	}
	,refreshHandler: function(widget, data) 
	{
		var controller = this;
		var renderContext = this.renderContext;
		getItemAddCallback(data);
	}
	
	,postRefreshHandler: function(widget) 
	{
		var controller = this;
		var renderContext = this.renderContext;		
		
		//Apply onClick CMCheckoutConversionEvent to drop-down "Checkout" buttons
		if(cmPassCoremetrics != 'OFF')		{
			
			cmApplyConversionEventOnclick();
		}	
    }
	
});

/** Current Order Context */
wc.render.declareContext("currentOrder_Context", {workAreaMode:"create", "storeId" : storeId, "catalogId" : catalogId, "langId" : langId}, "");

/** Items In Cart Area Controller */
wc.render.declareRefreshController(
{
	id: "itemsInCartAreaController",
	renderContext: wc.render.getContextById("currentOrder_Context"),
	url: "BECItemsInCartView?storeId=" + storeId + "&orderId=.",
	formId: ""
	,modelChangedHandler: function(message, widget) 
	{
		var controller = this;
		var renderContext = this.renderContext;
		if(message.actionId == "AjaxAddOrderItem"
			|| message.actionId == "AjaxOrderItemUpdate") 	//TODO: need to filter so not all updates trigger a refresh.
        {
			widget.refresh();
		}
	}	
	
	,postRefreshHandler: function(widget) 
	{
		updateSLIItemsInCart();
	}
});

//---------------------------------------------------------------------------------------
//popups
//---------------------------------------------------------------------------------------
var POPUP_PLACEHOLDER_ID = "popupMessagingPlaceholder";
var LOADING_MESSAGE = '<table height="100%" style="background-color: #ffffff;"><tr><td><img id="loadingImage" name="loadingImage" src="/images/loading_2.gif" align="center" border="0"/><img src="/images/spacer.gif" width="10" border="0" height="1"/><span class="msg_errors" style="font-weight: normal;">One moment please....</span></td></tr></table>';
/**
 * Creates and shows a modal popup.
 * NOTE: requires popupMessagingPlaceholder to exist in the page.
 *	this is the element that the new popup widget is placed after in the generated source. 
 *
 * @param id - the widget id, must be unique.
 * @param closeId - the id of the elment to be used to close the popup.
 * @param contentUrl - url to retrieve as content of the popup.
 *
 * TODO: extend Dialog with title bar and close button as default in template. 
 */
function alertDialog(id, closeId, contentUrl)
{
	var newPopup = dojo.widget.byId(id);
	if(!newPopup)
	{	//lazy create - only do one time.
		newPopup = dojo.widget.createWidget("Dialog", // widgetType
     		{	widgetId: id,
     			bgColor: "white",
     			bgOpacity: "0.2",
     			closeOnBackgroundClick: true,
     			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
    	newPopup.setUrl(contentUrl);
    	
    	//set the close control after onLoad of the popup is executed so we will have the 
    	//close element available.
		dojo.event.connect(newPopup, "onLoad", function () 
			{ 
				newPopup.setCloseControl(document.getElementById(closeId));	
			});
    }
	newPopup.show();
}
/**
 * Creates a modal popup to indicate the system is processing.
 *
 */ 
function alertModalProcessingWithContent(id, content, width, height)
{
	var newPopup = getFloatingModalPopup(id, '', width, height, null, false, false);
	newPopup.setContent(content);
	newPopup.show();
	return newPopup;	
}
/**
 * Creates and shows a floating modal popup with content from the specified url.
 * NOTE: requires popupMessagingPlaceholder to exist in the page.
 *	this is the element that the new popup widget is placed after in the generated source.
 *
 * @param id - the widget id, must be unique.
 * @param title - the title for the popup window
 * @param contentUrl - url to retrieve as content of the popup.
 * @param width - size of the popup (px)
 * @param height - size of the popup (px)
 */
function alertFloatingModal(id, title, contentUrl, width, height, onLoadFunction, css)
{
	var newPopup = getFloatingModalPopup(id, title, width, height, onLoadFunction, css);
	newPopup.setUrl(contentUrl);
	newPopup.show();	
	return newPopup;	
}
/**
 * Creates and shows a floating modal popup with the supplied content.
 * NOTE: requires popupMessagingPlaceholder to exist in the page.
 *	this is the element that the new popup widget is placed after in the generated source.
 *
 * @param id - the widget id, must be unique.
 * @param title - the title for the popup window
 * @param content - html to use as content of the popup.
 * @param width - size of the popup (px)
 * @param height - size of the popup (px)
 */
function alertFloatingModalWithContent(id, title, content, width, height, onLoadFunction)
{
	var newPopup = getFloatingModalPopup(id, title, width, height, onLoadFunction);
	newPopup.setContent(content);
	newPopup.show();
	return newPopup;	
}
/**
 * Creates and shows a floating modal popup with content from the specified url.
 * NOTE: requires popupMessagingPlaceholder to exist in the page.
 *	this is the element that the new popup widget is placed after in the generated source.
 *
 * @param id - the widget id, must be unique.
 * @param title - the title for the popup window
 * @param contentUrl - url to retrieve as content of the popup.
 * @param width - size of the popup (px)
 * @param height - size of the popup (px)
 *
 *   NOTE: for below parameters see setWidgetPosition comments.
 * @param position - name for position type
 * @param x - offset
 * @param y - offset
 * @param position_id - element to position relative to if a relative position type.
 */
function alertFloatingModalAtPosition(id, title, contentUrl, width, height, onLoadFunction, position, x, y, position_id, css)
{
	var newPopup = alertFloatingModal(id, title, contentUrl, width, height, onLoadFunction, css);
	newPopup.setPopupPosition(position, x, y, position_id);
	return newPopup;
}
/**
 * Creates and shows a floating modal popup with the supplied content.
 * NOTE: requires popupMessagingPlaceholder to exist in the page.
 *	this is the element that the new popup widget is placed after in the generated source.
 *
 * @param id - the widget id, must be unique.
 * @param title - the title for the popup window
 * @param content - html to use as content of the popup.
 * @param width - size of the popup (px)
 * @param height - size of the popup (px)
 *
 *   NOTE: for below parameters see setWidgetPosition comments.
 * @param position - name for position type
 * @param x - offset
 * @param y - offset
 * @param position_id - element to position relative to if a relative position type.
 */
function alertFloatingModalWithContentAtPosition(id, title, content, width, height, onLoadFunction, position, x, y, position_id)
{
	var newPopup = alertFloatingModalWithContent(id, title, content, width, height, onLoadFunction);
	newPopup.setPopupPosition(position, x, y, position_id);
	return newPopup;
}
/**
 * Creates a floating modal popup and returns it.
 * NOTE: requires popupMessagingPlaceholder to exist in the page.
 *	this is the element that the new popup widget is placed after in the generated source.
 *
 * @param id - the widget id, must be unique.
 * @param title - the title for the popup window
 * @param width - size of the popup (px) (OPTIONAL)- if no width then check height
 * @param height - size of the popup (px) (OPTIONAL) - if no height then check width
 * @param onLoadFunction - function or name of function to call onload of the popup (OPTIONAL)
 */
function getFloatingModalPopup(id, title, width, height, onLoadFunction, showTitleBar, backgroundClose, css)
{
	var newPopup = dojo.widget.byId(id);
	
	var templateCssPath = eSiteStyleDir + '/dojo/widget/templates/FloatingPane.css';
	
	if (css)
	{
		templateCssPath = css;
	}
	
	if(!newPopup)
	{	//lazy create - only do one time.
		newPopup = dojo.widget.createWidget("ModalFloatingPane", // widgetType
     		{	widgetId: id,
     			bgColor: "white",
     			bgOpacity: "0.2",
     			closeOnBackgroundClick: (backgroundClose == undefined ? true : backgroundClose),
     			resizable: false,
     			title: title,
     			templateCssPath: templateCssPath,
     			loadingMessage: LOADING_MESSAGE,
     			positionProps: null,
				titleBarDisplay: (showTitleBar == undefined ? true : showTitleBar),
     			placeModalDialog: function() 
     			{
     				dojo.widget.ModalDialogBase.prototype.placeModalDialog.call(this);
     				if(this.positionProps)
     				{
     					setWidgetPosition(this, this.positionProps.position, 
     						this.positionProps.x, this.positionProps.y, this.positionProps.position_id);
     				}
     			},
     			setPopupPosition: function(position, x, y, position_id)
     			{
     				this.positionProps = {position: position, x: x, y: y, position_id: position_id};	
     				this.placeModalDialog();
     			}
     		}, // 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
    	);	
    	
    	if(onLoadFunction)
    	{
			dojo.event.connect(newPopup, "onLoad", onLoadFunction);
		}

		if (width && height)
		{
    		newPopup.resizeTo(width, height);
    	}
    	else if (width)
    	{
    		newPopup.domNode.style.width = width + "px";
    	}
    	else if (height)
    	{
    		newPopup.domNode.style.height = height + "px";
    	}
    }
    return newPopup;
}

/**
 * Set the position of the popup. Position types are as follows:
 *    top-center       vertically aligned with the top of the current viewable area in the browser and horizontally centered 
 *    screen-corner    upper left corner of popup in upper left corner of screen  
 *    screen-center    center of popup is centered vertically and horizontally
 *    mouse-corner     upper left corner on the tip of the mouse
 *    mouse-center     center of popup on the tip of the mouse
 *                        WARNING: Popups that load their content via AJAX may have an initial 
 *		                  element.clientHeight that is less than the final height once the content
 *		                  is loaded. In this case the popup will be centered horizontally but 
 *		                  not vertically.
 *    element-right    Top of popup aligned with top of element specified by <code>position_id</code>,
 *                     left side aligned with right side of element.
 *    element-bottom   Top of popup adjacent to bottom of element specified by <code>position_id</code>,
 *                     left side aligned with left side of element.
 *    element-top      Bottom of popup adjacent to top of element specified by <code>position_id</code>,
 *                     left side aligned with left side of element.
 *    element-top-center Bottom of popup adjacent to top of element specified by <code>position_id</code>,
 *                     aligned with center of element.
 * 
 * @param position     String specifying one of the above position types.
 * @param x            Integer, horizontal offset from calculated position.
 * @param y            Integer, vertical offset from calculated position.
 * @param position_id  The HTML element id used for element-relative positioning
 * 					   (see element-right and element-bottom)
 */
function setWidgetPosition(widget, position, x, y, position_id)
{
	//get window top (y) and left (x)
	var scroll_offset = dojo.html.getScroll().offset;
	//get window width and height.
	var viewport_size = dojo.html.getViewport();
	//get popup width and height
	var mb = dojo.html.getMarginBox(widget.domNode);
	
	var leftx;
	var topy;
	if(position == "top-center")
	{
		leftx = (scroll_offset.x + (viewport_size.width - mb.width)/2 + x) + 'px';
		topy  = (viewport_size.height + y) + 'px';
	}
	else if(position == "screen-corner")
	{
		leftx = (scroll_offset.x + x) + 'px';
		topy  = (scroll_offset.y + y) + 'px';
	}
	else if(position == "screen-center")
	{
		leftx = scroll_offset.x + (viewport_size.width - mb.width)/2;
		topy = scroll_offset.y + (viewport_size.height - mb.height)/2;
	}
	/* TODO: determine mouse position
	else if(position == "mouse-corner")
	{
		leftx = (scroll_offset.x + this.popup_mouseposX + x) + 'px';
		topy  = (scroll_offset.y  + this.popup_mouseposY + y) + 'px';
	}
	else if(position == "mouse-center")
	{
		// WARNING: Popups that load their content via AJAX may have an initial 
		// element.clientHeight that is less than the final height once the content
		// is loaded. In this case the popup will be centered horizontally but 
		// not vertically.
		leftx = (scroll_offset.x + this.popup_mouseposX - mb.width/2 + x) + 'px';
		topy  = (scroll_offset.y  + this.popup_mouseposY - mb.height/2 + y) + 'px';
	}*/
	else if(position == "element-right" || position == "element-bottom" 
		|| position == "element-top" || position == "element-top-center")
	{
		if (position_id == undefined)
		{
			alert("Parameter 'positionId' (#4) required for 'element-right' position.");
			return false;
		}
		var position_element = document.getElementById(position_id);
		for(var p = position_element; p; p = p.offsetParent)
		{
			if(p.style.position != 'absolute')
			{
				x += p.offsetLeft;
				y += p.offsetTop;
			}
		}
		if(position == "element-right" )
		{
			x += position_element.clientWidth;
		}
		else if(position == "element-bottom")
		{
			y += position_element.clientHeight;
		}
		else if(position == "element-top" || position == "element-top-center")
		{
			y -= mb.height;
			if(position == "element-top-center")
			{
				var mbCenter = mb.width/2;
				var elCenter = position_element.clientWidth/2;
				x += elCenter;
				x -= mbCenter;				
				if((x + mb.width) > viewport_size.width)
				{
					x = viewport_size.width - mb.width;
				}
			}
		}
		leftx = x + 'px';
		topy  = y + 'px';
	}

	if(leftx && topy)
	{
		with(widget.domNode.style)
		{
			left = leftx;
			top = topy;
		}	
	}
}

/*
function createFloatingPane( fpId, fpStyleClass,
	fpTitle, fpDockable, fpMaxable, fpClosable, fpResizable,
	fpMaximizeFunc, fpCloseFunc,
	fpWidth, fpHeight, fpTop, fpLeft ){

	var fpNode = document.createElement("div");

     // create a div element for the contents of the floating pane
     // this is used to add content into the floating pane
	var fpContentNode = document.createElement("div");
	dojo.attr(fpContentNode, "id", fpId + "Content");
	fpNode.appendChild(fpContentNode);
	
	dojo.body().appendChild(fpNode);
	dojo.attr(fpNode,"id", fpId );
	
	if(fpStyleClass != null)
		dojo.addClass(fpNode, fpStyleClass );
	
     // create an instance of FloatingPane with the passed in variables
	var tmp = new dojox.layout.FloatingPane({
		title: fpTitle ,
		dockable: fpDockable,
		maxable: fpMaxable,
		closable: fpClosable,
		resizable: fpResizable
		}, fpNode );

	// Make it go top left when it is maximized
	tmp.connect(tmp,"maximize",function(e){
			dojo.byId(fpId).style.top = "0px";
			dojo.byId(fpId).style.left = "0px";
		});

	if(fpMaximizeFunc != null)
		tmp.connect(tmp,"maximize",fpMaximizeFunc);
	if(fpCloseFunc != null)
		tmp.connect(tmp,"close",fpCloseFunc);
	
	tmp.startup();
	// Resize does not require px
	tmp.resize({ w: fpWidth, h: fpHeight });
	// Style top/left require px
	dojo.byId(fpId).style.top = fpTop;
	dojo.byId(fpId).style.left = fpLeft;
}
*/
/**
 * Request Helper function  
 * TODO: possibly create RequestHelper widget to hold this and other similar functions.
 *
 * Parse the window.location.href value and return the value for the parameter you specify. 
 * It does this using javascript's built in regular expressions.
 *
 * @param name Request Parameter Name to retrieve from query String
 * @return String empty if not found or the value for the specified name. 
 */
function getRequestParameter(name)
{
    var value;
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );    
    if( results == null )
    {
        value = "";
    }
    else
    {
        value = results[1];
    }
    return value;
}

var sessionErrorDisplayed = false;
/**
 * Display the session timeout error and redirect to login page 
 */
function displaySessionError(userType)
{
	sessionErrorDisplayed = true;
	var isGuest = false;
	if (userType == 'G')
	{
		isGuest = true;
	}
	_showSessionTimeoutDialog(isGuest);
}

function redirectToLogin()
{
	document.location.href = "BECLogonForm?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId;
}
function isSessionErrorDisplayed()
{
	return sessionErrorDisplayed;
}

function _showSessionTimeoutDialog(isGuest) 
{
	if (isGuest)
	{
		var messageText = 'Because there has been no activity for more than 20 minutes, your session has expired. Please register again to continue.';
	
		var redirect = 
			'<a href="javascript:redirectToLogin();">' +
			'<img src="/images/btn_signin06.gif" border="0" alt="sign in"/>' +
			'</a>';
	}
	else
	{
		var messageText = 'Because there has been no activity for more than 20 minutes, your session has expired. Please sign in again to continue.';
	
		var redirect = 
			'<a href="javascript:redirectToLogin();">' +
			'<img src="/images/btn_signin06.gif" border="0" alt="sign in"/>' +
			'</a>';
	}

	var content = '<p class="addressError"><img src="/images/erroricon_whitex.gif" border="0" align="left" style="padding-right:5px"/>'+messageText+'</p>' +
		'<br/><p style="align:center">' + 
			redirect + 
		'</p>';

	var id = "sessionError";
	var title = "Session Timeout";
	var width = 500;
	var height = 150;

	var newPopup = dojo.widget.byId(id);
	if(!newPopup)
	{	//lazy create - only do one time.
		newPopup = dojo.widget.createWidget("ModalFloatingPane", // widgetType
     		{	widgetId: id,
     			bgColor: "white",
     			bgOpacity: "0.4",
     			closeOnBackgroundClick: false,
     			resizable: false,
     			title: title,
     			templateCssPath: eSiteStyleDir + "/dojo/widget/templates/FloatingPane.css"
     		}, // 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
    	newPopup.setContent(content);
    	newPopup.resizeTo(width, height);
    }
    else
    {
    	newPopup.setContent(content);	
    }
	newPopup.show();	
}

//Update SLI items in cart hidden form variable
function updateSLIItemsInCart()
{
	var sliItemsInCart = dojo.byId("sliItemsInCart");
	if (sliItemsInCart)
	{
		sliItemsInCartArea = dojo.byId("itemsInCartArea");
		itemsInCartCount = sliItemsInCartArea.getElementsByTagName("span")[0];
		
		sliItemsInCart.value = itemsInCartCount.innerHTML;
	}
}