//Functions used on the product list display page
$(function(){

	/* declare global vars
	**********************/
	__global = window.__global || {};
	__global.vars = window.__global.vars || {};
	__global.filter = window.__global.filter || {};
	__global.filter.current = null;
	/* declare local vars
	**********************/
	var bind_modalClose = true,
		$expandable = $('.expandable'),
		$productResults = $('#productResults'),
		$listToggler = $('a.listView'),
		$gridToggler = $('a.gridView'),
		$addToCart = $('.addToCart'),
		$quickView = $('#quickView'),
		$freeDelivery = $('#free_delivery'),
		$zipCodeCheck = $('#zip_code_check'),
		$onlineOnlyPrice = $('#online_only_price');
	/* Check the cookie and set user preferences for layout, results per page */
	applyUserPrefs();

	var $someModal = $('#modal');
	$someModal.dialog({
		modal: true,
		autoOpen: false
	});
	var $largeModal = $('#large_modal');
	$largeModal.dialog({
		modal: true,
		autoOpen: false,
		resizable: false,
		width: "auto"
	});

	/* Hover effects  */
	$productResults.find('> li').hover(
		function(){ $(this).addClass('active'); },
		function(){ $(this).removeClass('active'); }
	);
	/* Add to Cart */
	$addToCart.each(function(i, item){
		$this = $(item).parents('.availability-info');
		if ( $this.children('.quantity').length > 0 ) {
			$this.addClass('one_line');
		}
	});
	// Was .live() but that was causing modal issues.
	$("a.add", $addToCart).live('click', function(e) {
		e.preventDefault();
		var $this = $(this),
			href = $this.attr('href'),
			$parent = $this.parents('li') || $this.parents('.modal_content'),
			prod_id = $parent.attr('id').split(' ')[0].split('_')[1],
			$input = $this.parents('.pricingArea').find('.quantity input.qty'),
			quantity = $input.val();

		if ( $input.length != 0 ) {
			// If the value is not a number or is less than 1 reset the quantity value and field
			if ( isNaN(quantity) || quantity < 1 ) {
				quantity = 1;
				$input.val(quantity);
			}
			// Add item to cart
			updated_url = href.replace('&quantity=1', '&quantity=' + quantity);
			document.location = updated_url;
		}else{
			// If this is a gift card
			//document.location = '/ProductDisplay?langId=-1&storeId=10151&catalogId=10051&productId=' + prod_id + '&pl=1&N=4294925544';
			document.location = href;
		}
		return false;
	});
	// Quantity is hidden on load and shown on JS load.
	// If the user doesn't have JS Add to Cart will still function
	// submitting 1 item at a time.
	$('.quantity').show();
	$('input.qty').bind('focus', function(){this.select();});/* This is to remove onfocus="javascript:select()" from the DOM */
	// Submit the zip code value
	/*$('#zip_find_store').live('click', function() {
		submitZip($(this));
		return false;
	});*/
	$('.zipIn button').live('click', function() {
		submitZip($(this));
		return false;
	});
	/*
	 * Top Bar Functionality
	 *
	 */
	/* Results Per Page Dropdown */
	$('.show_results').bind('change', function() {
		var $this = $(this),
			url_string = 'rpp=',
			new_val = url_string + $this.val(),
			curr_url = window.location.href.toString();

			/*	Defect 12896  added page=1 */
			if(curr_url.indexOf('page=') != -1) {
				var pageString = curr_url.substring(curr_url.indexOf('page='), curr_url.length);
				var pageNumber = pageString.split('&');
				curr_url = curr_url.replace('&'+pageNumber[0],'');
				new_val = new_val + '&page=1';
			}
			/* end 12896 */

		updateURL(curr_url, new_val, url_string);

	});
	/* Go To Page button */
	$('a.go_to_page').bind('click', function(e) {
		e.preventDefault();
		var $this = $(this),
			$container = $this.parents('.goToPage'),
			$input_field = $('input[name=pageNumber]'),
			url_string = 'page=',
			total_pages = parseFloat($('.pageResults .totalPages').eq(0).text()),
			jump_page = $input_field.val(),
			has_decimal = jump_page.indexOf('.'),
			new_val = url_string + jump_page,
			curr_url = window.location.href,
			error_msg = 'Please enter a page number between <strong>1</strong> and <strong>' + total_pages +'</strong>'; /* Defect 13083 - Updated Error Message for Not Entering Page Number */

			/*$page_title = $this.parents('#one-column').find('h1');*/

		if (isNaN(jump_page) || $.trim(jump_page) == "") {
			// The passed value is empty or not a number
			userInvalidPageError($input_field, error_msg);
		}else{
			// The passed value is a valid number
			// If there is more than one page, set up this error message
			// Shouldn't this be something like "if (jump_page > total_pages)" ?
			if (total_pages >= 2 ) {
				error_msg = 'The requested page <strong>(' + jump_page + ')</strong> is not available. '+ error_msg;
			}
			if (jump_page <= total_pages && jump_page > 0 && has_decimal < 1) {
				// This means that we can legitly update the URL
				updateURL(curr_url, new_val, url_string);
			}else{
				userInvalidPageError($input_field, error_msg);
			}
		}
		return false;
	});
	// If the user presses the enter key while focused
	$('.go_to_page_field').bind('keydown', function(event) {
		if (event.keyCode == 13) {
			if($(this).val() != '') {
				$this.next('a.go_to_page').triggerHandler('click');
			}
		}
	});
	/* Bind click events to the grid/list view buttons. */
	$gridToggler.bind('click',function(evt){
		evt.preventDefault();
		if ($productResults.hasClass('listView')){
			$productResults.removeClass('listView').addClass('gridView');
			$listToggler.removeClass('current');
			$(this).addClass('current');
			createCookie('userPrefs', 'grid_view', 30);
		}
	});
	$listToggler.bind('click',function(evt){
		evt.preventDefault();
		if ($productResults.hasClass('gridView')){
			$productResults.removeClass('gridView').addClass('listView');
			$gridToggler.removeClass('current');
			$(this).addClass('current');
			createCookie('userPrefs', 'list_view', 30);
		}
	});

	//product detail
	/*
	var products = {};
	$.ajax({
		type:"GET",
		url:"javascript/product_info.json",
		dataType:"json",
		error: function(){
			console.log('Error on product information request.');
		},
		success: function(data){
			var html,
				$colorSwatches = $('#colorswatches li').not('.highlight');
			$.each(data.products, function(key, obj) {
				var myobj = obj.product,
					html = "";
				html += '<div class="css-arrow center bg"></div><div class="css-arrow center"></div>';
				html += '<img src="' + myobj.image + '" alt="Image of ' + myobj.title + '" />';
				html += '<div class="productinfo"><h4><a name="product_tooltip_title_' + myobj.item + '" href="#">' + myobj.title + '</a></h4>';
				html += '<span class="itemmodel">Item #: ' + myobj.item + ' | Model #: ' + myobj.model + '</span>';
				html += '<span class="price">$' + myobj.price + '</span></div>';
				products[myobj.item] = html;
			});
			$colorSwatches.dialog({
				content: function(){
					var itemId = $(this).attr('id').slice(12);
					return products[itemId];
				}
			});
		}
	});
	*/
	//image carousel functionality
	var $imgBlock = $('#imgBottomBlock');
	$imgBlock.delegate('a','click', function() {
		var $this = $(this);
		$imgBlock.find('.carousel a.border').removeClass('border');
		$this.addClass('border');
		$('#imgTopBlock .productimage').attr('src', $this.find('img').attr('src').replace('sm.jpg','lg.jpg'));
		return false;
	});

	if($('#productImagesCarousel').length) {
  		new Lowes.UI.Carousel('#productImagesCarousel', { loop:false, controlBar:false, visible:4 }).create();
	}

	if($('#alsoViewedBlock .carouselcont').length) {
		new Lowes.UI.Carousel('#alsoViewedBlock .carouselcont', { loop:false, controlBar:false, visible:5 }).create();
	}




	/* Compare Items */
	// Check the cookie for Compare Products
	var compProducts = readCookie('pcompitems');
	if (compProducts !== null) {
		precheck_items(compProducts);
	}
	$('div.compareBtn').bind('click', function() {
		var $this = $(this),
			item_num = $this.parents('li.active').eq(1).attr('id').split('_')[1],
			return_url = encodeURIComponent(document.location.href);

		if (compProducts !== null) {
			var cookie_items = compProducts.toString();
			items = cookie_items;
		}

		if ( !$this.hasClass('disabled') ) {
			document.location = '/LowesProductComparisionCmd?catalogId=10051&langId=-1&storeId=10151&NeParam=4294937087&NParam=4294857980&NttParam=&pcompitems=' + items + '&returnShoppingUrl=' + return_url;
		}

		return false;

	});
	/* Compare Items Checkboxes */
	$('.compare input').bind('click', function() {
		updateCompare($(this), true);
	});


		// Modals on the site.
	/*
	$('.modal').each(function(i, item){

		var $item = $(item),
			modal_id = $item.attr('href'),
			catEntryId = ( $item.parents('li').attr('id') !== undefined ) ? $item.parents('li').attr('id').split(' ')[0].split('_')[1] : getCatId();

			console.log('Cat Entry ID: ', catEntryId);

		switch (modal_id) {

			// If it's the check other store div
			case '#check_other_stores' :

				var request_url = '/ProductLocator?storeId=10151&langId=-1&catalogId=10051&catentryId=' + catEntryId,
					$modal = $('#large_modal');

				/*$item.overlay({

					close:'.close',
					fixed:false,
					mask:{
						color:'#000',
						opacity:0.2,
						zIndex:900
					},
					onBeforeLoad:function() {

						loading = $('<div class="modal_loading">Loading <img src="/images/modal_loader.gif" /></div>');
						//$modal.find('.modal_content').addClass('find_product').html(loading);
						$modal.find('.modal_content').addClass('find_product').html(loading).load(request_url, function(){

							var overlay = $item.data('overlay').getOverlay(),
								win_height = $(window).height(),
								scroll_top = $(window).scrollTop(),
								modal_height = $(overlay).height(),
								top;

							if (modal_height < win_height) {

								top = ( ( win_height - modal_height ) / 2 ) + scroll_top;

							} else {

								top = 10 + scroll_top;

							}

							overlay.animate({'top': top}, 500);

						});
					},
					target:'#large_modal',
					top:'center'

				});
			break;

			// If it's all other modals
			default :
				$item.overlay({
					close:'.modal_close',
					fixed:false,
					target:'#modal',
					mask:{
						color:'#fff',
						opacity:0,
						zIndex:900
					}
				}).bind('click', function(){

					var $this = $(this),
						$pos = $this.offset(),
						html = $(modal_id).html(),
						overlay = $this.data('overlay'),
						$modal = $('#modal'),
						modal = '';

					if ($modal.length == 0) {
						modal = '<div id="modal">';
						modal += '<div class="modal_container">';
						modal += '<div class="modal_close"></div>';
						modal += '<div tabindex="0" class="modal_content" role="dialog">';
						modal += html;
						modal += '</div></div></div>';
						modal.appendTo('#container');
					}

					overlay.getOverlay().css({top:$pos.top+15, left:$pos.left-180});
					$modal.find('.modal_content').html(html);

					if (modal_id == '#zip_code_check')
					{

						updateInput();

					}

					return false;

				});
			break;

		}

	}).live('click', function(){
		var $this = $(this),
			$parent = $this.parents('.modal_content'),
			overlay = $this.parents('.modal_content').data('overlay'),
			catEntryId = ( $parent.attr('id') !== undefined ) ? $parent.attr('id').split(' ')[0].split('_')[1] : getCatId();

		if ($parent != undefined)
		{

			var url = $this.attr('href').split('#')[1];
				url = '#' + url;

			if ($this.attr('href') == '#check_other_stores' || url == '#check_other_stores')
			{
				overlay.close();

				// If you are in a modal and click the "Check Other Stores" link then trigger the modal
				var check_store = $('#item_' + catEntryId).find('.modal[href=#check_other_stores]');
				check_store.data('overlay').load();
				check_store.triggerHandler('click');
			}
		}
	});
	*/




	/* This is to remove onerror="NoProductThumbnail(this)" from the DOM */
	$('img.productImg').bind('error', function(){this.src = "/wcsstore/B2BDirectStorefrontAssetStore/images/no_image_available_md.gif";});

	/* Bind event for "Check Other Stores" to show a modal dialog. */
	$('a[href*="#check_other_stores"]', $addToCart).bind('click', function(e){
		e.preventDefault;
		var $this = $(this),
			catEntryId = ( $this.parents('li').attr('id') !== undefined ) ? $this.parents('li').attr('id').split(' ')[0].split('_')[1] : getCatId(),
			request_url = '/ProductLocator?storeId=10151&langId=-1&catalogId=10051&catentryId=' + catEntryId,
			loading = $('<div class="modal_loading">Loading <img src="/images/modal_loader.gif" /></div>');
		$largeModal.dialog({title:"Check Other Stores"}).find('.modal_content').addClass('find_product').end().html(loading).dialog("open").load(request_url, function(){$largeModal.dialog("close").dialog("open");});
	});
	/* Free Delivery Tooltip */
	$('a[href*="#free_delivery"]').tooltip({
		position:{
			my:'center bottom',
			at:'center top'
		},
		content: function(){
			return $freeDelivery.html();
		}
	});
	/* Online Only Tooltip */
	$('a[href*="#online_only_price"]').tooltip({
		content: function(){
			return $onlineOnlyPrice.html();
		}
	});
	/* Zip Code Check */
	/*$zipCodeCheck.dialog({
		title: "Enter Zip Code",
		modal: true,
		autoOpen: false
	});*/
	$('a[href*="#zip_code_check"]').bind('click', function(){
		$zipCodeCheck.dialog({
			title: "Enter Zip Code",
			modal: true,
			resizable: false,
			draggable:false
		});
	});
	/* Buy the pair modal */
	/*
	$('#buyThePairBlock .img-thumb').bind('mouseenter', function() {
		$('.quick_view_btn', this).fadeIn('fast');
	}).bind('mouseleave', function() {
	    $('.quick_view_btn', this).fadeOut();
	});
	*/
	$('.buyPair').live('click',function(evt){
		evt.preventDefault();
		var $this = $(this),
			$modal = $('#buypair_modal'),
			topPos = $this.offset().top-$modal.height(),
			leftPos = $this.offset().left+($this.width()/2);
		$modal.find('.mid').html("<strong>Hello World!</strong> <p>This is where the AJAX data goes.</p>").end().css({"position":"absolute","top":topPos,"left":leftPos}).show();
	});
	/* Quick View */
	/* Set up the modal space */
	$quickView.dialog({
		title: "Quick View",
		modal: true,
		autoOpen: false,
		resizable: false,
		width: "auto"
	});
	/* Bind events for Quick View */
	$('a.productImgLink').bind({
		mouseenter : function() {
			$('<span class="quick_view_btn" />').appendTo(this).fadeIn('fast');
		},
		mouseleave : function() {
			$('.quick_view_btn', this).fadeOut().remove();
		},
		click : function(e) {
			e.preventDefault();
			var $this = $(this),
				$item = $this.parents('li.active'),
				/*item = {
					number : $item.attr('id').split('_')[1],
					title : $.trim($item.find('h3').text()),
					price : $.trim($item.find('p.pricing strong').text()),
					nlp : $item.find('.prod-price img').attr('src'),
					was : $.trim($item.find('.wasPrice').text()),
					save : $.trim($item.find('.save').text()),
					promo : $.trim($item.find('.promo_text').text()),
					info : $item.find('.productInfo').html(),
					rating : $item.find('.productRating').html(),
					rating_alt : $item.find('.productRating .hoverTip').attr('alt'),
					href : $.trim($item.find('h3 a').attr('href')),
					rebate: $.trim($item.find('.rebate strong').html()),
					availability: $item.find('.availability-info').html(),
					partNumber: $item.find('.item-partNumber').html(),
					categoryId: $item.find('.item-categoryId').html(),
					disclaimer: $item.find('.disclaimer').text()
				}*/
				item = {
					number:			$item.attr('id').split('_')[1],
					image:			$this.find('img').clone().attr("src", $this.find('img').attr('src').replace('sm.', 'lg.')),
					title:			$item.find('h3').html(),
					details:		$item.find('.productInfo').html(),
					pricing:		$item.find('p.pricing').html(),
					descriptors:	$item.find('div.priceDescriptors').html(),
					rating:			$item.find('.productRating').clone(true),
					quantity:		$item.find('p.quantity').html(),
					cartControls:	$item.find('div.addToCart').html(),
					messaging:		$item.find('div.productMsg').clone(true),
					partNumber: 	$item.find('.item-partNumber').html(),
					categoryId: 	$item.find('.item-categoryId').html(),
					disclaimer: 	$item.find('.disclaimer').text()
				};

			// Check if the availability area is ZIP code based
			/*var avail = item.availability;

			// If the ZIP code messaging exists for the product
			if ($(avail).hasClass('enter-zip-callout')) {
				// Build a zip code template.
				var zip_code = '<div id="enter-zip-callout">';
					zip_code += '<h3>Enter Your ZIP Code to View Real-Time Pricing and Availability for Your Local Store:</h3>';
					zip_code += '<label for="enter-zip-field">ZIP Code:</label>';
					zip_code += '<input type="text" value="Enter ZIP Code" id="enter-zip-field" name="enterZip" />';
					zip_code += '<a id="zip_find_store" href="#" class="button-grey"><span>Find Store</span></a>';
					zip_code += '<a href="/StoreLocatorDisplayView?storeId=10151&catalogId=10051" class="find-zip">Find My ZIP</a>';
					zip_code += '</div>';
				// Set avail to the zip code template.
				avail = zip_code;
			}*/

			// Image and Image Alt
			$('div.product-image', $quickView).html(item.image);							// Large product image
			$('h1.product-title', $quickView).html(item.title);								// Item Link and Title
			$('.product-details', $quickView).html(item.details);							// Item Number and Model Number
			$('.product-rating', $quickView).html(item.rating);								// Item rating
			$('.product-pricing', $quickView).html(item.pricing).append(item.descriptors);	// Item pricing
			$('.cart-controls', $quickView).html(item.quantity).append(item.cartControls);	// Quantity and add to cart
			$('.product-messaging', $quickView).html(item.messaging);						// Item messaging, free delivery, rebates, online only, etc.
			$('.quick-view-layout', $quickView).attr('id', 'item_' + item.number); 			// Set layout id for some reason
/*
			// NLP/Clearance Items
			if (item.nlp != null) {
				$('.promo_message', $quickView).html($('<img>').attr('src', item.nlp));
			} else {
				$('.promo_message', $quickView).empty();
			}
			$('.was_price', $quickView).text(item.was);								// Was price
			$('.save', $quickView).text(item.save);									// Save price
			$('.prod_detail', $quickView).attr('href', item.href);					// Item link
			$('.rebate', $quickView).html(item.rebate);								// Item rebate information
			$('.availability_info', $quickView).html(avail);						// Availability Information
			$('.prod_disclaimer', $quickView).html(item.disclaimer);				// Disclaimer
			$('.quick-view-layout', $quickView).attr('id', 'item_' + item.number);		// Cat Entry ID
			$quickView.find('.rating .hoverTip').attr('title', item.rating_alt);
*/

			// Update ZIP code list...
			updateInput();
			// Added for analytics tracking
			registerQuickView(item);
			// Show the modal
			$quickView.dialog("open");
		}
	});



	/* View more colors */
	$('div.colorsContainer a.showMore').toggle(
		function(evt){
			evt.preventDefault();
			$(this).parent().next('.moreColorsContainer').show();
		},
		function(evt){
			evt.preventDefault();
			$(this).parent().next('.moreColorsContainer').hide();
	});

	var swatchTip = '',
		$colorSwatches = $('#colorswatches li').not('.highlight');

	$.each($colorSwatches, function(key, obj) {
		myobj = obj.product;
		swatchTip += '<div class="css-arrow center bg">&nbsp;</div><div class="css-arrow center">&nbsp;</div>';
		swatchTip += '<img src="' + myobj.image + '" alt="Image of ' + myobj.title + '" />';
		swatchTip += '<div class="productinfo"><h4><a name="product_tooltip_title_' + myobj.item + '" href="#">' + myobj.title + '</a></h4>';
		swatchTip += '<span class="itemmodel">Item #: ' + myobj.item + ' | Model #: ' + myobj.model + '</span>';
		swatchTip += '<span class="price">$' + myobj.price + '</span></div>';
		products[myobj.item] = swatchTip;
	});

	$colorSwatches.tooltip({
		content: function(){
			var itemId = $(this).attr('id').slice(12);
			return products[itemId];
		}
	});

	$('.productRating .hoverTip').attr('title', "I am a tooltip.").tooltip({
		position:{
			my:'center bottom',
			at:'center top',
			offset:"0 0"
		},
		content:function(){return '<div class="css-arrow center bg"></div><div class="css-arrow center"></div><div>' + $(this).attr('alt') + '</div>';}
	});

	/* HoverTip Class to display Hovers */
/*
	$('.hoverTip').each(function(i, item) {
		var $item = $(item),
			$parent = $item.parent();

		switch ($parent.attr('class')) {

			case 'productRating':
				var rating_alt = $item.attr('alt');
					$item.data('rating_alt', rating_alt);
					$item.attr('alt',''); // Remove alt attr to supress the IE hover
				// ('.rating .hoverTip')
				$parent.tooltip({
					position:'bottom center',
					content:function(){return $item.data('rating_alt');}
				});
			break;

			case 'compareBtn':
				// ('.compareBtn .hoverTip')
				$item.tooltip({
					position:'bottom center',
					delay:0,
					effect:'fade',
					offset:[15,0],
					tipClass:'compare_tip',
					onBeforeShow: updateCompare
				});
			break;

			default:
				//$('.hoverTip').tooltip({delay:0, effect:'fade', offset:[15,0]});
				return false;
			break;

		}

		return false;
	});
*/

	/*
	 *	Multi-Select left navigation.
	 */
	/* setup click event, left nav show/hide filters */
	$('> li a.divider', $expandable).bind('click', multiSelectShowHideFilter);
	/* setup click event, all multi-select checkboxes */
	$('li ul li input:checkbox', $expandable).live('click', {modal:false}, multiSelectCheckboxes);
	/* setup click event, "view more" filter link */
	$('li ul li a.view_all', $expandable).bind('click', multiSelectViewMoreModal);
	/* setup click event, "go" submit button */
	$('li ul li a.go_btn', $expandable).bind('click', multiSelectSubmit);
	/* setup ajax listener, show "loading..." in "view more" modal */
	$("#sort_modal #dynamic_content").bind("ajaxSend", function(){
   		$(this).empty().html('<span id="loading">Loading...</span>');
 	});

	/* declare functions
	********************/

	/* utility, slice querystring into object */
	function queryStringToObject(queryString) {
		if (typeof queryString == 'undefined') return {};

		console.log('queryString = ' + queryString);
		var qsVars = {};
		queryString.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"), function(){
			qsVars[arguments[1]] = arguments[3];
		});

		return qsVars;
	}
	/* show-hide filters */
	function multiSelectShowHideFilter () {
		var $this = $(this),
			$parent = $this.parent('li');

		( $parent.hasClass('open') ) ? $parent.removeClass('open') : $parent.addClass('open').find('ul').css('display', 'none').fadeIn('fast');

		return false;
	}
	/* setup click events for "view more" modal checkboxes */
	function multiSelectViewMoreModalEvents () {
		$('#sort_modal .center input:checkbox').unbind('click').bind('click', {modal:true}, multiSelectCheckboxes);
		$('#sort_modal .center #updateButton a.update').unbind('click').bind('click', multiSelectUpdateFilter);
	}
	/* multi-select modal checkbox validation */
	function multiSelectCheckboxes(event) {
		var $this = $(this),
			name = $this.attr('name'),
			$checkboxes = event.data.modal ? $('input:checkbox', __global.vars.multiSelectModal) : $this.parents('li').eq(1).find('input:checkbox');

		if ( name.indexOf('_all') > 0 )
		{
			$this.parent('li').addClass('checked');
			$this[0].disabled = true;

			/* loop through each input, uncheck and unbold them */
			$checkboxes.each(function(i){
				if ( i > 0 ) { $(this).attr('checked', '').parent('li').removeClass('checked'); }
			});
		}
		else
		{
			var checkboxesActive = false;

			/*add or remove class to li in order to bold or unbold font*/
			if ($this.is(':checked'))
			{
				$this.parent('li').addClass('checked');
			}
			else
			{
				$this.parent('li').removeClass('checked');
			}

			$checkboxes.each(function(i){
				if ( i > 0 && $(this).is(':checked')) { checkboxesActive = true;}
			});

			/* uncheck/check, unbold/bold and enable/disable the "All" checkbox */
			if (checkboxesActive)
			{
				$checkboxes.eq(0).attr('checked', '').parent('li').removeClass('checked');
				$checkboxes.eq(0)[0].disabled = false;
			}
			else
			{
				$checkboxes.eq(0).attr('checked', 'checked').parent('li').addClass('checked');
				$checkboxes.eq(0)[0].disabled = true;
			}
		}
	}
	/* setup "view more" modal. request data, setup html and show/hide */
	function multiSelectViewMoreModal(){

		var $this = $(this),
			filter = $this.attr('rel'),
			filterCommand = $this.attr('href'),
			position = $this.offset(),
			qString = document.URL.split('?'),
			myqString = queryStringToObject(qString[1]);
			__global.vars.multiSelectModal = $('#sort_modal');

		/* check if filter is currently loaded into modal */
		if (__global.filter.current != filter)
		{
			/* tracks current filter loaded into modal */
			__global.filter.current = filter;
			__global.filter.currentObj = $this;

			/* setup modal "all" checkbox title */
			$('h3 label', __global.vars.multiSelectModal).html('All ' + __global.filter.current);

			for (value in myqString)
			{
				if (value != 'N')
				{
					filterCommand += '&' + value + '=' + myqString[value];
				}
			}
			console.log(' filterCommand = ' + filterCommand);
			multiSelectSetupMoreFilters(filterCommand);
		}
		else
		{
			multiSelectSyncCheckbox();
		}

		/* get "view all" link position and display modal next to it */
		__global.vars.multiSelectModal.css({'top' : (position.top - 60), 'left' : (position.left + 52)});
		__global.vars.multiSelectModal.fadeIn('fast');

		/* bind only once */
		if(bind_modalClose)
		{
			$('.top a, #updateButton a.cancel', __global.vars.multiSelectModal).bind('click', function(){

				__global.vars.multiSelectModal.fadeOut('fast');

				return false;
			});

			bind_modalClose = false;
		}

		return false;
	}
	/* check cache, if "view more" filter data != exist then get via ajax call and wrap response in html */
	function multiSelectSetupMoreFilters (filterCommand){
		__global.filter[__global.filter.current] = window.__global.filter[__global.filter.current] || {};

		console.log("setupmorefilters filter = " + __global.filter.current);

		/* check cache */
		if (typeof __global.filter[__global.filter.current].html == "undefined")
		{
			console.log('get ajax!');

			$.ajax({
				url: filterCommand,
				//url: 'javascript/json.js',
				dataType: 'json',
				success: function (data)
				{
					var json = data,
						columnCount = (json.moreDimensionsAjaxResp.facetList[0].values.length / 7),
						last = columnCount <= 1 ? ' last' : '';
						html = '<ul class="col' + last + '">',
						counter = 1;

					for (i = 0; i < json.moreDimensionsAjaxResp.facetList[0].values.length; i++)
					{
						var filterName = json.moreDimensionsAjaxResp.facetList[0].values[i].label,
							productCount = json.moreDimensionsAjaxResp.facetList[0].values[i].additionalInfo[0],
							nValue = json.moreDimensionsAjaxResp.facetList[0].values[i].additionalInfo[2];

						if (counter == 8)
						{
							last = '';
							last = columnCount >= 1 && columnCount <= 2 ? ' last' : '';

							html += '</ul><ul class="col' + last + '">';
						}
						else if (counter == 15)
						{
							html += '</ul><ul class="col last">';
						}

						html += '<li><input type="checkbox" value="' + nValue + '" id="' + __global.filter.current + '_item_' + (i+1) + '_modal" name="' + __global.filter.current + '_item_' + (i+1) + '_modal"> <label for="' + __global.filter.current + '_item_' + (i+1) + '_modal">' + filterName + '</label> <span>(' + productCount + ')</span></li>';

						counter++;
					}

					html += '</ul>'

					/* cache html wrapped json */
					__global.filter[__global.filter.current].html = html;

					/* insert html into modal */
					$('#dynamic_content', __global.vars.multiSelectModal).empty().html(__global.filter[__global.filter.current].html);

					/* setup click events, modal checkboxes */
					multiSelectViewMoreModalEvents();
				}
			});

			__global.filter[__global.filter.current].currentCount = 0;
		}
		else
		{
			console.log("get cached!");

			/* insert html into modal */
			$('#dynamic_content', __global.vars.multiSelectModal).empty().html(__global.filter[__global.filter.current].html);

			multiSelectSyncCheckbox();

			multiSelectViewMoreModalEvents();
		}
	}

	function multiSelectUpdateFilter () {
		var $leftNavCheckbox = $('li', __global.filter.currentObj.closest('ul')),
			$insertPosition = $leftNavCheckbox.eq(1),
			$modalCheckboxClone = $('input:checked', __global.vars.multiSelectModal).parent('li').clone();

			console.log("update " + __global.filter.current + " counter, before = " + __global.filter[__global.filter.current].currentCount);

		/* clear from left nav all previously added filters before inserting new filters */
		if (__global.filter[__global.filter.current].currentCount > 0)
		{
			$leftNavCheckbox.slice(1,__global.filter[__global.filter.current].currentCount + 1).remove();

			/* re-cache new left nav checkboxes */
			$leftNavCheckbox = $('li', __global.filter.currentObj.closest('ul'));
			$insertPosition = $leftNavCheckbox.eq(1);
		}

		/* rename input and label id's for left nav */
		$modalCheckboxClone.each(function(i){
			$('input', this).attr('id', $('input', this).attr('id').replace('_modal', ''));
			$('label', this).attr('for', $('label', this).attr('for').replace('_modal', ''));
		});

		/* clone and move filters from modal to left nav filters */
		$insertPosition.before($modalCheckboxClone);

		/* hack for .trigger() */
		var event = new $.Event('click');
		event.preventDefault();

		/* trigger checkbox validation */
		$('input', $insertPosition).trigger(event);

		__global.vars.multiSelectModal.fadeOut('fast');

		/*track number of currect filters added to left nav from modal */
		__global.filter[__global.filter.current].currentCount = $modalCheckboxClone.length;

		console.log("update " + __global.filter.current + " counter, after = " + __global.filter[__global.filter.current].currentCount);
		console.log("-------------------------------");

		return false;
	}
	/* keeps modal checkboxes synced with user actions on the left nav checkboxes */
	function multiSelectSyncCheckbox () {
		$leftNavCheckbox = $('li', __global.filter.currentObj.closest('ul'));

		console.log("left nav - new " + __global.filter.current + " filters = " + $leftNavCheckbox.slice(1,__global.filter[__global.filter.current].currentCount + 1).length);

		$leftNavCheckbox.slice(1,__global.filter[__global.filter.current].currentCount + 1).each(function (){

			var $thisInput = $('input', $(this)),
			thisInputId = $thisInput.attr('id');

			console.log("checked modal = " + $('#' + thisInputId + '_modal', __global.vars.multiSelectModal).attr('checked'));


			if ($thisInput.attr('checked'))
			{
				if (!$('#' + thisInputId + '_modal', __global.vars.multiSelectModal).attr('checked'))
				{
					$('#' + thisInputId + '_modal', __global.vars.multiSelectModal).attr('checked', 'checked').parent('li').addClass('checked');
				}
			}
			else
			{
				$('#' + thisInputId + '_modal', __global.vars.multiSelectModal).attr('checked', '').parent('li').removeClass('checked');
			}
		});

		/* hack for .trigger() */
		var event = new $.Event('click');
		event.preventDefault();

		/* trigger modal checkbox validation */
		$('#dynamic_content input:checkbox', __global.vars.multiSelectModal).eq(0).trigger(event, {modal:true});

		console.log("-------------------------------");
	}
	/* gather all filter, build url and redirect page */
	function multiSelectSubmit () {
		var submitUrl = '/SearchCatalog?',
			$this = null,
			qString = document.URL.split('?'),
			myqString = queryStringToObject(qString[1]),
			currentNvalue = $('#currentNValue',$expandable).attr('value').replace(' ', '+');


		if (qString[0].indexOf('/SearchCatalog') <= 0)
		{
			submitUrl += 'searchQueryType=1&langId=-1&catalogId=10051&storeId=10151&';
		}

		console.log('submit 1st = ' + submitUrl);

		submitUrl += 'N=' + currentNvalue;

		$('li ul li input:checked', $expandable).each(function(index){

			console.log('index = ' + index);

			$this = $(this);

			console.log('name = ' + $this.attr('name'));

			if ( $this.attr('name').indexOf('_all') <= 0 )
			{
				submitUrl += '+' + $this.attr('value').toString();

				console.log('>>> submitUrl = ' + submitUrl);
			}

		});

		console.log(' url = ' + document.URL.split('?')[0]);

		for (value in myqString)
		{
			if (value != 'N')
			{
				submitUrl += '&' + value + '=' + myqString[value];
				console.log(' urlObject = ' + myqString[value]);
			}
		}

		console.log('submit url = ' + submitUrl);

		/* redirect page to new URL */
		window.location = submitUrl;

		return false;
	}

	// Check the userPrefs cookie, and if the value is set manipulate the layout.
	function applyUserPrefs(){
		var userPrefs = readCookie('userPrefs');
		if (userPrefs !== null) {
			// User can has preferences.
			var remove_class,
				add_class,
				$current_control,
				$other_control;

			// Grid/List Check
			if (userPrefs === 'list_view') {
				remove_class = 'gridView';
				add_class = 'listView';
				$current_control = $listToggler;
				$other_control = $gridToggler;
			} else {
				add_class = 'gridView';
				remove_class = 'listView';
				$current_control = $gridToggler;
				$other_control = $listToggler;
			}
			$productResults.removeClass(remove_class).addClass(add_class);
			$other_control.removeClass('current');
			$current_control.addClass('current');
		}
		return;
	}
	/* Shows Error Messages For When User Chooses Invalid Page Numbers */
	function userInvalidPageError($objjqInput, strErrorMessage) {
		// Throw an error message
		var $page_errors = $('div.page-errors');

		if ($page_errors.length == 0) {
			$('<div class="page-errors" />').html(strErrorMessage).insertAfter($('#one-column h1')).slideDown();
		}else{
			// Update so it only changes the error under $page_title
			$page_errors.html(strErrorMessage);
		}
		$('html, body').animate({scrollTop: 0}, 1000);
		$objjqInput.val('').focus();
	}

	function getCatId() {
		// Get the url and chop it up
		var url = window.location.search,
			params = url.split('?')[1].split('&'),
			productId;
		// Loop through the url parameters to look for productId
		for ( i=0; i<params.length; i++ ) {
			// Capture the value of productId if it exists, discarding the key
			if ( params[i].indexOf('productId=') >= 0 ) { productId = params[i].replace('productId=', ''); }
		}
		// Return the productId if found, or empty if not.
		return productId;
	}

	function updateCompare($this, input) {

		var curr_count,
			cookie_count;

		// If the user has items selected from a previous page, get the count.
		if (readCookie('pcompitems') !== null) {
			cookie_count = readCookie('pcompitems').split(',');
			curr_count = cookie_count.length;
			if ( cookie_count[0] == '' ) {
				curr_count = 0;
			}
		} else {
			curr_count = 0;
		}

		var $buttons = $('.compareBtn .hoverTip'),
			compare_items = [],
			total = 5,
			msg = 'Please select <strong>2</strong> or more items <br /> to compare.',
			full = 'You have selected <strong>' + total + '</strong> products for comparison and reached the limit.';

		// Unbind this event, if the max has been set it will be rebinded below.
		$('.item-actions').unbind('click');

		if ( $this !== undefined && input === true ) {

			var item_id = $this.parents('li').eq(1).attr('id').split('_')[1];

		}

		// Check the cookie for Compare Products
		if (readCookie('pcompitems') !== null) {

			var cookie_items = readCookie('pcompitems').split(',');
			for ( var i=0; i<cookie_items.length; i++ ) {

				if ( item_id != cookie_items[i] ) { compare_items.push(cookie_items[i]); }
				if ( cookie_items[0] == '' ) { compare_items.splice(0, 1); }

			}

		}

		// If the user clicked a checkbox
		if ( $this !== undefined && input === true ) {

			if ( $this.is(':checked') ) {

				compare_items.push(item_id);

			}

			curr_count = compare_items.length;
			createCookie('pcompitems', compare_items, 30);

		}

		$buttons.each(function(i, item){

			var $item = $(item),
				$parent = $item.parents('li').eq(1),
				parent_id = $parent.attr('id');

			// If the user has selected 2 products
			if (curr_count > 1)
			{
				$item.removeClass('disabled');

				msg = 'You have selected <strong>' + curr_count + '</strong> products for comparison, you may select <strong>' + (total-curr_count) + ' more</strong> products to compare.';

				if (curr_count >= total) {
					$('.compare input:not(:checked)').attr('disabled', 'disabled').parent('.compare').next().children('a').addClass('disabled');
					msg = full;

					// If the item is not already selected then bind function to these items
					if ( $item.hasClass('disabled') ) {

						/*$('#' + parent_id + ' .item-actions').overlay({
							close:'.close',
							fixed:false,
							mask:{
								color:'#000',
								opacity:0.2,
								zIndex:900
							},
							target:'#large_modal',
							top:'center',
							onBeforeLoad: function(){

								$('#large_modal .modal_content').html('<p>You have already selected <strong>' + total + '</strong> products to compare. <a href="#" class="clear_compare">Remove products</a> before making additional selections.');

							}
						}).bind('click', function(){

							console.log('Clicked ' + $item);

						});*/

					}

				} else {
					$('.compare input:not(:checked)').attr('disabled', '').parent('.compare').next().children('a').removeClass('disabled');
				}
			}
			else
			{
				$(item).addClass('disabled');
			}

		});

		$('.compare_tip').html(msg);

	}
	/* This will check all compare buttons that are checked, if they exist on the page. */
	function precheck_items(items) {

		var all_products = $('#productResults > li'),
			item;

		items = items.split(',');

		// Run a check of the items the user has selected
		for (var i=0; i<items.length; i++) {

			// Run a check of the items on the page
			for (var j=0; j<all_products.length; j++) {

				item = $(all_products[j]).attr('id').split('_')[1];

				if ( items[i] == item ) {

					$('#item_' + item + ' input[name=compare]').attr('checked', 'checked');

				}

			}

		}

		updateCompare();

	}

	function updateURL(curr_url, new_val, url_string) {

		/* If the URL has a # then remove it */
		if (curr_url.indexOf('#') > 0) {

			curr_url = curr_url.replace('#','');

		}

		var has_param = curr_url.indexOf(url_string);

		/* If the current URL has the existing URL string replace it */
		if (has_param > 0) {

			var url_arr = curr_url.split('?');
				url_arr = url_arr[1].split('&');

			for(i=0; i<url_arr.length; i++) {

				if (url_arr[i].indexOf(url_string) == 0) {

					new_url = curr_url.replace(url_arr[i], new_val);

				}

			}
			window.location = new_url;

		} else {
			/* Else set the URL */

			new_url = (curr_url.indexOf('?') < 0) ? curr_url + '?&' + new_val : curr_url + '&' + new_val;

			window.location = new_url;

		}
	}

	function updateInput() {

		$('#zipCode, #enter-zip-field').each(function(i, item){

			var $this = $(item);

			$this.data('val_text', $this.val());

		}).live('focus', function(){

			var $this = $(this),
				value = $this.val();

			if (value == $this.data('val_text'))
			{
				$this.val('');
			}

			$this.attr('maxlength', 5);

		}).live('blur', function(){

			var $this = $(this),
				value = $this.val(),
				val_text = $this.data('val_text');

			if (value == '' || value == ' ')
			{
				$this.val(val_text);
			}

			$this.attr('maxlength', val_text.length);

		}).bind('keydown', function(event) {

			var $this = $(this);

			if (event.keyCode == 13) {

				if($this.val() != '') {
					submitZip($this);
				}

			}

		});;

	}

	function submitZip($this) {

		var input_val = $this.parents('ul').find('input').val() || $this.parents('#enter-zip-callout').find('input').val(),
			user_zip = $.trim(input_val),
			$masthead_zip_form = $('#storeSearchForm');

		$masthead_zip_form.find('input[name=zipCode]').val(user_zip);
		$masthead_zip_form.submit();

		return false;

	}

	function registerQuickView(item) {
		var cmProductviewData = window.cmProductviewData || {};

		cmProductviewData.pagename='QUICKVIEW: ' + item.title + '(' + item.partNumber + ')';
		cmProductviewData.partNumber=item.partNumber;
		cmProductviewData.shortDescription=item.title;
		cmProductviewData.categoryId=item.categoryId;
		cmProductviewData.storeId=mastConfig.storeId;
		cmProductviewData.actAsPageview="Y";
		cmProductviewData.explorerAttributes=null;
		cmProductviewData.relationship=null;
		cmProductviewData.searchTerm=null;
		cmProductviewData.resultCount=null;
		var cmWrapperCall = function() {
			cmCreateProductviewTag(
				cmProductviewData.pagename,
				cmProductviewData.partNumber,
				cmProductviewData.shortDescription,
				cmProductviewData.categoryId,
				cmProductviewData.storeId,
				cmProductviewData.actAsPageview,
				"0",
				cmProductviewData.explorerAttributes,
				cmProductviewData.relationship,
				cmProductviewData.searchTerm,
				cmProductviewData.resultCount
			);
		};
		cmWrapperCall();
	}
	//=====================================================================
	//Function that detect if session cookie "pcompitems" contains items
	function setItemsAdded(){
		if(pcompCookie = getCookie("pcompitems") && pcompCookie.length > 0){
			itemsAdded = true;
			arrPcompitems = getCookie("pcompitems").split(",");
		}else{
			itemsAdded = false;
		}
		setCompareNowRel();
	}
	//=====================================================================
	//Function that sets the content rel property for compare now anchors
	//depending of the value of sessions cookie "pcompitems"
	function setCompareNowRel(){
		itemsAddedCount = arrPcompitems.length;
		itemsToAddCount = 5 - itemsAddedCount;

		sAddedTxt = (itemsAddedCount > 1 || itemsAddedCount == 0)? "s" : "";
		sToAddTxt = (itemsToAddCount > 1)? "s" : "";

		if(itemsAddedCount < 5){
			relText = "You have selected " + itemsAddedCount + " product" + sAddedTxt + " for comparison, you may select " + itemsToAddCount + " more product" + sToAddTxt + " to compare.";
		}
		else {
			relText = "You have selected " + itemsAddedCount + " product" + sAddedTxt + " for comparison, and reached the limit.";
		}

		for (pC=0;pC<prodCounter;pC++){
			var compareAnchor = document.getElementById("compareAnchor"+pC);
			if (compareAnchor){
				compareAnchor.rel = relText;
			}
		}

	}
	//=====================================================================
	//Function that sets the Session Cookie value for Product Compare tool
	function setCompareItems(catentryId,checkState,checkId){
		if(checkState){
			if(arrPcompitems.length>=5){
				//document.getElementById("estTax-help"+checkId).style.display='block';
				//dojo.removeClass(dojo.byId('estTax-help'+checkId), 'hidden');
				//dojo.byId('noComp'+checkId).click();
				$('#dialog_prod_comp').show();
				document.getElementById("compareCheck"+checkId).checked = false;
			}else{
				arrPcompitems.push(catentryId);
				$('#dialog_prod_comp').hide();
			}
		}else{
			for(i=0;i<arrPcompitems.length;i++){
				if(arrPcompitems[i] == catentryId){
					arrPcompitems.splice(i,1);
				}
			}
		}
		setCookie("pcompitems",arrPcompitems.toString());
		//arrPcompitems = getCookie("pcompitems").split(",");
		setItemsAdded();
		compareLinkActivation();
	}
	//=====================================================================
	//Function that compare if a Product is on "pcompitems" list
	//and sets the status of checkbox
	function setCompareCheck(catentryId){
		for (pC=0;pC<prodCounter;pC++){
			var compareCheck = document.getElementById("compareCheck"+pC);
			var vCatentryId = 0;
			var isAdded = false;
			if(compareCheck){
				for(i=0;i<arrPcompitems.length;i++){
					vCatentryId = compareCheck.value;
					if(arrPcompitems[i] == vCatentryId){
						isAdded = true;
					}
				}
				compareCheck.checked = isAdded;
			}
		}
		compareLinkActivation();
	}
	//=====================================================================
	//Function that activates - deactivates the Compare Now links.
	function compareLinkActivation(){
		var firstLink = -1;
		var count = 0;
		for (var i = 0; i < prodCounter; i++){
			var checkbox = document.getElementById("compareCheck"+i);
			var $link = $("#compareAnchor"+i);
			if (checkbox){
				if (checkbox.checked){
					if (firstLink == -1){
						if (arrPcompitems.length > 1){
							count++;
						}
						firstLink = i;
					}else{
						$link.addClass("active");
						count++;
					}
				}else{
					$link.removeClass("active");
				}
			}
		}
		if (firstLink > -1){
			var $compareAnchor = $("#compareAnchor"+firstLink);
			if (count > 0){
				$compareAnchor.addClass("active");
			}else{
				$compareAnchor.removeClass("active");
			}
		}
	}
	//=====================================================================
	//Function that submit Compare Items Form
	function submitCompareItems(catentryId){
		if(itemsAdded && arrPcompitems.length > 1){
			var submit = false;
			if (catentryId == 1) {
				submit = true;
			} else {
				for(i=0;i<arrPcompitems.length;i++){
					if(arrPcompitems[i] == catentryId){
						submit = true;
						break;
					}
				}
			}

			if (submit) {
				document.LowesProductComparisionForm.pcompitems.value = arrPcompitems.toString();
				document.LowesProductComparisionForm.returnShoppingUrl.value=document.location.href
				document.LowesProductComparisionForm.submit();
			}
		}
	}
	//=====================================================================
	function defaultQV_zip(x){
		if(document.getElementById(x).value == ""){
			document.getElementById(x).value = "Enter ZIP Code";
			document.getElementById(x).maxLength = 20;
		}
	}
	//=====================================================================
	function clearQV_zip(x){
		if (document.getElementById(x).value == "Enter ZIP Code"){
			document.getElementById(x).value = "";
			document.getElementById(x).maxLength = 5;
		}
	}
	//=====================================================================
	function submitZipCodeForm(e,prodURL){
		if (e.keyCode == 13){
			document.storeSearchForm.zipCode.value = document.storeSearchFormQV.enterZip.value;
			document.storeSearchForm.isQvSearch.value="searchQV";
			document.storeSearchForm.qvRedirect.value=prodURL;
			document.storeSearchForm.submit();
			return false;
		}
	}
	//=====================================================================
	function giftCardAddToCartContinue( a , url) {
		var eps = dojo.getObject("lowes.catalog.endecaParams", true);
		if ( eps ) {
			var o = new Object();
			if (eps.N)   { o.N = eps.N   };
			if (eps.Ne)  { o.N = eps.Ne  };
			if (eps.Ntt) { o.N = eps.Ntt };
			if (eps.Ns)  { o.N = eps.Ns  };
			var eo = dojo.objectToQuery( o );
			if ( eo ) {
				window.location = url + '&' + eo;
			}
		} else {
			window.location = url;
		}
	}
	//=====================================================================
	//Function that returns the URL for the pagination form
	function callChangePageNumber(formNumber){
		//Changed from form submit to query string because of the
		//Dynamic Cache
		var form = eval('document.paginatorForm' + formNumber);
		var totalPagesValue = form.totalPages.value;
		var currentPageValue = form.currentPage.value;
		var pageNumberValue = form.pageNumber.value;
		var sb = getDefaultURL();
		if (sb.indexOf('?') > -1) {
			sb += '&pageNumber=' + pageNumberValue;
		} else {
			sb += '?pageNumber=' + pageNumberValue;
		}
		if(totalPagesValue!=''){
			sb += '&totalPages=' + totalPagesValue;
		}
		if(currentPageValue!=''){
			sb += '&currentPage=' + currentPageValue;
		}
		var endecaParams = dojo.getObject("lowes.catalog.endecaParams", true);
		if ( endecaParams.Ntt && endecaParams.Ntt != null ){
			sb += '&Ntt=' + endecaParams.Ntt;
		}
		location.href = sb;
	}
	//=====================================================================
	//Function that set the view all parameter
	function callViewAll(totalRecords){
		var sb = getDefaultURL();

		if (sb.indexOf('?') > -1)
			sb += '&Va=' + totalRecords;
		else
			sb += '?Va=' + totalRecords;

		var endecaParams = dojo.getObject("lowes.catalog.endecaParams", true);
		if ( endecaParams.Ntt && endecaParams.Ntt != null ){
			sb += '&Ntt=' + endecaParams.Ntt;
		}

		location.href = sb;
	}
	//=====================================================================
	//Function that set the view type (Grid or List)
	/*
	function callSwapView(viewTypeName){

		var form = eval('document.paginatorForm1');
		var pageNumber = '';
		if (form) {
			pageNumber = form.currentPage.value;
		}
		var sb = getDefaultURL();

		if (sb.indexOf('?') > -1)
			sb += '&viewTypeName=' + viewTypeName;
		else
			sb += '?viewTypeName=' + viewTypeName;

		var endecaParams = dojo.getObject("lowes.catalog.endecaParams", true);
		if ( endecaParams.Ntt && endecaParams.Ntt != null ){
			sb += '&Ntt=' + endecaParams.Ntt;
		}
		if(pageNumber!=''){
			sb += '&pageNumber=' + pageNumber;
		}
		location.href = sb;
	}
	*/
	//=====================================================================
	//Function that set the Results per page parameter
	function callResultPerPageDromDown(sizePageParam){
		var sb = getDefaultURL();
		if (sb.indexOf('?') > -1)
			sb += '&rpp=' + sizePageParam;
		else
			sb += '?rpp=' + sizePageParam;

		var endecaParams = dojo.getObject("lowes.catalog.endecaParams", true);
		if ( endecaParams.Ntt && endecaParams.Ntt != null ){
			sb += '&Ntt=' + endecaParams.Ntt;
		}
		location.href = sb;
	}
	//=====================================================================
	/*
		Submits the OrderItemAddForm for the specific catentryId.
		This also sets the cmCategoryId value on the form with the value that was generated
		by the coremetrics pageview tag.  The OrderItemAddCmd will save the cmCategoryId value
		in a cookie so that it can be persisted and sent in the coremetrics shop5 tag.

		We have to set the cmCategoryId using javascript like this because we won't know the value
		until after the coremetrics pageview tag executes.
	*/
	function productListAddToCart( catentryId ) {

		var f = dojo.byId('OrderItemAddForm');
		if ( f ) {
			f.catEntryId.value = catentryId;
			f.productId.value = catentryId;
			try {
				var o = dojo.formToObject('OrderItemAddForm_' + catentryId);
				if ( o ) {
					f.parentProductCacheKey.value = o.parentProductCacheKey;
					f.paOfferPrice.value = o.paOfferPrice;
					f.quantity.value = o.quantity;
				}
				var pg = dojo.getObject("cmPageviewData");
				if ( pg && pg.categoryId ) {
					f.cmCategoryId.value = pg.categoryId;
				}
			} catch (e){}
			f.submit();
		} else {
			//This is only here temporarily for backwards compatability.  Once the .jsps have been pushed everywhere this should be removed
			var form = eval( 'document.OrderItemAddForm_' + catentryId );
			if ( form ) {
				if ( form.cmCategoryId ) {
					if ( typeof cmPageviewData != undefined ) {
						if ( cmPageviewData.categoryId ) {
							form.cmCategoryId.value = cmPageviewData.categoryId;
						}
					}
				}

				form.submit();
			}
		}
	}
});
