/***************************************************************************
 [AppFunctions.js]
 
*****************************************************************************/
function Omniture(OmEvent,prdId){
/* You may give each page an identifying name, server, and channel on the next lines. */
s.pageName=""
s.server=""
s.channel=""
s.pageType=""
s.prop1=""
s.prop2=""
s.prop3=""
s.prop4=""
s.prop5=""
/* E-commerce Variables */
s.campaign=""
s.state=""
s.zip=""
s.events=OmEvent 
s.products=";"+prdId
s.purchaseID=""
s.eVar1=""
s.eVar2=""
s.eVar3=""
s.eVar4=""
s.eVar5=""
/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
	try
	{
		if(s.t)
		{
			var s_code=s.t();if(s_code)document.write(s_code)//
		}
	}
	catch(ex)
	{
	}
}

function GetUrl(relativeUrl, secure) // Converts relative to absolute
{
	var BaseUrl = location.href.toLowerCase().replace('user/','').replace('affiliate/','').replace('includes/','').replace('popups/','');
	BaseUrl = BaseUrl.substr(0,BaseUrl.lastIndexOf('/'));
	if (secure != null)
	{
		if (secure)
			BaseUrl = BaseUrl.replace('http://','https://');
		else
			BaseUrl = BaseUrl.replace('https://','http://');
	}
	
	return BaseUrl+'/'+relativeUrl;
}

var chatWin = null;
function OpenLiveChat()
{
	try
	{
		if(chatWin != null)
		{
			try
			{
				chatWin.close();
			}
			catch(e) // Error, so null it
			{
				chatWin = null;
			}
		}

		//chatWin = window.open( GetUrl("LiveChatWindow.aspx"),"chatWin","width=236px, height=440px, scrollbars=no,status=yes");
		alert("Live chat is not implemented.");

		return false;
	}
	catch(e)
	{}	
};

function DoEmail()
{
	if(chatWin != null)
	{
		try
		{
			chatWin.close();
		}
		catch(e) // Error, so null it
		{
			chatWin = null;
		}
	}
		
	chatWin=window.open(  gUrlPrefix+"popups/SendEmail.aspx","chatWin","width=369px, height=442px, scrollbars=no,status=yes");
};

function DoCallback()
{
	if(chatWin != null)
	{
		try
		{
			chatWin.close();
		}
		catch(e) // Error, so null it
		{
			chatWin = null;
		}
	}

	chatWin=window.open( gUrlPrefix+"popups/GetCallBack.aspx?ReturnUrl="+location.href,"chatWin","width=300px, height=400px, scrollbars=no,status=yes");
};

function openOrderStatus(tbID)
{
	try
	{
		if (!tbID)
			tbID = "inputOrderStatus";
		
		document.location.href="OrderStatus.aspx?FON="+document.getElementById(tbID).value;
	}
	catch(e)
	{
		//alert(e.message);
	}
}

function openFedex(tbID) // moved from Footer.ascx
{
	try
	{
		if (!tbID)
			tbID = "inputTrackNum";
		var textbox = document.getElementById(tbID);
		var num = textbox.value;
		
		if (num.substr(0,2) == 'A0' || num.substr(0,2) == 'N0' || num.substr(0,2) == 'P0' || num.substr(0,4) == '1154')
		{
			var order = confirm('The number you entered appears to be an order number.  \n\nWould you like to track this as an order instead?');
			if (order)
			{
				location.href = GetUrl('user/DisplayOrderItems.aspx?orderID='+num);
				return;
			}
		}
		
		// strip bad characters
		var regEx = new RegExp("[0-9]");
		for (var i=0; i<num.length; i++)
		{
			var n = num.charAt(i);
			if ( !regEx.test(n) )
			{
				num = num.replace(num.charAt(i), '');
				i--; // just shrunk the list, don't skip over
			}
		}
		
		var url = "http://www.fedex.com/Tracking?ascend_header=1&clienttype=dotcom&cntry_code=us&language=english&tracknumbers=";
		if (num.length > 11)
		{
			url = url+num;
			PopupWindow(url);
		}
		else
		{
			alert('Sorry, that FedEx tracking number is too short');
		}
	}
	catch(e)
	{
		//alert(e.message);
	}
};

function BestPricePopup(id) // Could make this function obsolete too...
{
	PopupWindow('popups/BestPrice.aspx?id='+id, 180, 10, 'bestPrice');
};

function PopupWindow(url, width, height, name, scrollbars)
{
	if (name == null)
		name = '_blank';
	if (scrollbars == null)
		scrollbars = 'yes';
		
	/*if (theWindow) // Don't get too many popups (gets "'theWindow' is undefined" error)
		theWindow.close();*/

	if (width == null || height == null)
	{
		var win = window.open( url, name, "top=50,left=50,directories=no,status=yes,location=no,toolbar=no,scrollbars="+scrollbars+",resizable=yes,menubar=no,copyhistory=no");
	}
	else
	{
		var win = window.open( url, name, "width="+width+",height="+height+",top=50,left=50,directories=no,status=yes,location=no,toolbar=no,scrollbars="+scrollbars+",resizable=yes,menubar=no,copyhistory=no");		
	}
	if (win)
	{
		win.focus();
		theWindow = win;
	}
	else // Warn popup blockers
	{
		alert('A window could not be opened.\nIf you have a popup blocker, please check your popup blocker settings and try again.');
	}
};

function Show(id)
{
	var obj = document.getElementById(id);
	if (obj != null) { obj.style.display = "inline"; }
};

function Hide(id)
{
	var obj = document.getElementById(id);
	if (obj != null) { obj.style.display = "none"; }
};

function divPopup(text, className, posLeft, posTop, width, height)
{
	var div = document.getElementById('divPopup');
	
	// defaults
	className = (className)?className:'clickbg';
	posLeft = (posLeft)?posLeft:50;
	posTop = (posTop)?posTop:50;
	width = (width)?width:50;
	height = (height)?height:50;
	
	if( text.indexOf('>') < text.indexOf('<') )
	{
		text = text.slice( text.indexOf('>')+1, text.length );
	}
	
	if (!div) // create it if it doesn't exist
	{
		if (document.body.insertAdjacentHTML) // IE knows a fast way to do it
		{
			document.body.insertAdjacentHTML('BeforeEnd', '<div id="divPopup" style="POSITION: absolute;"></div>');
		}
		else // do it the slower but cross browser way
		{
			document.body.innerHTML += '<div id="divPopup" style="POSITION: absolute;"></div>';
		}
		
		div = document.getElementById('divPopup');
	}
	
	div.onmouseover = function() { setDivPopupVisibility(true); };
	div.onmouseout = function() { hideDivPopup(); };
	
	if (!document.body.insertAdjacentHTML)
	{
		//posLeft -= 20;
		posTop -= 10;
	}
	
	// set on div
	div.style.width = width;
	div.style.height = height;
	div.style.left = posLeft+'px';
	div.style.top = posTop+'px';
	div.className = className;
	div.innerHTML = text;
	div.style.display = 'inline';
	
	divHiding = false;
};

function setDivPopupVisibility(visible)
{
	var div = document.getElementById('divPopup');
	if (div)
	{
		if (visible)
			div.style.display = 'inline';
		else if (divHiding) // allow re-showing to stop hiding... otherwise can hide after re-show
			div.style.display = 'none';
	}
	divHiding = false;
};

var divHiding = false;
function hideDivPopup()
{
	if (!divHiding) // Don't hide if hidden (otherwise hides new ones sometimes)
		setTimeout('setDivPopupVisibility(false)', 1000);
		
	divHiding = true;
};

// Moves focus from the "src" TextBox (self id) to the "dst" TextBox after reaching length "len"
function MoveFocus(src, dst, len, e)
{
	var isNN = (navigator.appName.indexOf("Netscape")!=-1);
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	
	var source = document.getElementById(src);
	var dest = document.getElementById(dst);
	
	if (source.value.length >= len && !containsElement(filter,keyCode))
	{
		dest.focus();
		dest.select();
	}

	function containsElement(arr, ele) 
	{
		var found = false, index = 0;
	
		while(!found && index < arr.length)
		if(arr[index] == ele)
			found = true;
		else
			index++;
			
		return found;
	}
	return true;
};

function CheckSubmit(e, func)
{
	if(!e) e = window.event;
	
	// still don't have anything (happens on some browsers after the good one went)
	if (!e) return;
	
	var key = ( typeof(e.which) == 'number')?e.which:e.keyCode;
	if(key == 13)
	{	
		// Cancel the event (IE doesn't need this, but trying to get Firefox to behave)
		e.cancelBubble = true; // Cancel the event!!!  We're in control of it now.
		e.returnValue = false; // Still trying to convince Firefox to listen to us... (nevermind, was a Firefox 0.8 bug)
		
		//eval(func); // This way the function can be added in code-behind
		setTimeout(func, 100); // Want to run after we return (this works with autocomplete!
		return false;
	}
	else
	{
		return true; // Allow key to be processed/entered
	}
};

///////////////////////////////////////////////////
/// For custom validator (CustomRegexValidator.cs)
///////////////////////////////////////////////////
function CustomValidate(source, arguments)
{
	var obj = document.getElementById(source.controltovalidate);
	var NOT = false;
	
	if( source.ValidationExpression.indexOf("NOT->") == 0 )
	{
		NOT = true;
	}
	
	var regEx = new RegExp("^"+source.ValidationExpression.replace("NOT->","")+"$");

	if (arguments.Value != "" && arguments.Value.match(regEx))
	{
		if( NOT == false )
		{
			obj.style.borderColor = "#000000";
			obj.style.backgroundColor = "#FFFFFF";
		}
		else
		{
			arguments.IsValid = false; // mark as false so it shows in the summary
			obj.style.borderColor = "#EE8888";//"#FF0000";
		}
	}
	else
	{
		if( NOT == false )
		{
			arguments.IsValid = false; // mark as false so it shows in the summary
			obj.style.borderColor = "#EE8888";//"#FF0000";
		}
		else
		{
			obj.style.borderColor = "#000000";
			obj.style.backgroundColor = "#FFFFFF";
		}
		//obj.style.backgroundColor = "#FFDDDD";
	}
};

function ShowRequired(obj, onlyRequired)
{
	if (obj.value != "")
	{
		if (onlyRequired) // otherwise expression validator must reset it
		{
			obj.style.borderColor = "#000000";
			obj.style.backgroundColor = "#FFFFFF";
		}
	}
	else
	{
		obj.style.borderColor = "#EE8888";//"#FF0000";
		//obj.style.backgroundColor = "#FFDDDD";
	}
};

function ResetIfEmpty(obj)
{
	if (obj.value == "")
	{
		obj.style.borderColor = "#000000";
		obj.style.backgroundColor = "#FFFFFF";
	}
};

function BlurAll(source, arguments)
{
	var ids = document.getElementsByTagName("input");
	for (var i=0; i<ids.length; i++)
	{
		if (ids[i].id != "" && !ids[i].disabled)
		{
			ids[i].fireEvent("onBlur");
		}
	}
};
///////////////////////////////
// For product search item checkbox auto-saving
///////////////////////////////
var CompareIDs = '';

function AddRemoveCompare(cb) // Saves selection every time a checkbox is clicked
{	
	var id = ','+cb.parentNode.id;
	if (cb.checked && CompareIDs.indexOf(id) == -1) // checked & doesn't exist
	{
		CompareIDs += id;
	}
	else if (CompareIDs.indexOf(id) > -1) // not checked, but exists -> need to remove
	{
		CompareIDs = CompareIDs.replace(id,'');
	}
	
	//alert(CompareIDs);
}

function ReadCheckboxes() // Reads current selection from query string (to start in proper state)
{
	var list = location.href.replace('%2c', ',');
	
	if (list.indexOf('?') > -1 && list.indexOf('prodList=') > -1)
	{
		list = list.substr( list.indexOf('prodList=')+9 );
		if (list.indexOf('&') > -1)
			list = list.substring(0, list.indexOf('&'));
	}
	else // clear it out, doesn't have any
	{
		list = '';
	}

	//alert('read: '+list);
	if (list.length > 1)
		CompareIDs = ','+list; // the list always starts with a ',' (to make searching easy)

	// Hook event into all the hyperlinks (that aren't linkbuttons, since they postback...)
	var links = document.getElementsByTagName('a');
	var count = 0;
	for (var i=0; i<links.length; i++)
	{
		if (links[i].href.toLowerCase().indexOf('shist') > -1)
		{
			if (links[i].addEventListener)
			{
				links[i].addEventListener('click', SaveCheckboxes, false);
			}
			else if (links[i].attachEvent)
			{
				links[i].attachEvent('onclick', SaveCheckboxes);
			}
		}
	}
}

// This method needs to be called whenever a link is clicked from the breadcrumb, filters, or paging
// It needs to somehow override where the link is going, and append the 'prodList=' to it.
function SaveCheckboxes(e)
{
	if(!e) e = window.event;
	
	// still don't have anything (happens on some browsers after the good one went)
	if (!e) return;
	
	var target;
	
	// Find the link that sent this request
	if( e.srcElement != null )
		target = e.srcElement;		
	if( e.target != null )
		target = e.target;
		
	var url = target.href; // save the indended url (may change this later)
		
	var pids = CompareIDs;
	if (pids.length > 1 && pids.charAt(0) == ',')
	{
		pids = pids.substring(1);
	}
	else if (pids.length == 0)
	{
		return;
	}
			
	// Must parse the url according to what's already there
	if (url.indexOf('?') > -1 && url.indexOf('prodList=') > -1)
	{
		var end = url.substr( url.indexOf('prodList=')+9 );
		if ( end.indexOf('&') > -1 )
			end = end.substr( end.indexOf('&') );
		else
			end = '';
			
		var start = url.substring(0, url.indexOf('prodList=')+9);
		
		url = start+pids+end;
	}
	else if (url.indexOf('?') > -1)
	{
		url = url+'&prodList='+pids;
	}
	else // This isn't ever used, but here just in case
	{
		url = url+'?prodList='+pids;
	}
	
	//alert(url);
	
	// swap the url right before navigating (a very sneaky fix...)
	target.href = url;
}
			
function keyPress_ClickButton(e, toClick)
{
	var key = ( typeof(e.which) == 'number')?e.which:e.keyCode;
	//alert(key);
	
	if (key == 13)// Enter key
	{
		try
		{
			//alert('cancelin and clickin');
			var objectToClick = document.getElementById(toClick);
			objectToClick.click();
		}
		catch(e)
		{}
		
		e.cancelBubble = true;
		e.returnValue = false;
		return false;
		//return true;
	}
}

function keyPress_SkipFocus(e, toFocus)
{
	try
	{
		var key = ( typeof(e.which) == 'number')?e.which:e.keyCode;
		//alert(key);
		
		if (key == 13)// Enter key
		{
			try
			{
				//alert('cancelin and focusin');
				var objectToFocus = document.getElementById(toFocus);
				objectToFocus.focus();
			}
			catch(e)
			{}
			
			e.cancelBubble = true;
			e.returnValue = false;
			return false;
		}
	}
	catch(e)
	{
		return false;
	}
}

var bmlWin = null;
function BMLCore()
{
	if(bmlWin != null)
	{
		try
		{
			bmlWin.close();
		}
		catch (e)
		{
			bmlWin = null;
		}
	}
	
	//bmlWin=window.open( GetUrl("popups/BMLCore.aspx"),"bmlWin","width=502px, height=640px, scrollbars=yes,status=yes");
	bmlWin=window.open("https://www.securecheckout.billmelater.com/paycapture-content/fetch?hash=W5T27ENT&content=/bmlweb/coreiw.html", "bmlWin", "width=502px, height=640px, scrollbars=yes, status=yes");
};

var palaWin = null;
function BML_PALA()
{
	if(palaWin != null)
	{
		try
		{
			palaWin.close();
		}
		catch (e)
		{
			palaWin = null;
		}
	}
	
	//chatWin=window.open( GetUrl("popups/BML_PALA.aspx"),"chatWin","width=502px, height=790px, scrollbars=yes,status=yes");
	chatWin=window.open("https://www.securecheckout.billmelater.com/paycapture-content/fetch?hash=W5T27ENT&content=/bmlweb/coreiw.html", "chatWin", "width=502px, height=790px, scrollbars=yes, status=yes");
	
};

function ShowAllResults(resultGroup)
{

	var group = $(resultGroup);
	group.style.display = "inline";

}

var OrigImage = "";
function RolloverMainProductImage (isrc, ialt)
{
	if (OrigImage == "")
		OrigImage = document['MainProductImage'].src;
		
	document['MainProductImage'].src = isrc;
}

function RolloutMainProductImage ()
{
	if (OrigImage != "")
		document['MainProductImage'].src = OrigImage;
}
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) 
		curleft += obj.x;
		
	return curleft;
};
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while(obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) 
		curtop += obj.y;
	
	return curtop;
};
