

/* Static JavaScript */
var productActive = 1;
/*
 *
 *	History		: 5/12/2009 3:18:42 PM - addPriceEffectsToCells add service and price variables to url query string for order now links
*/

// list of qtys, list of reg $, list of sale $  (comma separated lists)
function initPriceTable(prodID, qtys, reg, sale, serviceCode) {
	// IE on Mac can't handle this properly, so don't add any DHTML behaviors
	if(isIEOnMac()) { return; }
	
	if(!document.serviceCodes) { document.serviceCodes = new Array(); }
	document.serviceCodes[serviceCode] = serviceCode;
	
	if(!document.priceTableQtys) { document.priceTableQtys = new Array(); }
	document.priceTableQtys[serviceCode] = qtys.split(',');
	
	if(!document.priceTableReg) { document.priceTableReg = new Array(); }
	document.priceTableReg[serviceCode] = reg.split(',');
	
	if(!document.priceTableSale) { document.priceTableSale = new Array(); }
	document.priceTableSale[serviceCode] = sale.split(',');
		
	if(!document.priceTableClasses) { document.priceTableClasses = new Array(); }
	
	document.priceTableClasses[serviceCode] = new Array();
	document.priceTableClasses[serviceCode]['cellRegular'] = '';
	document.priceTableClasses[serviceCode]['cellHighlighted'] = 'priceTableHighlighted';
	document.priceTableClasses[serviceCode]['labelRegular'] = 'priceTableLabel';
	document.priceTableClasses[serviceCode]['labelHighlighted'] = 'priceTableLabelHighlighted';
	
	document.productID = prodID;
	
	// init the order now button with lowest qty and price for standard level
	if(document.serviceCodes[serviceCode] != '') {
		var orderNowServiceCode = document.serviceCodes[serviceCode];
		var orderNowPrice = 0;
		var orderNowQty = 0;
		var orderNowLink = "/";
		
		/* set low price */
		if(document.priceTableSale[orderNowServiceCode][0] != '') {
			orderNowPrice = document.priceTableSale[orderNowServiceCode][0];
		}
		else if (document.priceTableReg[orderNowServiceCode][0] != '') {
			orderNowPrice = document.priceTableReg[orderNowServiceCode][0];
		}
		else if (document.priceTableReg[orderNowServiceCode][1] != '') {
			orderNowPrice = document.priceTableReg[orderNowServiceCode][1];
		}
		else {
			orderNowPrice = 0;
		}
		
		/* set low qty */
		if(document.priceTableQtys[orderNowServiceCode][0] != '') {
			orderNowQty = document.priceTableQtys[orderNowServiceCode][0];
		}
		else {
			orderNowQty = 0;
		}
		
		orderNowLink = 'https://www.qualitylogoproducts.com/order/index.cfm?productID='+document.productID+'&quantity='+orderNowQty+'&service='+orderNowServiceCode+'&price='+orderNowPrice;
	
		if(document.getElementById('nextStepOrderNow')!==null) {
			document.getElementById('nextStepOrderNow').href = orderNowLink;
		}
	
		
	}
	
	applyPriceTableEffects(serviceCode);
	printInitialEstimatedPrice(serviceCode);
}


// Determine if the browser is Internet Explorer on the Mac
// based off of code found at:  http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
function isIEOnMac() {
	// convert all characters to lowercase to simplify testing
	if(navigator.userAgent) {
		var agt = navigator.userAgent.toLowerCase();
		var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
		var is_mac = (agt.indexOf("mac")!=-1);
	
		if(is_ie && is_mac) {
			return true;
		}
	}

	return false;
}


function getCellIndex(obj) {
	var row = obj.parentNode;
	var cells = row.getElementsByTagName('td');

	for(var i=0; i<cells.length; i++) {
		if(cells[i] == obj) {
			return i-1;
		}
	}
}

// Now set event handlers for the table cells
// onMouseOver(rIndex, cellIndex, highlight||restore, serviceCode)
// onMouseOut(rIndex, cellIndex, highlight||restore, serviceCode)

function applyPriceTableEffects(serviceCode) {
	if(!document.priceTableKeys) {
		document.priceTableKeys = new Array();
	}
	document.priceTableKeys[serviceCode] = new Array();
	
	if (document.getElementById) {
		var regCells = getPriceTableCells('r', serviceCode);
		var saleCells = new Array();
		
		if(document.priceTableSale[serviceCode].length > 0) {
			saleCells = getPriceTableCells('s', serviceCode);
		}
		
		addPriceEffectsToCells(saleCells, 's', serviceCode, 0);
		if (saleCells.length > 0) {
			addPriceEffectsToCells(regCells, 'r', serviceCode, 1);
		}
		else {
			addPriceEffectsToCells(regCells, 'r', serviceCode, 0);
		}
	}	
	return true;
}

function optionalSlide(serviceCode) {
	var estimatedPriceDiv = 'div#estimatedPrice_'+serviceCode;
	if ($(estimatedPriceDiv).is(":hidden")) { $(estimatedPriceDiv).slideDown("normal"); }
}

function optionalHide(serviceCode) {
	var estimatedPriceDiv = 'div#estimatedPrice_'+serviceCode;
	if ($(estimatedPriceDiv).not(":hidden")) { $(estimatedPriceDiv).hide("fast"); }
}

function addPriceEffectsToCells(cells, regSale, serviceCode, hasSale) {
	for(var i=0; i<cells.length; i++) {
		// Get current value of the cell
		var qtyText = cells[i].firstChild.nodeValue;
		var qtyTextSpan = '<span onmouseover="'+"tooltip.show('Get a Sample, Quote or Order.'"+')"; onmouseout="tooltip.hide();">'+qtyText+'</span>';
		var qty = document.priceTableQtys[serviceCode][i];
		var regPrice = document.priceTableReg[serviceCode][i];
		var salePrice = document.priceTableSale[serviceCode][i];
		var linkPrice = 0;
		var tdCount = i+1;
		var tdId = serviceCode+'_'+regSale+tdCount;
		var nextStepLink = '';
		
		if(salePrice=='') {
			linkPrice=regPrice;
		}
		else if(salePrice==null) {
			linkPrice=regPrice;
		}
		else {
			linkPrice=salePrice;
		}
		
			//Create a new link element
			var newLinkElement = document.createElement('a');
			if(serviceCode=="BLANK") {
				newLinkElement.setAttribute('href','https://www.qualitylogoproducts.com/order/index.cfm?productID=' + document.productID + '&quantity=' + qty + '&service=' + serviceCode + '&price=' + linkPrice);
				qtyTextSpan = '<span onmouseover="'+"tooltip.show('Click to Place an Order.'"+')"; onmouseout="tooltip.hide();">'+qtyText+'</span>';
			}
			else {
				nextStepLink = 'https://www.qualitylogoproducts.com/nextStep.cfm?productID=' + document.productID + '&quantity=' + qty + '&service=' + serviceCode + '&price=' + linkPrice;
			
				newLinkElement.setAttribute('href',nextStepLink);
				newLinkElement.setAttribute('onclick', "__utmSetVar('Product Price Table - Next Step')");
				
				/* macdougall - set nextStep on main image link */
				if(document.getElementById('lightbox-link') !== null) {
					/* make sure this url only gets set once to min qty */

					if(i == 0) {
						document.getElementById('fullPicLink').href = 'https://www.qualitylogoproducts.com/nextStep.cfm?productID=' + document.productID + '&quantity=' + qty + '&service=' + serviceCode + '&price=' + linkPrice;
					}
				}

							
			}
			newLinkElement.setAttribute('name','ptablelink_' + serviceCode + '_' + i);
			newLinkElement.setAttribute('id','price' + document.productID + '_' + qty);
			
			// Set the text to be linked
			newLinkElement.innerHTML = qtyTextSpan;

			// Clear the old table cell text and add the new Anchor to the cell
			cells[i].firstChild.nodeValue = '';
			cells[i].appendChild(newLinkElement);

		//alert('macdougall '+regSale);

		// Add a mouseover event to the new Anchor element
		if(regSale == 'r') {
			cells[i].onmouseover= function() { var obj = eval('this'); highlightRestore(obj, 'r', 'h', obj.id.split('_')[0], hasSale); }
			//cells[i].onmouseout= function() { var obj = eval('this'); highlightRestore(obj, 'r', 'r', obj.id.split('_')[0]); }
		} else {
			cells[i].onmouseover= function() { var obj = eval('this'); highlightRestore(obj, 's', 'h', obj.id.split('_')[0], hasSale); }
			//cells[i].onmouseout= function() { var obj = eval('this'); highlightRestore(obj,  's', 'r', obj.id.split('_')[0]); }
		}
	}
	
	if(nextStepLink != '') {
					
		//onclicklink = 'https://www.qualitylogoproducts.com/nextStep.cfm?productID=' + document.productID + '&quantity=' + qty + '&service=' + serviceCode + '&price=' + linkPrice;
			
		//document.getElementById('fullPicLink').setAttribute('onclick', 'window.open(onclicklink)');
	
	}
	
	return true;	
}


function getPriceTableHeader(index, serviceCode) {
	var cells = getPriceTableCellsWorker("THEAD", 0, 0, serviceCode);	
	return cells[index];
}

function getPriceTableCells(regSale, serviceCode) {
	if(regSale == 's') {
		return getPriceTableCellsWorker("TBODY", 1, 0, serviceCode);		
	} else {
		return getPriceTableCellsWorker("TBODY", 0, 0, serviceCode);
	}
}

function getPriceTableLabel(regSale, serviceCode) {
	if(regSale == 's') {
		return getPriceTableCellsWorker("TBODY", 1, 1, serviceCode);		
	} else {
		return getPriceTableCellsWorker("TBODY", 0, 1, serviceCode);
	}
}	

function getPriceTableCellsWorker(node, index, firstCell, serviceCode) {
	var tables=document.getElementsByTagName('table');
	var objs = new Array();
	var inParentNodeCounter = 0;
	var cellTag = 'td';
	
	if(node == 'THEAD') {
		cellTag = 'th';
	}
	
	for (var i=0;i<tables.length;i++) {
		if(tables[i].id.match(/priceTable+/i) && tables[i].id.split('_')[1] == serviceCode ) {
			var trs=tables[i].getElementsByTagName('tr');
			for(var j=0;j<trs.length;j++) {
				if(trs[j].parentNode.nodeName==node) {
					// This is the row we want to work with
					if(inParentNodeCounter == index) {
						// Get all the cells in this node, skip the first though
						var tds=trs[j].getElementsByTagName(cellTag);
						if(firstCell != 1) {
							for(var k=1; k<tds.length; k++) {
								objs[objs.length] = tds[k];
							}
							return objs;
						} else {
							return tds[0];
						}
						
					}
					
					inParentNodeCounter++;
				}
			}
		}
	}
	
	
	return objs;	
}


/* get qty from cookie and highlight that column of price table by default */
function highlightDefaultQty(serviceCode) {
	/* don't do anything if service code is BLANK */
		var defaultQtyIndex = -1;
		if(document.qtyCookie!==undefined) {
			if(document.qtyCookie.accept()) {
				defaultQtyIndex = parseInt(document.qtyCookie.get(),10);
			}
			if(defaultQtyIndex != -1) {
				var priceID = defaultQtyIndex+1;
				var regID = serviceCode+'_r'+priceID;
				var rObj = document.getElementById(regID);
				var saleID = serviceCode+"_s"+priceID;
				var sObj = document.getElementById(saleID);
				
				/* macdougall testing */
				/*
				if(sObj!==null) {
					var keys = [];
					for(var key in sObj){
						keys.push(key);
					}
					alert('macdougall '+key);
				}
				*/
				

				
				
				/* if price level still doesn't exist, don't bother highlighting */
				/* macdougall test removing if and 1st else if */
				/*
				if(sObj!==null && serviceCode!='BLANK') {
					highlightRestore(rObj, 's', 'h', serviceCode, 1);
				}
				else if(rObj!==null && serviceCode!='BLANK') {
					highlightRestore(rObj, 'r', 'h', serviceCode, 0);
				}
				*/
				if(sObj!==null) {
					highlightRestore(rObj, 's', 'h', serviceCode, 1);
				}
				else if(rObj!==null) {
					highlightRestore(rObj, 'r', 'h', serviceCode, 0);
				}
				else if (rObj!==null) {
					if (rObj.className!='priceTableHighlighted')   {
						if ($('div.estimatedPrice').not(":hidden")) { 
							$('div.estimatedPrice').hide();
						}
					}
				}
			}
			else {
				if ($('div.estimatedPrice').not(":hidden")) { 
					$('div.estimatedPrice').hide();
				}
			}
		}
}

function ltrim ( str, charlist ) {
    // Strip whitespace (or other characters) from the beginning of a string
    // http://kevin.vanzonneveld.net/code/php_equivalents/php.js
    charlist = !charlist ? ' \s\xA0' : (charlist+'').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    var re = new RegExp('^[' + charlist + ']+', 'g');
    return (str+'').replace(re, '');
}


function highlightRestore(obj, regSale, highlightRestore, serviceCode, hasSale) {
		//alert('macdougall highlight restore');
		var cellIndex = getCellIndex(obj);
		var priceID = cellIndex+1;
		var regID = serviceCode+'_r'+priceID;
		var saleID = serviceCode+"_s"+priceID;
		var cObj = obj;
		var rObj = document.getElementById(regID);
		var sObj = document.getElementById(saleID);
		var lObj = getPriceTableLabel(regSale, serviceCode);
		var hObj = getPriceTableHeader(cellIndex, serviceCode);
		var aObj = cObj.getElementsByTagName('a')[0];
		var aRegObj = rObj.getElementsByTagName('a')[0];
		/* check if sale object is null, if so don't check sale stuff */
		if(sObj!==null) {
			var aSaleObj = sObj.getElementsByTagName('a')[0];
		}
		var price = 0;
		var qty = document.priceTableQtys[serviceCode][cellIndex];
		var savingsDollar = 0;
		var savingsPercent = 0;
		var setup = parseInt(ltrim(document.getElementById('productSetupCharge').innerHTML, '$'),10);
		var estimatedPriceDiv = 'div#estimatedPrice_'+serviceCode;
	

		if(regSale == 's') {
			price = document.priceTableSale[serviceCode][cellIndex];
			savingsDollar = (document.priceTableReg[serviceCode][cellIndex]-document.priceTableSale[serviceCode][cellIndex])*qty;
			savingsPercent = 100-((document.priceTableSale[serviceCode][cellIndex]/document.priceTableReg[serviceCode][cellIndex])*100);
		} 
		else if (regSale == 'r'){
			if(hasSale==0) {
				price = document.priceTableReg[serviceCode][cellIndex];
			}
			else {
				price = document.priceTableSale[serviceCode][cellIndex];
				savingsDollar = (document.priceTableReg[serviceCode][cellIndex]-document.priceTableSale[serviceCode][cellIndex])*qty;
				savingsPercent = 100-((document.priceTableSale[serviceCode][cellIndex]/document.priceTableReg[serviceCode][cellIndex])*100);
			}
		}
		else {
			price = document.priceTableReg[serviceCode][cellIndex];
		}
		
		//alert('regsale: '+regSale+' has sale: '+hasSale+' price: '+price+'savings: '+savingsDollar+' percent: '+savingsPercent);
		
		if(cellIndex == document.priceTableQtys[serviceCode].length-1) {
			if(isNaN(price)) {
				qty = 'Call';
			}
		}
		
		/* unhighlight everything by default when there's a new mouseover so we can leave things sticky	*/
		if (document.getElementById) {
			var regCells = getPriceTableCells('r', serviceCode);
			var saleCells = new Array();
			
			if(document.priceTableSale[serviceCode].length > 0) {
				saleCells = getPriceTableCells('s', serviceCode);
				for(var i=0; i<saleCells.length; i++) {
					saleCells[i].className = '';
					saleCells[i].getElementsByTagName('a')[0].className = '';
				}
			}
			for(var i=0; i<regCells.length; i++) {
				regCells[i].className = '';
				regCells[i].getElementsByTagName('a')[0].className = '';
				getPriceTableHeader(i, serviceCode).className = '';
			}
		}
		
		if(highlightRestore == 'h') {
			//alert('macdougall highlight');
			cObj.className = 'priceTableHighlighted';
			if(sObj!==null) {
				sObj.className = 'priceTableHighlighted';
				aSaleObj.className = 'priceTableHighlighted';
			}
			else {
				rObj.className = 'priceTableHighlighted';
				aRegObj.className = 'priceTableHighlighted';
			}
			lObj.className = 'priceTableLabelHighlighted';
			hObj.className = 'priceTableHighlighted';
			aObj.className = 'priceTableHighlighted';
			if ($(estimatedPriceDiv).is(":hidden")) { 
				//alert('macdougall slideDown');
				$(estimatedPriceDiv).slideDown("normal"); 
			}
			setEstimatedPrice(qty, price, serviceCode, savingsDollar, savingsPercent, setup);
			saveSelectedQty(cellIndex);		
		} else {
			cObj.className = '';
			rObj.className = '';
			if(sObj!==null) {
				sObj.className = '';
				aSaleObj.className = '';
			}
			lObj.className = '';
			hObj.className = '';
			aObj.className = '';
			aRegObj.className = '';
			setEstimatedPrice('', '', serviceCode, savingsDollar, savingsPercent, setup);
		}
}

// 02/09 add savings variable to show amount saved from regular price if sale price selected
// 02/17 add setup variable to pass setup charge
function setEstimatedPrice(quantity, price, serviceCode, savingsDollar, savingsPercent, setup) {
	var content = document.getElementById('estimatedPrice_' + serviceCode);
	var setupCharge = '';
	var totalCharge = 0;
	
	//alert('qty: '+quantity+'price: '+price+'service: '+serviceCode+'savings: '+savingsDollar+'percent: '+savingsPercent+'setup: '+setup);
	
	if(!isNaN(quantity) && !isNaN(price) && quantity != '' && price != '') { 
		if (isNaN(setup) || serviceCode=='BLANK') {
			totalCharge = quantity*price;
		}
		else {
			setupCharge = setup;
			totalCharge = quantity*price+setup;
		} 
		var str = formatCurrency(quantity * price);
		if(setupCharge != '' && serviceCode != 'BLANK') { 
			str += ' <span class="estimatedPriceSmall">+</span> ' + formatCurrency(setupCharge) + ' <span class="estimatedPriceSmall">Setup =</span> ' + formatCurrency(totalCharge) + '*';
		}
		else if (isNaN(setup) || serviceCode=='BLANK') {
			str += ' <span class="estimatedPriceSmall">+ Free Setup =</span> ' + formatCurrency(totalCharge) + '*';
		}
/*
		if(serviceCode.toUpperCase() == 'BLANK') {
			str += ' </strong>';
		} else {
			str += ' + </strong> Setup Charge';			
		}
	*/
		if(!isNaN(savingsDollar) && savingsDollar > 0) {
			str += ' <span class="estimatedPriceSavings">You Save '+formatCurrency(savingsDollar)+' ('+savingsPercent.toFixed(0)+'%)</span>';
		}
		
		content.innerHTML = str;
	} else if (quantity == 'Call') {
		content.innerHTML = '<strong>Call</strong>';
	} else {
		content.innerHTML = '&nbsp;<br>';
	}
}


function printInitialEstimatedPrice(serviceCode) {
	var content = document.getElementById('estimatedPrice_' + serviceCode);
	content.innerHTML = '&nbsp;<br>';
	// don't display any default content for new pricing table format
	/*
	if(serviceCode.toUpperCase() == 'BLANK') {
		content.innerHTML = '<strong>Total: $0.00 </strong><br>&nbsp;';
	} else {
		content.innerHTML = '<strong>Total: $0.00 + </strong> Setup Charge<br>&nbsp;';
	}
	*/
}
	
	
	
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	// don't return cents for new pricing table formatting
	//return (((sign)?'':'-') + '$' + num + '.' + cents);
	return (((sign)?'':'-') + '$' + num);
}	


function toggleTabs(tab) {
	//padding: 5px; margin-top: 5px; width: 540px; text-align: left;
	var dTab = document.getElementById('tabDetailsContent');
	var dTabTab = document.getElementById('tabDetails');
	var dTabLink = document.getElementById('tabDetailsLink');
	
	var sTab = document.getElementById('tabSpecsContent');
	var sTabTab = document.getElementById('tabSpecs');
	var sTabLink = document.getElementById('tabSpecsLink');
	
	var rTab = document.getElementById('tabReviewContent');
	var rTabTab = document.getElementById('tabReview');
	var rTabLink = document.getElementById('tabReviewLink');
		
	if(tab == 'Details') {
		dTab.style.height = null;
		dTab.style.display = 'b' + 'l' + 'oc' + 'k';
		dTabTab.className = 'tabbedHighlighted';
		dTabLink.className = 'tabbedLinkHighlighted';
		
		sTab.style.display = 'n' + 'on' + 'e';
		sTabTab.className = 'tabbedNormal';
		sTabLink.className = 'tabbedLink';
		
		rTab.style.display = 'n' + 'on' + 'e';
		rTabTab.className = 'tabbedNormal';
		rTabLink.className = 'tabbedLink';
	}
	if(tab == 'Specs') {
		sTab.style.height = null;
		sTab.style.display = 'b' + 'l' + 'oc' + 'k';
		sTabTab.className = 'tabbedHighlighted';
		sTabLink.className = 'tabbedLinkHighlighted';		
		
		dTab.style.display = 'n' + 'on' + 'e';
		dTabTab.className = 'tabbedNormal';
		dTabLink.className = 'tabbedLink';
		
		rTab.style.display = 'n' + 'on' + 'e';
		rTabTab.className = 'tabbedNormal';
		rTabLink.className = 'tabbedLink';		
	}
	if(tab == 'Review') {
		rTab.style.height = null;
		rTab.style.display = 'b' + 'l' + 'oc' + 'k';
		rTabTab.className = 'tabbedHighlighted';
		rTabLink.className = 'tabbedLinkHighlighted';		
		
		sTab.style.display = 'n' + 'on' + 'e';
		sTabTab.className = 'tabbedNormal';
		sTabLink.className = 'tabbedLink';		
		
		dTab.style.display = 'n' + 'on' + 'e';
		dTabTab.className = 'tabbedNormal';
		dTabLink.className = 'tabbedLink';		
	}		
}


function my_openBrWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}	


function addBookmark(title, url) {
	if( document.all ) {
		window.external.AddFavorite( url, title);		
	} else if( window.sidebar ) {
		window.sidebar.addPanel(title, url,"");
	} else if( window.opera && window.print ) {
		return true;
	}
}

/*
	SACK FUNCTIONS
	Assumes document.ajax object will already exist and be initialized
*/
function whenLoading(){
	var e = document.getElementById('showingReviews'); 
	e.innerHTML = "Retrieving ALL Product Reviews....";
}

function whenCompleted(ajax){
	var e = document.getElementById('prodReviews'); 
	e.innerHTML = ajax.response;
	
	e = document.getElementById('showingReviews');
	e.innerHTML = 'Showing all reviews';
	
	var anchor = document.getReviewsAnchor;
	anchor.firstChild.nodeValue = '';
}

function getAllProductReviews(anchor, productID) {
	document.getReviewsAnchor = anchor;
	
	var ajax = new sack();
	ajax.requestFile = "/product-reviews/getReviewsForProduct.cfm";
	ajax.setVar("ID", productID);
	//ajax.element = 'prodReviews';
	ajax.onLoading = whenLoading;
	ajax.onCompletion = whenCompleted;
	ajax.runAJAX();
}



/*
	SACK FUNCTIONS --- PRICE TABLE
	Assumes document.ajax object will already exist and be initialized
*/


function getPriceTable(productID, serviceCode) {
	ajax = new sack();
	ajax.requestFile = "/scheduled/writeCatalog/priceTable.cfm";
	ajax.setVar("ID", productID);
	ajax.setVar("serviceCode", serviceCode);
	ajax.setVar("divID", 'tabContent' + serviceCode);
	ajax.onLoading = whenLoadingPriceTable;
	ajax.onCompletion = whenCompletedPriceTable;
	ajax.runAJAX();
}




function useLinkHistory(hrefObj, ID) {
	document.location= '/backTo.cfm?ID=' + ID + '&type=category&url=' + hrefObj.href;
	return false;
}



function updateLiveSupportLink() {
	var lo = document.getElementById('actionSupport');
	var button = '';
	var message = 'Product - Live Web Chat';
	
	if(document.getElementById('nextStepLiveHelp')!==null) {
		button = document.getElementById('nextStepLiveHelp');
	}
	
	if(document.liveSupport.isAvailable()) {
		lo.style.display = 'block';
		lo.innerHTML = '<a href="#" onclick="document.liveSupport.setInUse(true); psaGxJow(); __utmSetVar('+"'Product - Live Web Chat'"+');" >Live Web Chat</a>';
		if(button.attributes!==null && button.attributes!==undefined) {
			button.attributes.getNamedItem("href").value = '#';	
		}	
	}
	else {
		if(button.attributes!==null && button.attributes!==undefined) {
			button.className = "nextStepLiveHelpButton";
			button.attributes.getNamedItem("onclick").value = '';
		}
	}
}


// ------------------------------------------------------------

// regClass -> hoverClass mapping
var tabClassMap = new Array();
/* turnoff javascript mouseovers for tabs, doesn't work well, should use css sprites */
/*
tabClassMap["nsl"] = "nslHover";
tabClassMap["nsc"] = "nscHover";
tabClassMap["nsr"] = "nsrHover";
tabClassMap["l:nss"] = "nssHoverR";
tabClassMap["r:nss"] = "nssHoverL";
tabClassMap["r:sls"] = "slsHover";
tabClassMap["l:srs"] = "srsHover";
tabClassMap["l:nsl"] = "nslHover";
tabClassMap["r:nsr"] = "nsrHover";
*/
// -------------------------------------------
tabClassMap["nsl"] = "nsl";
tabClassMap["nsc"] = "nsc";
tabClassMap["nsr"] = "nsr";
tabClassMap["l:nss"] = "nss";
tabClassMap["r:nss"] = "nss";
tabClassMap["r:sls"] = "sls";
tabClassMap["l:srs"] = "srs";
tabClassMap["l:nsl"] = "nsl";
tabClassMap["r:nsr"] = "nsr";
// nonSelectedClass -> selectedClass mapping
var tabSelectClassMap = new Array();
tabSelectClassMap["nsl"] = "sl";
tabSelectClassMap["nsc"] = "sc";
tabSelectClassMap["nsr"] = "sr";
tabSelectClassMap["l:nss"] = "sls";
tabSelectClassMap["r:nss"] = "srs";

// Name of the class that will be applied to the
// currently selected anchor element
var tabSelectedClassName = "sc";


/**
 * Make the specied anchor/tab the currently selected tab
 * (therefore make the currently selected tab look like the other non-selected tabs)
 *
 * @param a		The anchor/tab to make the "Selected Tab"
 * @return		void
 */
function tabSelect(a) {
	// find the currently selected anchor element (sibling to the specified 'a')
	var sa = null;
	var anchors = new Array();
	var nodes = a.parentNode.childNodes;

	for(var i=0; i<nodes.length; i++) {
		var node = nodes[i];
		if(node.nodeName == 'A') {
			anchors.push(node);	
		}
	}
	
	for(var i=0; i<anchors.length; i++) {
		var ca = anchors[i];
		var currClasses = ca.className.split(' '); //Element.classNames(ca).toArray();
		
		for(var ii=0; ii<currClasses.length; ii++) {
			if(currClasses[ii] == tabSelectedClassName) {
				sa = ca;
				break;
			}
		}
	}
	
	
	// first, remove the HOVER effects from the current anchor node
	// this allows us to do accurate classMap matching (no hover variants)
	tabOverOut(a);
	
	
	// replace the selected classes found with the respective non-selected class
	tabToggleClasses(sa, '', tabSelectClassMap);
	tabToggleClasses(getPrevSiblingByTag(sa, 'SPAN'), 'l', tabSelectClassMap);
	tabToggleClasses(getNextSiblingByTag(sa, 'SPAN'), 'r', tabSelectClassMap);

	
	// apply the selectedClasses to the specified anchor element
	// and it's sibling SPAN tags
	tabToggleClasses(a, '', tabSelectClassMap);
	tabToggleClasses(getPrevSiblingByTag(a, 'SPAN'), 'l', tabSelectClassMap);
	tabToggleClasses(getNextSiblingByTag(a, 'SPAN'), 'r', tabSelectClassMap);
	
	
	// Now make sure only the current anchor's associated content is shown
	tabToggleContent(a.id + 'Content');
}


/**
 * Hide the content for all tabs except the currently selected tab
 * 
 * @param selContentID	The text ID of the content that should be
 *						currently shown
 * @return				void
 */
function tabToggleContent(selContentID) {
	var elements = document.getElementById(selContentID).parentNode.childNodes;

	for (var i=0; i<elements.length; i++) {
		var e = elements[i];

		if(e.nodeName == 'DIV') {
			e.style.height = null;
			
			if(e.id == selContentID) {
				e.style.display = 'b' + 'l' + 'oc' + 'k';			
			} else {
				e.style.display = 'n' + 'on' + 'e';	
			}
		}
	}
}


/**
 * Toggle an anchor element and it's sibling span elements when the
 * anchor is moused-over so that we get a rollover effect.
 *
 * @param a		The anchor element that's being moused over/out
 * @return		void
 */
function tabOverOut(a) {
	try {
	tabToggleClasses(a, '', tabClassMap);
	tabToggleClasses(getPrevSiblingByTag(a, 'SPAN'), 'l', tabClassMap);
	tabToggleClasses(getNextSiblingByTag(a, 'SPAN'), 'r', tabClassMap);
	
	} catch(err) {
		//alert('error: ' + a);	
	}
}


/**
 * Search for any of the mapped classes to see if we need
 * to swap one class for another according to the map
 *
 * @param e		Element to swap classes on
 * @param lr	If we're looking for a class that has a variant specific to the
 *				left / right orientation of the element
 * @param classMap	The class mapping to use when doing matches
 * @return		void
 */
function tabToggleClasses(e, lr, classMap) {
	if(e == null) {
		return;	
	}

	var keyPrefix = '';
	if(lr.length > 0) {
		keyPrefix = lr.toLowerCase() + ':';	
	}
	
	
	// search for CURRENT classes by key and value
	var currClasses = e.className.split(' '); // Element.classNames(e).toArray();
	
	for(var i=0; i<currClasses.length; i++) {
		var currClass = currClasses[i];
		var modCurrClass = keyPrefix + currClass;
		
		for(var mapKey in classMap) {
			var mapVal = classMap[mapKey];
			var modMapKey = mapKey;
			if(mapKey.indexOf(':') < 0) {
				modMapKey = keyPrefix + modMapKey;
			}
			
			if(modMapKey == modCurrClass || modMapKey == currClass) {
				tabToggleClass(e, tabCleanClass(mapKey), mapVal);	
				break;
			} else if(mapVal != null && mapVal == currClass) {
				tabToggleClass(e, mapVal, tabCleanClass(mapKey));			
				break;
			}
		}
	}
}


/**
 * Search and replace classes on an element
 *
 * @param e		The element to perform the class swap on
 * @param searchClass	The class that should be removed and replaced with
 *						the 'replaceClass' parameter's value
 * @param replaceClass	The class that should be added to the elements list
 *						of classes
 * @return		void
*/
function tabToggleClass(e, searchClass, replaceClass) {
	//Element.removeClassName(e, searchClass);
	//Element.addClassName(e, replaceClass);
	jQuery(e).removeClass(searchClass);
	jQuery(e).addClass(replaceClass);
}


/**
 * Get the first sibling element (relative to the specified element) that
 * matches given tag type. (looks to the left/previous siblings)
 *
 * @param e		The element to start searching at
 * @param tag	The name / type of the tag we're searching for
 * @return		A reference to the found sibling node. Could be null if
 *				no match is found.
 *
 */
function getPrevSiblingByTag(e, tag) {
	var s = e.previousSibling;
	tag = tag.toUpperCase();
	
	while(s != null) {
		if(s.nodeName.toUpperCase() == tag) {
			return s;
		}
		
		s = s.previousSibling;
	}
	
	return null;
}


/**
 * Get the first sibling element (relative to the specified element) that
 * matches given tag type. (looks to the right/next siblings)
 *
 * @param e		The element to start searching at
 * @param tag	The name / type of the tag we're searching for
 * @return		A reference to the found sibling node. Could be null if
 *				no match is found.
 *
 */
function getNextSiblingByTag(e, tag) {
	var s = e.nextSibling;
	tag = tag.toUpperCase();
	
	while(s != null) {
		if(s.nodeName.toUpperCase() == tag) {
			return s;
		}
		
		s = s.nextSibling;
	}
	
	return null;
}


/**
 * Strip out any special prefixes used in class mappings from
 * the provided string. This way, just a bare class is left.
 *
 * @param s		The string to clean/strip of prefixes
 * @return		A string with any special prefixes removed
 *
 */
function tabCleanClass(s) {
	return s.replace(/([^:]+\:)/gi, '');
}



/**
 * Get the price table for a particular service and
 * place it within the content DIV for the specified service
 *
 * @param a				The anchor that was clicked on
 * @param serviceCode	The service code we want the prices for
 * @param productID		The numeric ID of the product we want pricing for
 * @return 				void
 */
function tabGetPriceTable(serviceCode) {
	var e = document.getElementById("tab" + serviceCode + "Content");
	var a = document.getElementById("tab" + serviceCode);

	if(e.innerHTML == '') {
		// get HTML via AJAX		
		var ajax = new sack();
		ajax.requestFile = "/catalog/priceTable.cfm";
		ajax.setVar("ID", document.productID);
		ajax.setVar("serviceCode", serviceCode);
		ajax.setVar("divID", e.id);
		ajax.onLoading = function(ajax) {
			var e = document.getElementById(ajax.getVar("divID")); 
			e.innerHTML = "<p>Retrieving Pricing....</p>";		
		}
		ajax.onCompletion = function(ajax) {
			eval(ajax.response);			
		}
		ajax.runAJAX();
	}
	
	tabSelect(a);	
}



/* Apply tab hover hover sytles and set initial tab */
function applyTabBehaviors() {
	tabToggleContent('tabDetailsContent');
	if (productActive==1) {
		tabToggleContent('tabSTANDARDContent');
	}

	jQuery("table.tabTable thead tr th a").mouseover(
		function() {
			tabOverOut(jQuery(this).get(0));
		}
	).mouseout(
		function() {
			tabOverOut(jQuery(this).get(0));
		}
	).click(
		function() {
			tabSelect(jQuery(this).get(0));
			return false;
		}
	)		
}



/* Apply product highlighting / hover sytles */
function applyProductHoverBehaviors() {
	 jQuery("#products td.similarProducts").mouseover(
	 	function() {
	 		jQuery(this).addClass("prodContainerHover");
		}
	 ).mouseout(
	 	function() {
			jQuery(this).removeClass("prodContainerHover");
		}
	 ).click(
	 	function() {
			// For some reason jQuery only accurately finds the anchor if I use the ":first" selector
			var a = jQuery(this).find("a:first");
			var href = a.attr('href');

			// Now redirec to the product page
	 		document.location.href = href; 
	 	}
	);
}

function updateServiceCode(serviceCode) {
	tabGetPriceTable(serviceCode);
	updateCalendarServiceCode(serviceCode);
	
	var e = document.getElementById('calProdTime');
	var opts = e.options;
	
	for(var i=0; i<opts.length; i++) {
		if(opts[i].value == serviceCode) {
			e.selectedIndex = i;
			break;
		}
	}
}


/**
 * Take care of making an actual call to UPS to get the transit information
 * or calling a method to guess if a selected ship date is outside the date
 * range that UPS will provide live transit info for
 */
function getUPSServices(shipDate) {
	var zip = document.calZipCode;
	var calUtils = document.calUtils;

	if(zip.length == 0) {
		return new Array();	
	}

	// If the shipDate is 60 days or more AFTER today, then
	// we need to GUESS the transit info, otherwise use the
	// live values.
	var diff = calUtils.dateDiff(
							calUtils.dateTimeToDate(new Date()),
							calUtils.dateTimeToDate(shipDate)
				);

	// What should be done when the services are found
	var onComplete = function(svcs) {
		updateUPSDates(svcs);	
	}


	if(parseInt(diff.totalDays) < 60) {
		// do regular get live services
		getLiveUPSServices(shipDate, onComplete);
	} else {
		// pass control to guess UPSServices
		guessUPSServiceData(shipDate, onComplete);
	}
}


/**
 * Cache all UPS calls so that we don't have to hit
 * UPS more than we need to. The cache data structure is
 * a nested hashmap, DataStruct[date][zipcode] = Services[]
 */
function getLiveUPSServices(shipDate, onComplete) {
	var dt = shipDate.valueOf();
	var zip = document.calZipCode;
	
	if(zip.length == 0) {
		return new Array();	
	}

	if(!document.upsData) {
		document.upsData = new Array();
	}
	
	if(!document.upsData[dt]) {
		document.upsData[dt] = new Array();
	}

	if(!document.upsData[dt][zip]) {
		// get data via AJAX		
		var ajax = new sack();
		ajax.requestFile = "/catalog/upsTransit.cfm";
		ajax.setVar("pickupDate", document.calUtils.getUniversalDateFormat(shipDate));
		ajax.setVar("destZip", zip);
		ajax.setVar("productID", document.productID);
		ajax.onCompletion = function(ajax) {
			var myObj = eval('(' + ajax.response + ')');	
			if(myObj.services) {
				document.upsData[dt][zip] = myObj.services;
				onComplete(document.upsData[dt][zip]);
			}
		}

		ajax.runAJAX(); 			
	
	} else {
		onComplete(document.upsData[dt][zip]);
	
	}
	
	
}


/*
	If the selected shipdate is 60 days or greater from today, UPS won't
	give us back shipping esitmations. So in order to provide shipping dates
	for 60 days (or greater) from today, we need to guess which services
	are available in an area, and the amount of time it would take a package to
	get there. Err on the side of caution. We will actually have to hit UPS
	to see which services are available in an area, as depending on the ship from
	and ship to zip codes, certain services aren't available.
	
	The information stored for the guestimate for each UPS service will be:
	zip -> [ {code, arrivalDate, service, ***shippingDays***}, {} ]
	
	The data structure to re-create is:
	zip -> [ {code, arrivalDate, service}, {} ], arrivalDate will be updated each time based on shippingDays
	
	@returns UPS services object
*/
function guessUPSServiceData(shipDate, onComplete) {
	var zip = document.calZipCode;
	var calUtils = document.calUtils;
	var gServices = null;
	var modShipDate = calUtils.dateTimeToDate(calUtils.getNextBusinessDay(new Date()));

	// Initialize the "guess" data structure if it hasn't been initialized
	if(!document.upsServicesGuess) {
		document.upsServicesGuess = new Array();
	}


	// Update onComplete to do some additional stuff so we don't have to repeat ourselves
	var updOnComplete = function(svcs) {
		var gServices = svcs;

		// Now add however many shipping days to the current date
		// for each UPS service 
		for(var i=0; i<gServices.length; i++) {
			gServices[i].arrivalDate = calUtils.addShippingDays(new Date(shipDate.getTime()), gServices[i]['shippingDays']);
		}

		onComplete(gServices);
	}


	// Closure to be called when the live services receives the service data back
	var liveServicesOnComplete = function(svcs) {
		var gServices = svcs;
		
		// Copy original arrival date and add new key "shippingDays" to make doing guessses easier.
		// This way we can re-use the guess services data structure over and over for different shipping
		// dates
		for(var i=0; i<gServices.length; i++) {
			gServices[i]['origArrivalDate'] = gServices[i]['arrivalDate'];
			gServices[i]['shippingDays'] = calUtils.countShippingDays(
																modShipDate,
																calUtils.dateTimeToDate(new Date(gServices[i]['origArrivalDate']))
											  );
		}

		document.upsServicesGuess[zip] = gServices;		

		updOnComplete(gServices);
	}


	// Get the services using the next business day as the ship date to see which services are available
	if(!document.upsServicesGuess[zip]) {
		gServices = getLiveUPSServices(modShipDate, liveServicesOnComplete);		
		

	} else {
		gServices = document.upsServicesGuess[zip];

		updOnComplete(gServices);
	}
	

}


function createRadioElement(id, name, value, checked) {
    var radioHtml = '<input type="radio" id="' + id + '" name="' + name + '" value="' + value + '"';
    if ( checked ) {
        radioHtml += ' checked="checked"';
    }
    radioHtml += '/>';


    return radioHtml;
}


function updateUPSDates(services) {
	var calStack = new Array();
	calStack.push(calOne);
	calStack.push(calTwo);
	calStack.push(calThree);

	var badZip = true; 

	for(var usi=0; usi < document.upsServices.length; usi++) {
		var lObj = document.getElementById('ups' + document.upsServices[usi]);
		lObj.innerHTML = 'Not Available';

		/* check if this is being called from order form where shippingMethod-1 field exists */
		/* disable selection of not avail shipping opts */
		if(document.getElementById('shippingMethod-1') !== null) {
			if(document.upsServices[usi]=='GND') {
				document.getElementById('shippingMethod-1').disabled = true;
			}
			else if(document.upsServices[usi]=='3DS') {
				document.getElementById('shippingMethod-2').disabled = true;
			}
			else if(document.upsServices[usi]=='2DA') {
				document.getElementById('shippingMethod-3').disabled = true;
			}
			else if(document.upsServices[usi]=='1DA') {
				document.getElementById('shippingMethod-4').disabled = true;
			}
 		}
	}


	for(var i=0; i<calStack.length; i++) {
		var cal = calStack[i];

		for(var si=0; si < services.length; si++) {
			var svc = services[si];
			var svcDate = new Date(svc.arrivalDate);
			if(document.calUtils.isInSameMonthYear(cal.getTheDate(), svcDate)) {
				dayObj = cal.getDayObj(svcDate.getDate());
				if(dayObj != null) {
					dayObj.className='calUps' + svc.code;
					dayObj.innerHTML = '<a href="#" title="' + svc.service + '" id="' + document.calUtils.buildDayObjIdFromDate(svcDate) + '" onClick="updateOrderDate(this.id); return false;" >' + svcDate.getDate() + '</a>';
				}
				else {
					/* reenable valid shipping selections */
					if(document.getElementById('shippingMethod-1') !== null) {
						if(svc.code == 'GND') {
							document.getElementById('shippingMethod-1').disabled = false;
							badZip = false;
						}
						else if(svc.code == '3DS') {
							document.getElementById('shippingMethod-2').disabled = false;
							badZip = false;
						}
						else if(svc.code == '2DA') {
							document.getElementById('shippingMethod-3').disabled = false;
							badZip = false;
						}
						else if(svc.code == '1DA') {
							document.getElementById('shippingMethod-4').disabled = false;
							badZip = false;
						}
					}
				}						
				document.getElementById('ups' + svc.code).innerHTML = document.calUtils.getSimpleDateFormat(svcDate);	
			}
		}
	}
	
		
	if(document.getElementById('shippingMethod-1') !== null) {
			/* if all are disabled add element and set to UNKNOWN, uncheck any other options */
			if(badZip) {
				document.getElementById('shippingMethod-1').checked = false;
				document.getElementById('shippingMethod-2').checked = false;
				document.getElementById('shippingMethod-3').checked = false;
				document.getElementById('shippingMethod-4').checked = false;
				
				var shippingNoteContent = '<label for="shippingMethod-5" class="inlineLabel shippingLabel"><input name="shippingMethod" id="shippingMethod-5" value="UNKNOWN" type="radio" class=" required" checked="checked" />An error occurred and we\'re unable to calculate delivery. Customer service will contact you to discuss delivery options.</label>';
				
				tabBody=document.getElementById('calLegendDeliveryTableBody');
				row=document.createElement("tr");
				cell1 = document.createElement("td");
				cell1.setAttribute('id','shippingNote');
				cell1.setAttribute('class','calCaptShipping');
				cell1.setAttribute('colspan','2');
				//textnode1=document.createTextNode(shippingNoteContent);
				//cell1.appendChild(textnode1);
				row.appendChild(cell1);
				tabBody.appendChild(row);
				document.getElementById('shippingNote').colSpan='2';
				
				document.getElementById('shippingNote').innerHTML = shippingNoteContent;
				document.getElementById('upsGND').innerHTML = 'Invalid Zip Code';
				document.getElementById('ups1DA').innerHTML = 'Invalid Zip Code';
				document.getElementById('ups2DA').innerHTML = 'Invalid Zip Code';
				document.getElementById('ups3DS').innerHTML = 'Invalid Zip Code';
			}
			else {
				if(document.getElementById('shippingNote') !== null) {
					document.getElementById('shippingNote').innerHTML = '';
				}
			}
	}		
				
		
}


// @param startMonth	Date object that determines the month/year of the left-most calendar.
//						It will NOT update the calendar if the month/year of the date passed in is less than the current month/year
function setCalendars(startMonth) {
	var today = new Date();
	var tmpStartMonth = new Date(startMonth.getFullYear(), startMonth.getMonth(), 1);
	
	if(document.calUtils.isInPast(tmpStartMonth)) {
		return false;
	}
	
	var firstMonth = new Date(startMonth.getFullYear(), startMonth.getMonth(), 1);
	var secondMonth = document.calUtils.copyDate(firstMonth);
	secondMonth.setMonth(firstMonth.getMonth() + 1);
	var thirdMonth = document.calUtils.copyDate(secondMonth);
	thirdMonth.setMonth(secondMonth.getMonth() + 1);

	calOne = new BasicCalendar('calOne', firstMonth, 'calMain', 'calDayName', 'calDayNum');				
	calTwo = new BasicCalendar('calTwo', secondMonth, 'calMain', 'calDayName', 'calDayNum');					
	calThree = new BasicCalendar('calThree', thirdMonth, 'calMain', 'calDayName', 'calDayNum');						
	
	document.calOne = calOne;
	document.calTwo = calTwo;
	document.calThree = calThree;

	document.calStartDate = startMonth;

	return true;
}


function updateCalendars() {
	var serviceCode = document.calServiceCode;
	
	var calOne = document.calOne;
	var calTwo = document.calTwo;
	var calThree = document.calThree;
	
	var showCalendars = false;
	var content = '';
	var calStack = new Array();

	var calUtils = document.calUtils;

	var today = new Date();
	var orderDate = document.calOrderDate;

	// make sure order date is on a business day
	if(document.calUtils.isDayOff(orderDate)) {
		orderDate = calUtils.addBusinessDays(orderDate, 1); 	
	}
	
	var prodTime = document.serviceSchedules[serviceCode]['prodTimeDays'];
	var shipDate = calUtils.addBusinessDays(orderDate, parseInt(prodTime) + parseInt(1));
	document.calShipDate = shipDate;
	
	document.getElementById('calOrderDate').innerHTML = calUtils.getSimpleDateFormat(orderDate);
	document.getElementById('calProdTimeLgnd').innerHTML = prodTime + ' Days';
	document.getElementById('calShipDate').innerHTML = calUtils.getSimpleDateFormat(shipDate);
	
	
	calStack.push(calOne);
	calStack.push(calTwo);
	calStack.push(calThree);

	if(serviceCode.toUpperCase() == 'BLANK') {
		return;
	}

	/*
	if(serviceCode.toUpperCase() != 'BLANK') {
		if(calOne.getFullYear() == shipDate.getFullYear() && calOne.getMonth() == shipDate.getMonth()) {
			calStack.push(calOne);
		} else if(calTwo.getFullYear() == shipDate.getFullYear() && calTwo.getMonth() == shipDate.getMonth()) {
			calStack.push(calOne);
			calStack.push(calTwo);
		}
	}
	*/	

	if(calStack.length > 0) {
		var cal = null;
		
		for(var si=0; si<calStack.length; si++) {
			cal = calStack[si];
			content += cal.build("updateOrderDate(this.id)", '', 'Click to Update Order Date');
		}

		document.getElementById('scheduleTitle').innerHTML = document.serviceSchedules[serviceCode]['title'] + ' Schedule';
		document.getElementById('calendars').innerHTML = content;		
		document.getElementById('calLegend').style.display = 'block';

		for(var si=0; si<calStack.length; si++) {
			cal = calStack[si];
			var dayObj = null;

			if(calUtils.isInSameMonthYear(shipDate, cal.getTheDate())) {
				dayObj = cal.getDayObj(shipDate.getDate());
				dayObj.className='calShip';
				dayObj.innerHTML = '<a href="#" id="' + calUtils.buildDayObjIdFromDate(shipDate) + '" title="Expected Ship Date" onClick="updateOrderDate(this.id);" >' + shipDate.getDate() + '</a>'; // onClick="alert(this.title); return false;" 
			}
			
			/*
			if(calUtils.isInSameMonthYear(today, cal.getTheDate()) {
				dayObj = cal.getDayObj(today.getDate());
				dayObj.className='calToday';
				dayObj.innerHTML = '<a href="#" title="Today" onClick="alert(this.title); return false;" >' + dayObj.innerHTML + '</a>';
			}
			*/
			
			if(calUtils.isInSameMonthYear(orderDate, cal.getTheDate())) {
				dayObj = cal.getDayObj(orderDate.getDate());
				dayObj.className='calOrder';
				dayObj.innerHTML = '<a href="#" title="Order Date" onClick="alert(this.title); return false;" >' + orderDate.getDate() + '</a>';
			}			
			
			var hds = calUtils.getHolidaysInMonth(new Date(cal.getFullYear(), cal.getMonth(), 1));
			for(var hdi = 0; hdi < hds.length; hdi++) {
				var hol = hds[hdi];
				dayObj = cal.getDayObj(hol.getTheDate().getDate());
				dayObj.className='calHoliday';
				dayObj.innerHTML = '<a href="#" title="' + hol.getTitle() + '" onClick="alert(this.title); return false;" >' + hol.getTheDate().getDate() + '</a>';
			}

		}
		
		for(var usi=0; usi < document.upsServices.length; usi++) {
			var lObj = document.getElementById('ups' + document.upsServices[usi]);
			if(document.calZipCode.length == 0) {
				lObj.innerHTML = 'Enter Zip Code';
			} else {
				lObj.innerHTML = 'Searching...';	
			}
		}
		
		// Kick-off the get the UPS schedule for the given ship date routine
		getUPSServices(document.calShipDate);
		
		
	} else {
		document.getElementById('scheduleTitle').innerHTML = '';
		document.getElementById('calendars').innerHTML = '';
		document.getElementById('calLegend').style.display = 'none';		
	}
	
	
	// Hide the "Previous month" arrow if we shouldn't allow the user to go in the past
	var thisMonth = calUtils.getFirstDayOfMonth(new Date());
	var calOneMonth = calUtils.getFirstDayOfMonth(document.calOne.getTheDate());
	if(calOneMonth <= thisMonth) {
		document.getElementById("calArrowLeft").style.visibility='hidden';
	} else {
		document.getElementById("calArrowLeft").style.visibility='visible';
	}
}


function navigateCalendars(direction) {
	var offset = 0;
	var d = direction.toLowerCase();
	
	if(d == 'p') {
		offset = parseInt(-1);	
	}
	if(d == 'n') {
		offset = parseInt(1);
	}
	
	if(offset != 0) {
		var newD = document.calUtils.copyDate(document.calStartDate);
		newD.setMonth(newD.getMonth() + offset);

		if(setCalendars(newD)) {
			updateCalendars();	
		}
	}
}

function updateCalendarServiceCode(serviceCode) {
	if(!document.calServiceCode || document.calServiceCode.toLowerCase() != serviceCode.toLowerCase()) {
		document.calServiceCode = serviceCode;
		updateCalendars();
		return true;
	}
	
	return false;
}

function updateZipCode(zipCode) {
	saveValidateZipCode(zipCode);
	updateCalendars();
}

function saveValidateZipCode(zipCode) {
	var zip = zipCode.replace(/^s+/, '').replace(/s+$/, '')
	var oldZip = document.calZipCode;
	
	document.calZipCode	= '';
	
	if(zip.match(/^[0-9]{5}$/)) {
		document.calZipCode = zip;
	}
	
	if(oldZip != document.calZipCode) {
		if(document.zipCookie.accept()) {
			document.zipCookie.set('CALZIP', document.calZipCode, 0, '/', '', false);
			document.searchZipCookie = new cookieManipulation("ZIPCODE");
			if(document.searchZipCookie.accept()) {
				document.zipCookie.set('ZIPCODE', document.calZipCode, 0, '/', '', false);
			}
		}		
	}
}

function saveSelectedQty(selectedQtyCellIndex) {
	if(document.qtyCookie.accept()) {
		document.qtyCookie.set('QTY', selectedQtyCellIndex, 0, '/', '', false);
	}
}

// Date anchors are in the format YYYY_MM_DD, split it up and create a date object out of it.
function updateOrderDate(myDate) {
	var orderDate = null;
	if(typeof(myDate) == 'object') {
		orderDate = myDate;
	} else {
		var parts = myDate.split('_');
		orderDate = new Date(parts[0], parts[1], parts[2]);		
	}
	

	// make sure the order date is on a BUSINESS DAY
	if(document.calUtils.isDayOff(orderDate)) {
		alert('Order Date can NOT fall on a non-business day');
		return false;
	}

	if(document.calUtils.isInPast(orderDate)) {
		alert('Invalid Order Date. The order date you select must occur on or after today.');
		return false;
	}

	if(setCalendars(orderDate)) {
		document.calOrderDate = orderDate;
		updateCalendars();	
		return true;
		
	} else {
		alert('Invalid Order Date. The order date you select must occur on or after today.');
		return false;
	}
	
	return false;
}


function toggleContent(elementID) {
	var target1 = document.getElementById(elementID + 'Content');

	if (target1.style.display == 'block') {
		target1.style.display = 'none';
	} else {
		target1.style.display = 'block';
	}
	
	return false;
}

/**********************************************************
			BEGIN PICTURE SET FUNCTIONS
***********************************************************/

function getNumPicSets() {
	return $('#fullPic').data("numPicSets");
}

function getTempPicSet() {
	if(!document.tempPicSet) {
		setTempPicSet(getInitPicSet());
	}
	
	return document.tempPicSet;
}

function setTempPicSet(picSet) {
	document.tempPicSet = picSet;
}

function getInitPicSet() {
	//var img = document.getElementById('fullPic');

	var picSet = {
		imageThumbURL: $('#fullPic').data("initThumbSrc"),
		imageFullURL: $('#fullPic').data("initFullSrc"),
		imageExtraLargeURL: $('#fullPic').data("initXlSrc"),
		imageAlt: $('#fullPic').attr("alt") 
	}
	
	return picSet;
}

function updatePic(altImg) {	
	var img = document.getElementById('fullPic');
	var a = document.getElementById('fullPicLink');
	
	if(document.getElementById('lightbox-link') != null) {
		a = document.getElementById('lightbox-link');
	}

	var ps = {
		imageThumbURL: altImg.src,
		imageFullURL: $(altImg).data("fullSrc"),
		imageExtraLargeURL: $(altImg).data("xlSrc"),
		imageAlt: altImg.alt
	}
	
	var altPs = ps;
	
	if(getNumPicSets() == 3) {
		altPs = getTempPicSet();
		setTempPicSet(ps);
		
		altImg.src = altPs.imageThumbURL;
		$(altImg).data("fullSrc", altPs.imageFullURL);
		$(altImg).data("xlSrc", altPs.imageExtraLargeURL);
		altImg.alt = altPs.imageAlt;
	}
	
	img.src = ps.imageFullURL;
	img.alt = ps.imageAlt;
	
	var magnifyDiv = document.getElementById('magnify');

/* macdougall - comment out setting of href on large image, statically setting to nextStep url */
	
	if(ps.imageExtraLargeURL.length > 0) {
		a.href = ps.imageExtraLargeURL;
		if( ps.imageExtraLargeURL == '#' ) {
			magnifyDiv.style.display = 'none';
		} else {
			magnifyDiv.style.display = '';
		}
	} else {
		a.href = '#';
		magnifyDiv.style.display = 'none';
	}
}

/**********************************************************
			END PICTURE SET FUNCTIONS
***********************************************************/


function detailsOnload() {
	document.liveSupport.registerListener( 'supportLink', function() { updateLiveSupportLink() } );

	/* Name this window so other windows can open URLs in it */
	if (document.images) { window.name = 'productDetails'; }

	//initDetailsPage();
	// - macdougall turning off lightbox
	initLightbox('fullPicLink');
	applyTabBehaviors();
	applyProductHoverBehaviors();
	
	document.calUtils = new CalendarUtils("Thanksgiving:4:thu:11|Day After Thanksgiving:4:fri:11|Labor Day:1:mon:9|New Year's Day:1:1|Day After New Year's Day:1:2|Day Before Independence Day:7:3|Independence Day:7:4|Christmas:12:25|Week of Christmas:12:25:ww|Christmas Eve:12:24||New Year's Eve:12:31|Memorial Day:-1:mon:5");
	
	document.upsServices = "1DA,2DA,3DS,GND".split(",");
	document.zipCookie = new cookieManipulation("CALZIP");
	document.qtyCookie = new cookieManipulation("QTY");
	document.qtyCookie.set('QTY', -1, 0, '/', '', false);

	// If the zip code in the form field is blank, set it to the
	// calZip cookie's value if there is a calZip cookie,
	// otherwise leave things as is
	var zipFld = document.getElementById('zipCode');
	if(document.zipCookie.accept() && zipFld.value.length == 0) {
		zipFld.value = document.zipCookie.get();
	}	
	
	saveValidateZipCode(zipFld.value);
	
	var busDay = document.calUtils.addBusinessDays(document.calUtils.getPreviousDay(new Date()), 1);
	if(setCalendars(busDay)) {
		document.calStartDate = busDay;
		document.calOrderDate = busDay;
		document.calServiceCode = 'STANDARD';
		updateCalendars();
	}
	
	jQuery(".altImg").hover(
		function() {
			jQuery(this).addClass('altImgHover');
		}
		,		
		function() {
			jQuery(this).removeClass('altImgHover');
		}
	);
	/*
	.click(
		function() {
			if(getNumPicSets() < 3) {
				// CLEAR the "highlighted" style from every alt img
				jQuery(".altImg").each(
					function() {
						jQuery(this).removeClass('altImgClicked');
					}
				);
				
				// SET the "highlighted" style for THIS alt image
				jQuery(this).addClass('altImgClicked');
			}
		}
	);
	
	jQuery(".altImg img").mouseover(function(e) {
		jQuery(this).fadeTo(300, 0.6, function(){
			jQuery(this).fadeTo(200, 1);
		})
	});	
	*/	
	
	dynamicJSInitializations();
		
	/* Init the price table initially */
	if (productActive==1) {
		initDefaultPriceTable();
	}
		
	/* Init tooltip */
	JT_init();	
	
}



/* Dynamic JavaScript */
function dynamicJSInitializations() {
	
}

