// common.js
// javascript functions


_ieversion = 99;
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
 if (ieversion>=8)
  _ieversion = 8;
 else if (ieversion>=7)
 _ieversion = 7;
 else if (ieversion>=6)
  _ieversion = 6;
 else if (ieversion>=5)
   _ieversion = 5;
}
   

_objectMoving = "";
_objectMovingIF = "";

_isIE6 = false;
_isIE7 =(_ieversion>=7)?true:false;
_isFOX =(navigator.userAgent.indexOf('Firefox')>=0)?true:false;
_isSafari =(navigator.userAgent.indexOf('Safari')>=0)?true:false;
_isIE = (_isIE6||_isIE7)?true:false;
_callHasSpecialAction = false;

// Add to the string object method for trim(), ltrim and rtrim.
// Exemple: var test = "hello ";
//          test = test.trim();
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function updateButtonClass(amtValue)
{

}

function setCityState(city,state,cityField,stateField)
{
		cityField.value = city;
		stateField.value = state;
}



function _isInteger(val) {
			var digits="1234567890";
			for (var i=0; i < val.length; i++) {
				if (digits.indexOf(val.charAt(i))==-1) { return false; }
				}
			return true;
		}





function openAddress(url, pageWidth, pageHeight, modal, closeCallBack)
{
	if(!pageWidth){
		pageWidth = 660;
	}

	if(!pageHeight){
		pageHeight = 400;
	}
	
	if(!modal){
		modal = false;
	}
	
	if(!closeCallBack){
		closeCallBack = "";
	}
	
	
	if($('shopBag'))
	{
		document.body.removeChild($('shopBag'));
	}
	
	j$( '<div class="iframeInnerCtn"><iframe src="' + url + '" width="' + pageWidth + '" height="' + pageHeight + '" frameborder="0"></iframe></div>' ).dialog({
			autoOpen: true 
		,	resize: 'auto'
		,	width: pageWidth
		,	dialogClass: 'iframeOuterCtn'
		,	modal : modal
		,	close: closeCallBack
	});
	
	return false;

	mainDiv = document.createElement('div');
	mainDiv.id = 'addressPopup';
	mainDiv.className = 'addAddress';
	
	overlay = document.createElement('div');
	overlay.className = 'overlayBG';
	mainDiv.appendChild(overlay);
	
	
	iframeEmpty = document.createElement('IFRAME');
	iframeEmpty.className = 'shoppingBagFrameInvisible';
	iframeEmpty.frameBorder = 0;
	iframeEmpty.name = 'iEmpty';
	iframeEmpty.id = 'iShoppingEmpty';
    iframeEmpty.src = '';
				
	mainDiv.appendChild(iframeEmpty);
	
	opaque = document.createElement('div');
	opaque.className = 'opaqueBG';
	mainDiv.appendChild(opaque);

	closeX = document.createElement('input');
	closeX.id = 'windowClose';
	closeX.className = 'button buttonClose';
	closeX.type = 'submit';
	closeX.value = 'x';
	closeX.onclick = closeAddressPopup;
	opaque.appendChild(closeX);
	
	
				
	iframe = document.createElement('IFRAME');
	iframe.className = 'shoppingBagFrame';
	iframe.frameBorder = 0;
	iframe.name = 'iShopping';
	iframe.scrolling = 'yes';
	iframe.id = 'iShopping';
	iframe.src = url;
				
	opaque.appendChild(iframe);
	document.body.appendChild(mainDiv);		
	
	if(document.all&&(_ieversion<7))
	{
		mainDivIF = document.createElement('IFRAME');		
		mainDivIF.id = 'shopBagIF';
		mainDivIF.className = 'shoppingBagContainer';
		mainDivIF.style.display = 'block';	
		mainDivIF.style.border = "0";	
		mainDivIF.scrolling = "no";
		mainDivIF.frameborder = false;	
		
			
		 //<!--- TODO: write javascript function to get css for non included css. current hard coded--->
		mainDivIF.src = siteUrl + "presentationLayer/blank.html";
		mainDivIF.zIndex = parseInt(100000)-1;	
		mainDivIF.style.filter = "alpha(opacity=0)";
		mainDivIF.style.position = 'absolute';
		mainDivIF.style.top = '100px';
		mainDivIF.style.left = '50%';
		mainDivIF.style.padding = '30';
		mainDivIF.frameBorder = false;
		mainDivIF.style.width = parseInt(780);		
		mainDivIF.style.height = parseInt(400)+25;
		mainDivIF.style.width = parseInt(780)+11;
		document.body.appendChild(mainDivIF);		
		
	}			

}

function closeAllDialogs()
{
	j$( ".ui-dialog-content" ).each( function () {
		try {
			j$( this ).dialog( "close" );
		} catch (e) {}
	});
}





function openShoppingBag(totAmount,MinAmount,addtoUrl)
{
    
	if($('shopBag'))
	{
		document.body.removeChild($('shopBag'));
	}
	
	mainDiv = document.createElement('div');
	mainDiv.id = 'shopBag';
	mainDiv.className = 'shoppingBagContainer';
	
	overlay = document.createElement('div');
	overlay.className = 'overlayBG';
	mainDiv.appendChild(overlay);
	
	iframeEmpty = document.createElement('IFRAME');
	iframeEmpty.className = 'shoppingBagFrameInvisible';
	iframeEmpty.frameBorder = 0;
	iframeEmpty.name = 'iEmpty';
	iframeEmpty.id = 'iShoppingEmpty';
    iframeEmpty.src = '';
				
	mainDiv.appendChild(iframeEmpty);
	
	opaque = document.createElement('div');
	opaque.className = 'opaqueBG';
	mainDiv.appendChild(opaque);

	closeX = document.createElement('input');
	closeX.id = 'windowClose';
	closeX.className = 'button buttonClose';
	closeX.type = 'submit';
	closeX.value = 'x';
	closeX.onclick = closeShopBag;
	opaque.appendChild(closeX);

	minimumOrder = document.createElement('div');
	minimumOrder.id = 'minOrder';
	minimumOrder.className = 'minimumOrder';
	opaque.appendChild(minimumOrder);
	minimumOrder.innerHTML = '';	
				
	iframe = document.createElement('IFRAME');
	iframe.className = 'shoppingBagFrame';
	iframe.frameBorder = 0;
	iframe.name = 'iShopping';
	iframe.scrolling = 'yes';
	iframe.id = 'iShopping';
	iframe.src = '/sharedPages/frontEndComponents/specificComponents/b2c/shoppingCart/shoppingCartDetailsPopUp.cfm';
	//iframe.src = '/sharedPages/frontEndComponents/specificComponents/b2c/shoppingCart/shoppingCartDetails.cfm';			
	opaque.appendChild(iframe);
	
	document.body.appendChild(mainDiv);		
	
	if(document.all&&(_ieversion<7))
	{
		mainDivIF = document.createElement('IFRAME');		
		mainDivIF.id = 'shopBagIF';
		mainDivIF.className = 'shoppingBagContainer';
		mainDivIF.style.display = 'block';	
		mainDivIF.style.border = "0";	
		mainDivIF.scrolling = "no";
		mainDivIF.frameborder = false;	
		
			
		 //<!--- TODO: write javascript function to get css for non included css. current hard coded--->
		mainDivIF.src = siteUrl + "presentationLayer/blank.html";
		mainDivIF.zIndex = parseInt(100000)-1;	
		mainDivIF.style.filter = "alpha(opacity=0)";
		mainDivIF.style.position = 'absolute';
		mainDivIF.style.top = '100px';
		mainDivIF.style.left = '50%';
		mainDivIF.style.padding = '30';
		mainDivIF.frameBorder = false;
		mainDivIF.style.width = parseInt(780);		
		mainDivIF.style.height = parseInt(400)+25;
		mainDivIF.style.width = parseInt(780)+11;
		document.body.appendChild(mainDivIF);		
		
	}			
 
}




function openCoordinatesBag()
{
    
	if($('CoordinatesshopBag'))
	{
		document.body.removeChild($('CoordinatesshopBag'));
	}
	
	mainDiv = document.createElement('div');
	mainDiv.id = 'CoordinatesshopBag';
	mainDiv.className = 'shoppingBagContainer';
	
	overlay = document.createElement('div');
	overlay.className = 'overlayBG';
	mainDiv.appendChild(overlay);
	
	iframeEmpty = document.createElement('IFRAME');
	iframeEmpty.className = 'shoppingBagFrameInvisible';
	iframeEmpty.frameBorder = 0;
	iframeEmpty.name = 'iEmpty';
	iframeEmpty.id = 'iShoppingEmpty';
    iframeEmpty.src = '';
				
	mainDiv.appendChild(iframeEmpty);
	
	opaque = document.createElement('div');
	opaque.className = 'opaqueBG';
	mainDiv.appendChild(opaque);

	closeX = document.createElement('INPUT');
	closeX.id = 'windowClose';
	closeX.className = 'button buttonClose';
	closeX.type = 'submit';
	closeX.value = 'x';
	closeX.onclick = closeCoordinatesshopBag;
	opaque.appendChild(closeX);
	
	h2Header = document.createElement('h2');
	h2Header.innerHTML = translate.coordinatesTitle;
	opaque.appendChild(h2Header);	

	minimumOrder = document.createElement('div');
	minimumOrder.id = 'minOrder';
	minimumOrder.className = 'minimumOrder';
	opaque.appendChild(minimumOrder);
	minimumOrder.innerHTML = '';	
	
	orderSumBar = document.createElement('div');
	orderSumBar.id = 'orderSumBar';
	
	
	tab1 = document.createElement('div');
	tab1.className = 'prodTitle';
	tab1.innerHTML = translate.product;
	
	tab2 = document.createElement('div');
	tab2.className = 'brandTitle';
	tab2.innerHTML = translate.style;
	
	tab3 = document.createElement('div');
	tab3.className = 'colorTitle';
	tab3.innerHTML = translate.color;
	
	tab4 = document.createElement('div');
	tab4.className = 'priceTitle';
	tab4.innerHTML = translate.price;
	
	tab5 = document.createElement('div');
	tab5.className = 'qtyTitle';
	tab5.innerHTML = translate.qty;
	
					
	tab6 = document.createElement('div');
	tab6.className = 'removeTitle';
	tab6.innerHTML = '';
				
	orderSumBar.appendChild(tab1);
	orderSumBar.appendChild(tab2);
	orderSumBar.appendChild(tab3);
	orderSumBar.appendChild(tab4);
	orderSumBar.appendChild(tab5);
	orderSumBar.appendChild(tab6);
	opaque.appendChild(orderSumBar);
				
	iframe = document.createElement('IFRAME');
	iframe.className = 'shoppingBagFrame';
	iframe.frameBorder = 0;
	iframe.name = 'iShopping';
	iframe.id = 'iShopping';
	iframe.src = '/sharedPages/frontEndComponents/specificComponents/b2c/coordinates/coordinatesDetails.cfm';
				
	opaque.appendChild(iframe);
				
	buttonHolder = document.createElement('div');
	buttonHolder.className = 'buttonHolder';
				
	addtobag = document.createElement('BUTTON');
	addtobag.className = 'shoppingCartCheckoutGrey mainButton';
	addtobag.name = 'addToBag';
	addtobag.id = 'addToBag';
	addtobag.innerHTML = 'Add to my bag'+ ' &raquo;';
	addtobag.onclick = closeCoordinatesshopBag;
		
	
	
	buttonHolder.appendChild(addtobag);
	
	opaque.appendChild(buttonHolder);
	document.body.appendChild(mainDiv);				
 
}



function closeShopBag() {
	
	//Fix for Ie7
	hiddenInput = document.createElement('INPUT');
	hiddenInput.type = 'text';
	hiddenInput.id = 'ieFix_hiddenField';
	hiddenInput.style.position = 'absolute';
	hiddenInput.style.top = '-33330px';
	hiddenInput.style.left = '-33330px';
	document.body.appendChild(hiddenInput)
		
	document.body.removeChild($('shopBag'));
	$('ieFix_hiddenField').focus();
	
	if(document.all&&(_ieversion<7))
	{
		document.body.removeChild($('shopBagIF'));
	}
	
}

function closeAddressPopup() {
	
	//Fix for Ie7
	hiddenInput = document.createElement('INPUT');
	hiddenInput.type = 'text';
	hiddenInput.id = 'ieFix_hiddenField';
	hiddenInput.style.position = 'absolute';
	hiddenInput.style.top = '-33330px';
	hiddenInput.style.left = '-33330px';
	document.body.appendChild(hiddenInput)
		
	document.body.removeChild($('addressPopup'));
	$('ieFix_hiddenField').focus();
	
	if(document.all&&(_ieversion<7))
	{
		document.body.removeChild($('shopBagIF'));
	}
	
}


function closeCoordinatesshopBag() {
	

	//Fix for Ie7
	hiddenInput = document.createElement('INPUT');
	hiddenInput.type = 'text';
	hiddenInput.id = 'ieFix_hiddenField';
	hiddenInput.style.position = 'absolute';
	hiddenInput.style.top = '-33330px';
	hiddenInput.style.left = '-33330px';
	document.body.appendChild(hiddenInput)
		
	document.body.removeChild($('CoordinatesshopBag'));
	$('ieFix_hiddenField').focus();
	
	if(document.all&&(_ieversion<7) )
	{
		document.body.removeChild($('shopBagIF'));
	}
	
}



	




boxesToClose = new Array('searchBox','shoppingBagWindow','myAccountBox');

function showBoxAndSetPosition(e,id)
{   
  	for(x=0;x<boxesToClose.length;x++)
  	{
  		hideBox(boxesToClose[x]);
  	}
  	
  //	setLeft = (_isFOX)?e.offsetLeft:getLeftPos(e);
  	
  	//$(id).style.left = e.offsetLeft+'px';
  	
  //	widthAdjust = (_isFOX)?1:-3;
  //	leftAdjust = (_isFOX)?6:9;
  	
  //	$(id).style.left = (setLeft-leftAdjust)+'px';
  //	$(id).style.width = (e.offsetWidth-widthAdjust)+'px';
  	$(id).style.display = 'block';
  	
}

//Used for IE
function getLeftPos(e)
{
	z = 0;
  	myElement = e;
  	while(myElement.tagName != 'BODY')
  	{
  		z+=myElement.offsetLeft;
  		myElement = myElement.parentNode;
  	}
  	
  	return z;
}

function getTopPos(e)
{
	z = 0;
  	myElement = e;
  	while(myElement.tagName != 'BODY')
  	{
  		z+=myElement.offsetTop;
  		myElement = myElement.parentNode;
  	}
  	
  	return z;
}


function hideBox(id)
{   if($(id))
  		$(id).style.display = 'none';
}

var timer;

function ShowShopingCartPopUpDelay()
{

	if($('shoppingBagWindow').style.display != 'block' && j$( '#shoppingCartDetailsDiv' ).length == 0)
	{
		timer = setTimeout('ShowShopingCartPopUp()',300);
	}
}

function ShowShopingCartPopUpDelayGiggle()
{

	if($('shoppingBagWindow').style.display != 'block')
	{
		timer = setTimeout('ShowShopingCartPopUpGiggle()',300);
	}
}

function ShowShopingCartPopUpDelayMyron()
{

	if($('shoppingBagWindow').style.display != 'block')
	{
		timer = setTimeout('ShowShopingCartPopUpMyron()',300);
	}
}

function ShowShopingCartPopClearTimeout()
{
	clearTimeout(timer);
}



function ShowShopingCartPopUp()
{	
	DWREngine._execute(_cfCatLevelsLocation, null, 'getShoppingbagBoxInfo','',ShowShoppingBoxText);	
}

function refreshShoppingCartText(){
	DWREngine._execute(_cfCatLevelsLocation, null, 'getShoppingbagBoxInfo','',refreshShoppingCartTextResult);	
}

function refreshShoppingCartTextResult(result){		   
	showCountObj = $('ShoppingBagInfoLine');
	
	if( result[0].ITEMTEXT == "" ){
		result[0].ITEMTEXT = "ITEM";
	}
	
	showCountObj.innerHTML = '( ' + result[0].AMOUNT + ' ' + result[0].ITEMTEXT + ' )';
	if (result[0].AMOUNT != '0')
	{
		//Check if id=topShoppingCart Class Should be changed
		if(typeof changeCartClass != 'undefined')
		changecss(); // This function is located in topNavigation.cfm
		
		if($('ShippingBagLineItems'))
			$('ShippingBagLineItems').innerHTML = result[0].SHOPPINGBAGTEXT;
	}		
}

function ShowShopingCartPopUpGiggle()
{	
	DWREngine._execute(_cfCatLevelsLocation, null, 'getShoppingbagBoxInfo','',ShowShoppingBoxTextGiggle);	
}

function ShowShopingCartPopUpMyron()
{	
	DWREngine._execute(_cfCatLevelsLocation, null, 'getShoppingbagBoxInfoMyron','',ShowShoppingBoxTextMyron);	
}

function getWinWidth() {
	if (window.innerWidth) {
		return window.innerWidth;
		} 
	else if (document.body.clientWidth) {
		return document.body.clientWidth;
		} 
	else {
		return 100;
	}
}

function ShowShoppingBoxText(result)
{
	if( j$( '#shoppingCartDetailsDiv' ).length == 0 ){
	   boxesToClose = new Array('searchBox','shoppingBagWindow','myAccountBox');
	   for(x=0;x<boxesToClose.length;x++)
	 	{
	 		hideBox(boxesToClose[x]);
	 	}
	   
		showCountObj = $('ShoppingBagInfoLine');
		if( result[0].ITEMTEXT == "" ){
			if( result[0].AMOUNT <= 1 )
				result[0].ITEMTEXT = "ITEM";
			else
				result[0].ITEMTEXT = "ITEMS";	
		}
		showCountObj.innerHTML = '( ' + result[0].AMOUNT + ' ' + result[0].ITEMTEXT + ' )';
		
		if (result[0].AMOUNT != '0')
		{
			//Check if id=topShoppingCart Class Should be changed
			if(typeof changeCartClass != 'undefined')
			changecss(); // This function is located in topNavigation.cfm
			
			if($('ShippingBagLineItems'))
				$('ShippingBagLineItems').innerHTML = result[0].SHOPPINGBAGTEXT;
			
			if($('shoppingBagWindow'))
				$('shoppingBagWindow').style.display = 'block';
			//showBoxAndSetPosition(passE,passId);	
		}		
	
			leftVal = getWinWidth()/2;
	
			if($('shoppingBagWindow'))
				$('shoppingBagWindow').style.left = leftVal + "px";	
	}
}

function ShowShoppingBoxTextGiggle(result)
{
   boxesToClose = new Array('searchBox','shoppingBagWindow','myAccountBox');
   for(x=0;x<boxesToClose.length;x++)
 	{
 		hideBox(boxesToClose[x]);
 	}
   
	showCountObj = $('ShoppingBagInfoLine');
	
	
	showCountObj.innerHTML = result[0].AMOUNT + ' ' +result[0].ITEMTEXT;
	
	if (result[0].AMOUNT != '0')
	{
		if($('ShippingBagLineItems'))
			$('ShippingBagLineItems').innerHTML = result[0].SHOPPINGBAGTEXT;
		
		if($('shoppingBagWindow'))
			$('shoppingBagWindow').style.display = 'block';
		//showBoxAndSetPosition(passE,passId);	
		timer=setTimeout("CloseShoppingCartPopUp()", 5000);
	}		

	
		if($('shoppingBagWindow'))
			$('shoppingBagWindow').style.left = "700px";	
}

function ShowShoppingBoxTextMyron(result)
{
   boxesToClose = new Array('searchBox','shoppingBagWindow','myAccountBox');
   for(x=0;x<boxesToClose.length;x++)
 	{
 		hideBox(boxesToClose[x]);
 	}
   
	showCountObj = $('ShoppingBagInfoLine');
	showCountObj.innerHTML = result[0].AMOUNT + ' ' +result[0].ITEMTEXT;
	
	if (result[0].AMOUNT != '0')
	{
		$('ShippingBagLineItems').innerHTML = result[0].SHOPPINGBAGTEXT;
		$('topShoppingCart').className = 'active';
		$('shoppingBagWindow').style.display = 'block';
		//showBoxAndSetPosition(passE,passId);	
	}		

		//leftVal = getWinWidth()/2;

		//$('shoppingBagWindow').style.left = leftVal + "px";	
}


function changeClassName(theitem, NewclassName) {
  if((document.getElementById(theitem).className != NewclassName)) {
    document.getElementById(theitem).className = NewclassName;
  } else {
    document.getElementById(theitem).className = '';
  }
}

function toggleOneItem(theitem) {
  if((document.getElementById(theitem).style.display == 'block') || (document.getElementById(theitem).style.display == -1))
  	{
    document.getElementById(theitem).style.display = 'none';
    document.getElementById('invisibleFrame').style.display = 'none';
    }
  else
    document.getElementById(theitem).style.display = 'block';
}


function openWindow(theURL,w,h) {
  posx=(screen.availWidth-w)/2;
  posy=(screen.availHeight-h)/2;
  window.open(theURL,'popup','toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable=yes'+',width='+w+',height='+h+',left='+posx+',top='+posy);
}

function getPageScroll(){

	var yScroll, arrayPageScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll, pageHeight, pageWidth, arrayPageSize;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function findClassProperties(style,rule)
{
	styles = document.styleSheets;
	for(x=0;x<styles.length;x++)
	{
		href = styles[x].href;
	
		if(href.indexOf(window.location.hostname) >= 0 && href.indexOf(style))	
		{
			rules = (styles[x].rules)?styles[x].rules:styles[x].cssRules;
			
			for(zz=0;zz<rules.length;zz++)
			{
				temp1 = rules[zz];
				temp2 = rule;
					
				if(temp1.type!=3)
				{	
					if(temp1.selectorText.toUpperCase() == rule.toUpperCase())
					{
						return rules[zz];	
					}		
					
				}	
			}									
		}			
	}
}

_cssClass = "";

function showAlert(obj) {
			
	var url, message, targetAlert, cssClass, closeBText, hideCloseBtn, closeOtherDialogs;
	
	url = (obj.url === undefined)?'':obj.url;
	message = (obj.message === undefined)?'':obj.message;
	targetAlert = (obj.target === undefined)?'alertbox':obj.target;	
	cssClass = (obj.cssClass === undefined)?'alertbox':obj.cssClass;
	closeBText = (obj.closeBText === undefined)?'X':obj.closeBText;
	hideCloseBtn = (obj.hideCloseBtn === undefined)?false:obj.hideCloseBtn;
	closeOtherDialogs = (obj.closeOtherDialogs === undefined)?true:obj.closeOtherDialogs;
	
	var args = {
			MESSAGE: message
		,	URL: url
		,	CLOSEBUTTONTEXT: closeBText
		,	TEMPLATE: 1
		,	DIVID: targetAlert
		,	CSSCLASS: cssClass
		,	HIDECLOSEBTN: hideCloseBtn
		,	CLOSEOTHERDIALOGS: closeOtherDialogs
	};
	
	if ( message != "" ) {
		
		args.PARAMS = args;
		
		args.CONTENT = message;
		
		callText_Result( args );
				
	} else {
	
		j$.post(
				siteUrl + "/com/b2c/genericProxy.cfc?returnFormat=json&method=getText"
			,	args
			,	callText_Result
			,	"json"
		);

	}
	
}

function showPopUp(obj) {
			
	/* function emptied as unused, see rev. 106781 for previous code */
}




function callText_Result(result)
{

	try{
		result.CONTENT = decodeURIComponent( result.CONTENT );
	} catch(e) {}
	
	if ( result.CLOSEOTHERDIALOGS ) {
		j$( ".ui-dialog-content" ).each( function () {
			try {
				j$( this ).dialog( "close" );
			} catch (e) {}
		});
	}
	
	var jAlert = j$("<div id='" + result.PARAMS.DIVID + "' class='" + result.PARAMS.CSSCLASS + "'></div>").html( result.CONTENT ).appendTo( "body" ).hide();
	
	jAlert.dialog({
			width: jAlert.css( "width" )
		,	autoOpen: true
		,	modal: g_ShowModal
	});
	
	if ( result.PARAMS.HIDECLOSEBTN )
		jAlert.parent().find( ".ui-dialog-titlebar" ).hide();
	
	if(_callHasSpecialAction)
	{
		eval(_callHasSpecialAction);
		_callHasSpecialAction = null;
	}			
		
}

function killAlertBox(divID,divIF)
{

	if (!divID || divID == '')
	{
		document.body.removeChild(_objectMoving);
		if(document.all&&(_ieversion<7))
		{
				document.body.removeChild(_objectMovingIF);			
		}	
	}
	else
	{
		DivObj = document.getElementById(divID);
		document.body.removeChild(DivObj);
     
     		
		if(document.all&&(_ieversion<7))
		{
			DivIFObj = document.getElementById(divID+'IF');
			document.body.removeChild(DivIFObj);
		}
	

     }
							
}					

lineCount = 0;
lastDrop = 2;
normCount = 1;


function deleteClone(o,msg)
{

	AmountOfRows = document.getElementById("lineItemsHolder").getElementsByTagName('DIV');
	
	countRows = 0;
	//lineCount--;
	for(i=0;i<AmountOfRows.length;i++)
	{
		if(AmountOfRows[i].id.indexOf('lineItem_color_') >= 0)
		{
			countRows++;
		}
	}
	
	

	if (countRows > 1)
	{
		count = parseInt(o.id.split('_')[1]);
		TopParent = document.getElementById("lineItemsHolder"); 
		
		ColorChild = document.getElementById("lineItem_color_"+count); 
		SizeChild = document.getElementById("lineItem_size_"+count); 
		QtyChild = document.getElementById("lineItem_qty_"+count); 
		
		TopParent.removeChild(ColorChild);
		TopParent.removeChild(SizeChild);
		TopParent.removeChild(QtyChild);
	}
	else
	{
		showAlert({message:msg,closeBText:'x',cssClass:'alertboxSmall'});
	}
}

function cloneItemLine(o)
{
	count = parseInt(o.id.split('_')[1]);
	idCount = lastDrop + 1;
	lineCount++
	
	//Color	
	toClone = $('lineItem_color_'+count).cloneNode(true);
	toCloneInner = toClone.innerHTML;
	
	toCloneInner = 	setDropDownObjects(toCloneInner,'color-',count,idCount,lineCount);
	
	
	
	div1 = document.createElement('DIV');
	div1.id = 'lineItem_color_'+normCount;	
	div1.className = 'selectBlock'; 
	div1.innerHTML = toCloneInner;
	
	
	$('lineItemsHolder').appendChild(div1);

	//_listMenus.addMember('menuWrap_'+idCount);
			
	//_listMenus.assignEvent("dropDownColorActions('colorId-"+lineCount+"');",idCount);
	
	//menuColorWrapId = idCount;
	
	//Size
	toClone = $('lineItem_size_'+count).cloneNode(true);
	toCloneInner = toClone.innerHTML;
	idCount = parseInt(idCount)+1;
	
	
	toCloneInner = 	setDropDownObjects(toCloneInner,'SizeSelectBox-',count,idCount,lineCount);
	
	div2 = document.createElement('DIV');
	div2.id = 'lineItem_size_'+normCount;
	div2.className = 'selectBlock'; 
	div2.innerHTML = toCloneInner;
	$('lineItemsHolder').appendChild(div2);

	//_listMenus.addMember('menuWrap_'+idCount);
	
	//Qty
	toClone = $('lineItem_qty_'+count).cloneNode(true);
	toCloneInner = toClone.innerHTML;
	
	idCount = parseInt(idCount)+1;
	
	toCloneInner = 	setDropDownObjects(toCloneInner,'itemQuantity-',count,idCount,lineCount);
	
	
	addImg = 'add_' + count;
	addImgNew = 'add_' + normCount;
	toCloneInner = toCloneInner.replace(addImg,addImgNew);
	
	minusImg = 'minus_' + count;
	minusImgNew = 'minus_' + normCount;
	toCloneInner = toCloneInner.replace(minusImg,minusImgNew);
	
	div3 = document.createElement('DIV');
	div3.id = 'lineItem_qty_'+normCount;
	div3.className = 'selectBlock'; 
	div3.innerHTML = toCloneInner;
	
	$('lineItemsHolder').appendChild(div3);
	//_listMenus.addMember('menuWrap_'+idCount);
	
	//_affect = 'SizeSelectBox-'+lineCount;
	//_resultKeys = new Array('SKU_ID','SIZE_DESC');
	//_res = new Array();
	//dropDownSetRelation(_res);
	
	//setCurrentMenu($('menuSelect_'+menuColorWrapId));
	//selectMenu($('colorId-'+lineCount+'_0'))
	
	normCount++;
	lastDrop +=3;
	
	 
}

function setDropDownObjects(str,valObj,c,idc,seq){
	
	//str = str.replace('menuWrap_'+c,'menuWrap_'+idc);
	//str = str.replace('menuSelect_'+c,'menuSelect_'+idc);
	//str = str.replace('menuHeader_'+c,'menuHeader_'+idc);
	//str = str.replace('menuArrow_'+c,'menuArrow_'+idc);
	//str = str.replace('color-'+c,'color-'+idc);
	//str = str.replace('add_'+c,'add_'+idc);
	
	RXstr = valObj+count;
	str = str.replace(eval('/'+RXstr+'/g'),valObj+seq);
	
	str = str.replace(/_listMenus./g,'//_listMenus.');
	
	return str;
}

_itemId = '';

bypassZoom = false;




// Color and size drop down relation 
//onRadioColorClick
function dropDownColorActions(img_value)
{
	//alert(tempId);
	//alert(img_value);
	img_value = img_value.split('|');
	img_ColorID	= img_value[0];
	img_price	= img_value[1];
	img_priceOnSale = img_value[2];
	if(img_value[4]) img_memberprice = img_value[4];
	if(img_value!='' && img_value[8]){
		lineNumber = img_value[8].split('-')[1];
	}else{
		lineNumber = '';
	}
	if(img_value[5]) convertPrice=img_value[5];
	if(img_value[6]) convertPriceONSale=img_value[6];
	if(img_value[7]) convertPriceMember=img_value[7];
	
	if(img_value!='')
	{
		//alert(translate.ourprice);
		priceDescription = ''
		convertDescription = ''
		priceDescription = img_price;
		if(img_priceOnSale != ''){
			priceDescription = priceDescription + ' |' + img_priceOnSale;
		}
		if(img_value[5]) convertDescription=convertDescription+'( '+convertPrice;
		if(img_value[6]) convertDescription=convertDescription+' | '+convertPriceONSale;
		if(img_value[7]) convertDescription=convertDescription+' | '+convertPriceMember;
		if(img_value[5]) convertDescription=convertDescription+' )';
		
		if($("isNewInd"))
		{
			if($("isNewInd").value == 'Y')
				priceDescription = priceDescription + ' | ' + translate.newLabel;
		}
		
		
		if($("productPrice"))
		{
			$("productPrice").innerHTML =img_price;
		}
		
		if($("productPriceonsale"))
		{
			if(img_priceOnSale != ''){
				$("productPriceonsale").innerHTML =' | <span class="productTextOnSale">' + translate.onSale + '</span>' +img_priceOnSale;
				//$("productPriceonsale").innerHTML = ' | ' + img_priceOnSale; // OSH Version NO Pipe
			} else {
				$("productPriceonsale").innerHTML = '';
			}	
		}
		
		if($("Price") && priceDescription)
		{
			$("Price").innerHTML =priceDescription;
		}
		
		if($("memberPrice") && img_memberprice)
		{
			$("memberPrice").innerHTML =img_memberprice;
		}
		
		if($("convertPrice") && convertDescription)
		{
			$("convertPrice").innerHTML =convertDescription;
		}		
		
		bypassImageZoomer = false;
		bypassImageZoomer =	bypassZoom;
		bypassZoom = false;
		if(_itemId=='')
		{
			_itemId = img_value[3];
			bypassImageZoomer = true;
		}	

		if($("lineColorSelected"))
		{
			$("lineColorSelected").value =lineNumber;
		}
		v = _itemId + "|" + img_ColorID;
		
		getSizesDetails(v);
		//getDimensionsDetails(img_ColorID,_itemId);
	
	    if(!bypassImageZoomer)
	    {
			setImageZoomer();	
		}	
		else
		{
			setImageForNoFlash();
		}
	}	
}


function dropDownColorFromQuickView(idx)
{
	img_value	= $(idx).value;

	img_value = img_value.split('|');
	img_ColorID	= img_value[0];
	img_price	= img_value[1];
	
	if(img_value[8]) convertPrice=img_value[8];
	if(img_value[9]) convertPriceONSale=img_value[9];
	if(img_value[10]) convertPriceMember=img_value[10];
	
	if($(idx).value != '' && $(idx).value != '0')
	{
		relationId = $(idx).id.split('-')[1];
		
		
		if(img_value[2]!='' && img_value[2] != '0.00')
		 {
		  img_priceOnSale	= '| <span class="sale">$'+img_value[2]+' '+ $('SaleText').value  +'</span>';
		 }
		 else
		 {
		 	img_priceOnSale	= '';
		 }
		 
		 if($("newproduct").value == 'Y' && img_priceOnSale == '')
		 {
		 	if($('actualCurLang').value == 'fre')
		 		isNew = '| NOUVEAU';
		 	else
				isNew = '| NEW';
		 }
		 else
		 {
		 	isNew = '';
		 }
		
		
		if($("ItemPriceValueID"))
		{
			$("ItemPriceValueID").innerHTML = '$'+ img_price +' '+img_priceOnSale + ' ' + isNew;
			if(img_value[7]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+'<br>'+img_value[7];
			
			
			
			if(img_value[8]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+'<br> ( '+convertPrice;
			if(img_value[9]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+' | '+convertPriceONSale;
			if(img_value[10]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+' | '+convertPriceMember;
			if(img_value[8]) $("ItemPriceValueID").innerHTML=$("ItemPriceValueID").innerHTML+' ) ';
		}
		
		_itemId = $('itemID').value;	
		
		getSizesQuickView(img_ColorID,_itemId);
		
	}
	else
	{

		$('colorId-0').value = '';
		
	}	
	
}


 function getSizesQuickView(colorId,itemId)
{
	DWREngine._execute(_cfCatLevelsLocation, null, 'getSizesByColorItem',itemId,colorId,updateSelectQuickView_result);
}


function updateSelectQuickView_result(result)
{
	_resultKeys = new Array('SKU_ID','SIZE_DESC');	
	dropDownSetRelation(result);
	setColorIMageQuickView();
}

function dropDownColorFromList(idx)
{
	img_name 	= $(idx).name;
	img_value	= $(idx).value;

	img_name = img_name.split('_');
	img_rowID = img_name[1];
	img_value = img_value.split('|');
	img_ColorID	= img_value[0];
	img_price	= img_value[1];
	
	
	if(img_value[8]) convertPrice=img_value[8];
	if(img_value[9]) convertPriceONSale=img_value[9];
	if(img_value[10]) convertPriceMember=img_value[10];
	
	if($(idx).value != '' && $(idx).value != '0')
	{
		relationId = $(idx).id.split('-')[1];
		j$("#tdPrice_" + img_rowID).html(img_price);
		
		_itemId = $('itemID_' + img_rowID).value;	
		getSizesFromList(img_ColorID,_itemId,img_rowID);
		
	}
	else
	{

		$(img_name).value = '';
		
	}	

}

 function getSizesFromList(colorId,itemId,rowId)
{
	DWREngine._execute(_cfCatLevelsLocation, null, 'getSizesByColorItemRow',itemId,colorId,rowId,updateSelectFromList_result);
}

function updateSelectFromList_result(result)
{
	var rowId = result[0].ROW_ID;
	var sb = $("SizeSelectBox_" + rowId);
	
	if ( sb.options.length == 0 || sb.options[ 0 ].value != "" )
		initialLength = 0;
	else
		initialLength = 1;
	
	// Clear the current drop down box value
	$("SizeSelectBox_" + rowId).options.length = initialLength;
    // alert(result);
	// Build drop down box here.
	for ( i=0; i < result.length; i++ )
	{
		addToSizeDropDown = true;

		if (result[i].INSTOCK == 'false')
		{
			sizeTEXT = result[i].SIZE_DESC + ' (Out of Stock)';
			addToSizeDropDown = false;
		}
		else
		{
			sizeTEXT = result[i].SIZE_DESC;
		}



		if(addToSizeDropDown)
		{
				optObj = new Option(sizeTEXT, result[i].SKU_ID, false);
				// Append the new option...
				sb.options[i+initialLength] = optObj;

				if(result.length == 1)
				{
					tempText = sb.options[initialLength].text;
					j$('#singleSize_' + rowId).html(tempText);
					if (tempText.indexOf('Out of Stock') < 0)
						sb.selectedIndex = initialLength;

					if($('singleSize_' + rowId))
					{
						sb.style.display = 'none';
						$('singleSize_' + rowId).style.display = 'block';
					}
				}
				else
				{
					if($('singleSize_' + rowId))
					{
						if(sb.style.display == 'none')
						{
							sb.style.display = 'block';
							$('singleSize_' + rowId).style.display = 'none';
						}
						
					}
				}
				
				if(result[i].PRICE){
				sb.options[i+initialLength].id = result[i].PRICE + '~' + result[i].TEMPSALEPRICE;
				}else {
				sb.options[i+initialLength].id = '';	
				}

		}
		



	}
}


function setColorIMageQuickView(){	

	if (img_value[5] == '')
	{
		$('productImageQV').src = '/static/webUpload/730/noImg_3.jpg';
	}
	else
	{
 		$('productImageQV').src = '/_static/webUpload/731/'+img_value[5];
	}
}

function FocusNextField(CurrentFieldname, NextFieldName, ActivateLength)
{
	currentField = document.getElementById(CurrentFieldname);
	nextField = document.getElementById(NextFieldName);
	
	if(currentField){
		if(currentField.value.length == ActivateLength){	
			if(nextField){		
				nextField.focus();
			}	
		}	
	}
}

function changeLanguageUrlRewrite(lang)
{
	urlPath = window.location.href;
 	urlPath = urlPath.toString();
 	
 	
 	if (lang == 'eng')
 	{
 		if(urlPath.indexOf('/eng/') > -1)
	 		urlPath = urlPath.replace('/eng/','/fre/');
	 	else
	 	{
	 		if(urlPath.indexOf('lang=eng') > -1)
	 			urlPath = urlPath.replace('lang=eng','lang=fre');
	 		else
	 		{
	 			if(urlPath.indexOf('?') > -1)
	 				urlPath = urlPath + '&lang=fre';
	 			else
	 				urlPath = urlPath + '?lang=fre';
	 		}
	 			
	 	}
	 }
	else
	{
		if(urlPath.indexOf('/fre/') > -1)
			urlPath = urlPath.replace('/fre/','/eng/');	
		else
	 	{
	 		if(urlPath.indexOf('lang=fre') > -1)
	 			urlPath = urlPath.replace('lang=fre','lang=eng');
	 		else
	 		{
	 			if(urlPath.indexOf('?') > -1)
	 				urlPath = urlPath + '&lang=eng';
	 			else
	 				urlPath = urlPath + '?lang=eng';
	 		}
	 	}
	}
		
	window.location.href = urlPath;
}


function showQuickView(o,direct)
{

	img = o.getElementsByTagName('IMG');
	divId = o.id.split('_')[1];
	imgExists = (img.length > 0)?true:false;
	
	divClassName = $('d_'+divId).className;
	if (_isFOX) {
		setLeft = (_isFOX)?o.offsetLeft:getLeftPos(o);
		setTop = (_isFOX)?o.offsetTop:getTopPos(o);
	} else {
		setLeft = (_isSafari)?o.offsetLeft:getLeftPos(o);
		setTop = (_isSafari)?o.offsetTop:getTopPos(o);
	}
	
	
	if(direct.toUpperCase()=='SHOW')
	{
		if(imgExists){img[0].className = 'opaque';}
		
		/*IMG_WIDTH = img[0].width;
		IMG_HEIGHT = img[0].height;
		//170
		//debug($('q_'+divId))
		
		BTN_WIDTH = $('q_dummy').width;
		BTN_HEIGHT = $('q_dummy').height;
		
		
		adjustLeft = Math.ceil((IMG_WIDTH/2)-(BTN_WIDTH/2));
		adjustTop = Math.ceil((IMG_WIDTH/2));
		
		
		$('d_'+divId).style.left = (setLeft+adjustLeft)+'px';
		$('d_'+divId).style.top = (setTop+adjustTop)+'px';*/
		$('d_'+divId).className = divClassName.replace('displayNone','displayBlock');
	}
	else
	{
		if(imgExists){img[0].className = '';}
		$('d_'+divId).className = divClassName.replace('displayBlock','displayNone');
	}
}


  	
  	/*
  	
  	widthAdjust = (_isFOX)?1:-3;
  	leftAdjust = (_isFOX)?6:9;
  	
  	$(id).style.left = (setLeft-leftAdjust)+'px';
  	$(id).style.width = (e.offsetWidth-widthAdjust)+'px';
  	$(id).style.display = 'block';

*/
	
	function showreturnPolicy(url)
	{
		showAlert({url:url,target:'returnsAlertBOX',cssClass:'alertboxCVC'});
	}
	
		function ThousandSeparator(decimalDigits,Value)
		{
		     // Separator Length. Here this is thousand separator
		     var separatorLength = 3;
		     var OriginalValue=Value;
		     var TempValue = "" + OriginalValue;
		     var NewValue = "";
		
		      // Store digits after decimal
		      var pStr;
		
		      // store digits before decimal
		      var dStr;
		
		      // Add decimal point if it is not there
		      if (TempValue.indexOf(".")==-1)
		     {
		           TempValue+="."
		     }
		
		    dStr=TempValue.substr(0,TempValue.indexOf("."));
		
		    pStr=TempValue.substr(TempValue.indexOf("."))
		
		    // Add 0 for remaining digits after decimal point
		    while (pStr.length-1< decimalDigits){pStr+="0"}
		
		    if(pStr ==".")
		            pStr =""; 
		   
		   if(dStr.length > separatorLength)
		  {
		        // Logic of separation
		       while( dStr.length > separatorLength)
		      {
		              NewValue = "," + dStr.substr(dStr.length - separatorLength) + NewValue;
		             dStr = dStr.substr(0,dStr.length - separatorLength);
		       }
		       NewValue = dStr + NewValue;
		   }
		   else
		  {
		       NewValue = dStr;
		   }
		   // Add decimal part
		   NewValue = NewValue + pStr;
			
			return NewValue;
		  } 
		  
function setQASCountry(cID){
	
	var country='CAN';
	if ($(cID).value=='US')
		country='USA';
	if ($(cID).value=='UK')	
		country='GBR';
		
	if($('COUNTRYSET'))	
		$('COUNTRYSET').value =country;
		//alert($('COUNTRYSET').value);
} 		  


function changeCountryProvice(cID){
	
	if (cID != null)
		countryId = $(cID).value;
	else
		countryId = $('countryID').value;
	
	DWREngine._execute(_cfCatLevelsLocation, null, 'callGetStates',countryId,'#variables.actualLang#',changeCountryProvice_result);

	if (cID != null)
		countryIdVar=cID;
    else
		countryIdVar='countryID';
}
function reloadPage(obj){
if(! eval(obj.options[obj.selectedIndex].value))
window.location.reload();
}

function updateNumberChildrenDropDownList(){
var childNumber = eval(document.getElementById('allChildrens').getElementsByTagName('div').length +1);
document.getElementById('Children').options[childNumber].selected = true;
if (childNumber < 11)document.getElementById('plusButton').style.display = 'block';
document.getElementById('numberChildren').value=childNumber-1;
}

function addBlocChildren(){
var allChildrens = document.getElementById('allChildrens');
var childNumber = eval(allChildrens.getElementsByTagName('div').length +1);

document.getElementById('numberChildren').value=childNumber;
if (childNumber < 11) {
var modelChild = document.getElementById('allChildrens').getElementsByTagName('div')[0].innerHTML;
var newChild = document.createElement('div');
modelChild = modelChild.replace(/child_name_1/gi,'child_name_'+childNumber);
modelChild = modelChild.replace(/blocChild_1/gi,'blocChild_'+childNumber);

modelChild = modelChild.replace(/BirthYearChild_1/gi,'BirthYearChild_'+childNumber);
modelChild = modelChild.replace(/BirthMonthChild_1/gi,'BirthMonthChild_'+childNumber);
modelChild = modelChild.replace(/BirthDayChild_1/gi,'BirthDayChild_'+childNumber);
modelChild = modelChild.replace(/genderChild_1/gi,'genderChild_'+childNumber);
modelChild = modelChild.replace(/child 1/gi,'Child '+childNumber);
modelChild = modelChild.replace(/updateInd_1/gi,'updateInd_'+childNumber);
modelChild = modelChild.replace(/user_child_id_1/gi,'user_child_id_'+childNumber);
modelChild = modelChild.replace(/selected/gi,'');
newChild.innerHTML = modelChild;
allChildrens.appendChild(newChild);
document.getElementById('updateInd_'+childNumber).value='i';
document.getElementById('child_name_'+childNumber).value='';
document.getElementById('Children').options[childNumber+1].selected = true;

document.getElementById('plusButton').style.display = 'none';


}
}

function changeCountryProvice_result(result){
  
  if(result.length==0){
  	 $('shprovince').options.length = 0;
     $('shprovince').options[1]=new Option('Other/Autre','OO');
  } else{
  	 $('shprovince').options.length = 1;
    for (i=0; i<result.length; i++) {

		$('shprovince').options[i+1] = new Option(result[i].NAME,result[i].STATE_ID);
	}
  }
  
  if($('COUNTRYSET')!= null)
	  setQASCountry(countryIdVar);

}

function updateStateOptions ( obj, field ) {
	
	var data = {
			method: "getStates"
		,	countryID: j$( obj ).val()
		,	stateDD: field
	};
	
	j$.post(
			siteUrl + "com/b2c/genericproxy.cfc?returnformat=json"
		,	data
		,	updateStateOptions_result
		,	"json"
	);
}

function updateStateOptions_result ( r ) {
	
	var jStateDD = j$( "#" + r.STATEDD );
	var state;
	
	if ( jStateDD.length == 0 )
		return false;
	
	jStateDD.find( "option[value!='']" ).remove();
	
	for ( var i=0; i<r.ASTATES.length; i++ ) {
		
		state = r.ASTATES[ i ];
		
		jStateDD.append( "<option value='" + state.STATE_ID + "'>" + state.NAME + "</option>" );
		
	}
	
	jStateDD.each( function () {
		this.options.selectedIndex = 0;
	});
	
}

		  
	function CurrencyFormatted(amount)
	{
		var i = parseFloat(amount);
		if(isNaN(i)) { i = 0.00; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		i = parseInt((i + .005) * 100);
		i = i / 100;
		s = new String(i);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
		s = minus + s;
		return s;
	}
	
	function CurrencyFormattedComma(amount)
	{
		amount = String(amount);
		
		var delimiter = ","; // replace comma if desired
		var a = amount.split('.',2)
		var d = a[1];
		var i = parseInt(a[0]);
		if(isNaN(i)) { return ''; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		var n = new String(i);
		var a = [];
		while(n.length > 3)
		{
			var nn = n.substr(n.length-3);
			a.unshift(nn);
			n = n.substr(0,n.length-3);
		}
		if(n.length > 0) { a.unshift(n); }
		n = a.join(delimiter);
		if(d.length < 1) { amount = n; }
		else { amount = n + '.' + d; }
		amount = minus + amount;
		return amount;
	}		  

function enforceReadonlyDropDowns ( filter ) {

	/* make sure readonly dropdowns can't be modified */
	if ( filter )
		var jDropdowns = filter.find( "select[ readonly ]" );
	else
		var jDropdowns = j$( "select[ readonly ]" );
	
	jDropdowns.each( function () {
		j$( this ).data( "previousValue", j$( this ).val() );
		j$( this ).data( "onchange", j$( this ).attr( "onchange" ) );
		j$( this ).removeAttr( "onchange" );
		j$( this ).unbind( "change" );
	});
	
	jDropdowns.change( function () {
		j$( this ).val( j$( this ).data( "previousValue" ) );
	});
	
};

function resetReadonlyDropdowns ( filter ) {
	
	/* reset readonly dropdowns to their initial state */
	if ( filter )
		var jDropdowns = filter.find( "select[ readonly ]" );
	else
		var jDropdowns = j$( "select[ readonly ]" );
	
	jDropdowns.unbind( "change" );
	
	jDropdowns.each( function () {
		j$( this ).change( j$( this ).data( "onchange" ) );
	});
	
};

//use this function to replace any element with a processing image, and return it to it's previous state (through the use of the action parameter
function toggleButtonInProgress ( buttonID, action ) {
	
	var jButton = j$( "#" + buttonID );
	
	if ( jButton.length ) {
	
		switch ( action ) {
		
			case "hide":
				
				var data = {
						original: jButton.html()
					,	width: jButton.css( "width" )
					,	height: jButton.css( "height" )
					,	background: jButton.css( "background" )
				};
				
				jButton.data( "toggleButton", data ).css({
						width: jButton.width()
					,	height: jButton.height()
					,	background: "url(" + g_imageInProgress + ") no-repeat center center"
				}).empty();
				
				break;
			
			case "show":
				
				var data = jButton.data( "toggleButton" );
				
				jButton.css({
						width: data.width
					,	height: data.height
					,	background: data.background
				}).html( data.original );
				
				break;
				
		}
		
	}
	
}

function addToRegistry() {

	var skuID = j$( "#giftRegistrySKU_ID" ).val();
	var quantity = j$( "#giftRegistryQuantity" ).val();

	if ( quantity == "" )
		quantity = 1;
	
	if ( skuID == "" )
		showAlert({ message: msg_addToRegistrySelectColorSize });
	else {
		
		var data = {
				method: "addSKUToRegistry"
			,	returnFormat: "json"
			,	skuID: skuID
			,	quantity: quantity
		};
		
		j$.post(
				siteUrl + "/com/b2c/shoppingcart-proxy.cfc"
			,	data
			,	function ( r ) {
					if ( r.SUCCESS ) {
						refreshRegistryToolbar( r.TOOLBARINFO );
						showAlert({ message: msg_skuAddedToRegistry_success });
					} else
						showAlert({ message: msg_skuAddedToRegistry_error });
				}
			,	"json"	
		);
		
	}
	
}

function refreshRegistryToolbar ( toolbarInfo ) {
	
	// if the toolbarInfo isn't passed in, we need to go get it
	if ( toolbarInfo === undefined ) {
		
		j$.post(
			siteUrl + "/com/b2c/shoppingcart-proxy.cfc"
			,	"method=getRegistrySummary&returnformat=json"
			,	refreshRegistryToolbar
			,	"json"	
		);
		
	}
	
	if ( toolbarInfo.REGISTRY_ID == "" ) {
		j$( "#registryToolbarLastItemEmpty" ).show();
		j$( "#registryToolbarLastItemFull" ).hide();
	} else {
		
		j$( "#registryToolbarQtyRequested" ).html( toolbarInfo.QTY_REQUESTED );
		j$( "#registryToolbarQtyOrdered" ).html( toolbarInfo.QTY_ORDERED );

		j$( "#registryToolbarLastItemDescription" ).html( toolbarInfo.LASTITEMDETAILS.DESCRIPTION );
		j$( "#registryToolbarLastItemPrice" ).html( toolbarInfo.LASTITEMDETAILS.PERMANENT_PRICE );
		j$( "#registrySummaryLastItemQuantity" ).html( toolbarInfo.LAST_QTY_REQUESTED );
		
		var jImage = j$( "#registryToolbarLastItemImage" );
		
		var src = jImage.attr( "src" ).match( /^(.+?)[^/]*$/i )[1];
		
		
		jImage.attr( "alt", toolbarInfo.LASTITEMDETAILS.DESCRIPTION ).attr( "src", src + toolbarInfo.LASTITEMDETAILS.IMAGE_2 );
		
		if ( toolbarInfo.LASTITEMDETAILS.COLOR != "" ) {
			j$( "#registryToolbarLastItemColor" ).html( toolbarInfo.LASTITEMDETAILS.COLOR ).parent().show();
		} else
			j$( "#registryToolbarLastItemColor" ).parent().hide();

		if ( toolbarInfo.LASTITEMDETAILS.DIMENSION != "" ) {
			j$( "#registryToolbarLastItemDimension" ).html( toolbarInfo.LASTITEMDETAILS.DIMENSION ).parent().show();
		} else
			j$( "#registryToolbarLastItemDimension" ).parent().hide();

		if ( toolbarInfo.LASTITEMDETAILS.SIZE != "" ) {
			j$( "#registryToolbarLastItemSize" ).html( toolbarInfo.LASTITEMDETAILS.SIZE ).parent().show();
		} else
			j$( "#registryToolbarLastItemSize" ).parent().hide();
		
		j$( "#registryToolbarLastItemEmpty" ).hide();
		j$( "#registryToolbarLastItemFull" ).show();
	}
	
}

function __IsValidEmailMask(email)
{

	filter = /^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$/

		if (filter.test(email))
		{
			return true;
		}
		else
		{
			return false;
		}
}

function isValidPhoneMask(phone){
	filter = /^\(?(\d{3})\)?[-| ]?(\d{3})[-| ]?(\d{4})$/
	return filter.test(phone);
}

function trackFromRefererTag(refererTag,url)
	{
		DWREngine._execute(_cfCatLevelsLocation, null, 'trackFromRefererTag',refererTag,url,trackFromRefererTag_result);
	}
	
	function trackFromRefererTag_result(result)
	{
		document.location.href = result;
	}
	
		  		
function init()
{
	DWREngine._errorHandler =  errorHandler;
}

function CloseShopingCartPopUpDelay(time)
{
	if(!time){
		time = 2000;
	}	
	timer = setTimeout('CloseShoppingCartPopUp()',time);
}


function startScroll(direction) 
{
	runwayScrolling = true; 
	scrollRunway(direction); 
}

function scrollRunway(direction)
{
	if(runwayScrolling)
	{
		document.getElementById('runwaySpace').scrollLeft+= direction;
		setTimeout("scrollRunway(" + direction + ")",1);
	}
}

function stopScroll() 
{ 
	runwayScrolling = false; 
}


function formatCurrency(amount) {
	
	var i = parseFloat(amount);
	
	if(isNaN(i)) { i = 0.00; }
	
	var minus = '';
	
	if(i < 0) { minus = '-'; }
	
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	
	if(s.indexOf('.') < 0) { s += '.00'; }
	
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	
	s = minus + '$' + s;
	
	return s;

}





function submitNewsletterSignup(myUrl, formId) 
{
	$(formId).action = myUrl;
	$(formId).submit();
}



function CheckNewsLetterUserExists(actionUrl, emailId, emailInvalidMessage, aEmailAlreadyMessage, aLoginLink, aFormId)
{
	var UserEmail = j$('#' + emailId).val().trim();
	if(__IsValidEmailMask(UserEmail))
	{
		var args = {method:'CheckUserInscDetails',email:UserEmail, actionUrl:actionUrl, emailAlreadyMessage:aEmailAlreadyMessage, loginLink:aLoginLink, formId: aFormId};
		j$.ajax({
		              url: siteUrl + "com/b2c/newsletter.cfc?returnformat=json"
		       ,      data: args
		       ,      success: CheckNewsLetterUserExists_Result
		       ,      dataType: "json"
		       ,      TYPE: "GET"
		});
	} 
	else
	{
		showAlert({message:emailInvalidMessage,cssClass:'fieldEmpty'});
	}     
  }
 
	  
function CheckNewsLetterUserExists_Result(r)
{    
	if (r.EXISTS && r.HASACCOUNT)
	{//User Has Account
		LoginLink = r.LOGINLINK;
		
		window.location.href = LoginLink;
		return false;
	}
	else if(!r.EXISTS)
	{//User does Not Exist
		submitNewsletterSignup(r.ACTIONURL, r.FORMID);
	}
	else
	{//Exists but does not have an account.
		var RegistMsg = r.EMAILALREADYMESSAGE;
		showAlert({message:RegistMsg,cssClass:'fieldEmpty'});
		return false;
	}//if Exists Ends
}




init();
