// ******************************************************************************
// File: TCI_mods.js               Author:  John Roush, TierraCast, Inc.
//                              Copyright:  TierraCast, Inc.
// Created: 10/3/11
//
// Revisions:  Check "mod" (modification) ID's below. Cross frference to to-do spreadsheet.
//

// include jQuery for old browser compatability
// mod26 20111101 JDR (This is included in the Sitefinity pages)

	
//Get current page name
var currentPath = window.location.pathname;
var currentPage = (currentPath.indexOf('Products') == 1) ? "ProductsPage" : currentPath.substring(currentPath.lastIndexOf('/') + 1);
var currentPage = (currentPath.indexOf('ProductDetail') == 1) ? "ProductDetail" : currentPage;
var productID = "";
var cartData = "";     // Used by checkCartChange()
var cartScannedOnce = false;

// Breadcrumb calculation
var parentCategory = "";
var parentCategoryURL = "";
var categoryImageAttrName = "";
var categoryURL = "";

var logoutLink="";
var saveToCartURL="";

// jQuery (document).ready() call
$( function() {
	
	// Trigger scripts for that page
	switch (currentPage) {
		case "ProductsPage":
			// mod6b 20111004 JDR - Display hyphened part numbers
			// mod6bProductNumbers();  //20111221 JDR - moved server-side
			mod37bBreadCrumb();
		case "ProductDetail":
		case "SearchByKeyword":
			mod37aProductBannerImage();
			// mod6b 20111004 JDR - Display hyphened part numbers
			// mod6bProductNumbers();  //20111221 JDR - moved server-side
			if ( currentPage == "ProductDetail" ) { getMeasurements(); }
			// markAsAddedToCart
			//mod29MarkItemAsAdded(); //20111221 JDR - moved server-side
			
			//mod37bBreadCrumb();  //called insire of mod37aProductBannerImage();
			mod38Pagination();
			break;

		case "CheckoutAddress":
			// mod7a 20111004 JDR - Bill To info is Read Only
			mod7aReadOnlyBillTo();
			break;

		case "CheckoutShipping":
			// mod11b 20111005 JDR - Hide Payment Status Widget, but use TermsCode to determine 
			//                       whether to display "Use My TierraCast Terms" or hide it.
			mod52a_AddressReformat('div#Content_ctl00_BillTo_Panel2');
			mod52a_AddressReformat('div#Content_ctl00_ShipTo_Panel2');
			/* 20120214 JDR - moved to Iciniti (Sitefinity Page Widgit properties) & Accpac settings mod11bUseTCITerms();  */

		case "ViewCart":
			// mod34 20111119 JDR - Move "Save Cart At" to top of page
			saveCartOnTop();
			// mod16 20111018 JDR - test to $100 minimum order
			// 20120111 - temporalily disable per Sarah
			//minorder();
			
			// mod48 20120108 JDR - Add descriptions
			$("div#Content_C005_savedCartList span.LABEL").append('<div id="notes"><span style="color:#d00;">&nbsp; &nbsp; CAUTION: &nbsp;</span> <span style="font-weight:normal;">Clicking \'Retrieve\' will overwrite your open Shopping Cart Contents.</span></span></div>');

			// Must have name to save cart - popup notice
			saveToCartURL = $("span#SaveToCartButton button").attr('onclick');
			$("span#SaveToCartButton button").attr('onclick','javascript:saveToCartButton(saveToCartURL)');

			// Caption header on Saved Carts List
			$("div#Content_C005_savedCartList.savedCarts table tr.caption").append('<td class="LABEL">Retrieve </td><td class="LABEL">Delete </td>');
			break;
			
			
		case "Login":
			//mod24 20111027 JDR - put cursor in User Name input textbox
			focusLogin();
			break;

		case "quick-order":
			// reformatting moved to C# in User Control
			break;
			
		case "CheckoutComplete":
			// (Thank You for Your Order page)
			// reformatting moved to C# in User Control
			mod45PaymentTerms();
			mod52a_AddressReformat('span#Content_ctl00_ViewWebOrder1_ctlBillTo');
			mod52a_AddressReformat('span#Content_ctl00_ViewWebOrder1_ctlShipTo');
			
			break;
			
		case "OrderEntry":
			mod47PaymentTerms();
			break;
			
		case "request-print-materials":
			mod56RequestPrintMaterials();
			break;

		default:
			// no default
	}

// Is this a page with category images on it?
// If so, then hyperlink them based on their classname.
	if ( $('img.catimages') && cartScannedOnce ) {
		$('img.catimages').hover( function() {
   				$(this).stop(true,true).animate({"opacity": '0.6'}, 200);
				},function(){
    			$(this).stop(true,true).animate({"opacity": '1'}, 200);		
			});
	}
	

			
			
			
			
	// ************************************************************************************************* //
	// ALWAYS RUN THESE CALLS
	// ************************************************************************************************* //
	/* mod17a - Get customer's name from the UserGreeting Widget, then hide the widget in CSS */
	writeNameInShoppingCart();

	// mod25a 20111101 JDR - trim total to two decimal places
	//trimCartTotal(); moved server side 1/7/12.

	// mod31 20111117 JDR - Disable autocomplete on all forms
	$('form').attr( "autocomplete", "off" );
	
	// mod46 20120108 JDR - Logout pop-up notice (did you save your cart?).
	if ( $("a#navPanelContent_TF0B7DFAE002_hlLogin.storeLoginStatus").text() == "Logout" ) {
		logoutLink = $("a#navPanelContent_TF0B7DFAE002_hlLogin.storeLoginStatus").attr('href');
		$("a#navPanelContent_TF0B7DFAE002_hlLogin.storeLoginStatus").attr('href','javascript:confirmLogout(logoutLink)');
	}
	

	/*
	//Check for changes in Quickorder cart
	if ( $("table.cartItemsLayout").first() ) {
		cartData = $("table.cartItemsLayout").first().html();
		var checkCart = window.setInterval("checkCartChanged()", 500);
	}
*/

/* If Sales person logged in, then display their menu navigation */
if ( $("div#onelineCartSummary1 div.customerName").text().substr(0,9) == "Customer:") {
	$("div#account-links").css('visibility','hidden'); 
	$("div#account-links").css({'width':'640px','display':'block','position':'absolute','top':'-40px','right':'90px','text-align':'right'});
	$("div#account-links a.btnlnk").css({'float':'right','padding-top':'3px'});
	$("body.store-page div#header-nav div.sfContentBlock").css('height','150px');
	$("body.store-page div#Div1.onelineCartSummary").css('top','-165px');
	$("div#account-links").css('visibility','visible');
}


});  // Close out jQuery (document).ready() call



/*
function checkCartChanged() {
	cartDataCurrent = $("table.cartItemsLayout").first().html();
	if ( cartData != cartDataCurrent ) {
		console.log("cart changed");
		reformatQuickOrder();
		cartData = $("table.cartItemsLayout").first().html();
	}
}
*/



// ************************************************************************************************* //
// PAGE-SPECIFIC FUNCTIONS
// ************************************************************************************************* //

// mod6b 20111004 JDR - Display hyphened part numbers
//Search by Keyword page (Sitefinity)
/*
function mod6bProductNumbers() {
	var productNumbers = $('.itemNumberMod6a');
	for (count=0;count<productNumbers.length;count++) {
		// Parse product number
		var productNumber = trim(productNumbers[count].innerHTML);
		productID = productNumber;
		productNumbers[count].innerHTML = hyphenateProductNumber(productNumber);
		
		// Now that it's formatted properly, display it.
		productNumbers[count].style.visibility = "visible";
 	}
}
*/


/* mod7a 20111004 JDR - Set Bill To fields to ReadOnly */
/*       20111118 JDR - use jQuery instead */
function mod7aReadOnlyBillTo() {
	$("#Content_ctl00_billingAddress_ctlCompany").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlName").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlAddress1").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlAddress2").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlAddress3").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlAddress4").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlCity").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlStateList").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlCountry").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlPostalCode").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlPhone").attr("disabled", true);
	$("#Content_ctl00_billingAddress_ctlFax").attr("disabled", true);
	
	// mod43a
	// Label Name and Address Line 4 correctly
 	$("label[for='Content_ctl00_billingAddress_ctlName']").text('Name');
	$("label[for='Content_ctl00_shippingAddress_ctlName']").text('Name');
 	$("label[for='Content_ctl00_billingAddress_ctlAddress4']").text('Billing Contact');
	$("label[for='Content_ctl00_shippingAddress_ctlAddress4']").text('Shipping Contact');
	$("label[for='Content_ctl00_billingAddress_ctlEmail']").text('Email Order to:');
	
	
	// Set color for international states
	if ($("#Content_ctl00_billingAddress_ctlStateCode")) {
		$("#Content_ctl00_billingAddress_ctlStateCode").css('color','#666');
	}
	
	//mod43b
	// Set spacing for the form
	$("table.AddressForm tbody tr").not("table.AddressForm tbody tr:nth-child(10)").css('height','26px');
	// Set spacing to non-zero if this line has content in it
	if ( $("table.AddressForm tbody tr:nth-child(8) td").html().trim() != "" ) {
		$("table.AddressForm tbody tr:nth-child(8)").css('height','26px');
	} else {
		$("table.AddressForm tbody tr:nth-child(8)").remove();
	}
	if ( $("table.AddressForm tbody tr:nth-child(9) td").html().trim() != "" ) {
		$("table.AddressForm tbody tr:nth-child(9)").css('height','26px');
	} else {
		$("table.AddressForm tbody tr:nth-child(9)").remove();
	}
	
	
	// mod54a 20120115 JDR - Hide shipping, set billing to read-only
	$("input#Content_ctl00_shippingAddress_ctlEmail").parent().parent().hide();
	$("input#Content_ctl00_billingAddress_ctlEmail").attr("disabled", true);
	/* 
	var billingEmail = $("input#Content_ctl00_billingAddress_ctlEmail").parent().html();
	var billingEmail2 = billingEmail.replace(/Email/g,'Email2');
	var shippingEmail = $("input#Content_ctl00_shippingAddress_ctlEmail").parent().html();
	console.log(billingEmail);
	console.log(shippingEmail);
	
	$("input#Content_ctl00_shippingAddress_ctlEmail").parent().html(billingEmail2);
	$("input#Content_ctl00_billingAddress_ctlEmail").parent().html(shippingEmail);
	$("input#Content_ctl00_shippingAddress_ctlEmail").attr("disabled", true);
	$("input#Content_ctl00_billingAddress_ctlEmail2").parent().html(billingEmail);
	*/
}




// mod11b 20111005 JDR - Hide Payment Status Widget, but use TermsCode to determine 
//                       whether to display "Use My TierraCast Terms" or hide it.
function mod11bUseTCITerms() {
	// Hide Payment Status Widget from view (we're just using its data for the "if" below)
	var accountStatus = $('.accountStatus');
	accountStatus[0].style.visibility = "hidden";  /* also hidden by CSS */
	
	// Get current terms
	var accountStatus = $('.data');
	var TermsCode = trim(accountStatus[1].innerHTML);
	
	/* hide if not N*, or (?) */
	if ( TermsCode.substring(0,3) == "2BC" || TermsCode.substring(0,4) == "30BC"
		|| TermsCode.substring(0,3) == "N30" || TermsCode.substring(0,3) == "N30"
		|| TermsCode.substring(0,4) == "WTRN" || TermsCode.substring(0,5) == "CODPU" ) {
			
		// Show it
		if (document.getElementById("Content_ctl02_ctlOnAccountButton")) {
			document.getElementById("Content_ctl02_ctlOnAccountButton").style.visibility = "visible"; 
		}

		//Show 2nd Radio button (Customer does have TCI Terms)
		var paymentOptions = document.getElementsByClassName("paymentOptions");
		var paymentOption = paymentOptions[0];
		var paymentOptionNodes = paymentOption.childNodes;		
		//paymentOptionNodes[5].textContent = "Use My TierraCast Terms1";
		paymentOptionNodes[5].style.visibility = "visible";
			
	} else {
		// Do nothing (leave it hidden)
		//Select 1st Radio button (only payment type available)
		var paymentOptions = document.getElementsByClassName("paymentOptions");
		var paymentOption = paymentOptions[0];
		var paymentOptionNodes = paymentOption.childNodes;		
		paymentOptionNodes[1].checked = "true";
	}
	
	// Change text in submission button
	$("input#Content_ctl02_btnSubmit").val("Submit this order");
}


// mod16 20111018 JDR - test to $100 minimum order
function minorder() {
	//console.log("minorder()");
	var total = 0.00;
	var cost = 0.00;

	var item_count = $('.icon');
	
	for (var i = item_count.length-1; i>=0; i--) {
				
		var cost_text = item_count[i].innerHTML;
		cost = cost_text.replace('$','');
		total += parseFloat(cost);
		//console.log('Running total: $' + total);
	}

	if ( total < 100.00 && document.getElementById('PageTitle_C004_btnCheckout_Button1') ) {
	document.getElementById('PageTitle_C004_btnCheckout_Button1').disabled = true;
	document.getElementById('PageTitle_C004_btnCheckout_Button1').value = '$100 minimum order';
	var buttons = $('.cart-buttons');
	var button = buttons[0];
	var total_message_div = document.createElement("div");
	total_message_div.innerHTML = 'Your current total is: $' + formatCurrency(total);
	button.appendChild(total_message_div);
	}
}


/* mod17a - Get customer's name from the UserGreeting Widget, then hide the widget in CSS */
function writeNameInShoppingCart() {
	if (document.getElementById('onelineCartSummary1') != null) {
		var greeting = document.getElementById('navPanelContent_TF0B7DFAE006_ctlGreeting').innerHTML;
		// Remove first two words (display name only)
		greeting = greeting.substr(5);
		greeting = greeting.substr(greeting.indexOf('&nbsp;') + 6);
		if (greeting.length > 0) {
			document.getElementById('onelineCartSummary1').innerHTML = greeting;
		} else {
			document.getElementById('onelineCartSummary1').innerHTML = 'Please log in here';
		}
	}
}



//mod24 20111027 JDR - put cursor in User Name input textbox
function focusLogin() {
	var loginFields = $('.login');
	if (loginFields[0]) { loginFields[0].focus();}
}


//mod25a 20111101 JDR - Trim off third decimal place from totals
function trimCartTotal() {
	if (document.getElementById('navPanelContent_TF0B7DFAE010_HyperLink4')) {
		var total = document.getElementById('navPanelContent_TF0B7DFAE010_HyperLink4');
		total.innerHTML = total.innerHTML.substr(0,total.innerHTML.length - 1);
		
		console.log ('dec: ' + total.innerHTML.indexOf(".") + ', len:' + total.innerHTML.length + ", '" + total.innerHTML + "'");
	}
}

// mod29 20111107 JDR - Mark recently added item as added to cart.
function mod29MarkItemAsAdded() {
	// Hide the cart from view - SEE CSS
	//$('.view-cart').parent().parent().css({'visibility':'hidden'});
	
	// Get all the items in the cart
	var itemsInCart = new Array();
	var itemsQuantity = new Array();
	$('tr.cart-item > td.itemNumber').each( function() { 
		itemsInCart.push($(this).text());
	});
	$('td.quantity > input').each( function() { 
		itemsQuantity.push($(this).val());
	});

	// Loose the heading values
	//if (itemsInCart.length > 0) {itemsInCart.shift();}  // No need to shift for itemsQuantity
	//console.log(itemsInCart.length);
	//console.log(itemsQuantity.length);
	
	// Scan through displayed items, and mark those that are in the cart
	$('.itemNumberMod6a').each( function() {
		var thisItemNumber = $(this).text().replace(/-/g,'');
		for (var i = 0; i < itemsInCart.length; i++) {
			if ( thisItemNumber == itemsInCart[i].trim() ) {
				$(this).css('color','green');
				$("\r\n<div class=\"itemQtyInCart\">Qty in cart: " 
					+ itemsQuantity[i] + "</div>")
					.css({'text-align':'left','margin':'100px 0 0 4px','z-index':'9999'
						,'font-size':'10px','font-family':'Tahoma,Helvetic','color':'green'})
					.insertAfter(this);

			}	
		}
	});
	
	$('div.view-cart').remove();



}









// mod34 20111118 JDR - Move the "Save to Cart" box to the top of the ViewCart page
function saveCartOnTop() {
	//console.log("Move 'save cart' to top of page");
	// Title this section
	$('<div id="cartListTitle">Shopping Cart Contents</div>').insertBefore('table.cartItems');
	
	// remove the old 'text link' to save the cart
	//$('div.saveButton a#Content_ctl01_btnSaveCart').remove();
	$('div.saveButton a#Content_C005_btnSaveCart').remove();
	
	// Move the div
	var saveToCart = '<div id="Content_C005_saveThisCart" class="saveThisCart">'
		+ $('#Content_C005_saveThisCart').html() + '</div>';
	$('#Content_C005_saveThisCart').remove();	
	$('div.view-cart').prepend( saveToCart );

	// Add text
	$('div.cartTitle').prepend('<span id="SaveToCartText">Describe this cart: </span>');
	
	// Create a Save to cart BUTTON
	$('div.cartTitle').append('<span id="SaveToCartButton">'
		+ '<button onclick="javascript:__doPostBack(\'ctl00$Content$C005$btnSaveCart\',\'\')">Save This Cart</button></span>');
	
	// Clearify the text
	$("label[for='Content_C005_chkShared']").text('<br /> all users at my company.');
	
	// Add clearer title
	$('<div id="SaveToCartTextTitle">Save This Shopping Cart</div>').insertBefore($('div#Content_C005_saveThisCart'));

	// Now that it's rebuilt, make it visable  (CSS has it hidden before the jQuery rebuild)
	$('div.view-cart').css('visibility','visible');
	$('div#Content_C005_saveThisCart div.checkbox').css('visibility','hidden');
	$('div#Content_C005_saveThisCart').css('visibility','visible');

}


// mod35a-f 20111207 JDR - Quick Order page mods
function reformatQuickOrder() {
	// mod35f 20111207 JDR - Qty field - max # of chars
	$("#Content_C007_EditCartItems21_tbQtyMain").attr('maxlength',5);
	
}




// mod37a - Product Detail Page - Banner Image
function mod37aProductBannerImage() {
	var imageSet = false;
	// What product ID are we looking at?
	var classList =$('body').attr('class').split(/\s+/);
	$.each( classList, function(index, item){
		// is this class a product #?
		var productNumber = item.substr(0,8);
		if ( isNumeric(productNumber) ) {
			// find category
			//SELECT [CategoryCode] FROM [WebCMS].[dbo].[WCC_CategoryLinks] where ItemCode = '94560412';
			setProductCategoryImage(productNumber);
			imageSet = true;
			
		}
	});
	
	if (!imageSet) {
		//console.log("read URL");
		// Get image based on URL
		//var currentLocation = window.location.pathname.split('/');
		var currentLocation = window.location.pathname;
		var locationStructure = currentLocation.split('/');
		if (locationStructure.length == 3) {
			// set hyperlink
		$('div.category_image a').attr({ 
			href: '#',
			alt: locationStructure[2].replace(/_+/g,' ')
		});
		// set image
		$('.category_image img').attr({ 
			src: '/imagelib/categories/' + locationStructure[2].replace(/_+/g,'').toLowerCase() + '.jpg',
			title: locationStructure[2].replace(/_+/g,' '),
			alt: locationStructure[2].replace(/_+/g,' ')
		});
		} else if (locationStructure.length == 4) {
			// Who is parent? (select correct child image if needed)
			if (locationStructure[2]=='Charms' && locationStructure[3] == 'Global_Spirit') {
				locationStructure[3] == 'Global_Spirit_Charms';
			}
			if (locationStructure[2]=='Charms' && locationStructure[3] == 'Celtic__and__Ethnic') {
				locationStructure[3] == 'Celtic__and__Ethnic_Charms';
			}
			if (locationStructure[2]=='Beads' && locationStructure[3] == 'Celtic__and__Ethnic') {
				locationStructure[3] == 'Celtic__and__Ethnic_Beads';
			}
			if (locationStructure[2]=='Charms' && locationStructure[3] == 'Celestial') {
				locationStructure[3] == 'Celestial_Charms';
			}
			if (locationStructure[2]=='Beads' && locationStructure[3] == 'Celestial') {
				locationStructure[3] == 'Celestial_Beads';
			}
		// set hyperlink
		$('.category_image a').attr({ 
			href: '#',
			alt: locationStructure[3].replace(/_+/g,' ')
		});
		// set image
		$('.category_image img').attr({ 
			src: '/imagelib/categories/' + locationStructure[3].replace(/_+/g,'').toLowerCase() + '.jpg',
			title: locationStructure[3].replace(/_+/g,' '),
			alt: locationStructure[3].replace(/_+/g,' ')
		});
		
		} else {
			// no batter image?
			$('.category_image').html('<div style="padding:20px 0 0 10px;color:red;height:40px;width:450px;border:solid 1px red;">ERROR: Webstore category image missing</div>');
		}
	}
}

function setProductCategoryImage(productID) {
	var xmlHttp = getXMLHttp();
	xmlHttp.onreadystatechange = function() {
		if(xmlHttp.readyState == 4) {
			setProductCategoryImage_Response(xmlHttp.responseText);
		}
	}
	xmlHttp.open("GET", "/GetProductCategoryImage.aspx?id=" + productID, true);
	xmlHttp.send(null);
}

function setProductCategoryImage_Response(response) {
	var categoryInfo = response.split('^');
	
 	if ( categoryInfo[0] == 'not found' ) {
		// do nothing
	} else if ( categoryInfo[0].trim() == '' ) {
		// no image listed in TCI_CategoryImageNames table
		$('.category_image').html('<div style="padding:20px 0 0 10px;color:red;height:40px;width:450px;border:solid 1px red;">ERROR: Webstore category #'
				+ categoryInfo[3] + ' not in TCI_CategoryImageNames</div>');
	} else {
		//Parse values
		var categoryImageURL = categoryInfo[0];
		categoryImageAttrName = categoryInfo[1];
		categoryURL = categoryInfo[2];

		var directories = /\//g;	// Regular Exoression for counting directories in URL

		if (categoryURL.match(directories).length == 3) {
			parentCategoryURL = categoryURL.substr(0,categoryURL.lastIndexOf("/"));
			parentCategory = parentCategoryURL.substr(parentCategoryURL.lastIndexOf("/") + 1).replace(/_/g," ");
		}
		
 		// set hyperlink
		$('.category_image a').attr({ 
			href: categoryURL,
			alt: categoryImageAttrName
		});
		// set image
		$('.category_image img').attr({ 
			src: categoryImageURL,
			title: categoryImageAttrName,
			alt: categoryImageAttrName
		});
		
		// Print breadcrumb on page
		mod37bBreadCrumb();

	}
}


function mod37bBreadCrumb() {

	/*
	// how did we get here? - Breadcrumb based on prior clicks
	var priorPage = document.referrer.split('/');
	var start = false;
	var output = '<a href="/" class="breadcrumbLink">Browse</a>';
	for (item in priorPage) {
		if (start) {
			output += ' / <a href="' + breadcrumbURL(priorPage,item) + '" class="breadcrumbLink">' + priorPage[item].replace(/_+/g,' ') + '</a>';
		}
		if ( priorPage[item] == 'Products' ) {
			start = true;
		}
	}
	
	var thisPage = location.href.substr((location.href.lastIndexOf('/') + 1))
	var productNumber = thisPage.substr(0,8);

	if ( isNumeric(productNumber) ) {
		output += ' / ' + '<span class="breadcrumbCurrentPage">' + hyphenateProductNumber(productNumber) + '</span>';
	} else {
		output += ' / ' + '<span class="breadcrumbCurrentPage">' + thisPage.replace(/_+/g,' ') + '</span>';
	}
	*/
	
	
	
	// Breadcrumb based on current location
	var currentLocation = window.location.pathname;
	var locationStructure = currentLocation.split('/');
	var start = false;
	var output = '<a href="/" class="breadcrumbLink">Browse</a>';
	if (locationStructure.length > 0 ) {
		for ( var item in locationStructure) {
			if (item < locationStructure.length - 1) {
				if (start) {
					output += ' / <a href="/Products' + breadcrumbURL(locationStructure,item)
						+ '" class="breadcrumbLink">' + locationStructure[item].replace(/_+/g,' ') + '</a>';
				}
			
				if ( locationStructure[item] == 'Products' ) {
					start = true;
				}
			} else {
				// current page
				var thisPage = location.href.substr((location.href.lastIndexOf('/') + 1))
				var productNumber = thisPage.substr(0,8);

				if ( isNumeric(productNumber) ) {
					// Parent Category
					if (parentCategory.length > 0 ) {
						 output += " / " + '<a href="' + parentCategoryURL 
						 	+ '" class="breadcrumbLink">' + parentCategory + '</a>';
					}
					// Current Category
					output += " / " + '<a href="' + categoryURL 
						 	+ '" class="breadcrumbLink">' + categoryImageAttrName + '</a>';
					output += ' / ' + '<span class="breadcrumbCurrentPage">' + hyphenateProductNumber(productNumber) + '</span>';
				} else {
					output += ' / ' + '<span class="breadcrumbCurrentPage">' + thisPage.replace(/_+/g,' ') + '</span>';
				}
			}
		}
	}

	$('.breadcrumb').html(output);
	
}


function mod38Pagination() {
	// Re-writes the pagination control and places it on the top & bottom of the page
	if ( $('.pageNumberLinks') ) {
		
		$('.pageNumberLinks').each(function()
		{
			var pageNumberLinks = $(this).html();
			
			// Write it to the new locations
			$('.pageNumberLinks_TCI').each(function()
			{
				$(this).html(pageNumberLinks);
			});
		});
		$('.pageNumberLinks_TCI').css('visibility','visible');
	}
}


function mod45PaymentTerms () {
	// Hide Terms if payment made
	if ( $("#Content_ctl00_ViewWebOrder1_ctlPaymentMethod").is(":visible") ) {
		// Hide Terms
		$("#Content_ctl00_ViewWebOrder1_ctlTerms").parent().parent().hide();
	} else {
		// Hide labels for credit card
		$("#Content_ctl00_ViewWebOrder1_ctlPaymentMethod").parent().parent().hide();
		$("#Content_ctl00_ViewWebOrder1_ctlAuthorization").parent().parent().hide();
	}
	
}

function mod52a_AddressReformat(compressedAddressField) {
	if ($(addressField)) {

		var companyNameLoc = 0;
		var contactLoc = 1;
		var contactNameLoc = 0;
		var cityStateZipLoc = 0;
		var addressField = compressedAddressField;
		var addressList = $(addressField).html().split('<br>');
//console.log(addressList);
		if (addressList.length > 6 && addressList.length < 10) {
			cityStateZipLoc = addressList.length-3;
			addressList[cityStateZipLoc] += " &nbsp; " + addressList.pop();
			
			if (compressedAddressField.indexOf("ShipTo") > 0 ) {
				// Move address line 4 over the contact name
				contactNameLoc = addressList.length-4;
				addressList[contactLoc] = addressList[contactNameLoc];
			} 
			// Remove Adderss line 4
			addressList.splice(contactNameLoc,1);
			
			$(addressField).html(addressList.join('<br>'));
		}
	}
}





// mod46 20120108 JDR - Logout pop-up notice (did you save your cart?).
function confirmLogout(linkText) {
	if ( $("a#navPanelContent_TF0B7DFAE010_HyperLink1").text() == "0" ) {
		// Log out - there's nothing in the cart
		var runThis = linkText.replace("javascript:__doPostBack('","");
		runThis = runThis.replace("','')","");
		__doPostBack(runThis,'');
	} else {
		// Confirm you want to log out
		if (confirm("Have you saved your cart?\n\nIf not, press 'Cancel' to go back and save your cart.\n\nClick 'OK' to confirm logout.\n ")) {
			var runThis = linkText.replace("javascript:__doPostBack('","");
			runThis = runThis.replace("','')","");
			__doPostBack(runThis,'');
		} else {
			//console.log("do nothing");
		}
	}
}






function mod47PaymentTerms() {
	var defaultTerms = $("select#Content_ctl00_ctlTerms option:selected").val();
	// If net terms, then only that one Net terms, or Bank Card
	if ( defaultTerms.substr(0,1) == 'N' ) {
		$("select#Content_ctl00_ctlTerms option").each(function() {
			var currentValue = $(this).val();
			if (!(currentValue == 'BC' || currentValue == defaultTerms) ) {
				$(this).remove();
			}
		});
	} else {
		// Only list the current terms
		$("select#Content_ctl00_ctlTerms option").each(function() {
			var currentValue = $(this).val();
			if (currentValue != defaultTerms) {
				$(this).remove();
			}
		});
	}
}


// mod50 20120107 JDR - Require them to name the cart.
function saveToCartButton(linkText) {
	if ( $("div.cartTitle input#Content_C005_ctlSaveDescription").val() == "" ) {
		// Error
		if (confirm("Please describe the cart to be able to save it. ")) {
			//console.log("do nothing");
		}
	} else {
		// Save the cart
		var runThis = linkText.replace("javascript:__doPostBack('","");
		runThis = runThis.replace("','')","");
		__doPostBack(runThis,'');
	}
}




function getMeasurements() {
	var xmlHttp = getXMLHttp();
	
	// What product ID are we looking at?
	var classList =$('body').attr('class').split(/\s+/);
	$.each( classList, function(index, item){
		// is this class a product #?
		var productNumber = item.substr(0,8);
		if ( isNumeric(productNumber) ) {
			// find measurements
			xmlHttp.onreadystatechange = function() {
				if(xmlHttp.readyState == 4) {
					HandleResponse(xmlHttp.responseText);
				}
			}
			xmlHttp.open("GET", "/GetItemMeasurements.aspx?id=" + productNumber, true);
			xmlHttp.send(null);
		}
	});
}

function HandleResponse(response) {
	if ( response.trim() == '<span id="Label1"><div id="measurements">Measurements coming soon.</div></span>' ) {
		// do nothing if there are no measurements.
	} else {
		$('#ResponseDiv').html(response);
		// Bump down the Buy button & qty in cart message
		responseHeight = $('#ResponseDiv').height();
		// Buy button doesn't exist if you're not logged in
		if ($('.ics-buybuttonpanel').css('top')) {
			buybuttonTop = parseInt($('.ics-buybuttonpanel').css('top').replace("px", ""));
			$('.ics-buybuttonpanel').css('top',buybuttonTop + responseHeight);
		} else {
			buybuttonTop = 0;
			$('body.ProductDetail div.itemQtyInCart').css('top',buybuttonTop + responseHeight + 36);
		}
	}
	
}



function mod56RequestPrintMaterials () {
	 $("form#form1").attr("action", "/RequestPrintMaterialsProcessor.aspx");
	 $("form#form1 input#__VIEWSTATE").remove();
}

	
// ************************************************************************************************* //
// MAIN FUNCTIONS
// ************************************************************************************************* //


function trim(str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function setInputFieldReadOnly(e) {
	e.readOnly = "true";
	e.style.backgroundColor = "#ccc";
}

function formatCurrency(num) {
    num = isNaN(num) || num === '' || num === null ? 0.00 : num;
    return parseFloat(num).toFixed(2);
}

function isNumeric(str) {
	var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
	return reg.test(str)
}


function hyphenateProductNumber(productNumber) {
	return( productNumber.substring(0,2) + "-" + productNumber.substring(2,6) + "-" + productNumber.substring(6));
}

function breadcrumbURL(priorPage,count) {
	var output = '';
	for (i = 2; i <= count; i++) {
		output += "/" + priorPage[i];	
	}
	return(output);
}


// Get info
function getXMLHttp()
{
  var xmlHttp

  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
        //alert("Your browser does not support AJAX!")
        return false;
      }
    }
  }
  return xmlHttp;
}


// pop-up images (on hover)
function showHide(what) {
	var ta = document.getElementById(what);
	$(ta).toggle();
}
function showHover(id) {
	var helpbox = document.getElementById(id+"hov");
	helpbox.style.top = mouseY+'px';
	helpbox.style.left = mouseX+'px';
}

function hideHover(id) {
	var helpbox = document.getElementById(id+"hov");
	helpbox.style.top = -10000+'px';
	helpbox.style.left = -10000+'px';
}

function hideAll() {
	var popups = document.getElementsByName("hover");
	for (var i=0; i < popups.length; i++) {
		popups[i].style.top = -10000+'px';
		popups[i].style.left = -10000+'px';
	}
}


//console.log(document.referrer);


