var reviews = 0,page = getCurrentPage(),ie6 = false,resx,upsObj;
if(Prototype.Browser.IE && !(document.documentElement && typeof document.documentElement.style.maxHeight!="undefined")){
		ie6=true;
}
/*********************************
* Function Name:handleSuccess
* purpose:to handle the ajax response from swatchChange()
* @param1: o - response object from ajax request
* @param2: argument - array of params that get into swatchChange and review info
* returns: null
*********************************/
function handleSuccess(o, argument) {
  activeLink="about";
  var argString = argument;
  if(Windows.focusedWindow && Windows.focusedWindow.id == "quickWin"){
  	Windows.focusedWindow.getContent().update(o.responseText);
  	document.getElementById('BVdt').innerHTML = argString[1];
		document.getElementById('hideBV').innerHTML = argString[2];
  	
  }else{
		var detailContent = document.getElementById('detaildata');
		detailContent.innerHTML = o.responseText;
		document.getElementById('BVdt').innerHTML = argString[1];
		document.getElementById('hideBV').innerHTML = argString[2];
  }
  if($('BVFrame')){
		reviewLoad(argString[0].substr(0,5));
	}
}
function preswChange(itemForm,spec){
	var item = itemForm.parentId.value;
	item = item.toString().substr(0,5);
	itemForm.elements['color_desc_'+item].value = spec;
	swatchChange(itemForm);
}
/*********************************
* Function Name:swatchChange
* purpose: to change swatches and sizes using Ajax on the quickView and detail pages
* @param1: item - baseId
* @param2: size - size of item
* @param3: spec - the color of item
* @param4: qty - quantity ordered
* @param5: personalizedId - sku of personalization
* @param6: customText - personalized text
* @param7: cartId - the id of the lineItem in shoppingCartTemp
* returns: null
*********************************/
//function swatchChange(item,size,spec,qty,personalizeId,customText,cartId){
function swatchChange(itemForm){
	var summaryHTML="",reviewsHTML="",sendUrl=loadUpPars(itemForm),
	name = itemForm.name.toString().substring(4),item = itemForm.sizecat_desc.value,
	bvFrame;

	if($('BVFrame')){
		bvFrame = $('BVFrame');
		bvFrame.src = "";
		summaryHTML = document.getElementById('BVdt').innerHTML;
		reviewsHTML = document.getElementById('hideBV').innerHTML;
	}

	sendUrl+="&name="+name;
	argument=[item,summaryHTML,reviewsHTML];
	URL = '/ajax/detailData.php';
	ajax = new Ajax.Request(URL,{method: 'POST', parameters: sendUrl,onComplete:function(t) { handleSuccess(t,argument);}}); // handleSuccess at top
}
/*********************************
* Function Name:revewLoad
* purpose: to inject reviews into quickView and Detail Pages
* @param1: item - baseId
* returns: null
*********************************/
function reviewLoad(item){
	var bvStaging="";
  if(window.location.host == "www.softsurroundings.com"){
	 bvStaging = "";
	}else{ bvStaging = "bvstaging/";}
	var bvFrame = $('BVFrame');
	bvFrame.src = "http://reviews.softsurroundings.com/"+bvStaging+"4398/"+item+"/reviews.htm?format=embedded"; //iframe from bazaarVoice, does all heavy lifting
	if(reviews > 0 ){  //displays link at top of quickView and detail page if there are reveiws
		if($('reviewsLink')){
			$('reviewsLink').style.display = 'inline';
		}
	}
}
/*********************************
* Function Name:QuickSellItemChange
* purpose: to change swatches and sizes using Ajax on the upsells and bedding ensembles pages
* @param1: item - baseId
* @param2: size - size of item
* @param3: spec - color of item
* @param4: qty - quantity ordered
* @param5: divId - upsell or bedding ensemble
* @param6: personalizedId - sku of personalization
* @param7: customText - personalized text
* returns: null
*********************************/
function QuickSellItemChange(item){
	//,size,spec,qty,divId,personalizeId,customText
  var personalizeId = "";var customText="";var size="";var spec="";var qty="";var divId="";
	if(page != 'search'){divId='upsell';}
	if(document.formdetailBedding == undefined){quickForm = document.forms['form'+item];}
  else{quickForm = document.formdetailBedding;}
  if(quickForm.elements['size_desc_'+item].selectedIndex != undefined){size = quickForm.elements['size_desc_'+item].value;}
  else{size = quickForm.elements['size_desc_'+item].options[quickForm.elements['size_desc_'+item].selectedIndex].value;}
  if(quickForm.elements['color_desc_'+item].selectedIndex != undefined){spec = quickForm.elements['color_desc_'+item].value;}
  else{spec = quickForm.elements['color_desc_'+item].options[quickForm.elements['color_desc_'+item].selectedIndex].value;}
  if(quickForm.elements['personalizeId_'+item] != undefined){ personalizeId = quickForm.elements['personalizeId_'+item].value;}
  if(quickForm.elements['customText_'+item] != undefined){ customText = quickForm.elements['customText_'+item].value;}
  qty = quickForm.elements['quantity_'+item].value;
	var URL = '/ajax/quickSellSelects.php';
	var pars = 'item='+item+'&size='+size+'&spec='+spec+'&qty='+qty+'&divId='+divId+'&personalizeId_'+item+'='+personalizeId+'&customText_'+item+'='+customText;	
	if(divId=='upsell'){
		var target = 'divCross_'+item;
	}else{var target = 'item_'+item;}
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { $(target).innerHTML = t.responseText; }});
}
/*********************************
* Function Name:beddingSizeChange
* purpose: change all size selects to global bedding size on the bedding ensembles page
* @param1: globalSize - twin/queen/king/california king/
* @param2: skuList - list of skus that belong to that ensemble
* returns: null
*********************************/
function beddingSizeChange(globalSize,skuList){
	var URL = '/ajax/beddingSelects.php';
	var pars = '&globalSize='+globalSize+'&skuList='+skuList;
	var target = 'items';	
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { $(target).innerHTML = t.responseText; }});
}
/*********************************
* Function Name:startQuickView
* purpose: to initiate QuickView on the thumbnail page and throughout checkout
* @param1: parentId - baseId
* @param2: size - size of item
* @param3: spec - the color of item
* @param4: qty - quantity ordered
* @param5: personalizedId - sku of personalization
* @param6: customText - personalized text
* @param7: cartId - the id of the lineItem in shoppingCartTemp
* returns: null
*********************************/
function startQuickView(E,parentId,size,spec,qty,personalizeId,customText,cartId){
	//item,size,spec,personalizeId,customText,cartId
	var submitted = false, nosearch, URL = '/ajax/detailData.php';
	quickImg = document.getElementById("quickView");
	if(quickImg!=undefined && quickImg.style.visibility=="visible"){
		nosearch = document.getElementById("noSearchResults");
		if(page=="cart"){URL+="?suggest=1";}
		else if(page=="search" && nosearch != undefined){URL+="?suggest=3";}
	}
	/*Windows.closeAll();*/
	checkString="cart|wishlist|login|shipTo|itemOptions|billTo|payment|addressBook";
	if(!window.location.toString().match(checkString)){
		cmCreatePageElementTag("start_QuickView","QuickView",parentId,"1",window.location.toString());
	}
	var pars = "parentId="+parentId+"&color_desc_"+parentId+"="+spec+"&size_desc_"+parentId+"="+size;
	pars+="&quantity_"+parentId+"="+qty+"&personalizeId_"+parentId+"="+personalizeId;
	pars+="&customText_"+parentId+"="+customText+"&cartId="+cartId+"&quickView=1";
	var formName = getFormName(parentId);
	if(formName != parentId){pars+="&name="+formName;}
	activeLink="about"; //365
	
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { //380
	quickWin = new Window({className: "quickView", title:"",showEffect:Element.show,hideEffect:Element.hide,width:495, height:380, resizable: false, destroyOnClose: true, recenterAuto:false}); 
	quickWin.id="quickWin";
	quickWin.setZIndex(8);
	quickWin.maxZIndex = 8;
	//quickWin.setCloseCallback(closeQuickView);
	//quickWin.getContent().update(t.responseText);
	quickWin.getContent().innerHTML=t.responseText;
	quickWin.showCenter();
	reviewLoad(parentId); //in ajax.js
	}});
}

function getFormName(parentId){
	var baseId = parentId.toString().substr(0,5);
	var letter = "a";
	if(parentId.toString().length > 5){letter = parentId.toString().substr(5,1);}
	var form1 = "form"+parentId;
	if(document.forms[form1] != undefined){
		letter = letter.toString().charCodeAt(0);
		nextLetter = String.fromCharCode(letter+1);
		return getFormName(baseId+nextLetter);
	}else{
		return parentId;
	}
}
/*********************************
* Function Name:createNewLogIn
* purpose: to create new login on reciept page
* @param1: form - new login form on receipt page
* returns: null
*********************************/
function createNewLogIn(form){
	userName = form.newUserName.value;
	userName2 = form.newUserName2.value;
	newPass1 = form.newPassword1.value;
	newPass2 = form.newPassword2.value;
	custId = form.custId.value;
	var URL = '/ajax/newLogin.php';
	var pars = "nextPage=1&newUserName="+userName+"&newUserName2="+userName2+"&newPassword1="+newPass1+"&newPassword2="+newPass2+"&custId="+custId;
	var target = 'newAccount';	
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { $(target).innerHTML = t.responseText; }});	
}
/*********************************
* Function Name:changeCreditCard
* purpose: change credit card on payment page
* @param1: ccSelect - the select of customerSavedPayments 
* returns: null
*********************************/
function changeCreditCard(ccSelect){
		var URL = '/ajax/changeCC.php';
		var pars = "payRecord="+ccSelect.options[ccSelect.selectedIndex].value;
		if(ccSelect.options[ccSelect.selectedIndex].value==-1){
			var pars = "payRecord=0&reset=1";
		}
		var target = 'ccForm';		
		var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { $(target).innerHTML = t.responseText; }});
}
//faqPopups throughout site
/*********************************
* Function Name:faqPopUp
* purpose: handle the faq pop up Events ( ie..whats this?,web security,gift card
* @param1: faqId - the id of the faq that should be pop upped.
* returns: null
*********************************/
function faqPopUp(faqId){
	var loc = window.location.toString();
	var widthX="250";
	var heightY="250";
	var submitted="false";
	var URL = '/ajax/faqWin.php';
	var minWidthX=200;
	var minHeightY=200;
	switch(faqId){
		case 27:
			widthX = '450';
			heightY = '450';
			cmCreatePageElementTag("return","COFAQ","","1",loc); 
			break;
		case 28:
			widthX = '450';
			heightY = '450';
			cmCreatePageElementTag("shipping","COFAQ","","1",loc);
			break;
		case 7:
			widthX ='300';
			heightY = '300';
			cmCreatePageElementTag("security","COFAQ","","1",loc);
			break;
		case "giftCert":
			widthX ='300';minWidthX=300;
			heightY = '312';minHeightY=310;
			cmCreatePageElementTag("gift","COFAQ","","1",loc);
			URL = '/ajax/giftCertificateInquiry.php';
			break;
		case 36:
			widthX = "350";
			heightY = "350";
			break;
	}
	if(Windows.focusedWindow){
		Windows.focusedWindow.close();
	}
	
		win = new Window({className: "pop", title: "", width:widthX+"px", height:heightY+"px", minWidth:minWidthX, minHeight:minHeightY,destroyOnClose: true, recenterAuto:false,showEffect:Element.show,hideEffect:Element.hide});
		setUpObserver(win,"popUpContent",95);
		win.showCenter();
	//background-color:#dff4f9;
	//$(win.getId()+"_top").style.width = widthX+"px";
	$(win.getId()+"_content").style.backgroundColor = "#dff4f9";
	var newHeightY = heightY - 95;
	var pars = "faqId="+faqId+"&width="+widthX+"px"+"&height="+newHeightY+"px"+"&submitted="+submitted;
	var target = win;	
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { $(win).getContent().update(t.responseText); }});							
}
/*********************************
* Function Name:giftCertSubmit
* purpose: to process the giftCertificate form that is located in the faq popup 
* @param1: gcform - the gift certificate form to be processed
* returns: null
*********************************/
function giftCertSubmit(gcform){
	var submitted="true";
	var widthX = '300px';
	var win = Windows.focusedWindow;	
	var height = win.height-72;
	if(gcform.name == "mcInquiry"){
		mcAction=1;
		merchCreditNo=gcform.elements['merchCreditNo'].value;
		var pars = "height="+height+"px&width="+widthX+"&mcAction="+mcAction+"&merchCreditNo="+merchCreditNo+"&submitted="+submitted;
	}else{
		gcAction=1;
		giftCertNo=gcform.elements['giftCertNo'].value;
		var pars = "height="+height+"px&width="+widthX+"&gcAction="+gcAction+"&giftCertNo="+giftCertNo+"&submitted="+submitted;
	}
	var URL = '/ajax/giftCertificateInquiry.php';
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { $(win).getContent().update(t.responseText); }});
}

//sourceCode double check
/*********************************
* Function Name:sourceWin
* purpose: to allow a second chance at collecting a key number on the billing page
* @param1: nextPage - the index of the nextPage array in checkoutController.php
* returns: null
*********************************/
function sourceWin(nextPage){
		if(document.forms.billToForm.elements['keyCode'].value == ""){
			var URL = '/ajax/source.php';
			var pars = "nextPage="+nextPage+"&height="+(350-70)+"px";
			win = new Window({className: "pop", title: "", width:'450px', Height:'350px', minWidth:450,minHeight:350, destroyOnClose: true, recenterAuto:false,showEffect:Element.show,hideEffect:Element.hide});	
			$(win.getId()+"_content").style.backgroundColor = "#dff4f9";
			setUpObserver(win,"popUpContent",70);
			win.showCenter();
			var loc = window.location.toString();
			cmCreatePageElementTag("popUp","KeyNumber","","1",loc);  //coremetrics remove from bag
			var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { $(win).getContent().update(t.responseText); }});
		}else{
			document.forms.billToForm.elements['nextPage'].value=nextPage;
			document.forms.billToForm.submit();
		}
}
/*********************************
* Function Name:submitBillToForm
* purpose: to submit the billTo page from the Key Number PopUp
* @param1: nextPage - the index of the nextPage array in checkoutController.php
* returns: null
*********************************/
function submitBillToForm(nextPage){
		document.forms.billToForm.elements['keyCode'].value=$('keyCode2').value;
		document.forms.billToForm.elements['nextPage'].value=nextPage;
		document.forms.billToForm.submit();
	}

function jsonIt(){
	var item_count=0;
}
function dropCart(){
	var cartCookie = readCookie("CartCookie");
	var numItems = 0;
	if(cartCookie){numItems = cartCookie.substr(27,5);}
	var jsonFakeIt = new jsonIt();
	jsonFakeIt.item_count=numItems;
	buildCart(jsonFakeIt,"detail","");
	return false;
}
/*********************************
* Function Name:buildCart
* purpose: to redisplay the cart after an add, edit, remove
* @param1: xmlDoc - a parsable representation of the xml response - probably from /ajax/processOrder.php
* @param2: page - the page that the request is happening on
* @param3: type - itemOptions.php, gift or shipping options
* returns: divId - the newly updated cart div
*********************************/
function buildCart(json,page,type){
	var divId="";
	var pattern = /(cart|login|shipTo|billTo|addressBook|itemOptions|payment|finalize)/i;
	if(json.item_count > 0){divId="cartPage";}
	else{divId="content";}
	if(pattern.test(page)){ // we are in checkout and can deal with normal ajax request
	 	getCheckOutCartContents(page,type,divId);
	}else{ 
	 	getQuickCartContents(page,type,json.item_count);//we are on detail, search or wishlist and have items in cart - need json response
	 }
	var shoppingBag = getShoppingBag();
	$('shoppingBag').innerHTML= shoppingBag;
	return divId;
}
/*********************************
* Function Name:getQuickCartContents
* purpose: to animate or update the quickCart 
* @param1: page - the current page
* @param2: type - itemOptions page - shippping or gift type
* returns: 
*********************************/
function getQuickCartContents(page,type,numItems){
	var cartURL = '/ajax/buildCart.php';
	if(numItems > 4){numItems=4;}
	if(type!=undefined){type="&"+type;}
	var pars="page="+page+type;
	ajax = new Ajax.Request(cartURL,{method: 'POST', parameters: pars,requestHeaders:{Accept: 'application/json'},onComplete: function(t) { 
		var jsonCart = t.responseText.evalJSON(true);
		var cartText = decodeURIComponent(jsonCart.cart);
		cartText = cartText.replace(/\+/g,' ');
		var subTotalText = decodeURIComponent(jsonCart.subtotals);
		subTotalText = subTotalText.replace(/\+/g,' ');
		var qckshd = $('qcksht');if(qckshd){qckshd.style.display = "block";}
		var quickCart = $('quickCart');
		var quickCartWrapper = $('quickCartWrapper');
		if(quickCart){
			quickCart.innerHTML=cartText;
			quickCart.className = "quickCart"+numItems;
		}
		var scrollpos = f_scrollTop(); 
		var header = $('header');
		var headpos = new Array("0","0");
		if(header){ headpos = findPos(header);}
		var headHeight = headpos[1]+header.offsetHeight;
		quickCartWrapper.style.top = headHeight-3+"px";
		window.scrollTo(0,25);
		if(quickCart && quickCart.style.display == 'none'){
			var end = getQuickCartOptions();
			var select0 = $('select0');if(select0){select0.style.visibility = 'hidden';}
			var select1 = $('select1');if(select1){select1.style.visibility = 'hidden';}
			var select2 = $('select2');if(select2){select2.style.visibility = 'hidden';}
			new Effect.SlideDown('quickCart',{queue:'end',afterFinish: selectView("hidden",numItems)});
			new Insertion.After('quickCart',subTotalText+end);
			$('sbi').src = "/media/images/graphics/quickcart_bag1_box.jpg";
			$('shoppingBag').style. backgroundImage = "url(/media/images/graphics/quickcart_bg1.jpg)";
		}else{
			if(quickCartWrapper){
				if($('subTotals')){quickCartWrapper.removeChild($('subTotals'));}
			if($('grpDisc')){quickCartWrapper.removeChild($('grpDisc'));}}
			new Insertion.After('quickCart',subTotalText);
		}
		var pattern = /(billTo|shipTo|login|payment|finalize|cart|itemOptions|addressBook)/i;
		if(!pattern.test(page)){
			var shopLink = $('shopLink');
			if(shopLink){ shopLink.onclick = closeQuickCart;}
		}
		//Event.observe(document, 'click',body_bind);
		removeFocus();
	}});
}

function selectView(view,numItems,divId){
	var f = $$('.rmie'),i;
	switch(divId){
	case "BVReviewsContainer":
		if(numItems > 3 && ie6){ //ie6 is global at top
				for(i=0; i < f.length; i++){
					f[i].style.visibility = view;
				}
		}else if((numItems==0 || numItems==3) && ie6){
				for(i=0; i < f.length; i++){
					f[i].style.visibility = view;
				}
		}
	 break;
	case "avWin":
			for(i=0; i < f.length; i++){
				f[i].style.visibility = view;
				}
 	 break;
	}
}
/*********************************
* Function Name:getCheckOutCartContents
* purpose: to handle the ajax request of the cart during the checkout process
* @param1: page - the current page 
* @param2: type - itemOptions page - shippping or gift type
* @param3: divId - the id of the div to update with the ajax response text
* returns: null
*********************************/
function getCheckOutCartContents(page,type,divId) { 
	var cartURL = '/ajax/buildCart.php';
	var secureLogo="";
	if(type!=undefined){type="&"+type;}
	var pars="page="+page+type;
	secureLogo = $("secureLogo");
	ajax = new Ajax.Request(cartURL,{method: 'POST', parameters: pars,onComplete:function(t) { 
	$(divId).innerHTML=t.responseText;
	if(secureLogo){
	var wishList="";
	wishList = $("wishlistStats");
	if(wishList) {
	new Insertion.After('wishlistStats', secureLogo);
  } else {
		new Insertion.After('subTotals', secureLogo);
  }
  }
	if(divId.toString().match("content")){
		Rounded("div#titleBar","transparent","#CAECF5","small");
	}
	removeFocus();
	}});
}
/*********************************
* Function Name:buildWishList
* purpose: buildWishList
* @param1: type - are we on the wishlist page in my account? are we in checkout and have a window? 
* returns: null
*********************************/
function buildWishList(){
	var type = "wishlist";
	var div = "wishListAjax";
	if(Windows.focusedWindow){
		type="win"; 
		div = win.getId().toString()+"_content";
	}
	var URL = '/ajax/buildWishList.php';
	var pars="type="+type;
	ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { 
		$(div).innerHTML=t.responseText; 
		if(type=='win'){
			$("wishListItemsAjax").style.height = "240px";
			$("wishListItemsAjax").style.overflowY = "auto";
			$(div).style.border = "1px solid #5BA6BD";
			$('wishListCart').style.border = "none"; 
		}
		}});
}
/*********************************
* Function Name:processOrder
* purpose: to control the addition, edit, and removal of an item to or from the cart or wishlist
* @param1: itemForm - the form of the item, could be detail page, quickView, cross-sell - contains most everything
* returns: null
*********************************/
function processOrder(E,itemForm){
	var URL = '/ajax/processOrder.php';
	var type="";
	var divId="";
	if(page.match("itemOptions")){
	 type=window.location.search.toString().replace("?","");
	}
	if(itemForm.name.match(/Form/)){ //we are removing an item from cart.  capital F on Form means checkout and cart page.
		var wishlist=0;
		var lineItemId  = findLineItemId(itemForm);  //ajax.js
		baseId = itemForm.elements[lineItemId+'sku'].value.substr(0,5);
		if(itemForm.name=="wishlistForm"){wishlist=1;}
		var pars = "parentId="+itemForm.elements[lineItemId+'sku'].value+"&quantity_"+baseId+"=0&cartId="+lineItemId+"&page="+page+"&type="+type+"&wishlist="+wishlist;
	}else{// we are editing or adding
		var cartId = "";
		var wishCartId="";
		if(itemForm.cartId){cartId = itemForm.cartId.value;}
		if($('wishlistItem_'+cartId)){itemForm.wishlist.value = 1;var wishCartId="&wishCartId=1";}
		var pars = loadUpPars(itemForm); //create a string of all elements of a form  +&form.element.name=value+
		pars+=wishCartId;
		baseId=itemForm.name.toString().replace("form","");
		pars+="&page="+page;
		if(type!=""){pars+="&"+type;}
		
	}
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,requestHeaders: {Accept: 'application/json'},onSuccess: function(t){processJSONResponse(t,E,itemForm);}}); 
}
/*********************************
* Function Name:findLineItemId
* purpose: to locate the lineItemId of an item that is being removed from the cart
* @param1: itemForm - the page form of a checkout page or cart page ie... cartForm, shipToForm...
* returns: lineItemId - the shoppingCartTemp id
*********************************/
function findLineItemId(itemForm){
	lineItemId = "";
	for(x=0;x<itemForm.length;x++){
			if(itemForm.elements[x].name.match(/Qty/)){ //find item with qty = 0
				if(itemForm.elements[x].value==0){ 
					index = itemForm.elements[x].name.indexOf('Qty');
					lineItemId = itemForm.elements[x].name.substr(0,index); //grab lineItemId
					x=itemForm.length;
				}
			}
	}
	return lineItemId;
}
/*********************************
* Function Name:addWishList
* purpose: to add an item in the wishlist and popup a window to prove it
* @param1: itemForm - the page form of a checkout page or cart page ie... cartForm, shipToForm...
* returns: null
*********************************/
function addWishList(itemForm){
	 var lineItemId = findLineItemId(itemForm);
	 var sku = itemForm.elements[lineItemId+'sku'].value;
	 var temp = sku.toString();
	 var item = temp.substring(0,5);
	 var color = temp.substring(5,7);
	 var size = temp.substring(7,10);
	 var personalizeId="";
	 var customText="";
	 if(page.match("itemOptions")){
	 	type=window.location.search.toString().replace("?","");
	 }
	 if(itemForm.elements[lineItemId+'per'] != undefined){
	 personalizeId = itemForm.elements[lineItemId+'per'].value;
	 }
	 if(itemForm.elements[lineItemId+'cust'] != undefined){
	 customText = itemForm.elements[lineItemId+'cust'].value;
		}
	 var URL = '/ajax/processOrder.php';
	 var pars = "parentId="+item+"&quantity_"+item+"=1&sku_"+item+"="+sku+"&wishlist=1&color_desc_"+item+"="+color;
	 pars+="&size_desc_"+item+"="+size+"&page="+page;
	 pars+="&personalizeId_"+item+"="+personalizeId+"&customText_"+item+"="+customText;
	 var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,requestHeaders: {Accept: 'application/json'}, onComplete: function(t) { 
	 var json = t.responseText.evalJSON(true);
	 	if(json.success.toString()=="true"){
	 		startWishList();
	 	}else{
	 		alert("Sorry, a wishlist processing error occured");
	 	}
	 	}});
	  var pars = "parentId="+item+"&quantity_"+item+"=0&sku_"+item+"="+sku+"&color_desc_"+item+"="+color;
	 	pars+="&size_desc_"+item+"="+size+"&page="+page;
	 	pars+="&personalizeId_"+item+"="+personalizeId+"&customText_"+item+"="+customText+"&cartId="+lineItemId;
	 	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,requestHeaders: {Accept: 'application/json'}, onComplete: function(t) { 
	 	var json2 = t.responseText.evalJSON(true);
	 	if(json2.success.toString()=="true"){
	 			buildCart(json2,page,type);
	 	}else{
	 			alert("Sorry, a wishlist processing error occured");
	 		}
	 	}});		 		
}
/*********************************
* Function Name:startWishList
* purpose: to pop up a window containing a customers wishlist
* returns: null
*********************************/
function startWishList(){
	if(Windows.focusedWindow && $("wishListItemsAjax")){ Windows.focusedWindow.close();} 
	win = new Window({className: "wishlist", title: "", width:'550px', height:'350px', destroyOnClose: true, recenterAuto:false,showEffect:Element.show,hideEffect:Element.hide});	
	win.showCenter();
	win.id = "wishlistWin";
	win.setZIndex(6);
	buildWishList('win'); //win <- we are in checkout not on the detail page or wishlist
}
/*********************************
* Function Name:processPersonalization
* purpose: pop up window that allows a person to personalize an item once its been updated or added to the cart
* @param1: itemForm - form containing everything about the newly added or edited item.
* @param2: page - page to redirect to..where are we going?
* returns: null
*********************************/
function processPersonalization(itemForm,page){
	var pars = loadUpPars(itemForm);
	if(Windows.focusedWindow){ Windows.focusedWindow.close();}
	var URL = '/ajax/personalize.php';
	var divText="";
	var baseId=itemForm.parentId.value.substr(0,5);
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t){
	var win = new Window({className: "soft", title: "", width:620, height:355, destroyOnClose: true, recenterAuto:false,showEffect:Element.show,hideEffect:Element.hide});	
	win.showCenter();
	div = win.getId().toString()+"_content";
	$(div).innerHTML=t.responseText;
	$('personalization').style.height = (355-95)+"px";
	$('personalization').style.overflowY = "auto";
	}});
}

function loadUpPars(itemForm){
	var pars = "";
	var add= true;
	for(x=0;x<itemForm.length;x++){
		add=true;
		if(itemForm.elements[x].name == "radio" && !itemForm.elements[x].checked){add=false;}
		if(add){
			if(x!=0){pars+="&";} 
				pars+=itemForm.elements[x].name+"="+itemForm.elements[x].value; //load up form paramaters 
		}
	}
	pars = pars.replace(/\?/g,'*.*');
	return pars;
}

function validatePersonalize(perForm){
	var pars = loadUpPars(perForm);
	var URL = '/ajax/personalize.php';
	pars += "&submit=Submit";
	
	type="";
	var ajax = new Ajax.Request(URL,{method: 'POST',requestHeaders:{Accept: 'application/json'},parameters: pars,onComplete: function(t){
		var json = t.responseText.evalJSON(true);
		if(json.success.toString()=="true"){
			if(Windows.focusedWindow){ Windows.focusedWindow.close(); }
			type="";
			if(page.match("itemOptions")){
	 			type=window.location.search.toString().replace("?","");
			}
			switch(page){
				case "detail":
					if(perForm.elements['wishlist']!= undefined){
						if(perForm.elements['wishlist'].value == '1'){
							window.location = secureBase+"wishlist.php";
						}else{
							buildCart(json,page,type);
						}
					}
					break;
				case "search":
					if(perForm.elements['wishlist']!= undefined){
						if(perForm.elements['wishlist'].value == '1'){
							window.location = secureBase+"wishlist.php";
						}else{
							buildCart(json,page,type);
						}
					}
					break;
				case "wishlist":
					buildWishList(type);
					break;
				default:
					buildCart(json,page,type);
				break;
			}
		}else{
			var errors = processErrors(json.errors,"|");
			$('perProcessError').innerHTML = errors;
		}
		
	}});
}

function processErrors(errorString,delimator){
	var errors="";
	var errorArray = errorString.split(delimator);
	var numError = errorArray.length;
	for(i=0;i < numError; i++){
		errors+= '<span class=\"error\">'+errorArray[i]+'</span><br>';
	}
	return errors;
}
var monoProd = "";var monoParent = "";var monoDescrip = "";var monoQty;
var handleMonogramPopUPSuccess = function callBack(o) {
		win = new Window({className: "soft", title:"", width:620, height:580, destroyOnClose: true, resize:false, recenterAuto:false,showEffect:Element.show,hideEffect:Element.hide}); 
		win.getContent().update(o.responseText); 
		win.showCenter();
		$('monoContent').style.height = (580-80)+"px";
	  $('monoContent').style.overflowY = "auto";
}
function monogramPopUP(productid,qty,parentid,desc){
	monoProd = productid;
	monoParent = parentid;
	monoDescrip = desc;
	monoQty = qty;
	var sendUrl = '&productid='+productid+'&qty='+qty+'&parentid='+parentid+'&desc='+desc;
	var URL = '/ajax/monogram.php';
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: sendUrl,onComplete: handleMonogramPopUPSuccess});	
}
var handleMonogramFieldSuccess = function callBack(o){
	//set vars
	 var monText = $('monogramText');
	 var t = o.responseText;
	 var h4 = "<br><h4 id=\"monoH4\" class=\"titleH4\">Monogram Initials</h4>";
	 var p = "<p>Please enter the letters in the order in which you would like";
	  p+= " them to appear, as monogrammed items are <b>not returnable</b>. Note:";
	  p+= " We are not liable for misspellings or incorrect letters entered by the customer.</p>";
	 if(t.length > 7){
	 	  monText.innerHTML= h4+"\n<div class=\"specs\">"+p+t+"</div>";
	  	monText.show();
	 }else{
	  	monText.innerHTML= '';
	 		monText.hide();
	 }
	 var f = $$('input.monoLineId');
	 var monRowCount = $('monogramRowCount');
	 monRowCount.value = f.length;
}
function monogramGetFields(personalize){
	var monoStyle = $('style');
	var monoColor = $('color');
	var index=monoStyle.selectedIndex;
	monogramType=monoStyle.value;
	monogramColor=monoColor.value;
	if(!monogramColor){
		if($('errorList')){
			$('errorList').update('<li class=\"error\">Please Select a Color</li>');
		}else{
			new Insertion.After('style', '<ul id=\"errorList\"><li class=\"error\">Please Select a Color</li></ul>');
		}
		$('monogramText').update("");
		$('monogramText').hide();
	}else{
		if($('errorList')){
			$('errorList').remove();
		}
		var selectedOptionText=monoStyle.options[index].text;
		//set up regular expression to match
		var singleFieldWords=/(NAME|SINGLE|LAUREL SPRAY)/i;
		//
		if(singleFieldWords.exec(selectedOptionText)===null){//if none of the regular expression words are found
			var sendUrl = '&monoId='+personalize+monogramType+monogramColor;
			//YAHOO.util.Connect.asyncRequest('POST','monogramData.php',callbackMonogramFields,sendUrl);
			
			var URL = '/ajax/monogramData.php';
			var ajax = new Ajax.Request(URL,{method: 'POST', parameters: sendUrl,onComplete: handleMonogramFieldSuccess});	
		}else{
			makeOne(index,selectedOptionText);
		}
	}
}
function makeOne(index,selectedOptionText){
	var wordField=/(NAME)/i,formText="";
	if(wordField.exec(selectedOptionText)===null){
		formText=formText+"<span id=\"span1\">Enter center initial: </span>";
		len = " maxlength=\"1\" ";
		size = " size=\"1\" ";
	}
	else{
		formText=formText+"<span id=\"span1\">Enter your name: </span>";
		len = " maxlength=\"8\" ";
		size = " size=\"8\" ";
	}
	inputTag="<input type=\"text\" name=\"monogram1\""+len+size;
	inputTag+=" id=\"monogram1\" value=\"\"></p>";
	var h4 = "\n<br><h4 id=\"monoH4\" class=\"titleH4\">Monogram Initials</h4>";
	 var p = "<p>Please enter the letters in the order in which you would like";
	  p+= " them to appear, as monogrammed items are <b>not returnable</b>. Note:";
	  p+= " We are not liable for misspellings or incorrect letters entered by the customer.</p>";
	var monoRowCnt = $('monogramRowCount');
  monoRowCnt.value=1;
  var d = $('monogramText');
  var divText = h4+"\n<div class=\"specs\">"+p+formText+inputTag+"</div>";
  d.innerHTML = divText;
  d.style.display = 'block';
}
var monograms = Array();
function handleMonogramValidate(o,argument){
	if(o.responseText==""){
		var argString = o.argument;
		var winText=getWinText(argument);
		win.close();
		winConfirm = new Window({className: "pop", title:"", width:450, height:315,minWidth:325, minHeight:200, destroyOnClose: true, recenterAuto:true,showEffect:Element.show,hideEffect:Element.hide});
		winConfirm.getContent().update(winText);
		$(winConfirm.getId()+"_content").style.backgroundColor = "#dff4f9";
		setUpObserver(winConfirm,"popUpContent",72);
	  winConfirm.show();
	}else{
		if($('errorList')){
			$('errorList').update(o.responseText);
		}else{
			if($('style').value==""){
				new Insertion.After('style', '<ul id=\"errorList\">'+o.responseText+'</ul>');
			}else{
				new Insertion.After('monoH4', '<ul id=\"errorList\">'+o.responseText+'</ul>');
			}
		}
	}
}
function validateMonogram(){
	var monoStyle = $('style');
	var monoColor = $('color');
	var monoRowCount = $('monogramRowCount');
	var personalize = $('personalize');
	var parentId = $('parentId');
	var customText = "";
	var sendUrl = '&personalize='+personalize.value+'&style='+monoStyle.value+'&color='
								+monoColor.value+'&monogramRowCount='+monoRowCount.value+'&Submit=SaveMonogramming';
	var inputCnt = monoRowCount.value
	for(i=1;i<=inputCnt;i++){
		var monoLineId = $('monogram'+i);
		if(i>1){customText=customText+"|";}
    customText = customText+monoLineId.value;
		sendUrl = sendUrl + '&monogram'+i+'='+monoLineId.value;
	}
	var argument=[personalize.value,monoStyle.value,monoColor.value,customText,parentId.value];
	var URL = '/ajax/monogram.php';
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: sendUrl,onComplete:function(t) { handleMonogramValidate(t,argument);}});
}
function getWinText(argString){
	var monoColor = $('color');
	var monoStyle = $('style');
	var color = monoColor.options[monoColor.selectedIndex].text;
	var styles = monoStyle.options[monoStyle.selectedIndex].text;
	var g="";
	for(i=0;i<argString.length;i++){
		if(i>0){g+=",";}
		g+="'"+argString[i]+"'";
	}
	var numLet = argString[3].split("|");
	var prompText = "";
	var custText= "";
	for(i=1;i<=numLet.length;i++){
		if(i>1){prompText+="<br>";custText+="<br>";}
		prompText+= $('span'+i).innerHTML;
		custText+=numLet[i-1];
	}
	htmlStr=getReviewHeader(230);
	htmlStr+="<h4 class=\"checkOutStep\">Confirm Monogramming</h4>";
	htmlStr+="<p>Please review your monogram selections to make sure the information you entered is correct,";
	htmlStr+=" as monogrammed items are <b>not returnable</b>. When you have finished, click the <b>Confirm</b>";
	htmlStr+=" button to save or the <b>Edit</b> button to make any changes.</p>";
	htmlStr+=" <table><tr><td id=\"prompText\">";
	htmlStr+=" Thread Color:<br>Monogram Style:<br>"+prompText+"</td>";
  htmlStr+=" <td id=\"atts\"> "+color+"<br> "+styles+"<br> "+custText+"</td></tr></table>";
	htmlStr+="<div class=\"buttons\">";
	htmlStr+="<img src=\"/media/images/buttons/edit_button.gif\" onclick=\"editMonogram(monoProd,monoQty,monoParent,monoDescrip);\" class=\"button\">";
	htmlStr+="<img src=\"/media/images/buttons/confirm_button.gif\" onclick=\"submitMonogram("+g+");\" class=\"button\">";
	htmlStr+="</div>";
	htmlStr+="</div>";
	return htmlStr;
}
function submitMonogram(personalize,color,styles,custText,parentId){
	personalizeId = $('personalizeId_'+parentId);
	customText = $('customText_'+parentId);
	personalizeId.value=personalize+color+styles;
	customText.value=custText;
	$('detailMono_'+parentId).update("Monogrammed "+custText);
	winConfirm.close();
}
function editMonogram(productid,qty,parentid,desc){
	winConfirm.close();
	monogramPopUP(productid,qty,parentid,desc);
}
function changeSpec(text,spec){
	if(spec=="color"){
		var color = $('color');
		for(i=0;i< color.options.length; i++){
			if(color.options[i].value == text){
				color.options.selectedIndex = i;
			}
		}
	}else{
		var style = $('style');
		for(i=0;i< style.options.length; i++){
			if(style.options[i].value == text){
				style.options.selectedIndex = i;
			}
		}
	}
	monogramGetFields($('personalize').value);
}
function emailFriend(productid,submitted,desc){
	var sendUrl = '';
	var URL = '/ajax/sendtofriend.php';
	var newHeightY = 450 - 75;
	var pars = "&width="+450+"px"+"&height="+newHeightY+"px"+"&submitted="+submitted+"&productid="+productid+"&desc="+desc;
	if(submitted==0){
		var win = new Window({className: "pop", title: "", width:450+"px", height:450+"px", destroyOnClose: true, recenterAuto:false,showEffect:Element.show,hideEffect:Element.hide});
		win.showCenter();
		$(win.getId()+"_top").style.width = 450+"px";
		$(win.getId()+"_content").style.backgroundColor = "#dff4f9";
	}else{
		var win = Windows.focusedWindow;
		emailForm = document.emailProductForm;
		pars+="&"+loadUpPars(emailForm);
	}
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete:function(t) { win.getContent().update(t.responseText); }});
}
function emitBazaarVoiceProfile(profileURL){
	var URL = '/ajax/bazaarVoiceProfile.php';
	var Height = 600 - 45;
	var pars = "profileURL="+profileURL+"&width=800px&height="+Height+"px";
	var win = new Window({className: "pop", title: "", width:800+"px", height:600+"px", destroyOnClose: true, recenterAuto:false,showEffect:Element.show,hideEffect:Element.hide});
	win.showCenter();
	$(win.getId()+"_top").style.width = 800+"px";
	$(win.getId()+"_content").style.backgroundColor = "#dff4f9";
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,onComplete: function(t) { win.getContent().update(t.responseText); }});
}
/*********************************
* Function Name:sflEvent
* purpose: handle the save for later onclick event
* @param1: lineItemIndex - the shoppingCartTemp id
* @param2: item - baseId 
* returns:null
*********************************/
function sflEvent(E,lineItemIndex,item){ //save for later Event
	var children = $('lineItem_'+lineItemIndex).childNodes;
	for(var i=0; i< children.length;i++){
		children[i].onmouseover = "";
	}
	removeFocus(); 
	var loc = window.location.toString();
	cmCreatePageElementTag("save","WishList",item,"0",loc); 
	var docForm = createCartForm(lineItemIndex);
	addWishList(docForm);
	//processOrder(docForm);
	//startWishList();
	
}
/*********************************
* Function Name:vywEvent
* purpose: handle the view your wishlist Event
* returns: null
*********************************/
function vywEvent(){ //view your wishlist Event
	var loc = window.location.toString();
	cmCreatePageElementTag("view","WishList","","0",loc); 
	startWishList();
}
/*********************************
* Function Name:atwEvent
* purpose: handle the wishlist add to bag
* @param1: lineItemId - wishlist item id
* returns: null
*********************************/
function atwEvent(lineItemId){
	type="";
	var wishForm = document.forms['wishlistForm'];
	var loc = window.location.toString();
	if(wishForm.elements['qtyPurch'+lineItemId].value==-1){
		//replace error
		$('wishlistError').innerHTML = '<span class=\"error\">Please enter a quantity before adding item '+wishForm.elements[lineItemId+'sku'].value+' to your cart.</span>';
	}else{
		cmCreatePageElementTag("add","WishList","","0",loc);  //coremetrics remove from bag
		URL = "/ajax/wishlistAdd.php?addToCart="+lineItemId+"&qtyPurch="+wishForm.elements['qtyPurch'+lineItemId].value;
		var ajax = new Ajax.Request(URL,{method: 'POST',requestHeaders: {Accept: 'application/json'},onComplete: function(t) { 
		var json = t.responseText.evalJSON(true);
		if(json.success.toString() == "true"){ 
			if(page.match("itemOptions")){type=window.location.search.toString().replace("?","");}
			buildCart(json,page,type); }
	  }});
	}
}
/*********************************
* Function Name:eybEvent
* purpose: handle the edit your bag Event
* @param1: item - baseId
* @param2: size
* @param3: color
* @param4: qty - number ordered
* @param5: personalization - sku of personalization
* @param6: customText - the customText of personalization or monogramming
* @param7: lineItemIndex - the shoppingCartTemp id
* returns: null
*********************************/
function eybEvent(E,item,size,color,qty,personalization,customText,lineItemIndex){  //edit your bag Event
	var children,i;
	try{ children = $('lineItem_'+lineItemIndex).childNodes;
	}catch(exep){
	 children = $('wishlistItem_'+lineItemIndex).childNodes;
	}
	for(i=0; i< children.length;i++){
		children[i].onmouseover = "";
	}
	removeFocus(); 
	var loc = window.location.toString();
	cmCreatePageElementTag("edit","Edit",item,"1",loc);	
	startQuickView(E,item,size,color,qty,personalization,customText,lineItemIndex);
}

/*********************************
* Function Name:aybEvent
* purpose: handle the add your bag event
* @param1: item - baseId
* returns: null
*********************************/
function aybEvent(E,itemFormName){
	disableFutures(E);
	var loc = window.location.toString();
	var itemForm = document.forms["form"+itemFormName];
	if(itemForm.parentId != null){var item = itemForm.parentId.value;}
	else{
		var item = itemForm.crossSell.value;
		cmCreatePageElementTag("add","CROSS SELL PROD",item,"1",loc);  //ADD cross sell to bag
	}
  item = item.toString().substr(0,5);
	var pattern = /(\/P\/|detail)/i
	var cartId = "";
	if(itemForm.cartId){cartId = itemForm.cartId.value;}
	var detailpage = pattern.test(loc);
	if(!detailpage && cartId ==""){
		cmCreatePageElementTag("add","QuickView",item,"1",loc);  //coremetrics add to bag
	}
	if(itemForm.elements['wishlist']){itemForm.elements['wishlist'].value = '0';}
	processOrder(E,itemForm);
	return false;
}
/*********************************
* Function Name:rfbEvent
* purpose: handle remove from bag Event
* @param1: lineItemIndex - the shoppingCartTemp id
* @param2: item - baseId
* returns: null
*********************************/
function rfbEvent(E,lineItemIndex,item){ //remove from bag Event
	var loc = window.location.toString();
	cmCreatePageElementTag("remove","Edit",item,"1",loc);  //coremetrics remove from bag
	var docForm = createCartForm(lineItemIndex);
	var children = $('lineItem_'+lineItemIndex).childNodes;
	for(var i=0; i< children.length;i++){
		children[i].onmouseover = "";
	}
	removeFocus(); // checkout.js - removes prodOptions
	processOrder(E,docForm); 
}
/*********************************
* Function Name:rfw
* purpose: handle remove from wishlist Event
* @param1: item - baseId
* returns: null
*********************************/
function rfwEvent(E,lineItemIndex,item){
	var wishlistItemImg = $('image_'+lineItemIndex);
	if(wishlistItemImg){ wishlistItemImg.onmouseover = "";}
	removeFocus();
	document.wishlistForm.elements[lineItemIndex+"Qty"].value=0;
	
	if(Prototype.Browser.IE){
		var Input = "<input name='cartId' type='hidden' value='"+lineItemIndex+"'>";
		var cartId = document.createElement(Input);
	}else{
		var cartId = document.createElement("input");
		cartId.setAttribute("type", "hidden");
 	 	cartId.setAttribute("name", "cartId");
  	cartId.setAttribute("value", lineItemIndex);
	}
	document.forms['wishlistForm'].appendChild(cartId);
	processOrder(E,document.wishlistForm);
	
}
/*********************************
* Function Name:removeInserted
* purpose: to clean up after the quickCart has closed
* returns: 
*********************************/
function removeInserted(){
	var qCD = $('quickCartDir'),subTot = $('subTotals'),qckS = $('qcksht'),disc = $('grpDisc');
	if(qCD){$('quickCartWrapper').removeChild(qCD);}
	if(disc){$('quickCartWrapper').removeChild(disc);}
	if(subTot){$('quickCartWrapper').removeChild(subTot);}
	if(qckS){qckS.style.display = "none";}
	$('sbi').src = "/media/images/graphics/bag.jpg";
	$('shoppingBag').style. backgroundImage = "url(/media/images/graphics/quickcart_bg2.jpg)";
	if($('select0')){$('select0').style.visibility = 'visible';}
	if($('select1')){$('select1').style.visibility = 'visible';}
	if($('select2')){$('select2').style.visibility = 'visible';}
	var pattern = /(billTo|shipTo|login|payment|finalize|cart|itemOptions|addressBook)/i;
	if(!pattern.test(page)){
		var shopLink = $('shopLink');
		if(shopLink){ shopLink.onclick = dropCart;}
	}
}
/*********************************
* Function Name:closeQuickCart
* purpose: to handle the closing of the quickCart
* returns: 
*********************************/
function closeQuickCart(){
	//if(Event){ Event.stopObserving(document, 'click', body_bind);}
	new Effect.BlindUp('quickCart',{queue:'end',duration:1.0,onCreate: selectView("visible",4),afterFinish: removeInserted});
	return false;
}

function getShoppingBag(){
	var cartCookie = readCookie("CartCookie");
	var numItems = 0;
	var price = 0.00;
	var items = "items";
	if(cartCookie){
	var numItems = cartCookie.substr(27,5);
	var price = cartCookie.substr(32,12);
	}
	if(numItems == 1){items="item";}
	var shopLink = $('shopLink');
	var quickCart = $('quickCart');
	var str = '<a id=\"shopLink\" href="'+base+'cart.php">';
	str+= 'Shopping Bag</a>:&nbsp;<div class="numItem">'+(numItems*1)+'</div>'
	str+= '&nbsp;'+items+'&nbsp;<div class="total">Total&nbsp;$'+(price*1).toFixed(2)+'</div>';
	return str;
}

function getQuickCartOptions(){
	var str = "<div id=\"quickCartDir\"><a href=\""+window.location.toString()+"\" onclick=\"closeQuickCart();return false;\"><img id=\"close_box\" src=\"/media/images/buttons/close_box.gif\" /></a>";
	str+="<a href=\""+base+"cart.php\"><img src=\"/media/images/buttons/checkout_button_quickcart.gif\" /></a></div>";
	return str;
}

function processJSONResponse(t,E,itemForm){
	var json = t.responseText.evalJSON(true);
	type="";
	if(page.match("itemOptions")){
	 type=window.location.search.toString().replace("?","");
	}
	if(json.success.toString()=="true"){
		if(Windows.focusedWindow && Windows.focusedWindow.id != "wishlistWin"){ Windows.focusedWindow.close();}
		var cartId = "";
		var wishlist = 0;
		if(itemForm.wishlist){wishlist = itemForm.wishlist.value;}
		if(itemForm.cartId){cartId = itemForm.cartId.value;}
		if(wishlist==0 && cartId ==""){
			baseId=itemForm.name.toString().replace("form","");
		}
		if(json.personalize.toString()=="true"){ //item is personalized -- gift card
			processPersonalization(itemForm,page,baseId);
		}else{
			var wishlistItem = $('wishlistItem_'+cartId);
			if(wishlist==1 && wishlistItem == null){ window.location = "/wishlist.php";}
			if(wishlistItem != null){ buildWishList();}
			else{ buildCart(json,page,type);}
		}
	}else{
				processErrorsJSON(json,itemForm);
	}
	reinstateEvents(E,itemForm);
}
function processErrorsJSON(json,itemForm){
	 //some type of errors ... figure out where they go and update html
			if(itemForm.elements['crossSell']!=undefined){
					$('orderProcessErrorCross').innerHTML = '<span class=\"error\">'+json.errors.toString()+'</span>';
				}else if(itemForm.elements['wishlist'].value == '1'){ //customer wanted to add to wish list but was not logged on
					var locString=secureBase+"wishlist.php";
					locString+="?added="+itemForm.elements['sku_'+baseId].value;  //locString - log on then use params to save item
					locString+="&qty="+itemForm.elements['quantity_'+baseId].value;
					if(itemForm.elements['personalizeId_'+baseId] !=undefined){
						locString+="&personalizeId="+itemForm.elements['personalizeId_'+baseId].value;
						locString+="&personalization="+itemForm.elements['customText_'+baseId].value;
					}
					window.location = locString;
				}else{
					$('orderProcessError').innerHTML = '<span class=\"error\">'+json.errors.toString()+'</span>';
				}
}
function getCurrentPage(){
	var page = "";
	page=window.location.pathname.toString().replace("checkout/","");
	page=page.replace("/","");
	page=page.replace(".php","");
	var pattern = /(P\/|detail)/i
  if(pattern.test(page) && page.charAt(page.length-1) == "/"){ page = "detail";}
  else if(page.charAt(page.length-1) == "/"){page="search";}
	return page;
}
function createCartForm(lineItemIndex){
	var docForm;
	if($('quickCart') && $('quickCart').style.display != 'none'){
		//create a form and pass it to process order
		docForm= document.createElement("FORM");
		document.body.appendChild(docForm);
 		docForm.method = "POST";
 		docForm.name = "cartForm";
 		var x = document.getElementsByName(lineItemIndex+'sku');
 		sku = x[0];
 	  var skuNo = sku.value;
 	  docForm.appendChild(sku);
 		x = document.getElementsByName(lineItemIndex+'Qty');
 		qty = x[0];
 		qty.value=0;
 		x = document.getElementsByName(lineItemIndex+'per');
 		docForm.appendChild(qty);
 		if(x[0]!= undefined){ per = x[0]; docForm.appendChild(per);}
 		x = document.getElementsByName(lineItemIndex+'cust');
 		if(x[0]!= undefined){ cust = x[0]; docForm.appendChild(cust);}
	}else{
		docForm = document.forms[page+"Form"];
		docForm.elements[lineItemIndex+"Qty"].value=0;
	}
	if(Prototype.Browser.IE){
		var Input = "<input name='cartId' type='hidden' value='"+lineItemIndex+"'>";
		var cartId = document.createElement(Input);
	}else{
		var cartId = document.createElement("input");
		cartId.setAttribute("type", "hidden");
 	 	cartId.setAttribute("name", "cartId");
  	cartId.setAttribute("value", lineItemIndex);
	}
	docForm.appendChild(cartId);
	
	return docForm;
}

function popSubscribe(){
	subBox = document.createElement("DIV");
	subBox.name = "subBox";
	subBox.id= "subBox";
	var subBox = $('subBox');
	var footer = $('footer');
	if(footer){
		var footpos = findPos(footer);
		var win = new Window({className: "pop", title:"",
			showEffect:Element.show,hideEffect:Element.hide,
			width:230, height:365,
			left:(footpos[0]+92),top:(footpos[1]-360),
			resizable: true, destroyOnClose: true, recenterAuto:false, minWidth:230, minHeight:365}); 
		win.setZIndex(8);
		new Ajax.Updater({ success: win.getId()+"_content"}, '/ajax/subscribe.php', {
  	parameters: { update:1,height:(365-95)+"px" },
  	insertion: Insertion.bottom
		});
	setUpObserver(win,"popUpContent",95);
	win.show();
	$(win.getId()+"_content").style.backgroundColor = "#dff4f9";
		
	}else{
		window.location=base+"/subscribe.php";
	}
	
}
function validateSubscribe(){
	var subForm = document.emailSubscribe;
	var pars = loadUpPars(subForm);
	var size = Windows.focusedWindow.getSize();
	size = parseInt(size['height']);
	Height = size-95;
	pars+="&height="+Height.toString()+"px";
  var URL = "/ajax/subscribe.php";
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,requestHeaders: {Accept: 'application/json'},onComplete: function(t) { 
		var json = t.responseText.evalJSON(true);
		if(json.success.toString() == "true"){ 
			Windows.focusedWindow.getContent().update(decodeURIComponent(json.message).replace(/\+/g,' '));
		}else{
			 if($('errorBox')){$('errorBox').update("<ul style=\"margin:0px;padding:5px;\">"+decodeURIComponent(json.errors).replace(/\+/g,' ')+"</ul>");}
			}
	  }});
}
function setUpObserver(win,divId,subPix){
	var myObserver = { 
						onShow: function(eventName, newWin){
								if((divId=="BVReviewsContainer" || win.getId()!="quickView" || divId=="avWin") && ie6){
									selectView("hidden",3,divId);
								} 
						}
            ,onResize: function(eventName, newWin) {
                if(newWin == win){
                	var box = divId.toString();
    							if(divId=="avWin"){box="popUpContent";}
									var div = document.getElementById(box);
                	if(div != undefined){div.style.height = (newWin.height-subPix)+"px";}
                }
            }
            ,onDestroy: function(eventName, newWin) { 
                    if(newWin == win){ 
                        Windows.removeObserver(this);
                     	if((divId=="BVReviewsContainer" || win.getId()!="quickView" || divId=="avWin") && ie6){
												selectView("visible",3,divId);
											}
                   	win=null;
                   } 
                   
            } 
     } 
	Windows.addObserver(myObserver);
}
var activeLink="about";
function changeDetailInfo(curLink){
	var link = "Link";
	if(activeLink!=curLink && curLink != 'size' && curLink != 'reviews'){
		document.getElementById(activeLink).style.display = 'none';
		document.getElementById(activeLink+link).style.color = '#a16a47';
		document.getElementById(curLink).style.display = 'block';
		document.getElementById(curLink+link).style.color = '#5ba6bd';
		activeLink = curLink;
	}
	if(curLink=="reviews"){
		var win = new Window({className: "pop", title: "", 
			width:450, height:350, minWidth:325, minHeight:200, 
			destroyOnClose: true, resizable: true, recenterAuto:false,
			showEffect:Element.show,hideEffect:Element.hide
			}); 
		setUpObserver(win,"BVReviewsContainer",95);
		win.getContent().update($('hideBV').innerHTML); 
		win.showCenter();
		var loc = window.location.toString();
		var pattern = /form\d{5}/
		var result= null;
		var item= null;
		for(var i=0;i< document.forms.length;i++){
		  result = document.forms[i].name.toString().match(pattern);
			if(result != null){ item = document.forms[i].parentId.value; i=document.forms.length;}
		}
		cmCreatePageElementTag("read","Reviews",item,"1",loc);  //coremetrics remove from bag
	}
	if(curLink=="size"){
		var win = new Window({className: "pop", title:"", width:"625px", height:"400px",minWidth:620, minHeight:200, destroyOnClose: true, recenterAuto:true,showEffect:Element.show,hideEffect:Element.hide}); 
		win.id="sizeChart";
		setUpObserver(win,"popUpContent",95);
		var str=getReviewHeader(305);
		str+="<img src=\"/media/images/graphics/ss_size.gif\" width=\"600\" alt=\"Size Chart\" />";
		str+="</div>";
		win.getContent().update(str); 
		/*$(win.getId()+"_top").style.width = 620+"px";*/
		$(win.getId()+"_content").style.backgroundColor = "#dff4f9";
		win.show();
	}
}
function zoomWindow(E){
	var URL =  "http://s7d5.scene7.com/s7ondemand/zoom/flasht_zoom.jsp?company=SoftSurroundings";
	var element = Event.element(E);
	var sku = element.id.replace("pop","").replace("Large","").replace("Medium","");
	URL+="&sku="+sku+"_rs&zoomwidth=500&zoomheight=680";
	window.open(URL,"","toolbar=no,location=no,directories=no,"+
							"status=no,menubar=no,scrollbars=yes,"+
							"resizable=yes,width=500,height=700,top=0,left=0,right=0,bottom=0");
}

function addElement(domE){
		var E = document.createElement(domE.tag);
		numAtts=domE.attributes.length;
		for(var i=0;i<numAtts;i++){
			var attr = domE.attributes[i];
			E.setAttribute(attr.name,attr.value);
		}
		domE.parent.appendChild(E);	
}
function getReviewHeader(Height){
		var str="<div id=\"reviewHeader\">";
		str+="<img src=\"/media/images/graphics/logo_small.gif\" alt=\"Soft Surroundings\"><br />";
		str+= "<div id=\"patternRep\">";
	  str+= "</div>";
		str+="</div>";
		str+="<div id=\"popUpContent\" style=\"height:"+Height+"px; overflow:auto; padding:10px;\" >";
		return str;
}
function upsVal(shipTo){
	var URL = '/ajax/ups.php',AvCode=0,today = new Date(),month =parseInt(today.getUTCMonth())+1;	
	var pars=loadUpPars(shipTo);
	var ajax = new Ajax.Request(URL,{method: 'POST', parameters: pars,requestHeaders:{Accept: 'application/json'},onComplete: function(t) { 
			upsObj = t.responseText.evalJSON(true);
			var i=0;
			if(upsObj.error==0){
				if(upsObj.Addresses !=undefined){
					showAddressSelector(upsObj);
				}else{
					AvCode=1;
					if(shipTo.nextPage!==undefined){shipTo.nextPage.value=0;}
					if(shipTo.AvCode==undefined&&shipTo.AvDate==undefined&&upsObj.validated==1){ //already validated
						 addElement({'tag':'input','parent':shipTo,'attributes':[{'name':'type','value':'hidden'},
						 	{'name':'value','value':AvCode},{'name':'name','value':'AvCode'}]});
						 addElement({'tag':'input','parent':shipTo,'attributes':[{'name':'type','value':'hidden'},
						 	{'name':'value','value':today.getUTCFullYear()+"-"+month+"-"+today.getUTCDate()},
						 	{'name':'name','value':'AvDate'}]});
					}
					shipTo.submit();
				}
			}else{
				//errors
				//alert("Error Code:"+upsObj.error+"\nError Desc:"+upsObj.errorDesc);
				if(upsObj.error==2){AvCode=4;} //no candidates
				addElement({'tag':'input','parent':shipTo,'attributes':[{'name':'type','value':'hidden'},
						 	{'name':'value','value':AvCode},{'name':'name','value':'AvCode'}]});
				addElement({'tag':'input','parent':shipTo,'attributes':[{'name':'type','value':'hidden'},
						 	{'name':'value','value':today.getUTCFullYear()+"-"+month+"-"+today.getUTCDate()},
						 	{'name':'name','value':'AvDate'}]});
				if(shipTo.nextPage!==undefined){shipTo.nextPage.value=0;}
				shipTo.submit();
			}
	}});	
}

function showAddressSelector(upsObj){
	var html="",i=0,address;
	win = new Window({className: "pop", title: "", width:'630px', height:'485px', minWidth:450,minHeight:350, destroyOnClose: true, recenterAuto:false,showEffect:Element.show,hideEffect:Element.hide});	
	$(win.getId()+"_content").style.backgroundColor = "#dff4f9";
	setUpObserver(win,"avWin",95);
	if(document.shipToForm!== undefined){shipTo = document.shipToForm;}
	else{shipTo = document.addressBookForm;}
	html+= getReviewHeader(485-95);
	html+="<h1 class=\"faqMainQuestion faqWin\">Address Validation</h1>";
	html+="<p style=\"text-align:left;\">We're sorry - we were unable to validate the address you entered:</p>";
	html+="<p class=\"required\">"+shipTo.streetAddress.value+"<br />";
  if(shipTo.apt.value!=""){html+=shipTo.apt.value+"<br />";}
  html+=shipTo.city.value+", "+shipTo.state.value+" "+shipTo.zip.value+"</p>";
	html+="<p style=\"text-align:left;\">Please select one of the suggested addresses below and click the ";
	html+="\"Submit\" button. If you feel that the address above has been entered correctly, click the \"No,";
	html+=" please use the address I entered\" link below.</p>";
	html+="<form name=\"posAddrs\">";
	html+="<select style=\"width:100%;font-size:13pt;\" name=\"addrSelect\" size=\"8\" >";
	numAddrs=upsObj.Addresses.length;
	for(i=0;i<numAddrs;i++){
		address = upsObj.Addresses[i];
		html+="<option value=\""+i+"\">";
		html+=address.street+" ";
		if(address.apt!==undefined){html+=address.apt+" ";}
		html+=address.city+", "+address.state+" "+address.zip;
		html+="</option>";
	}
	html+="</select><br /><br />";
	html+="<input type=\"image\" src=\"/media/images/buttons/submit_button.gif\" value=\"submit\" name=\"submit\" onclick=\"pXAVchoice(1);return false;\">";
	html+="<a style=\"display:block;margin-top:10px;text-decoration:underline;\" href=\"/"+page+".php\" onclick=\"pXAVchoice(0);return false;\">No, please use the address I entered</a></form>";
	win.getContent().update(html); 
	win.showCenter();

}

function pXAVchoice(selected){
	var AvCode=2,today = new Date(),month =parseInt(today.getUTCMonth())+1,index,address;
	if(document.shipToForm!== undefined){shipTo = document.shipToForm;}
	else{shipTo = document.addressBookForm;}
	if(selected){	
		index = document.posAddrs.addrSelect.options[document.posAddrs.addrSelect.selectedIndex].value;
		address = upsObj.Addresses[index];
  	shipTo.streetAddress.value = address.street;
  	if(address.apt!== undefined){shipTo.apt.value = address.apt;}
  	else{shipTo.apt.value="";}
  	shipTo.city.value = address.city;
  	shipTo.zip.value = address.zip;
  	shipTo.state.value = address.state.toUpperCase();
  }else{AvCode=3;}
	addElement({'tag':'input','parent':shipTo,'attributes':[{'name':'type','value':'hidden'},
				{'name':'value','value':AvCode},{'name':'name','value':'AvCode'}]});
	addElement({'tag':'input','parent':shipTo,'attributes':[{'name':'type','value':'hidden'},
				{'name':'value','value':today.getUTCFullYear()+"-"+month+"-"+today.getUTCDate()},
				{'name':'name','value':'AvDate'}]});
	if(shipTo.nextPage!==undefined){shipTo.nextPage.value=0;}
  shipTo.submit();
}
function disableFutures(E){
	var element = Event.element(E),id=element.id,action=id.substring(0,3),number=id.substring(3,id.length),
	aybi,processText,winX=0,winY=0;
	if(action=="ayb"){
		aybl = document.getElementById(action+"l"+number);
		if(aybl!=undefined){
			aybl.style.visibility = 'hidden';
			if(aybl.parentNode.tagName=="TD"){
				processText = "<img src=\"/media/images/graphics/processing_w.gif\" id=\"prol"+number+"\"class=\"impc\" />";
			}else{
				processText = "<img src=\"/media/images/graphics/processing_ltb.gif\" id=\"prol"+number+"\"class=\"impc\" />";
			}
			if(Windows.focusedWindow && Windows.focusedWindow.id == "quickWin"){
				quickPos = Windows.focusedWindow.getLocation();
				winX = quickPos.left.toString().substring(0,quickPos.left.length-2)*1;
				winY = quickPos.top.toString().substring(0,quickPos.top.length-2)*1;
			}
			new Insertion.After(action+"l"+number,processText);
			pos = findPos(aybl);
			img = document.getElementById("prol"+number);
			img.style.position = "absolute";
			img.style.top = (pos[1]-winY+2)+'px';
			img.style.left = (pos[0]-winX-8)+'px';
			}
	}
}
function reinstateEvents(E,itemForm){
	var element = Event.element(E),id=element.id,action=id.substring(0,3),number=id.substring(3,id.length),
	aybi,formName,impc;
	if(itemForm!=""){	
		if(itemForm.name!="cartForm"){
			formName=itemForm.name.toString().replace("form","");
			aybl = document.getElementById(action+"l"+number);
			impc= document.getElementById("prol"+number);
		  if(impc!=undefined){impc.parentNode.removeChild(impc);}
		  aybl.style.visibility = "visible";
		}
	}
}