//********************************************************************
//*-------------------------------------------------------------------
//*	Common AJAX functions
//*-------------------------------------------------------------------
//********************************************************************
dojo.config.dojoBlankHtmlUrl="/gifts/blank.html";

dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.Tooltip");
dojo.require("wc.service.common");
dojo.require("wc.widget.RefreshArea");
dojo.require("bec.util.lang");
dojo.require("bec.util.browser");
dojo.require("bec.util.search");
dojo.require("dojo.cookie");
dojo.require("bec.analytics.Coremetrics");	
dojo.require("bec.widget.Button");
dojo.require("bec.widget.PopupDialog");
dojo.require("bec.product.AddToCart");
dojo.require("bec.product.AddToCartButton");
dojo.require("bec.order.CatalogQuickOrder");
//Logon Panel Support (checkout version is included in checkout pages)
dojo.require("bec.user.Logon");
dojo.require("bec.order.CommonCartServices");
dojo.require("bec.menu.MenuContentPane");
dojo.require("bec.widget.PopupPanelContainer");
dojo.require("bec.widget.PopupPanel");

//---------------------------------------------------------------------------------------
// define common 
//---------------------------------------------------------------------------------------
var popup;
var catalogQuickOrder;
var becLogonPage;
var becLogonPanel;
var becLogon;
var resetPassword;
var resetPasswordPopup;

var LOADING_MESSAGE = 
	'<span class="dijitContentPaneLoading"><img class="loadingImage" src="' + eSiteImgDir + '/loading_2.gif"/></span>';

dojo.addOnLoad(function() 
{
	dojoParseButtons();
	dojoParseRegisteredWidgets();
	
    try
    {
        popup = new bec.widget.PopupDialog({loadingMessage: LOADING_MESSAGE}); 
    }
    catch(e)
    {
        console.debug('error: ' + e);
    }   
    requestSubmitted = false;
});
/**
 * Find and parse and instantiate all buttons on the page.
 */
function dojoParseButtons()
{
	dojo.forEach(dojo.query("[dojoType='bec.widget.Button'],[dojoType='bec.product.AddToCartButton']"), function(button)
	{
		dojo.parser.instantiate([button], {dojoType: dojo.attr(button, "dojoType")});
	});
}

var parseList=new Array();
/**
 * parses those widgets registered to be parsed. 
 * searches for certain widgets and parses.
 * Should be ran on page load. 
 */
function dojoParseRegisteredWidgets()
{
	dojo.forEach(parseList, function(entry)
	{
		if(entry.parseType == "widget")
		{
			dojo.parser.instantiate([dojo.byId(entry.id)], {dojoType: entry.type});
		}
		else if(entry.parseType == "node")
		{
			dojo.parser.parse(dojo.byId(entry.id));
		}
	});	
}
/**
 * register a widget to be instantiated.
 */
function dojoParse(id, type)
{
	parseList.push({parseType: 'widget', id: id, type: type});
}
/**
 * register a node to be parsed for widgets.
 * This is used for sections of a page that rely heavily on widgets.
 * Simplifies the initialization by allowing dojo to manage it.
 */
function dojoParseNode(nodeId)
{
	parseList.push({parseType: 'node', id: nodeId});
}
//---------------------------------------------------------------------------------------
//cursor functions
//---------------------------------------------------------------------------------------
var busyCount = 0;
function cursor_wait() 
{
    busyCount++;
    //console.log("busyCount=" + busyCount);
    document.body.style.cursor = 'wait';
}
function cursor_clear() 
{
    busyCount = busyCount - 1;
    //console.log("busyCount=" + busyCount);
    if(busyCount < 1)
    {
        document.body.style.cursor = 'default';		 
		requestSubmitted = false;	//Reset the flag
    }
}
/** 
 * This variable indicates whether a request has been submitted or not.
 * The value is initialized to true and resets to false on full page load.
 */
var requestSubmitted = true;
/**
 * Checks whether a request can be submitted or not.
 * A new request may only be submitted when no request is currently running.
 * If a request is already running, then the new request will be rejected.
 *
 * @return {boolean} Indicates whether the new request can be submitted (true) or rejected (false).
 */
function submitRequest() 
{	
	console.log("requestSubmitted=" + requestSubmitted);
	var result = false;
	if(!requestSubmitted) 
	{
		requestSubmitted  = true;
		result = true;
	}
	return result;
}
function isRequestSubmitted()
{
	return requestSubmitted;
}
//---------------------------------------------------------------------------------------
//Sign In Service - most of this moved to Logon.js and ResetPassword.js
//---------------------------------------------------------------------------------------
function showEmailPanel()
{
	dijit.byId('emailDropDown').show();
}

function hideEmailPanel()
{
	dijit.byId('emailDropDown').hide();
}
function openLogonPanel()
{
	becLogon = null;
	if (!becLogonPanel)
	{
		becLogonPanel = new bec.user.LogonPanel();
	}
	becLogonPanel.open();	
}
function openLogonPopup(url)
{
	becLogonPanel = null;
	if (!becLogon)
	{
		becLogon = new bec.user.Logon();
	}	
	becLogon.open(url);
}
function getResetPasswordInstance()
{
	if (resetPasswordPopup)
	{
		return resetPasswordPopup;
	}
	else if(resetPassword)
	{
		return resetPassword;
	}
}

/** Process CM Category **/
function cmSetCategory()
{
	if(cmPassCoremetrics != 'OFF')
	{
		var cm_ref = document.referrer;
		var cm_set_mmc = false;
		var cm_ven='';
		var cm_cat='';
		var cm_pla='';
		var cm_ite='';
		var cm_mmc='';
		var cm_mmc_o='';
		var cm_mmc_params = '';
		var cmLookNVPArr =['cm_ven','cm_cat','cm_pla','cm_ite','cm_mmc','cm_mmc_o'];
		var cmCheckNVPArr = location.search.substring(1).split('&');
		var cmaddNVPArr = [cmCheckNVPArr.length];
		for(var i = 0; i < cmCheckNVPArr.length; i++)
		{
			cmaddNVPArr[i] = cmCheckNVPArr[i].split('=');
		}
	
		for(var i = 0; i < cmCheckNVPArr.length; i++)
		{
			for(var j = 0; j < cmLookNVPArr.length; j++)
			{
				if(cmLookNVPArr[j] == cmaddNVPArr[i][0])
				{
					window[cmLookNVPArr[j]] =  cmaddNVPArr[i][1];
					continue;
				}
			}
		}
	
		cm_ven=cm_ven.replace(/ /g,"%20");
		cm_cat=cm_cat.replace(/ /g,"%20");
		cm_pla=cm_pla.replace(/ /g,"%20");
		cm_ite=cm_ite.replace(/ /g,"%20");
		cm_mmc=cm_mmc.replace(/ /g,"%20");
		cm_mmc_o=cm_mmc_o.replace(/ /g,"%20");
	
		var amperNeeded=false;
		if(cm_ven!='')
		{
		  	cm_mmc_params+="cm_ven="+cm_ven;
		  	amperNeeded=true;
		}
		if(cm_cat!='')
		{
		  	if(amperNeeded)
		  	{  cm_mmc_params+='&'; }
		  	cm_mmc_params+="cm_cat="+cm_cat;
		  	amperNeeded=true;
		}
		if(cm_pla!='')
		{
		  	if(amperNeeded)
		  	{  cm_mmc_params+='&'; }
		  	cm_mmc_params+="cm_pla="+cm_pla;
		  	amperNeeded=true;
		}
		if(cm_ite!='')
		{
		  	if(amperNeeded)
		  	{  cm_mmc_params+='&'; }
		  	cm_mmc_params+="cm_ite="+cm_ite;
		  	amperNeeded=true;
		}
		if(cm_mmc!='')
		{
		  	if(amperNeeded)
		  	{  cm_mmc_params+='&'; }
		  	cm_mmc_params+="cm_mmc="+cm_mmc;
		  	amperNeeded=true;
		}
		else
		{
		  if ((cm_ven!='') && (cm_cat!='') && (cm_pla!='') && (cm_ite!=''))
		  {
		    	if(amperNeeded)
		    	{  cm_mmc_params+='&'; }
		    	cm_mmc_params+="cm_mmc="+cm_ven+"-_-"+cm_cat+"-_-"+cm_pla+"-_-"+cm_ite
		    	amperNeeded=true;
		  }
		}
		if(cm_mmc_o!='')
		{
		  	if(amperNeeded)
		  	{  cm_mmc_params+='&'; }
		  	cm_mmc_params+="cm_mmc_o="+cm_mmc_o;
		  	amperNeeded=true;
		}
	
		if(cm_mmc_params!='')
		{
		  	cm_set_mmc = true;
		}
		
		if(typeof virtual_cat != "undefined")
		{
			if(virtual_cat != null)
			{
				if(virtual_cat != '')
			    {
		     		updateCookie('virtCatCM', virtual_cat);
			    }
			}
		}
		
		//Determine if virtual category passed on URL string
		for(var i = 0; i < cmCheckNVPArr.length; i++)
		{ 	var pos = cmCheckNVPArr[i].indexOf('urlVirtualCat');
			if (pos == -1) continue;
			var vcValue = cmCheckNVPArr[i].substr(cmCheckNVPArr[i].indexOf('=')+1);
				if(vcValue != "") updateCookie('virtCatCM', vcValue);
		}
		
		//Determine if sliSearch value passed on URL string
		for(var i = 0; i < cmCheckNVPArr.length; i++)
		{ 	var pos = cmCheckNVPArr[i].indexOf('sliSearch');
			if (pos != -1)
				cmSearch = cmCheckNVPArr[i].substr(cmCheckNVPArr[i].indexOf('=')+1);
	
		}
	
		if(typeof clear_virtual_cat != "undefined")
		{
			if(clear_virtual_cat == "Yes")	expireCookie("virtCatCM", 0);
		}
		else
		{
			cmCategory = readCookie('virtCatCM');
		}
	
	   if((cmCategory == "") || (cmCategory == null))
	   {
		 	if(typeof cm_merch_cat != "undefined")
	     		cmCategory = cm_merch_cat;
	   }
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////
//	From old Utils.js
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//This function creates or modifies a cookie.
//USED FOR COREMETRICS  - TODO: should move to cm file
//////////////////////////////////////////////////////////
function updateCookie(name, value)
{
    dojo.cookie(name, escape(value), {path: '/'});
}
//////////////////////////////////////////////////////////
//This function reads a cookie.
//USED FOR COREMETRICS  - TODO: should move to cm file
//////////////////////////////////////////////////////////
function readCookie(name) 
{
    return dojo.cookie(name);
}	
//////////////////////////////////////////////////////////
//Sets the expiration date of a cookie (set to zero to delete cookie).
//USED FOR COREMETRICS  - TODO: should move to cm file
//////////////////////////////////////////////////////////
function expireCookie(name, minutes)
{
	var dateObj=new Date();
	dateObj.setMinutes(dateObj.getMinutes()+minutes);
	document.cookie = name + "=" + readCookie(name) + ";path=/;expires=" + dateObj;
}
//////////////////////////////////////////////////////////
//Convert char to ascii code
//USED FOR COREMETRICS  - TODO: should move to cm file
//////////////////////////////////////////////////////////
function toAscii (cmChar)  
{
	var symbols = " !\"#$%&'()*+'-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
	var loc;
	loc = symbols.indexOf(cmChar);
	if (loc >-1) 
	{ 
		return (32 + loc);
	}
	return(0);  // If not in range 32-126 return ZERO
}
//////////////////////////////////////////////////////////
//Convert decimal to Hex
//	USED FOR COREMETRICS  - TODO: should move to cm file
//////////////////////////////////////////////////////////
function Dec2Hex(Decimal) 
{
	var hexChars = "0123456789ABCDEF";
	var a = Decimal % 16;
	var b = (Decimal - a)/16;
	hex = "" + hexChars.charAt(b) + hexChars.charAt(a);
	L = hexChars.charAt(a);
	H = hexChars.charAt(b);
	return hex;
}

//////////////////////////////////////////////////////////
//Right trims spaces from a string
//////////////////////////////////////////////////////////
function RTrim(VALUE)
{
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length >= 0)
	{
    	var iTemp = v_length -1;    	
    	while(iTemp > -1)
    	{
    		if(VALUE.charAt(iTemp) == w_space)
    		{
    		}
    		else
    		{
    			strTemp = VALUE.substring(0,iTemp +1);
    			break;
    		}
    		iTemp = iTemp-1;
    	} //End While
	}
	return strTemp;
} //End Function
//////////////////////////////////////////////////////////
//This function is meant to remove html tags from a string
//There is a possibility that the HTML tags are in Mark Up 
//form, so change string from markup before replacing
//
//Returns input string with no html.
//////////////////////////////////////////////////////////
function clearHTMLTags(strHTML)
{		
	var strMarkedUp = strHTML.replace(/&lt;([^&]*)&gt;/g,"<$1>");	
	return strMarkedUp.replace(/<[^>]*>/g, "");   
} // //End Function

/**
 * Currency formatting pattern
 */
var PATTERN_DOLLAR = {pattern: "$#,##0.00"};
/**
 * This function parses price to remove '$', ',' and Awards Points
 * @param strPrice
 * @return Number
 */
function parsePrice(strPrice)
{		
	var rtnNumber = 0;
	if (strPrice)
	{
		try
		{
			var priceOnly;
			priceOnly = strPrice.replace(/[\$,\s]/g, "");
			
			if (priceOnly)
			{
				// remove Awards points if exist
				priceOnly = priceOnly.toLowerCase();
				
				if(priceOnly && priceOnly.indexOf('<br') != -1)
				{
					priceOnly = priceOnly.substring(0, priceOnly.indexOf('<br'));
				}
			}
			
			rtnNumber = Number(priceOnly);
		}
		catch(e)
		{
			console.debug("error parsing price " + e);
			rtnNumber = 0;
		}
	}	
	return rtnNumber;
}

